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-2011 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.
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 WINED3D_GLSL_SAMPLE_PROJECTED 0x1
43 #define WINED3D_GLSL_SAMPLE_RECT 0x2
44 #define WINED3D_GLSL_SAMPLE_LOD 0x4
45 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
59 struct glsl_sample_function
67 HEAP_NODE_TRAVERSE_LEFT,
68 HEAP_NODE_TRAVERSE_RIGHT,
80 struct constant_entry *entries;
81 unsigned int *positions;
85 /* GLSL shader private data */
86 struct shader_glsl_priv {
87 struct wined3d_shader_buffer shader_buffer;
88 struct wine_rb_tree program_lookup;
89 struct glsl_shader_prog_link *glsl_program;
90 struct constant_heap vconst_heap;
91 struct constant_heap pconst_heap;
93 GLhandleARB depth_blt_program_full[tex_type_count];
94 GLhandleARB depth_blt_program_masked[tex_type_count];
95 UINT next_constant_version;
98 /* Struct to maintain data about a linked GLSL program */
99 struct glsl_shader_prog_link {
100 struct wine_rb_entry program_lookup_entry;
101 struct list vshader_entry;
102 struct list pshader_entry;
103 GLhandleARB programId;
104 GLint *vuniformF_locations;
105 GLint *puniformF_locations;
106 GLint vuniformI_locations[MAX_CONST_I];
107 GLint puniformI_locations[MAX_CONST_I];
108 GLint posFixup_location;
109 GLint np2Fixup_location;
110 GLint bumpenvmat_location[MAX_TEXTURES];
111 GLint luminancescale_location[MAX_TEXTURES];
112 GLint luminanceoffset_location[MAX_TEXTURES];
113 GLint ycorrection_location;
114 GLenum vertex_color_clamp;
115 const struct wined3d_shader *vshader;
116 const struct wined3d_shader *pshader;
117 struct vs_compile_args vs_args;
118 struct ps_compile_args ps_args;
119 UINT constant_version;
120 const struct ps_np2fixup_info *np2Fixup_info;
123 struct glsl_program_key
125 const struct wined3d_shader *vshader;
126 const struct wined3d_shader *pshader;
127 struct ps_compile_args ps_args;
128 struct vs_compile_args vs_args;
131 struct shader_glsl_ctx_priv {
132 const struct vs_compile_args *cur_vs_args;
133 const struct ps_compile_args *cur_ps_args;
134 struct ps_np2fixup_info *cur_np2fixup_info;
137 struct glsl_ps_compiled_shader
139 struct ps_compile_args args;
140 struct ps_np2fixup_info np2fixup;
144 struct glsl_pshader_private
146 struct glsl_ps_compiled_shader *gl_shaders;
147 UINT num_gl_shaders, shader_array_size;
150 struct glsl_vs_compiled_shader
152 struct vs_compile_args args;
156 struct glsl_vshader_private
158 struct glsl_vs_compiled_shader *gl_shaders;
159 UINT num_gl_shaders, shader_array_size;
162 static const char *debug_gl_shader_type(GLenum type)
166 #define WINED3D_TO_STR(u) case u: return #u
167 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
168 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
169 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
170 #undef WINED3D_TO_STR
172 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
176 /* Extract a line from the info log.
177 * Note that this modifies the source string. */
178 static char *get_info_log_line(char **ptr)
183 if (!(q = strstr(p, "\n")))
185 if (!*p) return NULL;
195 /** Prints the GLSL info log which will contain error messages if they exist */
196 /* GL locking is done by the caller */
197 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
199 int infologLength = 0;
202 if (!WARN_ON(d3d_shader) && !FIXME_ON(d3d_shader))
205 GL_EXTCALL(glGetObjectParameterivARB(obj,
206 GL_OBJECT_INFO_LOG_LENGTH_ARB,
209 /* A size of 1 is just a null-terminated string, so the log should be bigger than
210 * that if there are errors. */
211 if (infologLength > 1)
215 infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
216 /* The info log is supposed to be zero-terminated, but at least some
217 * versions of fglrx don't terminate the string properly. The reported
218 * length does include the terminator, so explicitly set it to zero
220 infoLog[infologLength - 1] = 0;
221 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
224 if (gl_info->quirks & WINED3D_QUIRK_INFO_LOG_SPAM)
226 WARN("Info log received from GLSL shader #%u:\n", obj);
227 while ((line = get_info_log_line(&ptr))) WARN(" %s\n", line);
231 FIXME("Info log received from GLSL shader #%u:\n", obj);
232 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
234 HeapFree(GetProcessHeap(), 0, infoLog);
238 /* GL locking is done by the caller. */
239 static void shader_glsl_compile(const struct wined3d_gl_info *gl_info, GLhandleARB shader, const char *src)
241 TRACE("Compiling shader object %u.\n", shader);
242 GL_EXTCALL(glShaderSourceARB(shader, 1, &src, NULL));
243 checkGLcall("glShaderSourceARB");
244 GL_EXTCALL(glCompileShaderARB(shader));
245 checkGLcall("glCompileShaderARB");
246 print_glsl_info_log(gl_info, shader);
249 /* GL locking is done by the caller. */
250 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
252 GLint i, object_count, source_size = -1;
253 GLhandleARB *objects;
256 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
257 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
260 ERR("Failed to allocate object array memory.\n");
264 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
265 for (i = 0; i < object_count; ++i)
270 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
272 if (source_size < tmp)
274 HeapFree(GetProcessHeap(), 0, source);
276 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
279 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
280 HeapFree(GetProcessHeap(), 0, objects);
286 FIXME("Object %u:\n", objects[i]);
287 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
288 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
289 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
290 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
294 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
295 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
299 HeapFree(GetProcessHeap(), 0, source);
300 HeapFree(GetProcessHeap(), 0, objects);
303 /* GL locking is done by the caller. */
304 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
308 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
310 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
311 if (tmp == GL_PROGRAM_OBJECT_ARB)
313 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
316 FIXME("Program %u link status invalid.\n", program);
317 shader_glsl_dump_program_source(gl_info, program);
321 print_glsl_info_log(gl_info, program);
325 * Loads (pixel shader) samplers
327 /* GL locking is done by the caller */
328 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
329 const DWORD *tex_unit_map, GLhandleARB programId)
333 char sampler_name[20];
335 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
336 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
337 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
338 if (name_loc != -1) {
339 DWORD mapped_unit = tex_unit_map[i];
340 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
342 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
343 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
344 checkGLcall("glUniform1iARB");
346 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
352 /* GL locking is done by the caller */
353 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
354 const DWORD *tex_unit_map, GLhandleARB programId)
357 char sampler_name[20];
360 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
361 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
362 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
363 if (name_loc != -1) {
364 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
365 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
367 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
368 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
369 checkGLcall("glUniform1iARB");
371 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
377 /* GL locking is done by the caller */
378 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
379 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
382 unsigned int heap_idx = 1;
385 if (heap->entries[heap_idx].version <= version) return;
387 idx = heap->entries[heap_idx].idx;
388 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
389 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
391 while (stack_idx >= 0)
393 /* Note that we fall through to the next case statement. */
394 switch(stack[stack_idx])
396 case HEAP_NODE_TRAVERSE_LEFT:
398 unsigned int left_idx = heap_idx << 1;
399 if (left_idx < heap->size && heap->entries[left_idx].version > version)
402 idx = heap->entries[heap_idx].idx;
403 if (constant_locations[idx] != -1)
404 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
406 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
407 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
412 case HEAP_NODE_TRAVERSE_RIGHT:
414 unsigned int right_idx = (heap_idx << 1) + 1;
415 if (right_idx < heap->size && heap->entries[right_idx].version > version)
417 heap_idx = right_idx;
418 idx = heap->entries[heap_idx].idx;
419 if (constant_locations[idx] != -1)
420 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
422 stack[stack_idx++] = HEAP_NODE_POP;
423 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
436 checkGLcall("walk_constant_heap()");
439 /* GL locking is done by the caller */
440 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
442 GLfloat clamped_constant[4];
444 if (location == -1) return;
446 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
447 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
448 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
449 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
451 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
454 /* GL locking is done by the caller */
455 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
456 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
459 unsigned int heap_idx = 1;
462 if (heap->entries[heap_idx].version <= version) return;
464 idx = heap->entries[heap_idx].idx;
465 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
466 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
468 while (stack_idx >= 0)
470 /* Note that we fall through to the next case statement. */
471 switch(stack[stack_idx])
473 case HEAP_NODE_TRAVERSE_LEFT:
475 unsigned int left_idx = heap_idx << 1;
476 if (left_idx < heap->size && heap->entries[left_idx].version > version)
479 idx = heap->entries[heap_idx].idx;
480 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
482 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
483 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
488 case HEAP_NODE_TRAVERSE_RIGHT:
490 unsigned int right_idx = (heap_idx << 1) + 1;
491 if (right_idx < heap->size && heap->entries[right_idx].version > version)
493 heap_idx = right_idx;
494 idx = heap->entries[heap_idx].idx;
495 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
497 stack[stack_idx++] = HEAP_NODE_POP;
498 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
511 checkGLcall("walk_constant_heap_clamped()");
514 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
515 /* GL locking is done by the caller */
516 static void shader_glsl_load_constantsF(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
517 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
518 unsigned char *stack, UINT version)
520 const local_constant *lconst;
522 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
523 if (shader->reg_maps.shader_version.major == 1
524 && shader_is_pshader_version(shader->reg_maps.shader_version.type))
525 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
527 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
529 if (!shader->load_local_constsF)
531 TRACE("No need to load local float constants for this shader\n");
535 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
536 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, local_constant, entry)
538 GLint location = constant_locations[lconst->idx];
539 /* We found this uniform name in the program - go ahead and send the data */
540 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
542 checkGLcall("glUniform4fvARB()");
545 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
546 /* GL locking is done by the caller */
547 static void shader_glsl_load_constantsI(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
548 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
553 for (i = 0; constants_set; constants_set >>= 1, ++i)
555 if (!(constants_set & 1)) continue;
557 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
558 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
560 /* We found this uniform name in the program - go ahead and send the data */
561 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
562 checkGLcall("glUniform4ivARB");
565 /* Load immediate constants */
566 ptr = list_head(&shader->constantsI);
569 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
570 unsigned int idx = lconst->idx;
571 const GLint *values = (const GLint *)lconst->value;
573 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
574 values[0], values[1], values[2], values[3]);
576 /* We found this uniform name in the program - go ahead and send the data */
577 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
578 checkGLcall("glUniform4ivARB");
579 ptr = list_next(&shader->constantsI, ptr);
583 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
584 /* GL locking is done by the caller */
585 static void shader_glsl_load_constantsB(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
586 GLhandleARB programId, const BOOL *constants, WORD constants_set)
594 switch (shader->reg_maps.shader_version.type)
596 case WINED3D_SHADER_TYPE_VERTEX:
600 case WINED3D_SHADER_TYPE_GEOMETRY:
604 case WINED3D_SHADER_TYPE_PIXEL:
609 FIXME("Unknown shader type %#x.\n",
610 shader->reg_maps.shader_version.type);
615 /* TODO: Benchmark and see if it would be beneficial to store the
616 * locations of the constants to avoid looking up each time */
617 for (i = 0; constants_set; constants_set >>= 1, ++i)
619 if (!(constants_set & 1)) continue;
621 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
623 /* TODO: Benchmark and see if it would be beneficial to store the
624 * locations of the constants to avoid looking up each time */
625 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
626 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
629 /* We found this uniform name in the program - go ahead and send the data */
630 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
631 checkGLcall("glUniform1ivARB");
635 /* Load immediate constants */
636 ptr = list_head(&shader->constantsB);
639 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
640 unsigned int idx = lconst->idx;
641 const GLint *values = (const GLint *)lconst->value;
643 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
645 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
646 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
648 /* We found this uniform name in the program - go ahead and send the data */
649 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
650 checkGLcall("glUniform1ivARB");
652 ptr = list_next(&shader->constantsB, ptr);
656 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
658 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
662 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
664 /* GL locking is done by the caller (state handler) */
665 static void shader_glsl_load_np2fixup_constants(void *shader_priv,
666 const struct wined3d_gl_info *gl_info, const struct wined3d_state *state)
668 struct shader_glsl_priv *glsl_priv = shader_priv;
669 const struct glsl_shader_prog_link *prog = glsl_priv->glsl_program;
671 /* No GLSL program set - nothing to do. */
674 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
675 if (!use_ps(state)) return;
677 if (prog->ps_args.np2_fixup && prog->np2Fixup_location != -1)
680 UINT fixup = prog->ps_args.np2_fixup;
681 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
683 for (i = 0; fixup; fixup >>= 1, ++i)
685 const struct wined3d_texture *tex = state->textures[i];
686 const unsigned char idx = prog->np2Fixup_info->idx[i];
687 GLfloat *tex_dim = &np2fixup_constants[(idx >> 1) * 4];
691 ERR("Nonexistent texture is flagged for NP2 texcoord fixup.\n");
697 tex_dim[2] = tex->pow2_matrix[0];
698 tex_dim[3] = tex->pow2_matrix[5];
702 tex_dim[0] = tex->pow2_matrix[0];
703 tex_dim[1] = tex->pow2_matrix[5];
707 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
712 * Loads the app-supplied constants into the currently set GLSL program.
714 /* GL locking is done by the caller (state handler) */
715 static void shader_glsl_load_constants(const struct wined3d_context *context,
716 char usePixelShader, char useVertexShader)
718 const struct wined3d_gl_info *gl_info = context->gl_info;
719 struct wined3d_device *device = context->swapchain->device;
720 struct wined3d_stateblock *stateBlock = device->stateBlock;
721 struct shader_glsl_priv *priv = device->shader_priv;
722 float position_fixup[4];
724 GLhandleARB programId;
725 struct glsl_shader_prog_link *prog = priv->glsl_program;
726 UINT constant_version;
730 /* No GLSL program set - nothing to do. */
733 programId = prog->programId;
734 constant_version = prog->constant_version;
738 const struct wined3d_shader *vshader = stateBlock->state.vertex_shader;
740 /* Load DirectX 9 float constants/uniforms for vertex shader */
741 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->state.vs_consts_f,
742 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
744 /* Load DirectX 9 integer constants/uniforms for vertex shader */
745 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->state.vs_consts_i,
746 stateBlock->changed.vertexShaderConstantsI & vshader->reg_maps.integer_constants);
748 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
749 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->state.vs_consts_b,
750 stateBlock->changed.vertexShaderConstantsB & vshader->reg_maps.boolean_constants);
752 /* Upload the position fixup params */
753 shader_get_position_fixup(context, &stateBlock->state, position_fixup);
754 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, position_fixup));
755 checkGLcall("glUniform4fvARB");
760 const struct wined3d_shader *pshader = stateBlock->state.pixel_shader;
762 /* Load DirectX 9 float constants/uniforms for pixel shader */
763 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->state.ps_consts_f,
764 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
766 /* Load DirectX 9 integer constants/uniforms for pixel shader */
767 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->state.ps_consts_i,
768 stateBlock->changed.pixelShaderConstantsI & pshader->reg_maps.integer_constants);
770 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
771 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->state.ps_consts_b,
772 stateBlock->changed.pixelShaderConstantsB & pshader->reg_maps.boolean_constants);
774 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
775 * It can't be 0 for a valid texbem instruction.
777 for(i = 0; i < MAX_TEXTURES; i++) {
780 if(prog->bumpenvmat_location[i] == -1) continue;
782 data = (const float *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVMAT00];
783 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
784 checkGLcall("glUniformMatrix2fvARB");
786 /* texbeml needs the luminance scale and offset too. If texbeml
787 * is used, needsbumpmat is set too, so we can check that in the
788 * needsbumpmat check. */
789 if (prog->luminancescale_location[i] != -1)
791 const GLfloat *scale = (const GLfloat *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVLSCALE];
792 const GLfloat *offset = (const GLfloat *)&stateBlock->state.texture_states[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 (prog->ycorrection_location != -1)
803 float correction_params[4];
805 if (context->render_offscreen)
807 correction_params[0] = 0.0f;
808 correction_params[1] = 1.0f;
810 /* position is window relative, not viewport relative */
811 correction_params[0] = (float) context->current_rt->resource.height;
812 correction_params[1] = -1.0f;
814 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
818 if (priv->next_constant_version == UINT_MAX)
820 TRACE("Max constant version reached, resetting to 0.\n");
821 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
822 priv->next_constant_version = 1;
826 prog->constant_version = priv->next_constant_version++;
830 static void update_heap_entry(const struct constant_heap *heap, unsigned int idx,
831 unsigned int heap_idx, DWORD new_version)
833 struct constant_entry *entries = heap->entries;
834 unsigned int *positions = heap->positions;
835 unsigned int parent_idx;
839 parent_idx = heap_idx >> 1;
841 if (new_version <= entries[parent_idx].version) break;
843 entries[heap_idx] = entries[parent_idx];
844 positions[entries[parent_idx].idx] = heap_idx;
845 heap_idx = parent_idx;
848 entries[heap_idx].version = new_version;
849 entries[heap_idx].idx = idx;
850 positions[idx] = heap_idx;
853 static void shader_glsl_update_float_vertex_constants(struct wined3d_device *device, UINT start, UINT count)
855 struct shader_glsl_priv *priv = device->shader_priv;
856 struct constant_heap *heap = &priv->vconst_heap;
859 for (i = start; i < count + start; ++i)
861 if (!device->stateBlock->changed.vertexShaderConstantsF[i])
862 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
864 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
868 static void shader_glsl_update_float_pixel_constants(struct wined3d_device *device, UINT start, UINT count)
870 struct shader_glsl_priv *priv = device->shader_priv;
871 struct constant_heap *heap = &priv->pconst_heap;
874 for (i = start; i < count + start; ++i)
876 if (!device->stateBlock->changed.pixelShaderConstantsF[i])
877 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
879 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
883 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
885 unsigned int ret = gl_info->limits.glsl_varyings / 4;
886 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
887 if(shader_major > 3) return ret;
889 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
890 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
894 /** Generate the variable & register declarations for the GLSL output target */
895 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
896 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
897 const struct wined3d_shader_reg_maps *reg_maps, const struct shader_glsl_ctx_priv *ctx_priv)
899 const struct wined3d_state *state = &shader->device->stateBlock->state;
900 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
901 const struct wined3d_gl_info *gl_info = context->gl_info;
902 const struct wined3d_fb_state *fb = &shader->device->fb;
903 unsigned int i, extra_constants_needed = 0;
904 const local_constant *lconst;
907 /* There are some minor differences between pixel and vertex shaders */
908 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
909 char prefix = pshader ? 'P' : 'V';
911 /* Prototype the subroutines */
912 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
914 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
917 /* Declare the constants (aka uniforms) */
918 if (shader->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
936 /* No indirect addressing here. */
937 max_constantsF = gl_info->limits.glsl_ps_float_constants;
941 if (reg_maps->usesrelconstF)
943 /* Subtract the other potential uniforms from the max
944 * available (bools, ints, and 1 row of projection matrix).
945 * Subtract another uniform for immediate values, which have
946 * to be loaded via uniform by the driver as well. The shader
947 * code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex
948 * shader code, so one vec4 should be enough. (Unfortunately
949 * the Nvidia driver doesn't store 128 and -128 in one float).
951 * Writing gl_ClipVertex requires one uniform for each
952 * clipplane as well. */
953 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
954 if(ctx_priv->cur_vs_args->clip_enabled)
956 max_constantsF -= gl_info->limits.clipplanes;
958 max_constantsF -= count_bits(reg_maps->integer_constants);
959 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
960 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
961 * for now take this into account when calculating the number of available constants
963 max_constantsF -= count_bits(reg_maps->boolean_constants);
964 /* Set by driver quirks in directx.c */
965 max_constantsF -= gl_info->reserved_glsl_constants;
969 max_constantsF = gl_info->limits.glsl_vs_float_constants;
972 max_constantsF = min(shader->limits.constant_float, max_constantsF);
973 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
976 /* Always declare the full set of constants, the compiler can remove the
977 * unused ones because d3d doesn't (yet) support indirect int and bool
978 * constant addressing. This avoids problems if the app uses e.g. i0 and i9. */
979 if (shader->limits.constant_int > 0 && reg_maps->integer_constants)
980 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, shader->limits.constant_int);
982 if (shader->limits.constant_bool > 0 && reg_maps->boolean_constants)
983 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, shader->limits.constant_bool);
987 shader_addline(buffer, "uniform vec4 posFixup;\n");
988 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
992 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
994 if (!(map & 1)) continue;
996 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
998 if (reg_maps->luminanceparams & (1 << i))
1000 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1001 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1002 extra_constants_needed++;
1005 extra_constants_needed++;
1008 if (ps_args->srgb_correction)
1010 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1011 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1012 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1015 if (reg_maps->vpos || reg_maps->usesdsy)
1017 if (shader->limits.constant_float + extra_constants_needed
1018 + 1 < gl_info->limits.glsl_ps_float_constants)
1020 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1021 extra_constants_needed++;
1025 /* This happens because we do not have proper tracking of the constant registers that are
1026 * actually used, only the max limit of the shader version
1028 FIXME("Cannot find a free uniform for vpos correction params\n");
1029 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1030 context->render_offscreen ? 0.0f : fb->render_targets[0]->resource.height,
1031 context->render_offscreen ? 1.0f : -1.0f);
1033 shader_addline(buffer, "vec4 vpos;\n");
1037 /* Declare texture samplers */
1038 for (i = 0; i < shader->limits.sampler; ++i)
1040 if (reg_maps->sampler_type[i])
1042 const struct wined3d_texture *texture;
1044 switch (reg_maps->sampler_type[i])
1047 if (pshader && ps_args->shadow & (1 << i))
1048 shader_addline(buffer, "uniform sampler1DShadow %csampler%u;\n", prefix, i);
1050 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1053 texture = state->textures[i];
1054 if (pshader && ps_args->shadow & (1 << i))
1056 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1057 shader_addline(buffer, "uniform sampler2DRectShadow %csampler%u;\n", prefix, i);
1059 shader_addline(buffer, "uniform sampler2DShadow %csampler%u;\n", prefix, i);
1063 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1064 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1066 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1069 case WINED3DSTT_CUBE:
1070 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported Cube shadow sampler.\n");
1071 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1073 case WINED3DSTT_VOLUME:
1074 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported 3D shadow sampler.\n");
1075 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1078 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1079 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1085 /* Declare uniforms for NP2 texcoord fixup:
1086 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1087 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1088 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1089 if (pshader && ps_args->np2_fixup) {
1091 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1094 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1095 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1096 * samplerNP2Fixup stores texture dimensions and is updated through
1097 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1099 for (i = 0; i < shader->limits.sampler; ++i)
1101 if (reg_maps->sampler_type[i])
1103 if (!(ps_args->np2_fixup & (1 << i))) continue;
1105 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1106 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1110 fixup->idx[i] = cur++;
1114 fixup->num_consts = (cur + 1) >> 1;
1115 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1118 /* Declare address variables */
1119 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1121 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1124 /* Declare texture coordinate temporaries and initialize them */
1125 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1127 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1130 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1131 * helper function shader that is linked in at link time
1133 if (pshader && reg_maps->shader_version.major >= 3)
1137 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1139 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1140 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1141 * pixel shader that reads the fixed function color into the packed input registers.
1143 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1147 /* Declare output register temporaries */
1148 if (shader->limits.packed_output)
1149 shader_addline(buffer, "vec4 OUT[%u];\n", shader->limits.packed_output);
1151 /* Declare temporary variables */
1152 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1154 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1157 /* Declare attributes */
1158 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1160 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1162 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1166 /* Declare loop registers aLx */
1167 for (i = 0; i < reg_maps->loop_depth; i++) {
1168 shader_addline(buffer, "int aL%u;\n", i);
1169 shader_addline(buffer, "int tmpInt%u;\n", i);
1172 /* Temporary variables for matrix operations */
1173 shader_addline(buffer, "vec4 tmp0;\n");
1174 shader_addline(buffer, "vec4 tmp1;\n");
1176 /* Local constants use a different name so they can be loaded once at shader link time
1177 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1178 * float -> string conversion can cause precision loss.
1180 if (!shader->load_local_constsF)
1182 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, local_constant, entry)
1184 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1188 /* Start the main program */
1189 shader_addline(buffer, "void main() {\n");
1190 if(pshader && reg_maps->vpos) {
1191 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1192 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1193 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1194 * precision troubles when we just subtract 0.5.
1196 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1198 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1200 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1201 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1202 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1203 * correctly on drivers that returns integer values.
1205 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1209 /*****************************************************************************
1210 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1212 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1213 ****************************************************************************/
1216 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1217 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src);
1219 /** Used for opcode modifiers - They multiply the result by the specified amount */
1220 static const char * const shift_glsl_tab[] = {
1222 "2.0 * ", /* 1 (x2) */
1223 "4.0 * ", /* 2 (x4) */
1224 "8.0 * ", /* 3 (x8) */
1225 "16.0 * ", /* 4 (x16) */
1226 "32.0 * ", /* 5 (x32) */
1233 "0.0625 * ", /* 12 (d16) */
1234 "0.125 * ", /* 13 (d8) */
1235 "0.25 * ", /* 14 (d4) */
1236 "0.5 * " /* 15 (d2) */
1239 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1240 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1244 switch (src_modifier)
1246 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1247 case WINED3DSPSM_DW:
1248 case WINED3DSPSM_NONE:
1249 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1251 case WINED3DSPSM_NEG:
1252 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1254 case WINED3DSPSM_NOT:
1255 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1257 case WINED3DSPSM_BIAS:
1258 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1260 case WINED3DSPSM_BIASNEG:
1261 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1263 case WINED3DSPSM_SIGN:
1264 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1266 case WINED3DSPSM_SIGNNEG:
1267 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1269 case WINED3DSPSM_COMP:
1270 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1272 case WINED3DSPSM_X2:
1273 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1275 case WINED3DSPSM_X2NEG:
1276 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1278 case WINED3DSPSM_ABS:
1279 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1281 case WINED3DSPSM_ABSNEG:
1282 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1285 FIXME("Unhandled modifier %u\n", src_modifier);
1286 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1290 /** Writes the GLSL variable name that corresponds to the register that the
1291 * DX opcode parameter is trying to access */
1292 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1293 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1295 /* oPos, oFog and oPts in D3D */
1296 static const char * const hwrastout_reg_names[] = {"OUT[10]", "OUT[11].x", "OUT[11].y"};
1298 const struct wined3d_shader *shader = ins->ctx->shader;
1299 const struct wined3d_shader_reg_maps *reg_maps = ins->ctx->reg_maps;
1300 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1301 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
1307 case WINED3DSPR_TEMP:
1308 sprintf(register_name, "R%u", reg->idx);
1311 case WINED3DSPR_INPUT:
1312 /* vertex shaders */
1315 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1316 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1317 sprintf(register_name, "attrib%u", reg->idx);
1321 /* pixel shaders >= 3.0 */
1322 if (reg_maps->shader_version.major >= 3)
1324 DWORD idx = shader->u.ps.input_reg_map[reg->idx];
1325 unsigned int in_count = vec4_varyings(reg_maps->shader_version.major, gl_info);
1329 struct glsl_src_param rel_param;
1331 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1333 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1334 * operation there */
1337 if (shader->u.ps.declared_in_count > in_count)
1339 sprintf(register_name,
1340 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1341 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1342 rel_param.param_str, idx);
1346 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1351 if (shader->u.ps.declared_in_count > in_count)
1353 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1354 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1355 rel_param.param_str);
1359 sprintf(register_name, "IN[%s]", rel_param.param_str);
1365 if (idx == in_count) sprintf(register_name, "gl_Color");
1366 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1367 else sprintf(register_name, "IN[%u]", idx);
1372 if (!reg->idx) strcpy(register_name, "gl_Color");
1373 else strcpy(register_name, "gl_SecondaryColor");
1378 case WINED3DSPR_CONST:
1380 const char prefix = pshader ? 'P' : 'V';
1382 /* Relative addressing */
1385 struct glsl_src_param rel_param;
1386 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1387 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1388 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1392 if (shader_constant_is_local(shader, reg->idx))
1393 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1395 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1400 case WINED3DSPR_CONSTINT:
1401 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1402 else sprintf(register_name, "VI[%u]", reg->idx);
1405 case WINED3DSPR_CONSTBOOL:
1406 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1407 else sprintf(register_name, "VB[%u]", reg->idx);
1410 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1411 if (pshader) sprintf(register_name, "T%u", reg->idx);
1412 else sprintf(register_name, "A%u", reg->idx);
1415 case WINED3DSPR_LOOP:
1416 sprintf(register_name, "aL%u", ins->ctx->loop_state->current_reg - 1);
1419 case WINED3DSPR_SAMPLER:
1420 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1421 else sprintf(register_name, "Vsampler%u", reg->idx);
1424 case WINED3DSPR_COLOROUT:
1425 if (reg->idx >= gl_info->limits.buffers)
1426 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1428 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1431 case WINED3DSPR_RASTOUT:
1432 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1435 case WINED3DSPR_DEPTHOUT:
1436 sprintf(register_name, "gl_FragDepth");
1439 case WINED3DSPR_ATTROUT:
1440 if (!reg->idx) sprintf(register_name, "OUT[8]");
1441 else sprintf(register_name, "OUT[9]");
1444 case WINED3DSPR_TEXCRDOUT:
1445 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1446 sprintf(register_name, "OUT[%u]", reg->idx);
1449 case WINED3DSPR_MISCTYPE:
1453 sprintf(register_name, "vpos");
1455 else if (reg->idx == 1)
1457 /* Note that gl_FrontFacing is a bool, while vFace is
1458 * a float for which the sign determines front/back */
1459 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1463 FIXME("Unhandled misctype register %d\n", reg->idx);
1464 sprintf(register_name, "unrecognized_register");
1468 case WINED3DSPR_IMMCONST:
1469 switch (reg->immconst_type)
1471 case WINED3D_IMMCONST_SCALAR:
1472 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1475 case WINED3D_IMMCONST_VEC4:
1476 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1477 *(const float *)®->immconst_data[0], *(const float *)®->immconst_data[1],
1478 *(const float *)®->immconst_data[2], *(const float *)®->immconst_data[3]);
1482 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1483 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1488 FIXME("Unhandled register name Type(%d)\n", reg->type);
1489 sprintf(register_name, "unrecognized_register");
1494 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1497 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1498 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1499 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1500 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1504 /* Get the GLSL write mask for the destination register */
1505 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1507 DWORD mask = param->write_mask;
1509 if (shader_is_scalar(¶m->reg))
1511 mask = WINED3DSP_WRITEMASK_0;
1516 shader_glsl_write_mask_to_str(mask, write_mask);
1522 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1523 unsigned int size = 0;
1525 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1526 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1527 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1528 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1533 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1535 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1536 * but addressed as "rgba". To fix this we need to swap the register's x
1537 * and z components. */
1538 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1541 /* swizzle bits fields: wwzzyyxx */
1542 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1543 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1544 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1545 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1549 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1550 BOOL fixup, DWORD mask, char *swizzle_str)
1552 if (shader_is_scalar(¶m->reg))
1553 *swizzle_str = '\0';
1555 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1558 /* From a given parameter token, generate the corresponding GLSL string.
1559 * Also, return the actual register name and swizzle in case the
1560 * caller needs this information as well. */
1561 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1562 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src)
1564 BOOL is_color = FALSE;
1565 char swizzle_str[6];
1567 glsl_src->reg_name[0] = '\0';
1568 glsl_src->param_str[0] = '\0';
1569 swizzle_str[0] = '\0';
1571 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1572 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1573 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1576 /* From a given parameter token, generate the corresponding GLSL string.
1577 * Also, return the actual register name and swizzle in case the
1578 * caller needs this information as well. */
1579 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1580 const struct wined3d_shader_dst_param *wined3d_dst, struct glsl_dst_param *glsl_dst)
1582 BOOL is_color = FALSE;
1584 glsl_dst->mask_str[0] = '\0';
1585 glsl_dst->reg_name[0] = '\0';
1587 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1588 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1591 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1592 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1593 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1595 struct glsl_dst_param glsl_dst;
1598 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1599 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1604 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1605 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1607 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1610 /** Process GLSL instruction modifiers */
1611 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1613 struct glsl_dst_param dst_param;
1616 if (!ins->dst_count) return;
1618 modifiers = ins->dst[0].modifiers;
1619 if (!modifiers) return;
1621 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1623 if (modifiers & WINED3DSPDM_SATURATE)
1625 /* _SAT means to clamp the value of the register to between 0 and 1 */
1626 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1627 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1630 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1632 FIXME("_centroid modifier not handled\n");
1635 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1637 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1641 static inline const char *shader_get_comp_op(DWORD op)
1644 case COMPARISON_GT: return ">";
1645 case COMPARISON_EQ: return "==";
1646 case COMPARISON_GE: return ">=";
1647 case COMPARISON_LT: return "<";
1648 case COMPARISON_NE: return "!=";
1649 case COMPARISON_LE: return "<=";
1651 FIXME("Unrecognized comparison value: %u\n", op);
1656 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1657 DWORD sampler_idx, DWORD flags, struct glsl_sample_function *sample_function)
1659 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1660 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1661 BOOL shadow = shader_is_pshader_version(ctx->reg_maps->shader_version.type)
1662 && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1663 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1664 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1665 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1666 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1668 /* Note that there's no such thing as a projected cube texture. */
1669 switch(sampler_type) {
1675 sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1679 if (gl_info->supported[EXT_GPU_SHADER4])
1680 sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1681 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1682 sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1685 FIXME("Unsupported 1D shadow grad function.\n");
1686 sample_function->name = "unsupported1DGrad";
1691 sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1693 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1699 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1703 if (gl_info->supported[EXT_GPU_SHADER4])
1704 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1705 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1706 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1709 FIXME("Unsupported 1D grad function.\n");
1710 sample_function->name = "unsupported1DGrad";
1715 sample_function->name = projected ? "texture1DProj" : "texture1D";
1717 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1728 sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1732 if (gl_info->supported[EXT_GPU_SHADER4])
1733 sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1734 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1735 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1738 FIXME("Unsupported RECT shadow grad function.\n");
1739 sample_function->name = "unsupported2DRectGrad";
1744 sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1751 sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1755 if (gl_info->supported[EXT_GPU_SHADER4])
1756 sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1757 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1758 sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1761 FIXME("Unsupported 2D shadow grad function.\n");
1762 sample_function->name = "unsupported2DGrad";
1767 sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1770 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1778 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1782 if (gl_info->supported[EXT_GPU_SHADER4])
1783 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1784 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1785 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1788 FIXME("Unsupported RECT grad function.\n");
1789 sample_function->name = "unsupported2DRectGrad";
1794 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1801 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1805 if (gl_info->supported[EXT_GPU_SHADER4])
1806 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1807 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1808 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1811 FIXME("Unsupported 2D grad function.\n");
1812 sample_function->name = "unsupported2DGrad";
1817 sample_function->name = projected ? "texture2DProj" : "texture2D";
1820 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1824 case WINED3DSTT_CUBE:
1827 FIXME("Unsupported Cube shadow function.\n");
1828 sample_function->name = "unsupportedCubeShadow";
1829 sample_function->coord_mask = 0;
1835 sample_function->name = "textureCubeLod";
1839 if (gl_info->supported[EXT_GPU_SHADER4])
1840 sample_function->name = "textureCubeGrad";
1841 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1842 sample_function->name = "textureCubeGradARB";
1845 FIXME("Unsupported Cube grad function.\n");
1846 sample_function->name = "unsupportedCubeGrad";
1851 sample_function->name = "textureCube";
1853 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1857 case WINED3DSTT_VOLUME:
1860 FIXME("Unsupported 3D shadow function.\n");
1861 sample_function->name = "unsupported3DShadow";
1862 sample_function->coord_mask = 0;
1868 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1872 if (gl_info->supported[EXT_GPU_SHADER4])
1873 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1874 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1875 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1878 FIXME("Unsupported 3D grad function.\n");
1879 sample_function->name = "unsupported3DGrad";
1884 sample_function->name = projected ? "texture3DProj" : "texture3D";
1886 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1891 sample_function->name = "";
1892 sample_function->coord_mask = 0;
1893 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1898 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1899 BOOL sign_fixup, enum fixup_channel_source channel_source)
1901 switch(channel_source)
1903 case CHANNEL_SOURCE_ZERO:
1904 strcat(arguments, "0.0");
1907 case CHANNEL_SOURCE_ONE:
1908 strcat(arguments, "1.0");
1911 case CHANNEL_SOURCE_X:
1912 strcat(arguments, reg_name);
1913 strcat(arguments, ".x");
1916 case CHANNEL_SOURCE_Y:
1917 strcat(arguments, reg_name);
1918 strcat(arguments, ".y");
1921 case CHANNEL_SOURCE_Z:
1922 strcat(arguments, reg_name);
1923 strcat(arguments, ".z");
1926 case CHANNEL_SOURCE_W:
1927 strcat(arguments, reg_name);
1928 strcat(arguments, ".w");
1932 FIXME("Unhandled channel source %#x\n", channel_source);
1933 strcat(arguments, "undefined");
1937 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1940 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1942 struct wined3d_shader_dst_param dst;
1943 unsigned int mask_size, remaining;
1944 struct glsl_dst_param dst_param;
1945 char arguments[256];
1949 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1950 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1951 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1952 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1953 mask &= ins->dst[0].write_mask;
1955 if (!mask) return; /* Nothing to do */
1957 if (is_complex_fixup(fixup))
1959 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
1960 FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
1964 mask_size = shader_glsl_get_write_mask_size(mask);
1967 dst.write_mask = mask;
1968 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1970 arguments[0] = '\0';
1971 remaining = mask_size;
1972 if (mask & WINED3DSP_WRITEMASK_0)
1974 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1975 if (--remaining) strcat(arguments, ", ");
1977 if (mask & WINED3DSP_WRITEMASK_1)
1979 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1980 if (--remaining) strcat(arguments, ", ");
1982 if (mask & WINED3DSP_WRITEMASK_2)
1984 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1985 if (--remaining) strcat(arguments, ", ");
1987 if (mask & WINED3DSP_WRITEMASK_3)
1989 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1990 if (--remaining) strcat(arguments, ", ");
1995 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1996 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
2000 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
2004 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2005 DWORD sampler, const struct glsl_sample_function *sample_function, DWORD swizzle,
2006 const char *dx, const char *dy, const char *bias, const char *coord_reg_fmt, ...)
2008 const char *sampler_base;
2009 char dst_swizzle[6];
2010 struct color_fixup_desc fixup;
2011 BOOL np2_fixup = FALSE;
2014 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2016 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2018 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2019 fixup = priv->cur_ps_args->color_fixup[sampler];
2020 sampler_base = "Psampler";
2022 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2024 FIXME("Biased sampling from NP2 textures is unsupported\n");
2030 sampler_base = "Vsampler";
2031 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2034 shader_glsl_append_dst(ins->ctx->buffer, ins);
2036 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2038 va_start(args, coord_reg_fmt);
2039 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2043 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2046 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2047 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2049 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2050 (idx % 2) ? "zw" : "xy", dst_swizzle);
2051 } else if(dx && dy) {
2052 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2054 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2058 if(!is_identity_fixup(fixup)) {
2059 shader_glsl_color_correction(ins, fixup);
2063 /*****************************************************************************
2064 * Begin processing individual instruction opcodes
2065 ****************************************************************************/
2067 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
2068 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
2070 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2071 struct glsl_src_param src0_param;
2072 struct glsl_src_param src1_param;
2076 /* Determine the GLSL operator to use based on the opcode */
2077 switch (ins->handler_idx)
2079 case WINED3DSIH_MUL: op = '*'; break;
2080 case WINED3DSIH_ADD: op = '+'; break;
2081 case WINED3DSIH_SUB: op = '-'; break;
2084 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2088 write_mask = shader_glsl_append_dst(buffer, ins);
2089 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2090 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2091 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2094 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2095 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2097 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2098 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2099 struct glsl_src_param src0_param;
2102 write_mask = shader_glsl_append_dst(buffer, ins);
2103 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2105 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2106 * shader versions WINED3DSIO_MOVA is used for this. */
2107 if (ins->ctx->reg_maps->shader_version.major == 1
2108 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2109 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2111 /* This is a simple floor() */
2112 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2113 if (mask_size > 1) {
2114 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2116 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2119 else if(ins->handler_idx == WINED3DSIH_MOVA)
2121 /* We need to *round* to the nearest int here. */
2122 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2124 if (gl_info->supported[EXT_GPU_SHADER4])
2127 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2129 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2134 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2135 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2137 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2138 src0_param.param_str, src0_param.param_str);
2143 shader_addline(buffer, "%s);\n", src0_param.param_str);
2147 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2148 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2150 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2151 struct glsl_src_param src0_param;
2152 struct glsl_src_param src1_param;
2153 DWORD dst_write_mask, src_write_mask;
2154 unsigned int dst_size = 0;
2156 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2157 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2159 /* dp3 works on vec3, dp4 on vec4 */
2160 if (ins->handler_idx == WINED3DSIH_DP4)
2162 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2164 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2167 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2168 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2171 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2173 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2177 /* Note that this instruction has some restrictions. The destination write mask
2178 * can't contain the w component, and the source swizzles have to be .xyzw */
2179 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2181 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2182 struct glsl_src_param src0_param;
2183 struct glsl_src_param src1_param;
2186 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2187 shader_glsl_append_dst(ins->ctx->buffer, ins);
2188 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2189 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2190 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2193 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2194 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2195 * GLSL uses the value as-is. */
2196 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2198 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2199 struct glsl_src_param src0_param;
2200 struct glsl_src_param src1_param;
2201 DWORD dst_write_mask;
2202 unsigned int dst_size;
2204 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2205 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2207 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2208 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2212 shader_addline(buffer, "vec%u(%s == 0.0 ? 1.0 : pow(abs(%s), %s)));\n",
2213 dst_size, src1_param.param_str, src0_param.param_str, src1_param.param_str);
2217 shader_addline(buffer, "%s == 0.0 ? 1.0 : pow(abs(%s), %s));\n",
2218 src1_param.param_str, src0_param.param_str, src1_param.param_str);
2222 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2223 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2224 * GLSL uses the value as-is. */
2225 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2227 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2228 struct glsl_src_param src0_param;
2229 DWORD dst_write_mask;
2230 unsigned int dst_size;
2232 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2233 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2235 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2239 shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2240 dst_size, src0_param.param_str);
2244 shader_addline(buffer, "log2(abs(%s)));\n",
2245 src0_param.param_str);
2249 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2250 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2252 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2253 struct glsl_src_param src_param;
2254 const char *instruction;
2258 /* Determine the GLSL function to use based on the opcode */
2259 /* TODO: Possibly make this a table for faster lookups */
2260 switch (ins->handler_idx)
2262 case WINED3DSIH_MIN: instruction = "min"; break;
2263 case WINED3DSIH_MAX: instruction = "max"; break;
2264 case WINED3DSIH_ABS: instruction = "abs"; break;
2265 case WINED3DSIH_FRC: instruction = "fract"; break;
2266 case WINED3DSIH_EXP: instruction = "exp2"; break;
2267 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2268 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2269 default: instruction = "";
2270 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2274 write_mask = shader_glsl_append_dst(buffer, ins);
2276 shader_addline(buffer, "%s(", instruction);
2280 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2281 shader_addline(buffer, "%s", src_param.param_str);
2282 for (i = 1; i < ins->src_count; ++i)
2284 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2285 shader_addline(buffer, ", %s", src_param.param_str);
2289 shader_addline(buffer, "));\n");
2292 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2294 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2295 struct glsl_src_param src_param;
2296 unsigned int mask_size;
2300 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2301 mask_size = shader_glsl_get_write_mask_size(write_mask);
2302 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2304 shader_addline(buffer, "tmp0.x = dot(%s, %s);\n",
2305 src_param.param_str, src_param.param_str);
2306 shader_glsl_append_dst(buffer, ins);
2310 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s * inversesqrt(tmp0.x)));\n",
2311 mask_size, src_param.param_str);
2315 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s * inversesqrt(tmp0.x)));\n",
2316 src_param.param_str);
2320 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2321 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2322 * dst.x = 2^(floor(src))
2323 * dst.y = src - floor(src)
2324 * dst.z = 2^src (partial precision is allowed, but optional)
2326 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2327 * dst = 2^src; (partial precision is allowed, but optional)
2329 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2331 struct glsl_src_param src_param;
2333 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2335 if (ins->ctx->reg_maps->shader_version.major < 2)
2339 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2340 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2341 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2342 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2344 shader_glsl_append_dst(ins->ctx->buffer, ins);
2345 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2346 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2349 unsigned int mask_size;
2351 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2352 mask_size = shader_glsl_get_write_mask_size(write_mask);
2354 if (mask_size > 1) {
2355 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2357 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2362 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2363 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2365 struct glsl_src_param src_param;
2367 unsigned int mask_size;
2369 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2370 mask_size = shader_glsl_get_write_mask_size(write_mask);
2371 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2375 shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2376 mask_size, src_param.param_str);
2380 shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2381 src_param.param_str);
2385 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2387 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2388 struct glsl_src_param src_param;
2390 unsigned int mask_size;
2392 write_mask = shader_glsl_append_dst(buffer, ins);
2393 mask_size = shader_glsl_get_write_mask_size(write_mask);
2395 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2399 shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2400 mask_size, src_param.param_str);
2404 shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2405 src_param.param_str);
2409 /** Process signed comparison opcodes in GLSL. */
2410 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2412 struct glsl_src_param src0_param;
2413 struct glsl_src_param src1_param;
2415 unsigned int mask_size;
2417 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2418 mask_size = shader_glsl_get_write_mask_size(write_mask);
2419 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2420 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2422 if (mask_size > 1) {
2423 const char *compare;
2425 switch(ins->handler_idx)
2427 case WINED3DSIH_SLT: compare = "lessThan"; break;
2428 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2429 default: compare = "";
2430 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2433 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2434 src0_param.param_str, src1_param.param_str);
2436 switch(ins->handler_idx)
2438 case WINED3DSIH_SLT:
2439 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2440 * to return 0.0 but step returns 1.0 because step is not < x
2441 * An alternative is a bvec compare padded with an unused second component.
2442 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2443 * issue. Playing with not() is not possible either because not() does not accept
2446 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2447 src0_param.param_str, src1_param.param_str);
2449 case WINED3DSIH_SGE:
2450 /* Here we can use the step() function and safe a conditional */
2451 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2454 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2460 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2461 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2463 struct glsl_src_param src0_param;
2464 struct glsl_src_param src1_param;
2465 struct glsl_src_param src2_param;
2466 DWORD write_mask, cmp_channel = 0;
2469 BOOL temp_destination = FALSE;
2471 if (shader_is_scalar(&ins->src[0].reg))
2473 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2475 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2476 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2477 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2479 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2480 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2482 DWORD dst_mask = ins->dst[0].write_mask;
2483 struct wined3d_shader_dst_param dst = ins->dst[0];
2485 /* Cycle through all source0 channels */
2486 for (i=0; i<4; i++) {
2488 /* Find the destination channels which use the current source0 channel */
2489 for (j=0; j<4; j++) {
2490 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2492 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2493 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2496 dst.write_mask = dst_mask & write_mask;
2498 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2499 * The first lines may overwrite source parameters of the following lines.
2500 * Deal with that by using a temporary destination register if needed
2502 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2503 && ins->src[0].reg.type == ins->dst[0].reg.type)
2504 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2505 && ins->src[1].reg.type == ins->dst[0].reg.type)
2506 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2507 && ins->src[2].reg.type == ins->dst[0].reg.type))
2509 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2510 if (!write_mask) continue;
2511 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2512 temp_destination = TRUE;
2514 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2515 if (!write_mask) continue;
2518 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2519 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2520 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2522 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2523 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2526 if(temp_destination) {
2527 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2528 shader_glsl_append_dst(ins->ctx->buffer, ins);
2529 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2535 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2536 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2537 * the compare is done per component of src0. */
2538 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2540 struct wined3d_shader_dst_param dst;
2541 struct glsl_src_param src0_param;
2542 struct glsl_src_param src1_param;
2543 struct glsl_src_param src2_param;
2544 DWORD write_mask, cmp_channel = 0;
2547 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2548 ins->ctx->reg_maps->shader_version.minor);
2550 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2552 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2553 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2554 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2555 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2557 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2560 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2562 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2563 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2567 /* Cycle through all source0 channels */
2568 dst_mask = ins->dst[0].write_mask;
2570 for (i=0; i<4; i++) {
2572 /* Find the destination channels which use the current source0 channel */
2573 for (j=0; j<4; j++) {
2574 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2576 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2577 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2581 dst.write_mask = dst_mask & write_mask;
2582 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2583 if (!write_mask) continue;
2585 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2586 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2587 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2589 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2590 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2594 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2595 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2597 struct glsl_src_param src0_param;
2598 struct glsl_src_param src1_param;
2599 struct glsl_src_param src2_param;
2602 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2603 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2604 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2605 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2606 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2607 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2610 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2611 Vertex shaders to GLSL codes */
2612 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2615 int nComponents = 0;
2616 struct wined3d_shader_dst_param tmp_dst = {{0}};
2617 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2618 struct wined3d_shader_instruction tmp_ins;
2620 memset(&tmp_ins, 0, sizeof(tmp_ins));
2622 /* Set constants for the temporary argument */
2623 tmp_ins.ctx = ins->ctx;
2624 tmp_ins.dst_count = 1;
2625 tmp_ins.dst = &tmp_dst;
2626 tmp_ins.src_count = 2;
2627 tmp_ins.src = tmp_src;
2629 switch(ins->handler_idx)
2631 case WINED3DSIH_M4x4:
2633 tmp_ins.handler_idx = WINED3DSIH_DP4;
2635 case WINED3DSIH_M4x3:
2637 tmp_ins.handler_idx = WINED3DSIH_DP4;
2639 case WINED3DSIH_M3x4:
2641 tmp_ins.handler_idx = WINED3DSIH_DP3;
2643 case WINED3DSIH_M3x3:
2645 tmp_ins.handler_idx = WINED3DSIH_DP3;
2647 case WINED3DSIH_M3x2:
2649 tmp_ins.handler_idx = WINED3DSIH_DP3;
2655 tmp_dst = ins->dst[0];
2656 tmp_src[0] = ins->src[0];
2657 tmp_src[1] = ins->src[1];
2658 for (i = 0; i < nComponents; ++i)
2660 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2661 shader_glsl_dot(&tmp_ins);
2662 ++tmp_src[1].reg.idx;
2667 The LRP instruction performs a component-wise linear interpolation
2668 between the second and third operands using the first operand as the
2669 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2670 This is equivalent to mix(src2, src1, src0);
2672 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2674 struct glsl_src_param src0_param;
2675 struct glsl_src_param src1_param;
2676 struct glsl_src_param src2_param;
2679 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2681 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2682 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2683 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2685 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2686 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2689 /** Process the WINED3DSIO_LIT instruction in GLSL:
2690 * dst.x = dst.w = 1.0
2691 * dst.y = (src0.x > 0) ? src0.x
2692 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2693 * where src.w is clamped at +- 128
2695 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2697 struct glsl_src_param src0_param;
2698 struct glsl_src_param src1_param;
2699 struct glsl_src_param src3_param;
2702 shader_glsl_append_dst(ins->ctx->buffer, ins);
2703 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2705 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2706 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2707 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2709 /* The sdk specifies the instruction like this
2711 * if(src.x > 0.0) dst.y = src.x
2713 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2717 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2718 * dst.x = 1.0 ... No further explanation needed
2719 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2720 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2721 * dst.w = 1.0. ... Nothing fancy.
2723 * So we still have one conditional in there. So do this:
2724 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2726 * 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),
2727 * 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.
2728 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2730 shader_addline(ins->ctx->buffer,
2731 "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",
2732 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2735 /** Process the WINED3DSIO_DST instruction in GLSL:
2737 * dst.y = src0.x * src0.y
2741 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2743 struct glsl_src_param src0y_param;
2744 struct glsl_src_param src0z_param;
2745 struct glsl_src_param src1y_param;
2746 struct glsl_src_param src1w_param;
2749 shader_glsl_append_dst(ins->ctx->buffer, ins);
2750 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2752 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2753 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2754 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2755 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2757 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2758 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2761 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2762 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2763 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2765 * dst.x = cos(src0.?)
2766 * dst.y = sin(src0.?)
2770 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2772 struct glsl_src_param src0_param;
2775 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2776 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2778 switch (write_mask) {
2779 case WINED3DSP_WRITEMASK_0:
2780 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2783 case WINED3DSP_WRITEMASK_1:
2784 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2787 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2788 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2792 ERR("Write mask should be .x, .y or .xy\n");
2797 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2798 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2799 * generate invalid code
2801 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2803 struct glsl_src_param src0_param;
2806 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2807 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2809 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2812 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2813 * Start a for() loop where src1.y is the initial value of aL,
2814 * increment aL by src1.z for a total of src1.x iterations.
2815 * Need to use a temporary variable for this operation.
2817 /* FIXME: I don't think nested loops will work correctly this way. */
2818 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2820 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2821 const struct wined3d_shader *shader = ins->ctx->shader;
2822 struct glsl_src_param src1_param;
2823 const DWORD *control_values = NULL;
2824 const local_constant *constant;
2826 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2828 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2829 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2830 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2833 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2835 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, local_constant, entry)
2837 if (constant->idx == ins->src[1].reg.idx)
2839 control_values = constant->value;
2847 struct wined3d_shader_loop_control loop_control;
2848 loop_control.count = control_values[0];
2849 loop_control.start = control_values[1];
2850 loop_control.step = (int)control_values[2];
2852 if (loop_control.step > 0)
2854 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2855 loop_state->current_depth, loop_control.start,
2856 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2857 loop_state->current_depth, loop_control.step);
2859 else if (loop_control.step < 0)
2861 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2862 loop_state->current_depth, loop_control.start,
2863 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2864 loop_state->current_depth, loop_control.step);
2868 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2869 loop_state->current_depth, loop_control.start, loop_state->current_depth,
2870 loop_state->current_depth, loop_control.count,
2871 loop_state->current_depth);
2874 shader_addline(ins->ctx->buffer,
2875 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2876 loop_state->current_depth, loop_state->current_reg,
2877 src1_param.reg_name, loop_state->current_depth, src1_param.reg_name,
2878 loop_state->current_depth, loop_state->current_reg, src1_param.reg_name);
2881 ++loop_state->current_depth;
2882 ++loop_state->current_reg;
2885 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2887 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2889 shader_addline(ins->ctx->buffer, "}\n");
2891 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2893 --loop_state->current_depth;
2894 --loop_state->current_reg;
2897 if (ins->handler_idx == WINED3DSIH_ENDREP)
2899 --loop_state->current_depth;
2903 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2905 const struct wined3d_shader *shader = ins->ctx->shader;
2906 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2907 struct glsl_src_param src0_param;
2908 const DWORD *control_values = NULL;
2909 const local_constant *constant;
2911 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2912 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2914 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, local_constant, entry)
2916 if (constant->idx == ins->src[0].reg.idx)
2918 control_values = constant->value;
2926 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2927 loop_state->current_depth, loop_state->current_depth,
2928 control_values[0], loop_state->current_depth);
2932 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2933 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2934 loop_state->current_depth, loop_state->current_depth,
2935 src0_param.param_str, loop_state->current_depth);
2938 ++loop_state->current_depth;
2941 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2943 struct glsl_src_param src0_param;
2945 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2946 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2949 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2951 struct glsl_src_param src0_param;
2952 struct glsl_src_param src1_param;
2954 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2955 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2957 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2958 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2961 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2963 shader_addline(ins->ctx->buffer, "} else {\n");
2966 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2968 shader_addline(ins->ctx->buffer, "break;\n");
2971 /* FIXME: According to MSDN the compare is done per component. */
2972 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2974 struct glsl_src_param src0_param;
2975 struct glsl_src_param src1_param;
2977 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2978 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2980 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2981 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2984 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2986 shader_addline(ins->ctx->buffer, "}\n");
2987 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
2990 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2992 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2995 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2997 struct glsl_src_param src1_param;
2999 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3000 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
3003 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3005 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3006 * function only suppresses the unhandled instruction warning
3010 /*********************************************
3011 * Pixel Shader Specific Code begins here
3012 ********************************************/
3013 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3015 const struct wined3d_shader *shader = ins->ctx->shader;
3016 struct wined3d_device *device = shader->device;
3017 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3018 ins->ctx->reg_maps->shader_version.minor);
3019 struct glsl_sample_function sample_function;
3020 const struct wined3d_texture *texture;
3021 DWORD sample_flags = 0;
3023 DWORD mask = 0, swizzle;
3025 /* 1.0-1.4: Use destination register as sampler source.
3026 * 2.0+: Use provided sampler source. */
3027 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3028 else sampler_idx = ins->src[1].reg.idx;
3029 texture = device->stateBlock->state.textures[sampler_idx];
3031 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3033 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3034 DWORD flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3035 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3036 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3038 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3039 if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
3040 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3041 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3042 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3043 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
3044 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
3045 case WINED3DTTFF_COUNT4:
3046 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
3050 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3052 DWORD src_mod = ins->src[0].modifiers;
3054 if (src_mod == WINED3DSPSM_DZ) {
3055 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3056 mask = WINED3DSP_WRITEMASK_2;
3057 } else if (src_mod == WINED3DSPSM_DW) {
3058 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3059 mask = WINED3DSP_WRITEMASK_3;
3062 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3064 /* ps 2.0 texldp instruction always divides by the fourth component. */
3065 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3066 mask = WINED3DSP_WRITEMASK_3;
3070 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3071 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3073 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3074 mask |= sample_function.coord_mask;
3076 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3077 else swizzle = ins->src[1].swizzle;
3079 /* 1.0-1.3: Use destination register as coordinate source.
3080 1.4+: Use provided coordinate source register. */
3081 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3084 shader_glsl_write_mask_to_str(mask, coord_mask);
3085 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3086 "T%u%s", sampler_idx, coord_mask);
3090 struct glsl_src_param coord_param;
3091 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3092 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3094 struct glsl_src_param bias;
3095 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3096 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3097 "%s", coord_param.param_str);
3099 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3100 "%s", coord_param.param_str);
3105 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3107 const struct wined3d_shader *shader = ins->ctx->shader;
3108 struct wined3d_device *device = shader->device;
3109 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3110 struct glsl_src_param coord_param, dx_param, dy_param;
3111 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3112 struct glsl_sample_function sample_function;
3114 DWORD swizzle = ins->src[1].swizzle;
3115 const struct wined3d_texture *texture;
3117 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3119 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3120 shader_glsl_tex(ins);
3124 sampler_idx = ins->src[1].reg.idx;
3125 texture = device->stateBlock->state.textures[sampler_idx];
3126 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3127 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3129 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3130 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3131 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3132 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3134 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3135 "%s", coord_param.param_str);
3138 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3140 const struct wined3d_shader *shader = ins->ctx->shader;
3141 struct wined3d_device *device = shader->device;
3142 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3143 struct glsl_src_param coord_param, lod_param;
3144 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3145 struct glsl_sample_function sample_function;
3147 DWORD swizzle = ins->src[1].swizzle;
3148 const struct wined3d_texture *texture;
3150 sampler_idx = ins->src[1].reg.idx;
3151 texture = device->stateBlock->state.textures[sampler_idx];
3152 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3153 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3155 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3156 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3158 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3160 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3161 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3163 /* Plain GLSL only supports Lod sampling functions in vertex shaders.
3164 * However, the NVIDIA drivers allow them in fragment shaders as well,
3165 * even without the appropriate extension. */
3166 WARN("Using %s in fragment shader.\n", sample_function.name);
3168 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3169 "%s", coord_param.param_str);
3172 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3174 /* FIXME: Make this work for more than just 2D textures */
3175 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3176 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3178 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3182 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3183 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3184 ins->dst[0].reg.idx, dst_mask);
3186 DWORD reg = ins->src[0].reg.idx;
3187 DWORD src_mod = ins->src[0].modifiers;
3188 char dst_swizzle[6];
3190 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3192 if (src_mod == WINED3DSPSM_DZ)
3194 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3195 struct glsl_src_param div_param;
3197 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3199 if (mask_size > 1) {
3200 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3202 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3205 else if (src_mod == WINED3DSPSM_DW)
3207 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3208 struct glsl_src_param div_param;
3210 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3212 if (mask_size > 1) {
3213 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3215 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3218 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3223 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3224 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3225 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3226 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3228 DWORD sampler_idx = ins->dst[0].reg.idx;
3229 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3230 struct glsl_sample_function sample_function;
3231 struct glsl_src_param src0_param;
3234 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3236 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3237 * scalar, and projected sampling would require 4.
3239 * It is a dependent read - not valid with conditional NP2 textures
3241 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3242 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3247 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3248 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3252 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3253 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3257 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3258 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3262 FIXME("Unexpected mask size %u\n", mask_size);
3267 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3268 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3269 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3271 DWORD dstreg = ins->dst[0].reg.idx;
3272 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3273 struct glsl_src_param src0_param;
3275 unsigned int mask_size;
3277 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3278 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3279 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3281 if (mask_size > 1) {
3282 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3284 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3288 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3289 * Calculate the depth as dst.x / dst.y */
3290 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3292 struct glsl_dst_param dst_param;
3294 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3296 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3297 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3298 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3299 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3302 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3303 dst_param.reg_name, dst_param.reg_name);
3306 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3307 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3308 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3309 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3311 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3313 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3314 DWORD dstreg = ins->dst[0].reg.idx;
3315 struct glsl_src_param src0_param;
3317 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3319 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3320 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3323 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3324 * Calculate the 1st of a 2-row matrix multiplication. */
3325 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3327 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3328 DWORD reg = ins->dst[0].reg.idx;
3329 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3330 struct glsl_src_param src0_param;
3332 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3333 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3336 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3337 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3338 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3340 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3341 DWORD reg = ins->dst[0].reg.idx;
3342 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3343 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3344 struct glsl_src_param src0_param;
3346 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3347 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + tex_mx->current_row, reg, src0_param.param_str);
3348 tex_mx->texcoord_w[tex_mx->current_row++] = reg;
3351 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3353 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3354 DWORD reg = ins->dst[0].reg.idx;
3355 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3356 struct glsl_sample_function sample_function;
3357 struct glsl_src_param src0_param;
3359 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3360 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3362 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3364 /* Sample the texture using the calculated coordinates */
3365 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3368 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3369 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3370 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3372 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3373 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3374 struct glsl_sample_function sample_function;
3375 struct glsl_src_param src0_param;
3376 DWORD reg = ins->dst[0].reg.idx;
3378 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3379 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3381 /* Dependent read, not valid with conditional NP2 */
3382 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3384 /* Sample the texture using the calculated coordinates */
3385 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3387 tex_mx->current_row = 0;
3390 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3391 * Perform the 3rd row of a 3x3 matrix multiply */
3392 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3394 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3395 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3396 struct glsl_src_param src0_param;
3398 DWORD reg = ins->dst[0].reg.idx;
3400 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3402 shader_glsl_append_dst(ins->ctx->buffer, ins);
3403 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3404 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3406 tex_mx->current_row = 0;
3409 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3410 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3411 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3413 struct glsl_src_param src0_param;
3414 struct glsl_src_param src1_param;
3415 DWORD reg = ins->dst[0].reg.idx;
3416 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3417 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3418 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3419 struct glsl_sample_function sample_function;
3421 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3422 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3424 /* Perform the last matrix multiply operation */
3425 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3426 /* Reflection calculation */
3427 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3429 /* Dependent read, not valid with conditional NP2 */
3430 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3432 /* Sample the texture */
3433 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3435 tex_mx->current_row = 0;
3438 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3439 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3440 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3442 DWORD reg = ins->dst[0].reg.idx;
3443 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3444 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3445 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3446 struct glsl_sample_function sample_function;
3447 struct glsl_src_param src0_param;
3449 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3451 /* Perform the last matrix multiply operation */
3452 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3454 /* Construct the eye-ray vector from w coordinates */
3455 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3456 tex_mx->texcoord_w[0], tex_mx->texcoord_w[1], reg);
3457 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3459 /* Dependent read, not valid with conditional NP2 */
3460 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3462 /* Sample the texture using the calculated coordinates */
3463 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3465 tex_mx->current_row = 0;
3468 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3469 * Apply a fake bump map transform.
3470 * texbem is pshader <= 1.3 only, this saves a few version checks
3472 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3474 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3475 struct glsl_sample_function sample_function;
3476 struct glsl_src_param coord_param;
3482 sampler_idx = ins->dst[0].reg.idx;
3483 flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3484 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3486 /* Dependent read, not valid with conditional NP2 */
3487 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3488 mask = sample_function.coord_mask;
3490 shader_glsl_write_mask_to_str(mask, coord_mask);
3492 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3493 * so we can't let the GL handle this.
3495 if (flags & WINED3D_PSARGS_PROJECTED) {
3497 char coord_div_mask[3];
3498 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3499 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3500 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3501 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3502 case WINED3DTTFF_COUNT4:
3503 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3505 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3506 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3509 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3511 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3512 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3513 coord_param.param_str, coord_mask);
3515 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3517 struct glsl_src_param luminance_param;
3518 struct glsl_dst_param dst_param;
3520 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3521 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3523 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3524 dst_param.reg_name, dst_param.mask_str,
3525 luminance_param.param_str, sampler_idx, sampler_idx);
3529 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3531 struct glsl_src_param src0_param, src1_param;
3532 DWORD sampler_idx = ins->dst[0].reg.idx;
3534 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3535 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3537 shader_glsl_append_dst(ins->ctx->buffer, ins);
3538 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3539 src0_param.param_str, sampler_idx, src1_param.param_str);
3542 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3543 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3544 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3546 struct glsl_sample_function sample_function;
3547 struct glsl_src_param src0_param;
3548 DWORD sampler_idx = ins->dst[0].reg.idx;
3550 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3552 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3553 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3554 "%s.wx", src0_param.reg_name);
3557 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3558 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3559 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3561 struct glsl_sample_function sample_function;
3562 struct glsl_src_param src0_param;
3563 DWORD sampler_idx = ins->dst[0].reg.idx;
3565 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3567 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3568 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3569 "%s.yz", src0_param.reg_name);
3572 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3573 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3574 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3576 struct glsl_sample_function sample_function;
3577 struct glsl_src_param src0_param;
3578 DWORD sampler_idx = ins->dst[0].reg.idx;
3580 /* Dependent read, not valid with conditional NP2 */
3581 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3582 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3584 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3585 "%s", src0_param.param_str);
3588 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3589 * If any of the first 3 components are < 0, discard this pixel */
3590 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3592 struct glsl_dst_param dst_param;
3594 /* The argument is a destination parameter, and no writemasks are allowed */
3595 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3596 if (ins->ctx->reg_maps->shader_version.major >= 2)
3598 /* 2.0 shaders compare all 4 components in texkill */
3599 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3601 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3602 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3603 * 4 components are defined, only the first 3 are used
3605 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3609 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3610 * dst = dot2(src0, src1) + src2 */
3611 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3613 struct glsl_src_param src0_param;
3614 struct glsl_src_param src1_param;
3615 struct glsl_src_param src2_param;
3617 unsigned int mask_size;
3619 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3620 mask_size = shader_glsl_get_write_mask_size(write_mask);
3622 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3623 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3624 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3626 if (mask_size > 1) {
3627 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3628 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3630 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3631 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3635 static void shader_glsl_input_pack(const struct wined3d_shader *shader, struct wined3d_shader_buffer *buffer,
3636 const struct wined3d_shader_signature_element *input_signature,
3637 const struct wined3d_shader_reg_maps *reg_maps,
3638 enum vertexprocessing_mode vertexprocessing)
3640 WORD map = reg_maps->input_registers;
3643 for (i = 0; map; map >>= 1, ++i)
3645 const char *semantic_name;
3650 if (!(map & 1)) continue;
3652 semantic_name = input_signature[i].semantic_name;
3653 semantic_idx = input_signature[i].semantic_idx;
3654 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3656 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3658 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3659 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3660 shader->u.ps.input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3662 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3663 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3665 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3668 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3669 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3670 else if (semantic_idx == 1)
3671 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3672 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3674 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3675 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3679 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3680 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3685 /*********************************************
3686 * Vertex Shader Specific Code begins here
3687 ********************************************/
3689 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry)
3691 struct glsl_program_key key;
3693 key.vshader = entry->vshader;
3694 key.pshader = entry->pshader;
3695 key.vs_args = entry->vs_args;
3696 key.ps_args = entry->ps_args;
3698 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3700 ERR("Failed to insert program entry.\n");
3704 static struct glsl_shader_prog_link *get_glsl_program_entry(const struct shader_glsl_priv *priv,
3705 const struct wined3d_shader *vshader, const struct wined3d_shader *pshader,
3706 const struct vs_compile_args *vs_args, const struct ps_compile_args *ps_args)
3708 struct wine_rb_entry *entry;
3709 struct glsl_program_key key;
3711 key.vshader = vshader;
3712 key.pshader = pshader;
3713 key.vs_args = *vs_args;
3714 key.ps_args = *ps_args;
3716 entry = wine_rb_get(&priv->program_lookup, &key);
3717 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3720 /* GL locking is done by the caller */
3721 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3722 struct glsl_shader_prog_link *entry)
3724 struct glsl_program_key key;
3726 key.vshader = entry->vshader;
3727 key.pshader = entry->pshader;
3728 key.vs_args = entry->vs_args;
3729 key.ps_args = entry->ps_args;
3730 wine_rb_remove(&priv->program_lookup, &key);
3732 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3733 if (entry->vshader) list_remove(&entry->vshader_entry);
3734 if (entry->pshader) list_remove(&entry->pshader_entry);
3735 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3736 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3737 HeapFree(GetProcessHeap(), 0, entry);
3740 static void handle_ps3_input(struct wined3d_shader_buffer *buffer,
3741 const struct wined3d_gl_info *gl_info, const DWORD *map,
3742 const struct wined3d_shader_signature_element *input_signature,
3743 const struct wined3d_shader_reg_maps *reg_maps_in,
3744 const struct wined3d_shader_signature_element *output_signature,
3745 const struct wined3d_shader_reg_maps *reg_maps_out)
3748 const char *semantic_name_in;
3749 UINT semantic_idx_in;
3752 unsigned int in_count = vec4_varyings(3, gl_info);
3754 char destination[50];
3755 WORD input_map, output_map;
3757 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3759 input_map = reg_maps_in->input_registers;
3760 for (i = 0; input_map; input_map >>= 1, ++i)
3762 if (!(input_map & 1)) continue;
3765 /* Declared, but not read register */
3766 if (in_idx == ~0U) continue;
3767 if (in_idx >= (in_count + 2))
3769 FIXME("More input varyings declared than supported, expect issues.\n");
3773 if (in_idx == in_count) {
3774 sprintf(destination, "gl_FrontColor");
3775 } else if (in_idx == in_count + 1) {
3776 sprintf(destination, "gl_FrontSecondaryColor");
3778 sprintf(destination, "IN[%u]", in_idx);
3781 semantic_name_in = input_signature[i].semantic_name;
3782 semantic_idx_in = input_signature[i].semantic_idx;
3785 output_map = reg_maps_out->output_registers;
3786 for (j = 0; output_map; output_map >>= 1, ++j)
3790 if (!(output_map & 1)
3791 || semantic_idx_in != output_signature[j].semantic_idx
3792 || strcmp(semantic_name_in, output_signature[j].semantic_name)
3793 || !(mask = input_signature[i].mask & output_signature[j].mask))
3797 shader_glsl_write_mask_to_str(mask, reg_mask);
3799 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3800 destination, reg_mask, j, reg_mask);
3804 for (i = 0; i < in_count + 2; ++i)
3808 if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
3811 if (set[i] == ~0U) set[i] = 0;
3814 if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
3815 if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
3816 if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
3817 if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
3818 reg_mask[size] = '\0';
3820 if (i == in_count) sprintf(destination, "gl_FrontColor");
3821 else if (i == in_count + 1) sprintf(destination, "gl_FrontSecondaryColor");
3822 else sprintf(destination, "IN[%u]", i);
3824 if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3825 else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3828 HeapFree(GetProcessHeap(), 0, set);
3831 /* GL locking is done by the caller */
3832 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3833 const struct wined3d_shader *vs, const struct wined3d_shader *ps,
3834 const struct wined3d_gl_info *gl_info)
3836 GLhandleARB ret = 0;
3837 DWORD ps_major = ps ? ps->reg_maps.shader_version.major : 0;
3839 const char *semantic_name;
3842 const struct wined3d_shader_signature_element *output_signature = vs->output_signature;
3843 WORD map = vs->reg_maps.output_registers;
3845 shader_buffer_clear(buffer);
3847 shader_addline(buffer, "#version 120\n");
3851 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3853 for (i = 0; map; map >>= 1, ++i)
3857 if (!(map & 1)) continue;
3859 semantic_name = output_signature[i].semantic_name;
3860 semantic_idx = output_signature[i].semantic_idx;
3861 write_mask = output_signature[i].mask;
3862 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3864 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3867 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n",
3868 reg_mask, i, reg_mask);
3869 else if (semantic_idx == 1)
3870 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n",
3871 reg_mask, i, reg_mask);
3873 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3875 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3876 reg_mask, i, reg_mask);
3878 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3880 if (semantic_idx < 8)
3882 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3883 write_mask |= WINED3DSP_WRITEMASK_3;
3885 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3886 semantic_idx, reg_mask, i, reg_mask);
3887 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3888 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3891 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3893 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3895 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3897 shader_addline(buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3900 shader_addline(buffer, "}\n");
3905 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3906 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3907 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3909 /* First, sort out position and point size. Those are not passed to the pixel shader */
3910 for (i = 0; map; map >>= 1, ++i)
3912 if (!(map & 1)) continue;
3914 semantic_name = output_signature[i].semantic_name;
3915 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3917 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3919 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3920 reg_mask, i, reg_mask);
3922 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3924 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3928 /* Then, fix the pixel shader input */
3929 handle_ps3_input(buffer, gl_info, ps->u.ps.input_reg_map, ps->input_signature,
3930 &ps->reg_maps, output_signature, &vs->reg_maps);
3932 shader_addline(buffer, "}\n");
3935 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3936 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3937 shader_glsl_compile(gl_info, ret, buffer->buffer);
3942 /* GL locking is done by the caller */
3943 static void hardcode_local_constants(const struct wined3d_shader *shader,
3944 const struct wined3d_gl_info *gl_info, GLhandleARB programId, char prefix)
3946 const local_constant *lconst;
3951 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, local_constant, entry)
3953 value = (const float *)lconst->value;
3954 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3955 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3956 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3958 checkGLcall("Hardcoding local constants");
3961 /* GL locking is done by the caller */
3962 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
3963 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
3964 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
3966 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
3967 const struct wined3d_gl_info *gl_info = context->gl_info;
3968 const DWORD *function = shader->function;
3969 struct shader_glsl_ctx_priv priv_ctx;
3971 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3972 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3974 memset(&priv_ctx, 0, sizeof(priv_ctx));
3975 priv_ctx.cur_ps_args = args;
3976 priv_ctx.cur_np2fixup_info = np2fixup_info;
3978 shader_addline(buffer, "#version 120\n");
3980 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
3982 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3984 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
3986 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3987 * drivers write a warning if we don't do so
3989 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3991 if (gl_info->supported[EXT_GPU_SHADER4])
3993 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
3996 /* Base Declarations */
3997 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
3999 /* Pack 3.0 inputs */
4000 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4001 shader_glsl_input_pack(shader, buffer, shader->input_signature, reg_maps, args->vp_mode);
4003 /* Base Shader Body */
4004 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4006 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4007 if (reg_maps->shader_version.major < 2)
4009 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4010 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4013 if (args->srgb_correction)
4015 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4016 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4017 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4018 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4019 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4020 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4022 /* Pixel shader < 3.0 do not replace the fog stage.
4023 * This implements linear fog computation and blending.
4024 * TODO: non linear fog
4025 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4026 * -1/(e-s) and e/(e-s) respectively.
4028 if (reg_maps->shader_version.major < 3)
4031 case FOG_OFF: break;
4033 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4034 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4035 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4036 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4039 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4040 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4041 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4042 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4045 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4046 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4047 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4048 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4053 shader_addline(buffer, "}\n");
4055 TRACE("Compiling shader object %u\n", shader_obj);
4056 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4058 /* Store the shader object */
4062 /* GL locking is done by the caller */
4063 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4064 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4065 const struct vs_compile_args *args)
4067 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4068 const struct wined3d_gl_info *gl_info = context->gl_info;
4069 const DWORD *function = shader->function;
4070 struct shader_glsl_ctx_priv priv_ctx;
4072 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4073 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4075 shader_addline(buffer, "#version 120\n");
4077 if (gl_info->supported[EXT_GPU_SHADER4])
4078 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4080 memset(&priv_ctx, 0, sizeof(priv_ctx));
4081 priv_ctx.cur_vs_args = args;
4083 /* Base Declarations */
4084 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4086 /* Base Shader Body */
4087 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4089 /* Unpack outputs */
4090 shader_addline(buffer, "order_ps_input(OUT);\n");
4092 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4093 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4094 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4095 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4097 if (args->fog_src == VS_FOG_Z)
4098 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4099 else if (!reg_maps->fog)
4100 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4102 /* We always store the clipplanes without y inversion */
4103 if (args->clip_enabled)
4104 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4106 /* Write the final position.
4108 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4109 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4110 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4111 * contains 1.0 to allow a mad.
4113 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4114 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4116 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4118 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4119 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4120 * which is the same as z = z * 2 - w.
4122 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4124 shader_addline(buffer, "}\n");
4126 TRACE("Compiling shader object %u\n", shader_obj);
4127 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4132 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4133 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4134 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4136 struct wined3d_state *state = &shader->device->stateBlock->state;
4139 struct glsl_ps_compiled_shader *new_array;
4140 struct glsl_pshader_private *shader_data;
4141 struct ps_np2fixup_info *np2fixup = NULL;
4144 if (!shader->backend_data)
4146 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4147 if (!shader->backend_data)
4149 ERR("Failed to allocate backend data.\n");
4153 shader_data = shader->backend_data;
4155 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4156 * so a linear search is more performant than a hashmap or a binary search
4157 * (cache coherency etc)
4159 for (i = 0; i < shader_data->num_gl_shaders; ++i)
4161 if (!memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)))
4163 if (args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
4164 return shader_data->gl_shaders[i].prgId;
4168 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4169 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4170 if (shader_data->num_gl_shaders)
4172 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4173 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4174 new_size * sizeof(*shader_data->gl_shaders));
4176 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4181 ERR("Out of memory\n");
4184 shader_data->gl_shaders = new_array;
4185 shader_data->shader_array_size = new_size;
4188 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4190 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4191 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4193 pixelshader_update_samplers(&shader->reg_maps, state->textures);
4195 shader_buffer_clear(buffer);
4196 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4197 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4198 *np2fixup_info = np2fixup;
4203 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4204 const DWORD use_map) {
4205 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4206 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4207 return stored->fog_src == new->fog_src;
4210 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4211 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4212 const struct vs_compile_args *args)
4216 struct glsl_vs_compiled_shader *new_array;
4217 DWORD use_map = shader->device->strided_streams.use_map;
4218 struct glsl_vshader_private *shader_data;
4221 if (!shader->backend_data)
4223 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4224 if (!shader->backend_data)
4226 ERR("Failed to allocate backend data.\n");
4230 shader_data = shader->backend_data;
4232 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4233 * so a linear search is more performant than a hashmap or a binary search
4234 * (cache coherency etc)
4236 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4237 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4238 return shader_data->gl_shaders[i].prgId;
4242 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4244 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4245 if (shader_data->num_gl_shaders)
4247 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4248 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4249 new_size * sizeof(*shader_data->gl_shaders));
4251 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4256 ERR("Out of memory\n");
4259 shader_data->gl_shaders = new_array;
4260 shader_data->shader_array_size = new_size;
4263 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4265 shader_buffer_clear(buffer);
4266 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4267 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4272 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4273 * It sets the programId on the current StateBlock (because it should be called
4274 * inside of the DrawPrimitive() part of the render loop).
4276 * If a program for the given combination does not exist, create one, and store
4277 * the program in the hash table. If it creates a program, it will link the
4278 * given objects, too.
4281 /* GL locking is done by the caller */
4282 static void set_glsl_shader_program(const struct wined3d_context *context,
4283 struct wined3d_device *device, BOOL use_ps, BOOL use_vs)
4285 const struct wined3d_state *state = &device->stateBlock->state;
4286 struct wined3d_shader *vshader = use_vs ? state->vertex_shader : NULL;
4287 struct wined3d_shader *pshader = use_ps ? state->pixel_shader : NULL;
4288 const struct wined3d_gl_info *gl_info = context->gl_info;
4289 struct shader_glsl_priv *priv = device->shader_priv;
4290 struct glsl_shader_prog_link *entry = NULL;
4291 GLhandleARB programId = 0;
4292 GLhandleARB reorder_shader_id = 0;
4295 struct ps_compile_args ps_compile_args;
4296 struct vs_compile_args vs_compile_args;
4298 if (vshader) find_vs_compile_args(state, vshader, &vs_compile_args);
4299 if (pshader) find_ps_compile_args(state, pshader, &ps_compile_args);
4301 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4304 priv->glsl_program = entry;
4308 /* If we get to this point, then no matching program exists, so we create one */
4309 programId = GL_EXTCALL(glCreateProgramObjectARB());
4310 TRACE("Created new GLSL shader program %u\n", programId);
4312 /* Create the entry */
4313 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4314 entry->programId = programId;
4315 entry->vshader = vshader;
4316 entry->pshader = pshader;
4317 entry->vs_args = vs_compile_args;
4318 entry->ps_args = ps_compile_args;
4319 entry->constant_version = 0;
4320 entry->np2Fixup_info = NULL;
4321 /* Add the hash table entry */
4322 add_glsl_program_entry(priv, entry);
4324 /* Set the current program */
4325 priv->glsl_program = entry;
4327 /* Attach GLSL vshader */
4330 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer, vshader, &vs_compile_args);
4331 WORD map = vshader->reg_maps.input_registers;
4334 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4335 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4336 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4337 checkGLcall("glAttachObjectARB");
4338 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4341 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4343 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4344 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4345 checkGLcall("glAttachObjectARB");
4347 /* Bind vertex attributes to a corresponding index number to match
4348 * the same index numbers as ARB_vertex_programs (makes loading
4349 * vertex attributes simpler). With this method, we can use the
4350 * exact same code to load the attributes later for both ARB and
4353 * We have to do this here because we need to know the Program ID
4354 * in order to make the bindings work, and it has to be done prior
4355 * to linking the GLSL program. */
4356 for (i = 0; map; map >>= 1, ++i)
4358 if (!(map & 1)) continue;
4360 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4361 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4363 checkGLcall("glBindAttribLocationARB");
4365 list_add_head(&vshader->linked_programs, &entry->vshader_entry);
4368 /* Attach GLSL pshader */
4371 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4372 pshader, &ps_compile_args, &entry->np2Fixup_info);
4373 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4374 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4375 checkGLcall("glAttachObjectARB");
4377 list_add_head(&pshader->linked_programs, &entry->pshader_entry);
4380 /* Link the program */
4381 TRACE("Linking GLSL shader program %u\n", programId);
4382 GL_EXTCALL(glLinkProgramARB(programId));
4383 shader_glsl_validate_link(gl_info, programId);
4385 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4386 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4387 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4389 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4390 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4392 for (i = 0; i < MAX_CONST_I; ++i)
4394 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4395 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4397 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4398 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4399 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4401 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4402 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4404 for (i = 0; i < MAX_CONST_I; ++i)
4406 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4407 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4413 for(i = 0; i < MAX_TEXTURES; i++) {
4414 sprintf(name, "bumpenvmat%u", i);
4415 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4416 sprintf(name, "luminancescale%u", i);
4417 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4418 sprintf(name, "luminanceoffset%u", i);
4419 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4422 if (ps_compile_args.np2_fixup) {
4423 if (entry->np2Fixup_info) {
4424 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4426 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4431 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4432 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4433 checkGLcall("Find glsl program uniform locations");
4435 if (pshader && pshader->reg_maps.shader_version.major >= 3
4436 && pshader->u.ps.declared_in_count > vec4_varyings(3, gl_info))
4438 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4439 entry->vertex_color_clamp = GL_FALSE;
4441 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4444 /* Set the shader to allow uniform loading on it */
4445 GL_EXTCALL(glUseProgramObjectARB(programId));
4446 checkGLcall("glUseProgramObjectARB(programId)");
4448 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4449 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4450 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4451 * vertex shader with fixed function pixel processing is used we make sure that the card
4452 * supports enough samplers to allow the max number of vertex samplers with all possible
4453 * fixed function fragment processing setups. So once the program is linked these samplers
4456 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4457 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4459 /* If the local constants do not have to be loaded with the environment constants,
4460 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4463 if (pshader && !pshader->load_local_constsF)
4464 hardcode_local_constants(pshader, gl_info, programId, 'P');
4465 if (vshader && !vshader->load_local_constsF)
4466 hardcode_local_constants(vshader, gl_info, programId, 'V');
4469 /* GL locking is done by the caller */
4470 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
4472 GLhandleARB program_id;
4473 GLhandleARB vshader_id, pshader_id;
4474 const char *blt_pshader;
4476 static const char *blt_vshader =
4480 " gl_Position = gl_Vertex;\n"
4481 " gl_FrontColor = vec4(1.0);\n"
4482 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4485 static const char * const blt_pshaders_full[tex_type_count] =
4491 "uniform sampler2D sampler;\n"
4494 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4500 "uniform samplerCube sampler;\n"
4503 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4507 "#extension GL_ARB_texture_rectangle : enable\n"
4508 "uniform sampler2DRect sampler;\n"
4511 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4515 static const char * const blt_pshaders_masked[tex_type_count] =
4521 "uniform sampler2D sampler;\n"
4522 "uniform vec4 mask;\n"
4525 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4526 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4532 "uniform samplerCube sampler;\n"
4533 "uniform vec4 mask;\n"
4536 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4537 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4541 "#extension GL_ARB_texture_rectangle : enable\n"
4542 "uniform sampler2DRect sampler;\n"
4543 "uniform vec4 mask;\n"
4546 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4547 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4551 blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
4554 FIXME("tex_type %#x not supported\n", tex_type);
4558 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4559 shader_glsl_compile(gl_info, vshader_id, blt_vshader);
4561 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4562 shader_glsl_compile(gl_info, pshader_id, blt_pshader);
4564 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4565 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4566 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4567 GL_EXTCALL(glLinkProgramARB(program_id));
4569 shader_glsl_validate_link(gl_info, program_id);
4571 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4574 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4575 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4579 /* GL locking is done by the caller */
4580 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4582 const struct wined3d_gl_info *gl_info = context->gl_info;
4583 struct wined3d_device *device = context->swapchain->device;
4584 struct shader_glsl_priv *priv = device->shader_priv;
4585 GLhandleARB program_id = 0;
4586 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4588 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4590 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4591 else priv->glsl_program = NULL;
4593 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4595 if (old_vertex_color_clamp != current_vertex_color_clamp)
4597 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4599 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4600 checkGLcall("glClampColorARB");
4604 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4608 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4609 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4610 GL_EXTCALL(glUseProgramObjectARB(program_id));
4611 checkGLcall("glUseProgramObjectARB");
4613 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4614 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4615 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4616 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4618 shader_glsl_load_np2fixup_constants(priv, gl_info, &device->stateBlock->state);
4622 /* GL locking is done by the caller */
4623 static void shader_glsl_select_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info,
4624 enum tex_types tex_type, const SIZE *ds_mask_size)
4626 BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
4627 struct shader_glsl_priv *priv = shader_priv;
4628 GLhandleARB *blt_program;
4631 blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
4634 *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
4635 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4636 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4637 GL_EXTCALL(glUniform1iARB(loc, 0));
4641 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4646 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
4647 GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
4651 /* GL locking is done by the caller */
4652 static void shader_glsl_deselect_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info)
4654 struct shader_glsl_priv *priv = shader_priv;
4655 GLhandleARB program_id;
4657 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4658 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4660 GL_EXTCALL(glUseProgramObjectARB(program_id));
4661 checkGLcall("glUseProgramObjectARB");
4664 static void shader_glsl_destroy(struct wined3d_shader *shader)
4666 struct wined3d_device *device = shader->device;
4667 struct shader_glsl_priv *priv = device->shader_priv;
4668 const struct wined3d_gl_info *gl_info;
4669 const struct list *linked_programs;
4670 struct wined3d_context *context;
4672 char pshader = shader_is_pshader_version(shader->reg_maps.shader_version.type);
4676 struct glsl_pshader_private *shader_data = shader->backend_data;
4678 if (!shader_data || !shader_data->num_gl_shaders)
4680 HeapFree(GetProcessHeap(), 0, shader_data);
4681 shader->backend_data = NULL;
4685 context = context_acquire(device, NULL);
4686 gl_info = context->gl_info;
4688 if (priv->glsl_program && priv->glsl_program->pshader == shader)
4691 shader_glsl_select(context, FALSE, FALSE);
4697 struct glsl_vshader_private *shader_data = shader->backend_data;
4699 if (!shader_data || !shader_data->num_gl_shaders)
4701 HeapFree(GetProcessHeap(), 0, shader_data);
4702 shader->backend_data = NULL;
4706 context = context_acquire(device, NULL);
4707 gl_info = context->gl_info;
4709 if (priv->glsl_program && priv->glsl_program->vshader == shader)
4712 shader_glsl_select(context, FALSE, FALSE);
4717 linked_programs = &shader->linked_programs;
4719 TRACE("Deleting linked programs\n");
4720 if (linked_programs->next) {
4721 struct glsl_shader_prog_link *entry, *entry2;
4725 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4726 delete_glsl_program_entry(priv, gl_info, entry);
4729 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4730 delete_glsl_program_entry(priv, gl_info, entry);
4738 struct glsl_pshader_private *shader_data = shader->backend_data;
4742 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4743 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4744 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4745 checkGLcall("glDeleteObjectARB");
4748 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4752 struct glsl_vshader_private *shader_data = shader->backend_data;
4756 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4757 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4758 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4759 checkGLcall("glDeleteObjectARB");
4762 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4765 HeapFree(GetProcessHeap(), 0, shader->backend_data);
4766 shader->backend_data = NULL;
4768 context_release(context);
4771 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4773 const struct glsl_program_key *k = key;
4774 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4775 const struct glsl_shader_prog_link, program_lookup_entry);
4778 if (k->vshader > prog->vshader) return 1;
4779 else if (k->vshader < prog->vshader) return -1;
4781 if (k->pshader > prog->pshader) return 1;
4782 else if (k->pshader < prog->pshader) return -1;
4784 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4785 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4790 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4792 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4793 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4797 ERR("Failed to allocate memory\n");
4801 heap->entries = mem;
4802 heap->entries[1].version = 0;
4803 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4809 static void constant_heap_free(struct constant_heap *heap)
4811 HeapFree(GetProcessHeap(), 0, heap->entries);
4814 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4819 glsl_program_key_compare,
4822 static HRESULT shader_glsl_alloc(struct wined3d_device *device)
4824 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4825 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4826 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4827 gl_info->limits.glsl_ps_float_constants)) + 1;
4829 if (!shader_buffer_init(&priv->shader_buffer))
4831 ERR("Failed to initialize shader buffer.\n");
4835 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4838 ERR("Failed to allocate memory.\n");
4842 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4844 ERR("Failed to initialize vertex shader constant heap\n");
4848 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4850 ERR("Failed to initialize pixel shader constant heap\n");
4854 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4856 ERR("Failed to initialize rbtree.\n");
4860 priv->next_constant_version = 1;
4862 device->shader_priv = priv;
4866 constant_heap_free(&priv->pconst_heap);
4867 constant_heap_free(&priv->vconst_heap);
4868 HeapFree(GetProcessHeap(), 0, priv->stack);
4869 shader_buffer_free(&priv->shader_buffer);
4870 HeapFree(GetProcessHeap(), 0, priv);
4871 return E_OUTOFMEMORY;
4874 /* Context activation is done by the caller. */
4875 static void shader_glsl_free(struct wined3d_device *device)
4877 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4878 struct shader_glsl_priv *priv = device->shader_priv;
4882 for (i = 0; i < tex_type_count; ++i)
4884 if (priv->depth_blt_program_full[i])
4886 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
4888 if (priv->depth_blt_program_masked[i])
4890 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
4895 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4896 constant_heap_free(&priv->pconst_heap);
4897 constant_heap_free(&priv->vconst_heap);
4898 HeapFree(GetProcessHeap(), 0, priv->stack);
4899 shader_buffer_free(&priv->shader_buffer);
4901 HeapFree(GetProcessHeap(), 0, device->shader_priv);
4902 device->shader_priv = NULL;
4905 static BOOL shader_glsl_dirty_const(void)
4907 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4911 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
4913 /* ARB_shader_texture_lod or EXT_gpu_shader4 is required for the SM3
4914 * texldd and texldl instructions. */
4915 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] || gl_info->supported[EXT_GPU_SHADER4])
4917 caps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4918 caps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4922 caps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4923 caps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4926 caps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4927 caps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4929 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4930 * Direct3D minimum requirement.
4932 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4933 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4935 * The problem is that the refrast clamps temporary results in the shader to
4936 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4937 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4938 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4939 * offer a way to query this.
4941 caps->PixelShader1xMaxValue = 8.0;
4943 caps->VSClipping = TRUE;
4945 TRACE_(d3d_caps)("Hardware vertex shader version %u.%u enabled (GLSL).\n",
4946 (caps->VertexShaderVersion >> 8) & 0xff, caps->VertexShaderVersion & 0xff);
4947 TRACE_(d3d_caps)("Hardware pixel shader version %u.%u enabled (GLSL).\n",
4948 (caps->PixelShaderVersion >> 8) & 0xff, caps->PixelShaderVersion & 0xff);
4951 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4953 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4955 TRACE("Checking support for fixup:\n");
4956 dump_color_fixup_desc(fixup);
4959 /* We support everything except YUV conversions. */
4960 if (!is_complex_fixup(fixup))
4966 TRACE("[FAILED]\n");
4970 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4972 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4973 /* WINED3DSIH_ADD */ shader_glsl_arith,
4974 /* WINED3DSIH_AND */ NULL,
4975 /* WINED3DSIH_BEM */ shader_glsl_bem,
4976 /* WINED3DSIH_BREAK */ shader_glsl_break,
4977 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4978 /* WINED3DSIH_BREAKP */ NULL,
4979 /* WINED3DSIH_CALL */ shader_glsl_call,
4980 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4981 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4982 /* WINED3DSIH_CND */ shader_glsl_cnd,
4983 /* WINED3DSIH_CRS */ shader_glsl_cross,
4984 /* WINED3DSIH_CUT */ NULL,
4985 /* WINED3DSIH_DCL */ NULL,
4986 /* WINED3DSIH_DEF */ NULL,
4987 /* WINED3DSIH_DEFB */ NULL,
4988 /* WINED3DSIH_DEFI */ NULL,
4989 /* WINED3DSIH_DIV */ NULL,
4990 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
4991 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4992 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4993 /* WINED3DSIH_DST */ shader_glsl_dst,
4994 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4995 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4996 /* WINED3DSIH_ELSE */ shader_glsl_else,
4997 /* WINED3DSIH_EMIT */ NULL,
4998 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4999 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5000 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5001 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5002 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5003 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5004 /* WINED3DSIH_FTOI */ NULL,
5005 /* WINED3DSIH_IADD */ NULL,
5006 /* WINED3DSIH_IEQ */ NULL,
5007 /* WINED3DSIH_IF */ shader_glsl_if,
5008 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5009 /* WINED3DSIH_IGE */ NULL,
5010 /* WINED3DSIH_IMUL */ NULL,
5011 /* WINED3DSIH_ITOF */ NULL,
5012 /* WINED3DSIH_LABEL */ shader_glsl_label,
5013 /* WINED3DSIH_LD */ NULL,
5014 /* WINED3DSIH_LIT */ shader_glsl_lit,
5015 /* WINED3DSIH_LOG */ shader_glsl_log,
5016 /* WINED3DSIH_LOGP */ shader_glsl_log,
5017 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5018 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5019 /* WINED3DSIH_LT */ NULL,
5020 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5021 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5022 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5023 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5024 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5025 /* WINED3DSIH_MAD */ shader_glsl_mad,
5026 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5027 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5028 /* WINED3DSIH_MOV */ shader_glsl_mov,
5029 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5030 /* WINED3DSIH_MOVC */ NULL,
5031 /* WINED3DSIH_MUL */ shader_glsl_arith,
5032 /* WINED3DSIH_NOP */ NULL,
5033 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5034 /* WINED3DSIH_PHASE */ NULL,
5035 /* WINED3DSIH_POW */ shader_glsl_pow,
5036 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5037 /* WINED3DSIH_REP */ shader_glsl_rep,
5038 /* WINED3DSIH_RET */ shader_glsl_ret,
5039 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5040 /* WINED3DSIH_SAMPLE */ NULL,
5041 /* WINED3DSIH_SAMPLE_GRAD */ NULL,
5042 /* WINED3DSIH_SAMPLE_LOD */ NULL,
5043 /* WINED3DSIH_SETP */ NULL,
5044 /* WINED3DSIH_SGE */ shader_glsl_compare,
5045 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5046 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5047 /* WINED3DSIH_SLT */ shader_glsl_compare,
5048 /* WINED3DSIH_SQRT */ NULL,
5049 /* WINED3DSIH_SUB */ shader_glsl_arith,
5050 /* WINED3DSIH_TEX */ shader_glsl_tex,
5051 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5052 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5053 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5054 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5055 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5056 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5057 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5058 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5059 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5060 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5061 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5062 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5063 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5064 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5065 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5066 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5067 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5068 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5069 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5070 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5071 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5072 /* WINED3DSIH_UTOF */ NULL,
5075 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5076 SHADER_HANDLER hw_fct;
5078 /* Select handler */
5079 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5081 /* Unhandled opcode */
5084 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5089 shader_glsl_add_instruction_modifiers(ins);
5092 const struct wined3d_shader_backend_ops glsl_shader_backend =
5094 shader_glsl_handle_instruction,
5096 shader_glsl_select_depth_blt,
5097 shader_glsl_deselect_depth_blt,
5098 shader_glsl_update_float_vertex_constants,
5099 shader_glsl_update_float_pixel_constants,
5100 shader_glsl_load_constants,
5101 shader_glsl_load_np2fixup_constants,
5102 shader_glsl_destroy,
5105 shader_glsl_dirty_const,
5106 shader_glsl_get_caps,
5107 shader_glsl_color_fixup_supported,