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.
33 #include "wine/port.h"
38 #include "wined3d_private.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
41 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
42 WINE_DECLARE_DEBUG_CHANNEL(d3d);
43 WINE_DECLARE_DEBUG_CHANNEL(winediag);
45 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
46 #define WINED3D_GLSL_SAMPLE_RECT 0x2
47 #define WINED3D_GLSL_SAMPLE_LOD 0x4
48 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
62 struct glsl_sample_function
70 HEAP_NODE_TRAVERSE_LEFT,
71 HEAP_NODE_TRAVERSE_RIGHT,
83 struct constant_entry *entries;
84 unsigned int *positions;
88 /* GLSL shader private data */
89 struct shader_glsl_priv {
90 struct wined3d_shader_buffer shader_buffer;
91 struct wine_rb_tree program_lookup;
92 struct glsl_shader_prog_link *glsl_program;
93 struct constant_heap vconst_heap;
94 struct constant_heap pconst_heap;
96 GLhandleARB depth_blt_program_full[tex_type_count];
97 GLhandleARB depth_blt_program_masked[tex_type_count];
98 UINT next_constant_version;
101 /* Struct to maintain data about a linked GLSL program */
102 struct glsl_shader_prog_link {
103 struct wine_rb_entry program_lookup_entry;
104 struct list vshader_entry;
105 struct list pshader_entry;
106 GLhandleARB programId;
107 GLint *vuniformF_locations;
108 GLint *puniformF_locations;
109 GLint vuniformI_locations[MAX_CONST_I];
110 GLint puniformI_locations[MAX_CONST_I];
111 GLint posFixup_location;
112 GLint np2Fixup_location;
113 GLint bumpenvmat_location[MAX_TEXTURES];
114 GLint luminancescale_location[MAX_TEXTURES];
115 GLint luminanceoffset_location[MAX_TEXTURES];
116 GLint ycorrection_location;
117 GLenum vertex_color_clamp;
118 const struct wined3d_shader *vshader;
119 const struct wined3d_shader *pshader;
120 struct vs_compile_args vs_args;
121 struct ps_compile_args ps_args;
122 UINT constant_version;
123 const struct ps_np2fixup_info *np2Fixup_info;
126 struct glsl_program_key
128 const struct wined3d_shader *vshader;
129 const struct wined3d_shader *pshader;
130 struct ps_compile_args ps_args;
131 struct vs_compile_args vs_args;
134 struct shader_glsl_ctx_priv {
135 const struct vs_compile_args *cur_vs_args;
136 const struct ps_compile_args *cur_ps_args;
137 struct ps_np2fixup_info *cur_np2fixup_info;
140 struct glsl_ps_compiled_shader
142 struct ps_compile_args args;
143 struct ps_np2fixup_info np2fixup;
147 struct glsl_vs_compiled_shader
149 struct vs_compile_args args;
153 struct glsl_shader_private
157 struct glsl_vs_compiled_shader *vs;
158 struct glsl_ps_compiled_shader *ps;
160 UINT num_gl_shaders, shader_array_size;
163 static const char *debug_gl_shader_type(GLenum type)
167 #define WINED3D_TO_STR(u) case u: return #u
168 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
169 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
170 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
171 #undef WINED3D_TO_STR
173 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
177 static const char *shader_glsl_get_prefix(enum wined3d_shader_type type)
181 case WINED3D_SHADER_TYPE_VERTEX:
184 case WINED3D_SHADER_TYPE_GEOMETRY:
187 case WINED3D_SHADER_TYPE_PIXEL:
191 FIXME("Unhandled shader type %#x.\n", type);
196 /* Extract a line from the info log.
197 * Note that this modifies the source string. */
198 static char *get_info_log_line(char **ptr)
203 if (!(q = strstr(p, "\n")))
205 if (!*p) return NULL;
215 /** Prints the GLSL info log which will contain error messages if they exist */
216 /* GL locking is done by the caller */
217 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
219 int infologLength = 0;
222 if (!WARN_ON(d3d_shader) && !FIXME_ON(d3d_shader))
225 GL_EXTCALL(glGetObjectParameterivARB(obj,
226 GL_OBJECT_INFO_LOG_LENGTH_ARB,
229 /* A size of 1 is just a null-terminated string, so the log should be bigger than
230 * that if there are errors. */
231 if (infologLength > 1)
235 infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
236 /* The info log is supposed to be zero-terminated, but at least some
237 * versions of fglrx don't terminate the string properly. The reported
238 * length does include the terminator, so explicitly set it to zero
240 infoLog[infologLength - 1] = 0;
241 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
244 if (gl_info->quirks & WINED3D_QUIRK_INFO_LOG_SPAM)
246 WARN("Info log received from GLSL shader #%u:\n", obj);
247 while ((line = get_info_log_line(&ptr))) WARN(" %s\n", line);
251 FIXME("Info log received from GLSL shader #%u:\n", obj);
252 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
254 HeapFree(GetProcessHeap(), 0, infoLog);
258 /* GL locking is done by the caller. */
259 static void shader_glsl_compile(const struct wined3d_gl_info *gl_info, GLhandleARB shader, const char *src)
261 TRACE("Compiling shader object %u.\n", shader);
262 GL_EXTCALL(glShaderSourceARB(shader, 1, &src, NULL));
263 checkGLcall("glShaderSourceARB");
264 GL_EXTCALL(glCompileShaderARB(shader));
265 checkGLcall("glCompileShaderARB");
266 print_glsl_info_log(gl_info, shader);
269 /* GL locking is done by the caller. */
270 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
272 GLint i, object_count, source_size = -1;
273 GLhandleARB *objects;
276 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
277 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
280 ERR("Failed to allocate object array memory.\n");
284 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
285 for (i = 0; i < object_count; ++i)
290 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
292 if (source_size < tmp)
294 HeapFree(GetProcessHeap(), 0, source);
296 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
299 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
300 HeapFree(GetProcessHeap(), 0, objects);
306 FIXME("Object %u:\n", objects[i]);
307 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
308 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
309 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
310 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
314 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
315 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
319 HeapFree(GetProcessHeap(), 0, source);
320 HeapFree(GetProcessHeap(), 0, objects);
323 /* GL locking is done by the caller. */
324 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
328 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
330 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
331 if (tmp == GL_PROGRAM_OBJECT_ARB)
333 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
336 FIXME("Program %u link status invalid.\n", program);
337 shader_glsl_dump_program_source(gl_info, program);
341 print_glsl_info_log(gl_info, program);
345 * Loads (pixel shader) samplers
347 /* GL locking is done by the caller */
348 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
349 const DWORD *tex_unit_map, GLhandleARB programId)
352 char sampler_name[20];
355 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
357 snprintf(sampler_name, sizeof(sampler_name), "ps_sampler%u", i);
358 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
359 if (name_loc != -1) {
360 DWORD mapped_unit = tex_unit_map[i];
361 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
363 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
364 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
365 checkGLcall("glUniform1iARB");
367 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
373 /* GL locking is done by the caller */
374 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
375 const DWORD *tex_unit_map, GLhandleARB programId)
378 char sampler_name[20];
381 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
383 snprintf(sampler_name, sizeof(sampler_name), "vs_sampler%u", i);
384 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
385 if (name_loc != -1) {
386 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
387 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
389 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
390 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
391 checkGLcall("glUniform1iARB");
393 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
399 /* GL locking is done by the caller */
400 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
401 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
404 unsigned int heap_idx = 1;
407 if (heap->entries[heap_idx].version <= version) return;
409 idx = heap->entries[heap_idx].idx;
410 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
411 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
413 while (stack_idx >= 0)
415 /* Note that we fall through to the next case statement. */
416 switch(stack[stack_idx])
418 case HEAP_NODE_TRAVERSE_LEFT:
420 unsigned int left_idx = heap_idx << 1;
421 if (left_idx < heap->size && heap->entries[left_idx].version > version)
424 idx = heap->entries[heap_idx].idx;
425 if (constant_locations[idx] != -1)
426 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
428 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
429 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
434 case HEAP_NODE_TRAVERSE_RIGHT:
436 unsigned int right_idx = (heap_idx << 1) + 1;
437 if (right_idx < heap->size && heap->entries[right_idx].version > version)
439 heap_idx = right_idx;
440 idx = heap->entries[heap_idx].idx;
441 if (constant_locations[idx] != -1)
442 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
444 stack[stack_idx++] = HEAP_NODE_POP;
445 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
456 checkGLcall("walk_constant_heap()");
459 /* GL locking is done by the caller */
460 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
462 GLfloat clamped_constant[4];
464 if (location == -1) return;
466 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
467 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
468 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
469 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
471 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
474 /* GL locking is done by the caller */
475 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
476 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
479 unsigned int heap_idx = 1;
482 if (heap->entries[heap_idx].version <= version) return;
484 idx = heap->entries[heap_idx].idx;
485 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
486 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
488 while (stack_idx >= 0)
490 /* Note that we fall through to the next case statement. */
491 switch(stack[stack_idx])
493 case HEAP_NODE_TRAVERSE_LEFT:
495 unsigned int left_idx = heap_idx << 1;
496 if (left_idx < heap->size && heap->entries[left_idx].version > version)
499 idx = heap->entries[heap_idx].idx;
500 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
502 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
503 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
508 case HEAP_NODE_TRAVERSE_RIGHT:
510 unsigned int right_idx = (heap_idx << 1) + 1;
511 if (right_idx < heap->size && heap->entries[right_idx].version > version)
513 heap_idx = right_idx;
514 idx = heap->entries[heap_idx].idx;
515 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
517 stack[stack_idx++] = HEAP_NODE_POP;
518 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
529 checkGLcall("walk_constant_heap_clamped()");
532 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
533 /* GL locking is done by the caller */
534 static void shader_glsl_load_constantsF(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
535 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
536 unsigned char *stack, UINT version)
538 const struct wined3d_shader_lconst *lconst;
540 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
541 if (shader->reg_maps.shader_version.major == 1
542 && shader_is_pshader_version(shader->reg_maps.shader_version.type))
543 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
545 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
547 if (!shader->load_local_constsF)
549 TRACE("No need to load local float constants for this shader\n");
553 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
554 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
556 GLint location = constant_locations[lconst->idx];
557 /* We found this uniform name in the program - go ahead and send the data */
558 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
560 checkGLcall("glUniform4fvARB()");
563 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
564 /* GL locking is done by the caller */
565 static void shader_glsl_load_constantsI(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
566 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
571 for (i = 0; constants_set; constants_set >>= 1, ++i)
573 if (!(constants_set & 1)) continue;
575 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
576 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
578 /* We found this uniform name in the program - go ahead and send the data */
579 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
580 checkGLcall("glUniform4ivARB");
583 /* Load immediate constants */
584 ptr = list_head(&shader->constantsI);
587 const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
588 unsigned int idx = lconst->idx;
589 const GLint *values = (const GLint *)lconst->value;
591 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
592 values[0], values[1], values[2], values[3]);
594 /* We found this uniform name in the program - go ahead and send the data */
595 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
596 checkGLcall("glUniform4ivARB");
597 ptr = list_next(&shader->constantsI, ptr);
601 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
602 /* GL locking is done by the caller */
603 static void shader_glsl_load_constantsB(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
604 GLhandleARB programId, const BOOL *constants, WORD constants_set)
612 prefix = shader_glsl_get_prefix(shader->reg_maps.shader_version.type);
614 /* TODO: Benchmark and see if it would be beneficial to store the
615 * locations of the constants to avoid looking up each time */
616 for (i = 0; constants_set; constants_set >>= 1, ++i)
618 if (!(constants_set & 1)) continue;
620 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
622 /* TODO: Benchmark and see if it would be beneficial to store the
623 * locations of the constants to avoid looking up each time */
624 snprintf(tmp_name, sizeof(tmp_name), "%s_b[%i]", prefix, i);
625 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
628 /* We found this uniform name in the program - go ahead and send the data */
629 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
630 checkGLcall("glUniform1ivARB");
634 /* Load immediate constants */
635 ptr = list_head(&shader->constantsB);
638 const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
639 unsigned int idx = lconst->idx;
640 const GLint *values = (const GLint *)lconst->value;
642 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
644 snprintf(tmp_name, sizeof(tmp_name), "%s_b[%i]", prefix, idx);
645 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
647 /* We found this uniform name in the program - go ahead and send the data */
648 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
649 checkGLcall("glUniform1ivARB");
651 ptr = list_next(&shader->constantsB, ptr);
655 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
657 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
661 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
663 /* GL locking is done by the caller (state handler) */
664 static void shader_glsl_load_np2fixup_constants(void *shader_priv,
665 const struct wined3d_gl_info *gl_info, const struct wined3d_state *state)
667 struct shader_glsl_priv *glsl_priv = shader_priv;
668 const struct glsl_shader_prog_link *prog = glsl_priv->glsl_program;
670 /* No GLSL program set - nothing to do. */
673 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
674 if (!use_ps(state)) return;
676 if (prog->ps_args.np2_fixup && prog->np2Fixup_location != -1)
679 UINT fixup = prog->ps_args.np2_fixup;
680 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
682 for (i = 0; fixup; fixup >>= 1, ++i)
684 const struct wined3d_texture *tex = state->textures[i];
685 const unsigned char idx = prog->np2Fixup_info->idx[i];
686 GLfloat *tex_dim = &np2fixup_constants[(idx >> 1) * 4];
690 ERR("Nonexistent texture is flagged for NP2 texcoord fixup.\n");
696 tex_dim[2] = tex->pow2_matrix[0];
697 tex_dim[3] = tex->pow2_matrix[5];
701 tex_dim[0] = tex->pow2_matrix[0];
702 tex_dim[1] = tex->pow2_matrix[5];
706 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
711 * Loads the app-supplied constants into the currently set GLSL program.
713 /* GL locking is done by the caller (state handler) */
714 static void shader_glsl_load_constants(const struct wined3d_context *context,
715 BOOL usePixelShader, BOOL useVertexShader)
717 const struct wined3d_gl_info *gl_info = context->gl_info;
718 struct wined3d_device *device = context->swapchain->device;
719 struct wined3d_stateblock *stateBlock = device->stateBlock;
720 const struct wined3d_state *state = &stateBlock->state;
721 struct shader_glsl_priv *priv = device->shader_priv;
722 float position_fixup[4];
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 = state->vertex_shader;
740 /* Load DirectX 9 float constants/uniforms for vertex shader */
741 shader_glsl_load_constantsF(vshader, gl_info, state->vs_consts_f,
742 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
744 /* Load DirectX 9 integer constants/uniforms for vertex shader */
745 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, state->vs_consts_i,
746 stateBlock->changed.vertexShaderConstantsI & vshader->reg_maps.integer_constants);
748 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
749 shader_glsl_load_constantsB(vshader, gl_info, programId, state->vs_consts_b,
750 stateBlock->changed.vertexShaderConstantsB & vshader->reg_maps.boolean_constants);
752 /* Upload the position fixup params */
753 shader_get_position_fixup(context, state, position_fixup);
754 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, position_fixup));
755 checkGLcall("glUniform4fvARB");
760 const struct wined3d_shader *pshader = state->pixel_shader;
762 /* Load DirectX 9 float constants/uniforms for pixel shader */
763 shader_glsl_load_constantsF(pshader, gl_info, state->ps_consts_f,
764 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
766 /* Load DirectX 9 integer constants/uniforms for pixel shader */
767 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, state->ps_consts_i,
768 stateBlock->changed.pixelShaderConstantsI & pshader->reg_maps.integer_constants);
770 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
771 shader_glsl_load_constantsB(pshader, gl_info, programId, state->ps_consts_b,
772 stateBlock->changed.pixelShaderConstantsB & pshader->reg_maps.boolean_constants);
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 *)&state->texture_states[i][WINED3D_TSS_BUMPENV_MAT00];
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 *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LSCALE];
792 const GLfloat *offset = (const GLfloat *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LOFFSET];
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 struct wined3d_shader_lconst *lconst;
908 /* There are some minor differences between pixel and vertex shaders */
909 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
910 prefix = shader_glsl_get_prefix(reg_maps->shader_version.type);
912 /* Prototype the subroutines */
913 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
915 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
918 /* Declare the constants (aka uniforms) */
919 if (shader->limits.constant_float > 0)
921 unsigned max_constantsF;
922 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
923 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
924 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
925 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
926 * a dx9 card, as long as it doesn't also use all the other constants.
928 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
929 * declare only the amount that we're assured to have.
931 * Thus we run into problems in these two cases:
932 * 1) The shader really uses more uniforms than supported
933 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
937 /* No indirect addressing here. */
938 max_constantsF = gl_info->limits.glsl_ps_float_constants;
942 if (reg_maps->usesrelconstF)
944 /* Subtract the other potential uniforms from the max
945 * available (bools, ints, and 1 row of projection matrix).
946 * Subtract another uniform for immediate values, which have
947 * to be loaded via uniform by the driver as well. The shader
948 * code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex
949 * shader code, so one vec4 should be enough. (Unfortunately
950 * the Nvidia driver doesn't store 128 and -128 in one float).
952 * Writing gl_ClipVertex requires one uniform for each
953 * clipplane as well. */
954 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
955 if(ctx_priv->cur_vs_args->clip_enabled)
957 max_constantsF -= gl_info->limits.clipplanes;
959 max_constantsF -= count_bits(reg_maps->integer_constants);
960 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
961 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
962 * for now take this into account when calculating the number of available constants
964 max_constantsF -= count_bits(reg_maps->boolean_constants);
965 /* Set by driver quirks in directx.c */
966 max_constantsF -= gl_info->reserved_glsl_constants;
968 if (max_constantsF < shader->limits.constant_float)
970 static unsigned int once;
973 ERR_(winediag)("The hardware does not support enough uniform components to run this shader,"
974 " it may not render correctly.\n");
976 WARN("The hardware does not support enough uniform components to run this shader.\n");
981 max_constantsF = gl_info->limits.glsl_vs_float_constants;
984 max_constantsF = min(shader->limits.constant_float, max_constantsF);
985 shader_addline(buffer, "uniform vec4 %s_c[%u];\n", prefix, max_constantsF);
988 /* Always declare the full set of constants, the compiler can remove the
989 * unused ones because d3d doesn't (yet) support indirect int and bool
990 * constant addressing. This avoids problems if the app uses e.g. i0 and i9. */
991 if (shader->limits.constant_int > 0 && reg_maps->integer_constants)
992 shader_addline(buffer, "uniform ivec4 %s_i[%u];\n", prefix, shader->limits.constant_int);
994 if (shader->limits.constant_bool > 0 && reg_maps->boolean_constants)
995 shader_addline(buffer, "uniform bool %s_b[%u];\n", prefix, shader->limits.constant_bool);
997 for (i = 0; i < WINED3D_MAX_CBS; ++i)
999 if (reg_maps->cb_sizes[i])
1000 shader_addline(buffer, "uniform vec4 %s_cb%u[%u];\n", prefix, i, reg_maps->cb_sizes[i]);
1005 shader_addline(buffer, "uniform vec4 posFixup;\n");
1006 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", shader->limits.packed_output);
1010 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1012 if (!(map & 1)) continue;
1014 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1016 if (reg_maps->luminanceparams & (1 << i))
1018 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1019 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1020 extra_constants_needed++;
1023 extra_constants_needed++;
1026 if (ps_args->srgb_correction)
1028 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1029 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1030 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1033 if (reg_maps->vpos || reg_maps->usesdsy)
1035 if (shader->limits.constant_float + extra_constants_needed
1036 + 1 < gl_info->limits.glsl_ps_float_constants)
1038 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1039 extra_constants_needed++;
1043 /* This happens because we do not have proper tracking of the constant registers that are
1044 * actually used, only the max limit of the shader version
1046 FIXME("Cannot find a free uniform for vpos correction params\n");
1047 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1048 context->render_offscreen ? 0.0f : fb->render_targets[0]->resource.height,
1049 context->render_offscreen ? 1.0f : -1.0f);
1051 shader_addline(buffer, "vec4 vpos;\n");
1055 /* Declare texture samplers */
1056 for (i = 0; i < shader->limits.sampler; ++i)
1058 if (reg_maps->sampler_type[i])
1060 const struct wined3d_texture *texture;
1062 switch (reg_maps->sampler_type[i])
1065 if (pshader && ps_args->shadow & (1 << i))
1066 shader_addline(buffer, "uniform sampler1DShadow %s_sampler%u;\n", prefix, i);
1068 shader_addline(buffer, "uniform sampler1D %s_sampler%u;\n", prefix, i);
1071 texture = state->textures[i];
1072 if (pshader && ps_args->shadow & (1 << i))
1074 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1075 shader_addline(buffer, "uniform sampler2DRectShadow %s_sampler%u;\n", prefix, i);
1077 shader_addline(buffer, "uniform sampler2DShadow %s_sampler%u;\n", prefix, i);
1081 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1082 shader_addline(buffer, "uniform sampler2DRect %s_sampler%u;\n", prefix, i);
1084 shader_addline(buffer, "uniform sampler2D %s_sampler%u;\n", prefix, i);
1087 case WINED3DSTT_CUBE:
1088 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported Cube shadow sampler.\n");
1089 shader_addline(buffer, "uniform samplerCube %s_sampler%u;\n", prefix, i);
1091 case WINED3DSTT_VOLUME:
1092 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported 3D shadow sampler.\n");
1093 shader_addline(buffer, "uniform sampler3D %s_sampler%u;\n", prefix, i);
1096 shader_addline(buffer, "uniform unsupported_sampler %s_sampler%u;\n", prefix, i);
1097 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1103 /* Declare uniforms for NP2 texcoord fixup:
1104 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1105 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1106 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1107 if (pshader && ps_args->np2_fixup) {
1109 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1112 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1113 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1114 * samplerNP2Fixup stores texture dimensions and is updated through
1115 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1117 for (i = 0; i < shader->limits.sampler; ++i)
1119 if (reg_maps->sampler_type[i])
1121 if (!(ps_args->np2_fixup & (1 << i))) continue;
1123 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1124 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1128 fixup->idx[i] = cur++;
1132 fixup->num_consts = (cur + 1) >> 1;
1133 shader_addline(buffer, "uniform vec4 %s_samplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1136 /* Declare address variables */
1137 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1139 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1142 /* Declare texture coordinate temporaries and initialize them */
1143 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1145 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1148 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1149 * helper function shader that is linked in at link time
1151 if (pshader && reg_maps->shader_version.major >= 3)
1153 UINT in_count = min(vec4_varyings(reg_maps->shader_version.major, gl_info), shader->limits.packed_input);
1156 shader_addline(buffer, "varying vec4 %s_in[%u];\n", prefix, in_count);
1158 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1159 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1160 * pixel shader that reads the fixed function color into the packed input registers. */
1161 shader_addline(buffer, "vec4 %s_in[%u];\n", prefix, in_count);
1164 /* Declare output register temporaries */
1165 if (shader->limits.packed_output)
1166 shader_addline(buffer, "vec4 %s_out[%u];\n", prefix, shader->limits.packed_output);
1168 /* Declare temporary variables */
1169 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1171 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1174 /* Declare attributes */
1175 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1177 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1179 if (map & 1) shader_addline(buffer, "attribute vec4 %s_in%u;\n", prefix, i);
1183 /* Declare loop registers aLx */
1184 if (reg_maps->shader_version.major < 4)
1186 for (i = 0; i < reg_maps->loop_depth; ++i)
1188 shader_addline(buffer, "int aL%u;\n", i);
1189 shader_addline(buffer, "int tmpInt%u;\n", i);
1193 /* Temporary variables for matrix operations */
1194 shader_addline(buffer, "vec4 tmp0;\n");
1195 shader_addline(buffer, "vec4 tmp1;\n");
1197 /* Local constants use a different name so they can be loaded once at shader link time
1198 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1199 * float -> string conversion can cause precision loss.
1201 if (!shader->load_local_constsF)
1203 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
1205 shader_addline(buffer, "uniform vec4 %s_lc%u;\n", prefix, lconst->idx);
1209 /* Start the main program */
1210 shader_addline(buffer, "void main() {\n");
1211 if(pshader && reg_maps->vpos) {
1212 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1213 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1214 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1215 * precision troubles when we just subtract 0.5.
1217 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1219 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1221 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1222 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1223 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1224 * correctly on drivers that returns integer values.
1226 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1230 /*****************************************************************************
1231 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1233 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1234 ****************************************************************************/
1237 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1238 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src);
1240 /** Used for opcode modifiers - They multiply the result by the specified amount */
1241 static const char * const shift_glsl_tab[] = {
1243 "2.0 * ", /* 1 (x2) */
1244 "4.0 * ", /* 2 (x4) */
1245 "8.0 * ", /* 3 (x8) */
1246 "16.0 * ", /* 4 (x16) */
1247 "32.0 * ", /* 5 (x32) */
1254 "0.0625 * ", /* 12 (d16) */
1255 "0.125 * ", /* 13 (d8) */
1256 "0.25 * ", /* 14 (d4) */
1257 "0.5 * " /* 15 (d2) */
1260 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1261 static void shader_glsl_gen_modifier(enum wined3d_shader_src_modifier src_modifier,
1262 const char *in_reg, const char *in_regswizzle, char *out_str)
1266 switch (src_modifier)
1268 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1269 case WINED3DSPSM_DW:
1270 case WINED3DSPSM_NONE:
1271 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1273 case WINED3DSPSM_NEG:
1274 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1276 case WINED3DSPSM_NOT:
1277 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1279 case WINED3DSPSM_BIAS:
1280 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1282 case WINED3DSPSM_BIASNEG:
1283 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1285 case WINED3DSPSM_SIGN:
1286 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1288 case WINED3DSPSM_SIGNNEG:
1289 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1291 case WINED3DSPSM_COMP:
1292 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1294 case WINED3DSPSM_X2:
1295 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1297 case WINED3DSPSM_X2NEG:
1298 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1300 case WINED3DSPSM_ABS:
1301 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1303 case WINED3DSPSM_ABSNEG:
1304 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1307 FIXME("Unhandled modifier %u\n", src_modifier);
1308 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1312 /** Writes the GLSL variable name that corresponds to the register that the
1313 * DX opcode parameter is trying to access */
1314 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1315 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1317 /* oPos, oFog and oPts in D3D */
1318 static const char * const hwrastout_reg_names[] = {"vs_out[10]", "vs_out[11].x", "vs_out[11].y"};
1320 const struct wined3d_shader *shader = ins->ctx->shader;
1321 const struct wined3d_shader_reg_maps *reg_maps = ins->ctx->reg_maps;
1322 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1323 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
1324 const char *prefix = shader_glsl_get_prefix(reg_maps->shader_version.type);
1330 case WINED3DSPR_TEMP:
1331 sprintf(register_name, "R%u", reg->idx);
1334 case WINED3DSPR_INPUT:
1335 /* vertex shaders */
1338 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1339 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1340 sprintf(register_name, "%s_in%u", prefix, reg->idx);
1344 /* pixel shaders >= 3.0 */
1345 if (reg_maps->shader_version.major >= 3)
1347 DWORD idx = shader->u.ps.input_reg_map[reg->idx];
1348 unsigned int in_count = vec4_varyings(reg_maps->shader_version.major, gl_info);
1352 struct glsl_src_param rel_param;
1354 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1356 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1357 * operation there */
1360 if (shader->u.ps.declared_in_count > in_count)
1362 sprintf(register_name,
1363 "((%s + %u) > %u ? (%s + %u) > %u ? gl_SecondaryColor : gl_Color : %s_in[%s + %u])",
1364 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1365 prefix, rel_param.param_str, idx);
1369 sprintf(register_name, "%s_in[%s + %u]", prefix, rel_param.param_str, idx);
1374 if (shader->u.ps.declared_in_count > in_count)
1376 sprintf(register_name, "((%s) > %u ? (%s) > %u ? gl_SecondaryColor : gl_Color : %s_in[%s])",
1377 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1378 prefix, rel_param.param_str);
1382 sprintf(register_name, "%s_in[%s]", prefix, rel_param.param_str);
1388 if (idx == in_count) sprintf(register_name, "gl_Color");
1389 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1390 else sprintf(register_name, "%s_in[%u]", prefix, idx);
1395 if (!reg->idx) strcpy(register_name, "gl_Color");
1396 else strcpy(register_name, "gl_SecondaryColor");
1401 case WINED3DSPR_CONST:
1403 /* Relative addressing */
1406 struct glsl_src_param rel_param;
1407 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1409 sprintf(register_name, "%s_c[%s + %u]", prefix, rel_param.param_str, reg->idx);
1411 sprintf(register_name, "%s_c[%s]", prefix, rel_param.param_str);
1415 if (shader_constant_is_local(shader, reg->idx))
1416 sprintf(register_name, "%s_lc%u", prefix, reg->idx);
1418 sprintf(register_name, "%s_c[%u]", prefix, reg->idx);
1423 case WINED3DSPR_CONSTINT:
1424 sprintf(register_name, "%s_i[%u]", prefix, reg->idx);
1427 case WINED3DSPR_CONSTBOOL:
1428 sprintf(register_name, "%s_b[%u]", prefix, reg->idx);
1431 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1432 if (pshader) sprintf(register_name, "T%u", reg->idx);
1433 else sprintf(register_name, "A%u", reg->idx);
1436 case WINED3DSPR_LOOP:
1437 sprintf(register_name, "aL%u", ins->ctx->loop_state->current_reg - 1);
1440 case WINED3DSPR_SAMPLER:
1441 sprintf(register_name, "%s_sampler%u", prefix, reg->idx);
1444 case WINED3DSPR_COLOROUT:
1445 if (reg->idx >= gl_info->limits.buffers)
1446 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1448 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1451 case WINED3DSPR_RASTOUT:
1452 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1455 case WINED3DSPR_DEPTHOUT:
1456 sprintf(register_name, "gl_FragDepth");
1459 case WINED3DSPR_ATTROUT:
1460 if (!reg->idx) sprintf(register_name, "%s_out[8]", prefix);
1461 else sprintf(register_name, "%s_out[9]", prefix);
1464 case WINED3DSPR_TEXCRDOUT:
1465 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1466 sprintf(register_name, "%s_out[%u]", prefix, reg->idx);
1469 case WINED3DSPR_MISCTYPE:
1473 sprintf(register_name, "vpos");
1475 else if (reg->idx == 1)
1477 /* Note that gl_FrontFacing is a bool, while vFace is
1478 * a float for which the sign determines front/back */
1479 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1483 FIXME("Unhandled misctype register %d\n", reg->idx);
1484 sprintf(register_name, "unrecognized_register");
1488 case WINED3DSPR_IMMCONST:
1489 switch (reg->immconst_type)
1491 case WINED3D_IMMCONST_SCALAR:
1492 switch (reg->data_type)
1494 case WINED3D_DATA_FLOAT:
1495 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1497 case WINED3D_DATA_INT:
1498 sprintf(register_name, "%#x", reg->immconst_data[0]);
1500 case WINED3D_DATA_RESOURCE:
1501 case WINED3D_DATA_SAMPLER:
1502 case WINED3D_DATA_UINT:
1503 sprintf(register_name, "%#xu", reg->immconst_data[0]);
1506 sprintf(register_name, "<unhandled data type %#x>", reg->data_type);
1511 case WINED3D_IMMCONST_VEC4:
1512 switch (reg->data_type)
1514 case WINED3D_DATA_FLOAT:
1515 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1516 *(const float *)®->immconst_data[0], *(const float *)®->immconst_data[1],
1517 *(const float *)®->immconst_data[2], *(const float *)®->immconst_data[3]);
1519 case WINED3D_DATA_INT:
1520 sprintf(register_name, "ivec4(%#x, %#x, %#x, %#x)",
1521 reg->immconst_data[0], reg->immconst_data[1],
1522 reg->immconst_data[2], reg->immconst_data[3]);
1524 case WINED3D_DATA_RESOURCE:
1525 case WINED3D_DATA_SAMPLER:
1526 case WINED3D_DATA_UINT:
1527 sprintf(register_name, "uvec4(%#xu, %#xu, %#xu, %#xu)",
1528 reg->immconst_data[0], reg->immconst_data[1],
1529 reg->immconst_data[2], reg->immconst_data[3]);
1532 sprintf(register_name, "<unhandled data type %#x>", reg->data_type);
1538 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1539 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1543 case WINED3DSPR_CONSTBUFFER:
1546 struct glsl_src_param rel_param;
1547 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1548 sprintf(register_name, "%s_cb%u[%s + %u]", prefix, reg->idx, rel_param.param_str, reg->array_idx);
1552 sprintf(register_name, "%s_cb%u[%u]", prefix, reg->idx, reg->array_idx);
1557 FIXME("Unhandled register type %#x.\n", reg->type);
1558 sprintf(register_name, "unrecognized_register");
1563 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1566 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1567 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1568 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1569 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1573 /* Get the GLSL write mask for the destination register */
1574 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1576 DWORD mask = param->write_mask;
1578 if (shader_is_scalar(¶m->reg))
1580 mask = WINED3DSP_WRITEMASK_0;
1585 shader_glsl_write_mask_to_str(mask, write_mask);
1591 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1592 unsigned int size = 0;
1594 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1595 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1596 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1597 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1602 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1604 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1605 * but addressed as "rgba". To fix this we need to swap the register's x
1606 * and z components. */
1607 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1610 /* swizzle bits fields: wwzzyyxx */
1611 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1612 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1613 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1614 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1618 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1619 BOOL fixup, DWORD mask, char *swizzle_str)
1621 if (shader_is_scalar(¶m->reg))
1622 *swizzle_str = '\0';
1624 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1627 /* From a given parameter token, generate the corresponding GLSL string.
1628 * Also, return the actual register name and swizzle in case the
1629 * caller needs this information as well. */
1630 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1631 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src)
1633 BOOL is_color = FALSE;
1634 char swizzle_str[6];
1636 glsl_src->reg_name[0] = '\0';
1637 glsl_src->param_str[0] = '\0';
1638 swizzle_str[0] = '\0';
1640 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1641 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1643 if (wined3d_src->reg.type == WINED3DSPR_IMMCONST)
1645 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1649 char param_str[200];
1651 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, param_str);
1653 switch (wined3d_src->reg.data_type)
1655 case WINED3D_DATA_FLOAT:
1656 sprintf(glsl_src->param_str, "%s", param_str);
1658 case WINED3D_DATA_INT:
1659 sprintf(glsl_src->param_str, "floatBitsToInt(%s)", param_str);
1661 case WINED3D_DATA_RESOURCE:
1662 case WINED3D_DATA_SAMPLER:
1663 case WINED3D_DATA_UINT:
1664 sprintf(glsl_src->param_str, "floatBitsToUint(%s)", param_str);
1667 FIXME("Unhandled data type %#x.\n", wined3d_src->reg.data_type);
1668 sprintf(glsl_src->param_str, "%s", param_str);
1674 /* From a given parameter token, generate the corresponding GLSL string.
1675 * Also, return the actual register name and swizzle in case the
1676 * caller needs this information as well. */
1677 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1678 const struct wined3d_shader_dst_param *wined3d_dst, struct glsl_dst_param *glsl_dst)
1680 BOOL is_color = FALSE;
1682 glsl_dst->mask_str[0] = '\0';
1683 glsl_dst->reg_name[0] = '\0';
1685 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1686 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1689 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1690 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1691 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1693 struct glsl_dst_param glsl_dst;
1696 if ((mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst)))
1698 switch (dst->reg.data_type)
1700 case WINED3D_DATA_FLOAT:
1701 shader_addline(buffer, "%s%s = %s(",
1702 glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1704 case WINED3D_DATA_INT:
1705 shader_addline(buffer, "%s%s = %sintBitsToFloat(",
1706 glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1708 case WINED3D_DATA_RESOURCE:
1709 case WINED3D_DATA_SAMPLER:
1710 case WINED3D_DATA_UINT:
1711 shader_addline(buffer, "%s%s = %suintBitsToFloat(",
1712 glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1715 FIXME("Unhandled data type %#x.\n", dst->reg.data_type);
1716 shader_addline(buffer, "%s%s = %s(",
1717 glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1725 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1726 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1728 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1731 /** Process GLSL instruction modifiers */
1732 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1734 struct glsl_dst_param dst_param;
1737 if (!ins->dst_count) return;
1739 modifiers = ins->dst[0].modifiers;
1740 if (!modifiers) return;
1742 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1744 if (modifiers & WINED3DSPDM_SATURATE)
1746 /* _SAT means to clamp the value of the register to between 0 and 1 */
1747 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1748 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1751 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1753 FIXME("_centroid modifier not handled\n");
1756 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1758 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1762 static const char *shader_glsl_get_rel_op(enum wined3d_shader_rel_op op)
1766 case WINED3D_SHADER_REL_OP_GT: return ">";
1767 case WINED3D_SHADER_REL_OP_EQ: return "==";
1768 case WINED3D_SHADER_REL_OP_GE: return ">=";
1769 case WINED3D_SHADER_REL_OP_LT: return "<";
1770 case WINED3D_SHADER_REL_OP_NE: return "!=";
1771 case WINED3D_SHADER_REL_OP_LE: return "<=";
1773 FIXME("Unrecognized operator %#x.\n", op);
1778 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1779 DWORD sampler_idx, DWORD flags, struct glsl_sample_function *sample_function)
1781 enum wined3d_sampler_texture_type sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1782 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1783 BOOL shadow = shader_is_pshader_version(ctx->reg_maps->shader_version.type)
1784 && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1785 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1786 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1787 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1788 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1790 /* Note that there's no such thing as a projected cube texture. */
1791 switch(sampler_type) {
1797 sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1801 if (gl_info->supported[EXT_GPU_SHADER4])
1802 sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1803 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1804 sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1807 FIXME("Unsupported 1D shadow grad function.\n");
1808 sample_function->name = "unsupported1DGrad";
1813 sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1815 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1821 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1825 if (gl_info->supported[EXT_GPU_SHADER4])
1826 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1827 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1828 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1831 FIXME("Unsupported 1D grad function.\n");
1832 sample_function->name = "unsupported1DGrad";
1837 sample_function->name = projected ? "texture1DProj" : "texture1D";
1839 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1850 sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1854 if (gl_info->supported[EXT_GPU_SHADER4])
1855 sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1856 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1857 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1860 FIXME("Unsupported RECT shadow grad function.\n");
1861 sample_function->name = "unsupported2DRectGrad";
1866 sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1873 sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1877 if (gl_info->supported[EXT_GPU_SHADER4])
1878 sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1879 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1880 sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1883 FIXME("Unsupported 2D shadow grad function.\n");
1884 sample_function->name = "unsupported2DGrad";
1889 sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1892 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1900 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1904 if (gl_info->supported[EXT_GPU_SHADER4])
1905 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1906 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1907 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1910 FIXME("Unsupported RECT grad function.\n");
1911 sample_function->name = "unsupported2DRectGrad";
1916 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1923 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1927 if (gl_info->supported[EXT_GPU_SHADER4])
1928 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1929 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1930 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1933 FIXME("Unsupported 2D grad function.\n");
1934 sample_function->name = "unsupported2DGrad";
1939 sample_function->name = projected ? "texture2DProj" : "texture2D";
1942 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1946 case WINED3DSTT_CUBE:
1949 FIXME("Unsupported Cube shadow function.\n");
1950 sample_function->name = "unsupportedCubeShadow";
1951 sample_function->coord_mask = 0;
1957 sample_function->name = "textureCubeLod";
1961 if (gl_info->supported[EXT_GPU_SHADER4])
1962 sample_function->name = "textureCubeGrad";
1963 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1964 sample_function->name = "textureCubeGradARB";
1967 FIXME("Unsupported Cube grad function.\n");
1968 sample_function->name = "unsupportedCubeGrad";
1973 sample_function->name = "textureCube";
1975 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1979 case WINED3DSTT_VOLUME:
1982 FIXME("Unsupported 3D shadow function.\n");
1983 sample_function->name = "unsupported3DShadow";
1984 sample_function->coord_mask = 0;
1990 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1994 if (gl_info->supported[EXT_GPU_SHADER4])
1995 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1996 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1997 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
2000 FIXME("Unsupported 3D grad function.\n");
2001 sample_function->name = "unsupported3DGrad";
2006 sample_function->name = projected ? "texture3DProj" : "texture3D";
2008 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2013 sample_function->name = "";
2014 sample_function->coord_mask = 0;
2015 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
2020 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
2021 BOOL sign_fixup, enum fixup_channel_source channel_source)
2023 switch(channel_source)
2025 case CHANNEL_SOURCE_ZERO:
2026 strcat(arguments, "0.0");
2029 case CHANNEL_SOURCE_ONE:
2030 strcat(arguments, "1.0");
2033 case CHANNEL_SOURCE_X:
2034 strcat(arguments, reg_name);
2035 strcat(arguments, ".x");
2038 case CHANNEL_SOURCE_Y:
2039 strcat(arguments, reg_name);
2040 strcat(arguments, ".y");
2043 case CHANNEL_SOURCE_Z:
2044 strcat(arguments, reg_name);
2045 strcat(arguments, ".z");
2048 case CHANNEL_SOURCE_W:
2049 strcat(arguments, reg_name);
2050 strcat(arguments, ".w");
2054 FIXME("Unhandled channel source %#x\n", channel_source);
2055 strcat(arguments, "undefined");
2059 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
2062 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
2064 struct wined3d_shader_dst_param dst;
2065 unsigned int mask_size, remaining;
2066 struct glsl_dst_param dst_param;
2067 char arguments[256];
2071 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
2072 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
2073 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
2074 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
2075 mask &= ins->dst[0].write_mask;
2077 if (!mask) return; /* Nothing to do */
2079 if (is_complex_fixup(fixup))
2081 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
2082 FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
2086 mask_size = shader_glsl_get_write_mask_size(mask);
2089 dst.write_mask = mask;
2090 shader_glsl_add_dst_param(ins, &dst, &dst_param);
2092 arguments[0] = '\0';
2093 remaining = mask_size;
2094 if (mask & WINED3DSP_WRITEMASK_0)
2096 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
2097 if (--remaining) strcat(arguments, ", ");
2099 if (mask & WINED3DSP_WRITEMASK_1)
2101 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
2102 if (--remaining) strcat(arguments, ", ");
2104 if (mask & WINED3DSP_WRITEMASK_2)
2106 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
2107 if (--remaining) strcat(arguments, ", ");
2109 if (mask & WINED3DSP_WRITEMASK_3)
2111 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
2112 if (--remaining) strcat(arguments, ", ");
2117 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
2118 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
2122 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
2126 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2127 DWORD sampler, const struct glsl_sample_function *sample_function, DWORD swizzle,
2128 const char *dx, const char *dy, const char *bias, const char *coord_reg_fmt, ...)
2130 const char *sampler_base;
2131 char dst_swizzle[6];
2132 struct color_fixup_desc fixup;
2133 BOOL np2_fixup = FALSE;
2136 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2138 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2140 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2141 fixup = priv->cur_ps_args->color_fixup[sampler];
2142 sampler_base = "ps_sampler";
2144 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2146 FIXME("Biased sampling from NP2 textures is unsupported\n");
2154 sampler_base = "vs_sampler";
2155 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2158 shader_glsl_append_dst(ins->ctx->buffer, ins);
2160 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2162 va_start(args, coord_reg_fmt);
2163 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2167 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2170 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2171 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2173 shader_addline(ins->ctx->buffer, " * ps_samplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2174 (idx % 2) ? "zw" : "xy", dst_swizzle);
2175 } else if(dx && dy) {
2176 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2178 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2182 if(!is_identity_fixup(fixup)) {
2183 shader_glsl_color_correction(ins, fixup);
2187 /*****************************************************************************
2188 * Begin processing individual instruction opcodes
2189 ****************************************************************************/
2191 static void shader_glsl_binop(const struct wined3d_shader_instruction *ins)
2193 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2194 struct glsl_src_param src0_param;
2195 struct glsl_src_param src1_param;
2199 /* Determine the GLSL operator to use based on the opcode */
2200 switch (ins->handler_idx)
2202 case WINED3DSIH_ADD: op = '+'; break;
2203 case WINED3DSIH_AND: op = '&'; break;
2204 case WINED3DSIH_DIV: op = '/'; break;
2205 case WINED3DSIH_IADD: op = '+'; break;
2206 case WINED3DSIH_MUL: op = '*'; break;
2207 case WINED3DSIH_SUB: op = '-'; break;
2208 case WINED3DSIH_XOR: op = '^'; break;
2211 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2215 write_mask = shader_glsl_append_dst(buffer, ins);
2216 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2217 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2218 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2221 static void shader_glsl_relop(const struct wined3d_shader_instruction *ins)
2223 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2224 struct glsl_src_param src0_param;
2225 struct glsl_src_param src1_param;
2226 unsigned int mask_size;
2230 write_mask = shader_glsl_append_dst(buffer, ins);
2231 mask_size = shader_glsl_get_write_mask_size(write_mask);
2232 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2233 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2237 switch (ins->handler_idx)
2239 case WINED3DSIH_EQ: op = "equal"; break;
2240 case WINED3DSIH_GE: op = "greaterThanEqual"; break;
2241 case WINED3DSIH_IGE: op = "greaterThanEqual"; break;
2242 case WINED3DSIH_LT: op = "lessThan"; break;
2244 op = "<unhandled operator>";
2245 ERR("Unhandled opcode %#x.\n", ins->handler_idx);
2249 shader_addline(buffer, "uvec%u(%s(%s, %s)) * 0xffffffffu);\n",
2250 mask_size, op, src0_param.param_str, src1_param.param_str);
2254 switch (ins->handler_idx)
2256 case WINED3DSIH_EQ: op = "=="; break;
2257 case WINED3DSIH_GE: op = ">="; break;
2258 case WINED3DSIH_IGE: op = ">="; break;
2259 case WINED3DSIH_LT: op = "<"; break;
2261 op = "<unhandled operator>";
2262 ERR("Unhandled opcode %#x.\n", ins->handler_idx);
2266 shader_addline(buffer, "%s %s %s ? 0xffffffffu : 0u);\n",
2267 src0_param.param_str, op, src1_param.param_str);
2271 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2272 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2274 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2275 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2276 struct glsl_src_param src0_param;
2279 write_mask = shader_glsl_append_dst(buffer, ins);
2280 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2282 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2283 * shader versions WINED3DSIO_MOVA is used for this. */
2284 if (ins->ctx->reg_maps->shader_version.major == 1
2285 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2286 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2288 /* This is a simple floor() */
2289 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2290 if (mask_size > 1) {
2291 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2293 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2296 else if(ins->handler_idx == WINED3DSIH_MOVA)
2298 /* We need to *round* to the nearest int here. */
2299 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2301 if (gl_info->supported[EXT_GPU_SHADER4])
2304 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2306 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2311 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2312 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2314 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2315 src0_param.param_str, src0_param.param_str);
2320 shader_addline(buffer, "%s);\n", src0_param.param_str);
2324 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2325 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2327 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2328 struct glsl_src_param src0_param;
2329 struct glsl_src_param src1_param;
2330 DWORD dst_write_mask, src_write_mask;
2331 unsigned int dst_size = 0;
2333 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2334 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2336 /* dp3 works on vec3, dp4 on vec4 */
2337 if (ins->handler_idx == WINED3DSIH_DP4)
2339 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2341 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2344 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2345 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2348 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2350 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2354 /* Note that this instruction has some restrictions. The destination write mask
2355 * can't contain the w component, and the source swizzles have to be .xyzw */
2356 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2358 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2359 struct glsl_src_param src0_param;
2360 struct glsl_src_param src1_param;
2363 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2364 shader_glsl_append_dst(ins->ctx->buffer, ins);
2365 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2366 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2367 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2370 static void shader_glsl_cut(const struct wined3d_shader_instruction *ins)
2372 shader_addline(ins->ctx->buffer, "EndPrimitive();\n");
2375 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2376 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2377 * GLSL uses the value as-is. */
2378 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2380 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2381 struct glsl_src_param src0_param;
2382 struct glsl_src_param src1_param;
2383 DWORD dst_write_mask;
2384 unsigned int dst_size;
2386 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2387 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2389 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2390 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2394 shader_addline(buffer, "vec%u(%s == 0.0 ? 1.0 : pow(abs(%s), %s)));\n",
2395 dst_size, src1_param.param_str, src0_param.param_str, src1_param.param_str);
2399 shader_addline(buffer, "%s == 0.0 ? 1.0 : pow(abs(%s), %s));\n",
2400 src1_param.param_str, src0_param.param_str, src1_param.param_str);
2404 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2405 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2406 * GLSL uses the value as-is. */
2407 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2409 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2410 struct glsl_src_param src0_param;
2411 DWORD dst_write_mask;
2412 unsigned int dst_size;
2414 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2415 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2417 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2421 shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2422 dst_size, src0_param.param_str);
2426 shader_addline(buffer, "log2(abs(%s)));\n",
2427 src0_param.param_str);
2431 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2432 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2434 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2435 struct glsl_src_param src_param;
2436 const char *instruction;
2440 /* Determine the GLSL function to use based on the opcode */
2441 /* TODO: Possibly make this a table for faster lookups */
2442 switch (ins->handler_idx)
2444 case WINED3DSIH_MIN: instruction = "min"; break;
2445 case WINED3DSIH_MAX: instruction = "max"; break;
2446 case WINED3DSIH_ABS: instruction = "abs"; break;
2447 case WINED3DSIH_FRC: instruction = "fract"; break;
2448 case WINED3DSIH_EXP: instruction = "exp2"; break;
2449 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2450 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2451 default: instruction = "";
2452 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2456 write_mask = shader_glsl_append_dst(buffer, ins);
2458 shader_addline(buffer, "%s(", instruction);
2462 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2463 shader_addline(buffer, "%s", src_param.param_str);
2464 for (i = 1; i < ins->src_count; ++i)
2466 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2467 shader_addline(buffer, ", %s", src_param.param_str);
2471 shader_addline(buffer, "));\n");
2474 static void shader_glsl_nop(const struct wined3d_shader_instruction *ins) {}
2476 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2478 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2479 struct glsl_src_param src_param;
2480 unsigned int mask_size;
2484 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2485 mask_size = shader_glsl_get_write_mask_size(write_mask);
2486 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2488 shader_addline(buffer, "tmp0.x = dot(%s, %s);\n",
2489 src_param.param_str, src_param.param_str);
2490 shader_glsl_append_dst(buffer, ins);
2494 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s * inversesqrt(tmp0.x)));\n",
2495 mask_size, src_param.param_str);
2499 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s * inversesqrt(tmp0.x)));\n",
2500 src_param.param_str);
2504 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2505 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2506 * dst.x = 2^(floor(src))
2507 * dst.y = src - floor(src)
2508 * dst.z = 2^src (partial precision is allowed, but optional)
2510 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2511 * dst = 2^src; (partial precision is allowed, but optional)
2513 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2515 struct glsl_src_param src_param;
2517 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2519 if (ins->ctx->reg_maps->shader_version.major < 2)
2523 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2524 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2525 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2526 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2528 shader_glsl_append_dst(ins->ctx->buffer, ins);
2529 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2530 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2533 unsigned int mask_size;
2535 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2536 mask_size = shader_glsl_get_write_mask_size(write_mask);
2538 if (mask_size > 1) {
2539 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2541 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2546 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2547 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2549 struct glsl_src_param src_param;
2551 unsigned int mask_size;
2553 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2554 mask_size = shader_glsl_get_write_mask_size(write_mask);
2555 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2559 shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2560 mask_size, src_param.param_str);
2564 shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2565 src_param.param_str);
2569 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2571 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2572 struct glsl_src_param src_param;
2574 unsigned int mask_size;
2576 write_mask = shader_glsl_append_dst(buffer, ins);
2577 mask_size = shader_glsl_get_write_mask_size(write_mask);
2579 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2583 shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2584 mask_size, src_param.param_str);
2588 shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2589 src_param.param_str);
2593 /** Process signed comparison opcodes in GLSL. */
2594 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2596 struct glsl_src_param src0_param;
2597 struct glsl_src_param src1_param;
2599 unsigned int mask_size;
2601 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2602 mask_size = shader_glsl_get_write_mask_size(write_mask);
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);
2606 if (mask_size > 1) {
2607 const char *compare;
2609 switch(ins->handler_idx)
2611 case WINED3DSIH_SLT: compare = "lessThan"; break;
2612 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2613 default: compare = "";
2614 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2617 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2618 src0_param.param_str, src1_param.param_str);
2620 switch(ins->handler_idx)
2622 case WINED3DSIH_SLT:
2623 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2624 * to return 0.0 but step returns 1.0 because step is not < x
2625 * An alternative is a bvec compare padded with an unused second component.
2626 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2627 * issue. Playing with not() is not possible either because not() does not accept
2630 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2631 src0_param.param_str, src1_param.param_str);
2633 case WINED3DSIH_SGE:
2634 /* Here we can use the step() function and safe a conditional */
2635 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2638 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2644 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2645 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2647 struct glsl_src_param src0_param;
2648 struct glsl_src_param src1_param;
2649 struct glsl_src_param src2_param;
2650 DWORD write_mask, cmp_channel = 0;
2653 BOOL temp_destination = FALSE;
2655 if (shader_is_scalar(&ins->src[0].reg))
2657 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2659 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2660 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2661 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2663 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2664 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2666 DWORD dst_mask = ins->dst[0].write_mask;
2667 struct wined3d_shader_dst_param dst = ins->dst[0];
2669 /* Cycle through all source0 channels */
2670 for (i=0; i<4; i++) {
2672 /* Find the destination channels which use the current source0 channel */
2673 for (j=0; j<4; j++) {
2674 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2676 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2677 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2680 dst.write_mask = dst_mask & write_mask;
2682 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2683 * The first lines may overwrite source parameters of the following lines.
2684 * Deal with that by using a temporary destination register if needed
2686 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2687 && ins->src[0].reg.type == ins->dst[0].reg.type)
2688 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2689 && ins->src[1].reg.type == ins->dst[0].reg.type)
2690 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2691 && ins->src[2].reg.type == ins->dst[0].reg.type))
2693 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2694 if (!write_mask) continue;
2695 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2696 temp_destination = TRUE;
2698 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2699 if (!write_mask) continue;
2702 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2703 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2704 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2706 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2707 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2710 if(temp_destination) {
2711 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2712 shader_glsl_append_dst(ins->ctx->buffer, ins);
2713 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2719 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2720 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2721 * the compare is done per component of src0. */
2722 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2724 struct wined3d_shader_dst_param dst;
2725 struct glsl_src_param src0_param;
2726 struct glsl_src_param src1_param;
2727 struct glsl_src_param src2_param;
2728 DWORD write_mask, cmp_channel = 0;
2731 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2732 ins->ctx->reg_maps->shader_version.minor);
2734 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2736 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2737 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2738 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2739 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2741 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2744 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2746 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2747 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2751 /* Cycle through all source0 channels */
2752 dst_mask = ins->dst[0].write_mask;
2754 for (i=0; i<4; i++) {
2756 /* Find the destination channels which use the current source0 channel */
2757 for (j=0; j<4; j++) {
2758 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2760 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2761 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2765 dst.write_mask = dst_mask & write_mask;
2766 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2767 if (!write_mask) continue;
2769 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2770 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2771 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2773 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2774 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2778 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2779 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2781 struct glsl_src_param src0_param;
2782 struct glsl_src_param src1_param;
2783 struct glsl_src_param src2_param;
2786 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2787 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2788 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2789 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2790 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2791 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2794 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2795 Vertex shaders to GLSL codes */
2796 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2799 int nComponents = 0;
2800 struct wined3d_shader_dst_param tmp_dst = {{0}};
2801 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2802 struct wined3d_shader_instruction tmp_ins;
2804 memset(&tmp_ins, 0, sizeof(tmp_ins));
2806 /* Set constants for the temporary argument */
2807 tmp_ins.ctx = ins->ctx;
2808 tmp_ins.dst_count = 1;
2809 tmp_ins.dst = &tmp_dst;
2810 tmp_ins.src_count = 2;
2811 tmp_ins.src = tmp_src;
2813 switch(ins->handler_idx)
2815 case WINED3DSIH_M4x4:
2817 tmp_ins.handler_idx = WINED3DSIH_DP4;
2819 case WINED3DSIH_M4x3:
2821 tmp_ins.handler_idx = WINED3DSIH_DP4;
2823 case WINED3DSIH_M3x4:
2825 tmp_ins.handler_idx = WINED3DSIH_DP3;
2827 case WINED3DSIH_M3x3:
2829 tmp_ins.handler_idx = WINED3DSIH_DP3;
2831 case WINED3DSIH_M3x2:
2833 tmp_ins.handler_idx = WINED3DSIH_DP3;
2839 tmp_dst = ins->dst[0];
2840 tmp_src[0] = ins->src[0];
2841 tmp_src[1] = ins->src[1];
2842 for (i = 0; i < nComponents; ++i)
2844 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2845 shader_glsl_dot(&tmp_ins);
2846 ++tmp_src[1].reg.idx;
2851 The LRP instruction performs a component-wise linear interpolation
2852 between the second and third operands using the first operand as the
2853 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2854 This is equivalent to mix(src2, src1, src0);
2856 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2858 struct glsl_src_param src0_param;
2859 struct glsl_src_param src1_param;
2860 struct glsl_src_param src2_param;
2863 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2865 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2866 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2867 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2869 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2870 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2873 /** Process the WINED3DSIO_LIT instruction in GLSL:
2874 * dst.x = dst.w = 1.0
2875 * dst.y = (src0.x > 0) ? src0.x
2876 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2877 * where src.w is clamped at +- 128
2879 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2881 struct glsl_src_param src0_param;
2882 struct glsl_src_param src1_param;
2883 struct glsl_src_param src3_param;
2886 shader_glsl_append_dst(ins->ctx->buffer, ins);
2887 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2889 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2890 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2891 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2893 /* The sdk specifies the instruction like this
2895 * if(src.x > 0.0) dst.y = src.x
2897 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2900 * (where power = src.w clamped between -128 and 128)
2902 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2903 * dst.x = 1.0 ... No further explanation needed
2904 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2905 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2906 * dst.w = 1.0. ... Nothing fancy.
2908 * So we still have one conditional in there. So do this:
2909 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2911 * 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),
2912 * 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.
2913 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to.
2915 * Unfortunately pow(0.0 ^ 0.0) returns NaN on most GPUs, but lit with src.y = 0 and src.w = 0 returns
2916 * a non-NaN value in dst.z. What we return doesn't matter, as long as it is not NaN. Return 0, which is
2917 * what all Windows HW drivers and GL_ARB_vertex_program's LIT do.
2919 shader_addline(ins->ctx->buffer,
2920 "vec4(1.0, max(%s, 0.0), %s == 0.0 ? 0.0 : "
2921 "pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
2922 src0_param.param_str, src3_param.param_str, src1_param.param_str,
2923 src0_param.param_str, src3_param.param_str, dst_mask);
2926 /** Process the WINED3DSIO_DST instruction in GLSL:
2928 * dst.y = src0.x * src0.y
2932 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2934 struct glsl_src_param src0y_param;
2935 struct glsl_src_param src0z_param;
2936 struct glsl_src_param src1y_param;
2937 struct glsl_src_param src1w_param;
2940 shader_glsl_append_dst(ins->ctx->buffer, ins);
2941 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2943 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2944 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2945 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2946 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2948 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2949 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2952 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2953 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2954 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2956 * dst.x = cos(src0.?)
2957 * dst.y = sin(src0.?)
2961 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2963 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2964 struct glsl_src_param src0_param;
2967 if (ins->ctx->reg_maps->shader_version.major < 4)
2969 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2971 write_mask = shader_glsl_append_dst(buffer, ins);
2974 case WINED3DSP_WRITEMASK_0:
2975 shader_addline(buffer, "cos(%s));\n", src0_param.param_str);
2978 case WINED3DSP_WRITEMASK_1:
2979 shader_addline(buffer, "sin(%s));\n", src0_param.param_str);
2982 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2983 shader_addline(buffer, "vec2(cos(%s), sin(%s)));\n",
2984 src0_param.param_str, src0_param.param_str);
2988 ERR("Write mask should be .x, .y or .xy\n");
2995 if (ins->dst[0].reg.type != WINED3DSPR_NULL)
2998 if (ins->dst[1].reg.type != WINED3DSPR_NULL)
3002 write_mask = shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3003 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3004 shader_addline(buffer, "tmp0%s = sin(%s);\n", dst_mask, src0_param.param_str);
3006 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
3007 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3008 shader_addline(buffer, "cos(%s));\n", src0_param.param_str);
3010 shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
3011 shader_addline(buffer, "tmp0%s);\n", dst_mask);
3015 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
3016 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3017 shader_addline(buffer, "sin(%s));\n", src0_param.param_str);
3020 else if (ins->dst[1].reg.type != WINED3DSPR_NULL)
3022 write_mask = shader_glsl_append_dst_ext(buffer, ins, &ins->dst[1]);
3023 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3024 shader_addline(buffer, "cos(%s));\n", src0_param.param_str);
3028 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
3029 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
3030 * generate invalid code
3032 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
3034 struct glsl_src_param src0_param;
3037 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3038 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
3040 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
3043 /** Process the WINED3DSIO_LOOP instruction in GLSL:
3044 * Start a for() loop where src1.y is the initial value of aL,
3045 * increment aL by src1.z for a total of src1.x iterations.
3046 * Need to use a temporary variable for this operation.
3048 /* FIXME: I don't think nested loops will work correctly this way. */
3049 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
3051 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
3052 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3053 const struct wined3d_shader *shader = ins->ctx->shader;
3054 const struct wined3d_shader_lconst *constant;
3055 struct glsl_src_param src1_param;
3056 const DWORD *control_values = NULL;
3058 if (ins->ctx->reg_maps->shader_version.major < 4)
3060 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
3062 /* Try to hardcode the loop control parameters if possible. Direct3D 9
3063 * class hardware doesn't support real varying indexing, but Microsoft
3064 * designed this feature for Shader model 2.x+. If the loop control is
3065 * known at compile time, the GLSL compiler can unroll the loop, and
3066 * replace indirect addressing with direct addressing. */
3067 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
3069 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
3071 if (constant->idx == ins->src[1].reg.idx)
3073 control_values = constant->value;
3081 struct wined3d_shader_loop_control loop_control;
3082 loop_control.count = control_values[0];
3083 loop_control.start = control_values[1];
3084 loop_control.step = (int)control_values[2];
3086 if (loop_control.step > 0)
3088 shader_addline(buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d)\n{\n",
3089 loop_state->current_depth, loop_control.start,
3090 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
3091 loop_state->current_depth, loop_control.step);
3093 else if (loop_control.step < 0)
3095 shader_addline(buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d)\n{\n",
3096 loop_state->current_depth, loop_control.start,
3097 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
3098 loop_state->current_depth, loop_control.step);
3102 shader_addline(buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++)\n{\n",
3103 loop_state->current_depth, loop_control.start, loop_state->current_depth,
3104 loop_state->current_depth, loop_control.count,
3105 loop_state->current_depth);
3110 shader_addline(buffer, "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z)\n{\n",
3111 loop_state->current_depth, loop_state->current_reg,
3112 src1_param.reg_name, loop_state->current_depth, src1_param.reg_name,
3113 loop_state->current_depth, loop_state->current_reg, src1_param.reg_name);
3116 ++loop_state->current_reg;
3120 shader_addline(buffer, "for (;;)\n{\n");
3123 ++loop_state->current_depth;
3126 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
3128 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
3130 shader_addline(ins->ctx->buffer, "}\n");
3132 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
3134 --loop_state->current_depth;
3135 --loop_state->current_reg;
3138 if (ins->handler_idx == WINED3DSIH_ENDREP)
3140 --loop_state->current_depth;
3144 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
3146 const struct wined3d_shader *shader = ins->ctx->shader;
3147 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
3148 const struct wined3d_shader_lconst *constant;
3149 struct glsl_src_param src0_param;
3150 const DWORD *control_values = NULL;
3152 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
3153 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
3155 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
3157 if (constant->idx == ins->src[0].reg.idx)
3159 control_values = constant->value;
3167 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
3168 loop_state->current_depth, loop_state->current_depth,
3169 control_values[0], loop_state->current_depth);
3173 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3174 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
3175 loop_state->current_depth, loop_state->current_depth,
3176 src0_param.param_str, loop_state->current_depth);
3179 ++loop_state->current_depth;
3182 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
3184 struct glsl_src_param src0_param;
3186 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3187 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
3190 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
3192 struct glsl_src_param src0_param;
3193 struct glsl_src_param src1_param;
3195 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3196 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3198 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
3199 src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
3202 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
3204 shader_addline(ins->ctx->buffer, "} else {\n");
3207 static void shader_glsl_emit(const struct wined3d_shader_instruction *ins)
3209 shader_addline(ins->ctx->buffer, "EmitVertex();\n");
3212 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
3214 shader_addline(ins->ctx->buffer, "break;\n");
3217 /* FIXME: According to MSDN the compare is done per component. */
3218 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
3220 struct glsl_src_param src0_param;
3221 struct glsl_src_param src1_param;
3223 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3224 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3226 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
3227 src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
3230 static void shader_glsl_breakp(const struct wined3d_shader_instruction *ins)
3232 struct glsl_src_param src_param;
3234 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
3235 shader_addline(ins->ctx->buffer, "if (bool(%s)) break;\n", src_param.param_str);
3238 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
3240 shader_addline(ins->ctx->buffer, "}\n");
3241 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
3244 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
3246 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
3249 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
3251 struct glsl_src_param src1_param;
3253 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3254 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
3257 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3259 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3260 * function only suppresses the unhandled instruction warning
3264 /*********************************************
3265 * Pixel Shader Specific Code begins here
3266 ********************************************/
3267 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3269 const struct wined3d_shader *shader = ins->ctx->shader;
3270 struct wined3d_device *device = shader->device;
3271 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3272 ins->ctx->reg_maps->shader_version.minor);
3273 struct glsl_sample_function sample_function;
3274 const struct wined3d_texture *texture;
3275 DWORD sample_flags = 0;
3277 DWORD mask = 0, swizzle;
3279 /* 1.0-1.4: Use destination register as sampler source.
3280 * 2.0+: Use provided sampler source. */
3281 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3282 else sampler_idx = ins->src[1].reg.idx;
3283 texture = device->stateBlock->state.textures[sampler_idx];
3285 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3287 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3288 DWORD flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3289 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3290 enum wined3d_sampler_texture_type sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3292 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3293 if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE)
3295 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3296 switch (flags & ~WINED3D_PSARGS_PROJECTED)
3298 case WINED3D_TTFF_COUNT1:
3299 FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3301 case WINED3D_TTFF_COUNT2:
3302 mask = WINED3DSP_WRITEMASK_1;
3304 case WINED3D_TTFF_COUNT3:
3305 mask = WINED3DSP_WRITEMASK_2;
3307 case WINED3D_TTFF_COUNT4:
3308 case WINED3D_TTFF_DISABLE:
3309 mask = WINED3DSP_WRITEMASK_3;
3314 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3316 enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3318 if (src_mod == WINED3DSPSM_DZ) {
3319 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3320 mask = WINED3DSP_WRITEMASK_2;
3321 } else if (src_mod == WINED3DSPSM_DW) {
3322 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3323 mask = WINED3DSP_WRITEMASK_3;
3326 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3328 /* ps 2.0 texldp instruction always divides by the fourth component. */
3329 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3330 mask = WINED3DSP_WRITEMASK_3;
3334 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3335 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3337 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3338 mask |= sample_function.coord_mask;
3340 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3341 else swizzle = ins->src[1].swizzle;
3343 /* 1.0-1.3: Use destination register as coordinate source.
3344 1.4+: Use provided coordinate source register. */
3345 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3348 shader_glsl_write_mask_to_str(mask, coord_mask);
3349 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3350 "T%u%s", sampler_idx, coord_mask);
3354 struct glsl_src_param coord_param;
3355 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3356 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3358 struct glsl_src_param bias;
3359 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3360 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3361 "%s", coord_param.param_str);
3363 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3364 "%s", coord_param.param_str);
3369 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3371 const struct wined3d_shader *shader = ins->ctx->shader;
3372 struct wined3d_device *device = shader->device;
3373 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3374 struct glsl_src_param coord_param, dx_param, dy_param;
3375 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3376 struct glsl_sample_function sample_function;
3378 DWORD swizzle = ins->src[1].swizzle;
3379 const struct wined3d_texture *texture;
3381 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3383 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3384 shader_glsl_tex(ins);
3388 sampler_idx = ins->src[1].reg.idx;
3389 texture = device->stateBlock->state.textures[sampler_idx];
3390 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3391 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3393 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3394 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3395 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3396 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3398 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3399 "%s", coord_param.param_str);
3402 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3404 const struct wined3d_shader *shader = ins->ctx->shader;
3405 struct wined3d_device *device = shader->device;
3406 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3407 struct glsl_src_param coord_param, lod_param;
3408 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3409 struct glsl_sample_function sample_function;
3411 DWORD swizzle = ins->src[1].swizzle;
3412 const struct wined3d_texture *texture;
3414 sampler_idx = ins->src[1].reg.idx;
3415 texture = device->stateBlock->state.textures[sampler_idx];
3416 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3417 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3419 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3420 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3422 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3424 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3425 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3427 /* Plain GLSL only supports Lod sampling functions in vertex shaders.
3428 * However, the NVIDIA drivers allow them in fragment shaders as well,
3429 * even without the appropriate extension. */
3430 WARN("Using %s in fragment shader.\n", sample_function.name);
3432 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3433 "%s", coord_param.param_str);
3436 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3438 /* FIXME: Make this work for more than just 2D textures */
3439 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3440 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3442 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3446 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3447 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3448 ins->dst[0].reg.idx, dst_mask);
3452 enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3453 DWORD reg = ins->src[0].reg.idx;
3454 char dst_swizzle[6];
3456 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3458 if (src_mod == WINED3DSPSM_DZ)
3460 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3461 struct glsl_src_param div_param;
3463 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3465 if (mask_size > 1) {
3466 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3468 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3471 else if (src_mod == WINED3DSPSM_DW)
3473 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3474 struct glsl_src_param div_param;
3476 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3478 if (mask_size > 1) {
3479 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3481 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3484 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3489 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3490 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3491 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3492 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3494 DWORD sampler_idx = ins->dst[0].reg.idx;
3495 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3496 struct glsl_sample_function sample_function;
3497 struct glsl_src_param src0_param;
3500 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3502 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3503 * scalar, and projected sampling would require 4.
3505 * It is a dependent read - not valid with conditional NP2 textures
3507 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3508 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3513 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3514 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3518 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3519 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3523 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3524 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3528 FIXME("Unexpected mask size %u\n", mask_size);
3533 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3534 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3535 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3537 DWORD dstreg = ins->dst[0].reg.idx;
3538 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3539 struct glsl_src_param src0_param;
3541 unsigned int mask_size;
3543 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3544 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3545 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3547 if (mask_size > 1) {
3548 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3550 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3554 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3555 * Calculate the depth as dst.x / dst.y */
3556 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3558 struct glsl_dst_param dst_param;
3560 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3562 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3563 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3564 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3565 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3568 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3569 dst_param.reg_name, dst_param.reg_name);
3572 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3573 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3574 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3575 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3577 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3579 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3580 DWORD dstreg = ins->dst[0].reg.idx;
3581 struct glsl_src_param src0_param;
3583 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3585 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3586 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3589 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3590 * Calculate the 1st of a 2-row matrix multiplication. */
3591 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3593 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3594 DWORD reg = ins->dst[0].reg.idx;
3595 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3596 struct glsl_src_param src0_param;
3598 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3599 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3602 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3603 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3604 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3606 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3607 DWORD reg = ins->dst[0].reg.idx;
3608 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3609 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3610 struct glsl_src_param src0_param;
3612 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3613 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + tex_mx->current_row, reg, src0_param.param_str);
3614 tex_mx->texcoord_w[tex_mx->current_row++] = reg;
3617 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3619 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3620 DWORD reg = ins->dst[0].reg.idx;
3621 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3622 struct glsl_sample_function sample_function;
3623 struct glsl_src_param src0_param;
3625 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3626 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3628 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3630 /* Sample the texture using the calculated coordinates */
3631 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3634 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3635 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3636 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3638 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3639 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3640 struct glsl_sample_function sample_function;
3641 struct glsl_src_param src0_param;
3642 DWORD reg = ins->dst[0].reg.idx;
3644 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3645 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3647 /* Dependent read, not valid with conditional NP2 */
3648 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3650 /* Sample the texture using the calculated coordinates */
3651 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3653 tex_mx->current_row = 0;
3656 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3657 * Perform the 3rd row of a 3x3 matrix multiply */
3658 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3660 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3661 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3662 struct glsl_src_param src0_param;
3664 DWORD reg = ins->dst[0].reg.idx;
3666 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3668 shader_glsl_append_dst(ins->ctx->buffer, ins);
3669 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3670 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3672 tex_mx->current_row = 0;
3675 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3676 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3677 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3679 struct glsl_src_param src0_param;
3680 struct glsl_src_param src1_param;
3681 DWORD reg = ins->dst[0].reg.idx;
3682 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3683 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3684 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3685 struct glsl_sample_function sample_function;
3688 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3689 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3691 /* Perform the last matrix multiply operation */
3692 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3693 /* Reflection calculation */
3694 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3696 /* Dependent read, not valid with conditional NP2 */
3697 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3698 shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3700 /* Sample the texture */
3701 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3702 NULL, NULL, NULL, "tmp0%s", coord_mask);
3704 tex_mx->current_row = 0;
3707 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3708 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3709 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3711 DWORD reg = ins->dst[0].reg.idx;
3712 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3713 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3714 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3715 struct glsl_sample_function sample_function;
3716 struct glsl_src_param src0_param;
3719 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3721 /* Perform the last matrix multiply operation */
3722 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3724 /* Construct the eye-ray vector from w coordinates */
3725 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3726 tex_mx->texcoord_w[0], tex_mx->texcoord_w[1], reg);
3727 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3729 /* Dependent read, not valid with conditional NP2 */
3730 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3731 shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3733 /* Sample the texture using the calculated coordinates */
3734 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3735 NULL, NULL, NULL, "tmp0%s", coord_mask);
3737 tex_mx->current_row = 0;
3740 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3741 * Apply a fake bump map transform.
3742 * texbem is pshader <= 1.3 only, this saves a few version checks
3744 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3746 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3747 struct glsl_sample_function sample_function;
3748 struct glsl_src_param coord_param;
3754 sampler_idx = ins->dst[0].reg.idx;
3755 flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3756 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3758 /* Dependent read, not valid with conditional NP2 */
3759 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3760 mask = sample_function.coord_mask;
3762 shader_glsl_write_mask_to_str(mask, coord_mask);
3764 /* With projected textures, texbem only divides the static texture coord,
3765 * not the displacement, so we can't let GL handle this. */
3766 if (flags & WINED3D_PSARGS_PROJECTED)
3769 char coord_div_mask[3];
3770 switch (flags & ~WINED3D_PSARGS_PROJECTED)
3772 case WINED3D_TTFF_COUNT1:
3773 FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3775 case WINED3D_TTFF_COUNT2:
3776 div_mask = WINED3DSP_WRITEMASK_1;
3778 case WINED3D_TTFF_COUNT3:
3779 div_mask = WINED3DSP_WRITEMASK_2;
3781 case WINED3D_TTFF_COUNT4:
3782 case WINED3D_TTFF_DISABLE:
3783 div_mask = WINED3DSP_WRITEMASK_3;
3786 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3787 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3790 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3792 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3793 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3794 coord_param.param_str, coord_mask);
3796 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3798 struct glsl_src_param luminance_param;
3799 struct glsl_dst_param dst_param;
3801 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3802 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3804 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3805 dst_param.reg_name, dst_param.mask_str,
3806 luminance_param.param_str, sampler_idx, sampler_idx);
3810 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3812 struct glsl_src_param src0_param, src1_param;
3813 DWORD sampler_idx = ins->dst[0].reg.idx;
3815 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3816 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3818 shader_glsl_append_dst(ins->ctx->buffer, ins);
3819 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3820 src0_param.param_str, sampler_idx, src1_param.param_str);
3823 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3824 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3825 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3827 struct glsl_sample_function sample_function;
3828 struct glsl_src_param src0_param;
3829 DWORD sampler_idx = ins->dst[0].reg.idx;
3831 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3833 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3834 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3835 "%s.wx", src0_param.reg_name);
3838 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3839 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3840 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3842 struct glsl_sample_function sample_function;
3843 struct glsl_src_param src0_param;
3844 DWORD sampler_idx = ins->dst[0].reg.idx;
3846 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3848 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3849 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3850 "%s.yz", src0_param.reg_name);
3853 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3854 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3855 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3857 struct glsl_sample_function sample_function;
3858 struct glsl_src_param src0_param;
3859 DWORD sampler_idx = ins->dst[0].reg.idx;
3861 /* Dependent read, not valid with conditional NP2 */
3862 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3863 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3865 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3866 "%s", src0_param.param_str);
3869 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3870 * If any of the first 3 components are < 0, discard this pixel */
3871 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3873 struct glsl_dst_param dst_param;
3875 /* The argument is a destination parameter, and no writemasks are allowed */
3876 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3877 if (ins->ctx->reg_maps->shader_version.major >= 2)
3879 /* 2.0 shaders compare all 4 components in texkill */
3880 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3882 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3883 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3884 * 4 components are defined, only the first 3 are used
3886 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3890 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3891 * dst = dot2(src0, src1) + src2 */
3892 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3894 struct glsl_src_param src0_param;
3895 struct glsl_src_param src1_param;
3896 struct glsl_src_param src2_param;
3898 unsigned int mask_size;
3900 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3901 mask_size = shader_glsl_get_write_mask_size(write_mask);
3903 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3904 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3905 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3907 if (mask_size > 1) {
3908 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3909 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3911 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3912 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3916 static void shader_glsl_input_pack(const struct wined3d_shader *shader, struct wined3d_shader_buffer *buffer,
3917 const struct wined3d_shader_signature_element *input_signature,
3918 const struct wined3d_shader_reg_maps *reg_maps,
3919 enum vertexprocessing_mode vertexprocessing)
3921 WORD map = reg_maps->input_registers;
3924 for (i = 0; map; map >>= 1, ++i)
3926 const char *semantic_name;
3931 if (!(map & 1)) continue;
3933 semantic_name = input_signature[i].semantic_name;
3934 semantic_idx = input_signature[i].semantic_idx;
3935 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3937 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
3939 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3940 shader_addline(buffer, "ps_in[%u]%s = gl_TexCoord[%u]%s;\n",
3941 shader->u.ps.input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3943 shader_addline(buffer, "ps_in[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3944 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3946 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
3949 shader_addline(buffer, "ps_in[%u]%s = vec4(gl_Color)%s;\n",
3950 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3951 else if (semantic_idx == 1)
3952 shader_addline(buffer, "ps_in[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3953 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3955 shader_addline(buffer, "ps_in[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3956 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3960 shader_addline(buffer, "ps_in[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3961 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3966 /*********************************************
3967 * Vertex Shader Specific Code begins here
3968 ********************************************/
3970 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry)
3972 struct glsl_program_key key;
3974 key.vshader = entry->vshader;
3975 key.pshader = entry->pshader;
3976 key.vs_args = entry->vs_args;
3977 key.ps_args = entry->ps_args;
3979 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3981 ERR("Failed to insert program entry.\n");
3985 static struct glsl_shader_prog_link *get_glsl_program_entry(const struct shader_glsl_priv *priv,
3986 const struct wined3d_shader *vshader, const struct wined3d_shader *pshader,
3987 const struct vs_compile_args *vs_args, const struct ps_compile_args *ps_args)
3989 struct wine_rb_entry *entry;
3990 struct glsl_program_key key;
3992 key.vshader = vshader;
3993 key.pshader = pshader;
3994 key.vs_args = *vs_args;
3995 key.ps_args = *ps_args;
3997 entry = wine_rb_get(&priv->program_lookup, &key);
3998 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
4001 /* GL locking is done by the caller */
4002 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
4003 struct glsl_shader_prog_link *entry)
4005 struct glsl_program_key key;
4007 key.vshader = entry->vshader;
4008 key.pshader = entry->pshader;
4009 key.vs_args = entry->vs_args;
4010 key.ps_args = entry->ps_args;
4011 wine_rb_remove(&priv->program_lookup, &key);
4013 GL_EXTCALL(glDeleteObjectARB(entry->programId));
4014 if (entry->vshader) list_remove(&entry->vshader_entry);
4015 if (entry->pshader) list_remove(&entry->pshader_entry);
4016 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
4017 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
4018 HeapFree(GetProcessHeap(), 0, entry);
4021 static void handle_ps3_input(struct wined3d_shader_buffer *buffer,
4022 const struct wined3d_gl_info *gl_info, const DWORD *map,
4023 const struct wined3d_shader_signature_element *input_signature,
4024 const struct wined3d_shader_reg_maps *reg_maps_in,
4025 const struct wined3d_shader_signature_element *output_signature,
4026 const struct wined3d_shader_reg_maps *reg_maps_out)
4029 const char *semantic_name_in;
4030 UINT semantic_idx_in;
4033 unsigned int in_count = vec4_varyings(3, gl_info);
4035 char destination[50];
4036 WORD input_map, output_map;
4038 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
4040 input_map = reg_maps_in->input_registers;
4041 for (i = 0; input_map; input_map >>= 1, ++i)
4043 if (!(input_map & 1)) continue;
4046 /* Declared, but not read register */
4047 if (in_idx == ~0U) continue;
4048 if (in_idx >= (in_count + 2))
4050 FIXME("More input varyings declared than supported, expect issues.\n");
4054 if (in_idx == in_count)
4055 sprintf(destination, "gl_FrontColor");
4056 else if (in_idx == in_count + 1)
4057 sprintf(destination, "gl_FrontSecondaryColor");
4059 sprintf(destination, "ps_in[%u]", in_idx);
4061 semantic_name_in = input_signature[i].semantic_name;
4062 semantic_idx_in = input_signature[i].semantic_idx;
4065 output_map = reg_maps_out->output_registers;
4066 for (j = 0; output_map; output_map >>= 1, ++j)
4070 if (!(output_map & 1)
4071 || semantic_idx_in != output_signature[j].semantic_idx
4072 || strcmp(semantic_name_in, output_signature[j].semantic_name)
4073 || !(mask = input_signature[i].mask & output_signature[j].mask))
4077 shader_glsl_write_mask_to_str(mask, reg_mask);
4079 shader_addline(buffer, "%s%s = vs_out[%u]%s;\n",
4080 destination, reg_mask, j, reg_mask);
4084 for (i = 0; i < in_count + 2; ++i)
4088 if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
4091 if (set[i] == ~0U) set[i] = 0;
4094 if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
4095 if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
4096 if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
4097 if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
4098 reg_mask[size] = '\0';
4101 sprintf(destination, "gl_FrontColor");
4102 else if (i == in_count + 1)
4103 sprintf(destination, "gl_FrontSecondaryColor");
4105 sprintf(destination, "ps_in[%u]", i);
4107 if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
4108 else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
4111 HeapFree(GetProcessHeap(), 0, set);
4114 /* GL locking is done by the caller */
4115 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
4116 const struct wined3d_shader *vs, const struct wined3d_shader *ps,
4117 const struct wined3d_gl_info *gl_info)
4119 GLhandleARB ret = 0;
4120 DWORD ps_major = ps ? ps->reg_maps.shader_version.major : 0;
4122 const char *semantic_name;
4125 const struct wined3d_shader_signature_element *output_signature = vs->output_signature;
4126 WORD map = vs->reg_maps.output_registers;
4128 shader_buffer_clear(buffer);
4130 shader_addline(buffer, "#version 120\n");
4134 shader_addline(buffer, "void order_ps_input(in vec4 vs_out[%u])\n{\n", vs->limits.packed_output);
4136 for (i = 0; map; map >>= 1, ++i)
4140 if (!(map & 1)) continue;
4142 semantic_name = output_signature[i].semantic_name;
4143 semantic_idx = output_signature[i].semantic_idx;
4144 write_mask = output_signature[i].mask;
4145 shader_glsl_write_mask_to_str(write_mask, reg_mask);
4147 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
4150 shader_addline(buffer, "gl_FrontColor%s = vs_out[%u]%s;\n",
4151 reg_mask, i, reg_mask);
4152 else if (semantic_idx == 1)
4153 shader_addline(buffer, "gl_FrontSecondaryColor%s = vs_out[%u]%s;\n",
4154 reg_mask, i, reg_mask);
4156 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
4158 shader_addline(buffer, "gl_Position%s = vs_out[%u]%s;\n",
4159 reg_mask, i, reg_mask);
4161 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
4163 if (semantic_idx < 8)
4165 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
4166 write_mask |= WINED3DSP_WRITEMASK_3;
4168 shader_addline(buffer, "gl_TexCoord[%u]%s = vs_out[%u]%s;\n",
4169 semantic_idx, reg_mask, i, reg_mask);
4170 if (!(write_mask & WINED3DSP_WRITEMASK_3))
4171 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
4174 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
4176 shader_addline(buffer, "gl_PointSize = vs_out[%u].%c;\n", i, reg_mask[1]);
4178 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_FOG))
4180 shader_addline(buffer, "gl_FogFragCoord = clamp(vs_out[%u].%c, 0.0, 1.0);\n", i, reg_mask[1]);
4183 shader_addline(buffer, "}\n");
4187 UINT in_count = min(vec4_varyings(ps_major, gl_info), ps->limits.packed_input);
4188 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
4189 shader_addline(buffer, "varying vec4 ps_in[%u];\n", in_count);
4190 shader_addline(buffer, "void order_ps_input(in vec4 vs_out[%u])\n{\n", vs->limits.packed_output);
4192 /* First, sort out position and point size. Those are not passed to the pixel shader */
4193 for (i = 0; map; map >>= 1, ++i)
4195 if (!(map & 1)) continue;
4197 semantic_name = output_signature[i].semantic_name;
4198 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
4200 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
4202 shader_addline(buffer, "gl_Position%s = vs_out[%u]%s;\n",
4203 reg_mask, i, reg_mask);
4205 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
4207 shader_addline(buffer, "gl_PointSize = vs_out[%u].%c;\n", i, reg_mask[1]);
4211 /* Then, fix the pixel shader input */
4212 handle_ps3_input(buffer, gl_info, ps->u.ps.input_reg_map, ps->input_signature,
4213 &ps->reg_maps, output_signature, &vs->reg_maps);
4215 shader_addline(buffer, "}\n");
4218 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4219 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
4220 shader_glsl_compile(gl_info, ret, buffer->buffer);
4225 /* GL locking is done by the caller */
4226 static void hardcode_local_constants(const struct wined3d_shader *shader,
4227 const struct wined3d_gl_info *gl_info, GLhandleARB programId, const char *prefix)
4229 const struct wined3d_shader_lconst *lconst;
4234 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
4236 value = (const float *)lconst->value;
4237 snprintf(glsl_name, sizeof(glsl_name), "%s_lc%u", prefix, lconst->idx);
4238 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4239 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
4241 checkGLcall("Hardcoding local constants");
4244 /* GL locking is done by the caller */
4245 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
4246 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4247 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
4249 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4250 const struct wined3d_gl_info *gl_info = context->gl_info;
4251 const DWORD *function = shader->function;
4252 struct shader_glsl_ctx_priv priv_ctx;
4254 /* Create the hw GLSL shader object and assign it as the shader->prgId */
4255 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4257 memset(&priv_ctx, 0, sizeof(priv_ctx));
4258 priv_ctx.cur_ps_args = args;
4259 priv_ctx.cur_np2fixup_info = np2fixup_info;
4261 shader_addline(buffer, "#version 120\n");
4263 if (gl_info->supported[ARB_SHADER_BIT_ENCODING])
4264 shader_addline(buffer, "#extension GL_ARB_shader_bit_encoding : enable\n");
4265 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
4266 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
4267 /* The spec says that it doesn't have to be explicitly enabled, but the
4268 * nvidia drivers write a warning if we don't do so. */
4269 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4270 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4271 if (gl_info->supported[EXT_GPU_SHADER4])
4272 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4274 /* Base Declarations */
4275 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4277 /* Pack 3.0 inputs */
4278 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4279 shader_glsl_input_pack(shader, buffer, shader->input_signature, reg_maps, args->vp_mode);
4281 /* Base Shader Body */
4282 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4284 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4285 if (reg_maps->shader_version.major < 2)
4287 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4288 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4291 if (args->srgb_correction)
4293 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4294 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4295 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4296 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4297 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4298 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4300 /* Pixel shader < 3.0 do not replace the fog stage.
4301 * This implements linear fog computation and blending.
4302 * TODO: non linear fog
4303 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4304 * -1/(e-s) and e/(e-s) respectively.
4306 if (reg_maps->shader_version.major < 3)
4309 case FOG_OFF: break;
4311 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4312 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4313 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4314 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4317 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4318 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4319 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4320 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4323 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4324 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4325 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4326 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4331 shader_addline(buffer, "}\n");
4333 TRACE("Compiling shader object %u\n", shader_obj);
4334 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4336 /* Store the shader object */
4340 /* GL locking is done by the caller */
4341 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4342 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4343 const struct vs_compile_args *args)
4345 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4346 const struct wined3d_gl_info *gl_info = context->gl_info;
4347 const DWORD *function = shader->function;
4348 struct shader_glsl_ctx_priv priv_ctx;
4350 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4351 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4353 shader_addline(buffer, "#version 120\n");
4355 if (gl_info->supported[ARB_SHADER_BIT_ENCODING])
4356 shader_addline(buffer, "#extension GL_ARB_shader_bit_encoding : enable\n");
4357 if (gl_info->supported[EXT_GPU_SHADER4])
4358 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4360 memset(&priv_ctx, 0, sizeof(priv_ctx));
4361 priv_ctx.cur_vs_args = args;
4363 /* Base Declarations */
4364 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4366 /* Base Shader Body */
4367 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4369 /* Unpack outputs */
4370 shader_addline(buffer, "order_ps_input(vs_out);\n");
4372 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4373 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4374 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4375 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4377 if (args->fog_src == VS_FOG_Z)
4378 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4379 else if (!reg_maps->fog)
4380 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4382 /* We always store the clipplanes without y inversion */
4383 if (args->clip_enabled)
4384 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4386 /* Write the final position.
4388 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4389 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4390 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4391 * contains 1.0 to allow a mad.
4393 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4394 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4396 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4398 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4399 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4400 * which is the same as z = z * 2 - w.
4402 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4404 shader_addline(buffer, "}\n");
4406 TRACE("Compiling shader object %u\n", shader_obj);
4407 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4412 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4413 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4414 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4416 struct wined3d_state *state = &shader->device->stateBlock->state;
4417 struct glsl_ps_compiled_shader *gl_shaders, *new_array;
4418 struct glsl_shader_private *shader_data;
4419 struct ps_np2fixup_info *np2fixup;
4424 if (!shader->backend_data)
4426 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4427 if (!shader->backend_data)
4429 ERR("Failed to allocate backend data.\n");
4433 shader_data = shader->backend_data;
4434 gl_shaders = shader_data->gl_shaders.ps;
4436 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4437 * so a linear search is more performant than a hashmap or a binary search
4438 * (cache coherency etc)
4440 for (i = 0; i < shader_data->num_gl_shaders; ++i)
4442 if (!memcmp(&gl_shaders[i].args, args, sizeof(*args)))
4444 if (args->np2_fixup)
4445 *np2fixup_info = &gl_shaders[i].np2fixup;
4446 return gl_shaders[i].prgId;
4450 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4451 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4452 if (shader_data->num_gl_shaders)
4454 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4455 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders.ps,
4456 new_size * sizeof(*gl_shaders));
4460 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_shaders));
4465 ERR("Out of memory\n");
4468 shader_data->gl_shaders.ps = new_array;
4469 shader_data->shader_array_size = new_size;
4470 gl_shaders = new_array;
4473 gl_shaders[shader_data->num_gl_shaders].args = *args;
4475 np2fixup = &gl_shaders[shader_data->num_gl_shaders].np2fixup;
4476 memset(np2fixup, 0, sizeof(*np2fixup));
4477 *np2fixup_info = args->np2_fixup ? np2fixup : NULL;
4479 pixelshader_update_samplers(&shader->reg_maps, state->textures);
4481 shader_buffer_clear(buffer);
4482 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4483 gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4488 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4489 const DWORD use_map) {
4490 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4491 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4492 return stored->fog_src == new->fog_src;
4495 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4496 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4497 const struct vs_compile_args *args)
4501 DWORD use_map = shader->device->strided_streams.use_map;
4502 struct glsl_vs_compiled_shader *gl_shaders, *new_array;
4503 struct glsl_shader_private *shader_data;
4506 if (!shader->backend_data)
4508 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4509 if (!shader->backend_data)
4511 ERR("Failed to allocate backend data.\n");
4515 shader_data = shader->backend_data;
4516 gl_shaders = shader_data->gl_shaders.vs;
4518 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4519 * so a linear search is more performant than a hashmap or a binary search
4520 * (cache coherency etc)
4522 for (i = 0; i < shader_data->num_gl_shaders; ++i)
4524 if (vs_args_equal(&gl_shaders[i].args, args, use_map))
4525 return gl_shaders[i].prgId;
4528 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4530 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4531 if (shader_data->num_gl_shaders)
4533 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4534 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders.vs,
4535 new_size * sizeof(*gl_shaders));
4539 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_shaders));
4544 ERR("Out of memory\n");
4547 shader_data->gl_shaders.vs = new_array;
4548 shader_data->shader_array_size = new_size;
4549 gl_shaders = new_array;
4552 gl_shaders[shader_data->num_gl_shaders].args = *args;
4554 shader_buffer_clear(buffer);
4555 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4556 gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4561 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4562 * It sets the programId on the current StateBlock (because it should be called
4563 * inside of the DrawPrimitive() part of the render loop).
4565 * If a program for the given combination does not exist, create one, and store
4566 * the program in the hash table. If it creates a program, it will link the
4567 * given objects, too.
4570 /* GL locking is done by the caller */
4571 static void set_glsl_shader_program(const struct wined3d_context *context,
4572 struct wined3d_device *device, BOOL use_ps, BOOL use_vs)
4574 const struct wined3d_state *state = &device->stateBlock->state;
4575 struct wined3d_shader *vshader = use_vs ? state->vertex_shader : NULL;
4576 struct wined3d_shader *pshader = use_ps ? state->pixel_shader : NULL;
4577 const struct wined3d_gl_info *gl_info = context->gl_info;
4578 struct shader_glsl_priv *priv = device->shader_priv;
4579 struct glsl_shader_prog_link *entry = NULL;
4580 GLhandleARB programId = 0;
4581 GLhandleARB reorder_shader_id = 0;
4584 struct ps_compile_args ps_compile_args;
4585 struct vs_compile_args vs_compile_args;
4587 if (vshader) find_vs_compile_args(state, vshader, &vs_compile_args);
4588 if (pshader) find_ps_compile_args(state, pshader, &ps_compile_args);
4590 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4593 priv->glsl_program = entry;
4597 /* If we get to this point, then no matching program exists, so we create one */
4598 programId = GL_EXTCALL(glCreateProgramObjectARB());
4599 TRACE("Created new GLSL shader program %u\n", programId);
4601 /* Create the entry */
4602 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4603 entry->programId = programId;
4604 entry->vshader = vshader;
4605 entry->pshader = pshader;
4606 entry->vs_args = vs_compile_args;
4607 entry->ps_args = ps_compile_args;
4608 entry->constant_version = 0;
4609 entry->np2Fixup_info = NULL;
4610 /* Add the hash table entry */
4611 add_glsl_program_entry(priv, entry);
4613 /* Set the current program */
4614 priv->glsl_program = entry;
4616 /* Attach GLSL vshader */
4619 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer, vshader, &vs_compile_args);
4620 WORD map = vshader->reg_maps.input_registers;
4623 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4624 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4625 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4626 checkGLcall("glAttachObjectARB");
4627 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4630 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4632 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4633 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4634 checkGLcall("glAttachObjectARB");
4636 /* Bind vertex attributes to a corresponding index number to match
4637 * the same index numbers as ARB_vertex_programs (makes loading
4638 * vertex attributes simpler). With this method, we can use the
4639 * exact same code to load the attributes later for both ARB and
4642 * We have to do this here because we need to know the Program ID
4643 * in order to make the bindings work, and it has to be done prior
4644 * to linking the GLSL program. */
4645 for (i = 0; map; map >>= 1, ++i)
4647 if (!(map & 1)) continue;
4649 snprintf(tmp_name, sizeof(tmp_name), "vs_in%u", i);
4650 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4652 checkGLcall("glBindAttribLocationARB");
4654 list_add_head(&vshader->linked_programs, &entry->vshader_entry);
4657 /* Attach GLSL pshader */
4660 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4661 pshader, &ps_compile_args, &entry->np2Fixup_info);
4662 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4663 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4664 checkGLcall("glAttachObjectARB");
4666 list_add_head(&pshader->linked_programs, &entry->pshader_entry);
4669 /* Link the program */
4670 TRACE("Linking GLSL shader program %u\n", programId);
4671 GL_EXTCALL(glLinkProgramARB(programId));
4672 shader_glsl_validate_link(gl_info, programId);
4674 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4675 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4676 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4678 snprintf(glsl_name, sizeof(glsl_name), "vs_c[%u]", i);
4679 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4681 for (i = 0; i < MAX_CONST_I; ++i)
4683 snprintf(glsl_name, sizeof(glsl_name), "vs_i[%u]", i);
4684 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4686 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4687 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4688 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4690 snprintf(glsl_name, sizeof(glsl_name), "ps_c[%u]", i);
4691 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4693 for (i = 0; i < MAX_CONST_I; ++i)
4695 snprintf(glsl_name, sizeof(glsl_name), "ps_i[%u]", i);
4696 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4702 for(i = 0; i < MAX_TEXTURES; i++) {
4703 sprintf(name, "bumpenvmat%u", i);
4704 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4705 sprintf(name, "luminancescale%u", i);
4706 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4707 sprintf(name, "luminanceoffset%u", i);
4708 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4711 if (ps_compile_args.np2_fixup)
4713 if (entry->np2Fixup_info)
4714 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ps_samplerNP2Fixup"));
4716 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4720 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4721 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4722 checkGLcall("Find glsl program uniform locations");
4724 if (pshader && pshader->reg_maps.shader_version.major >= 3
4725 && pshader->u.ps.declared_in_count > vec4_varyings(3, gl_info))
4727 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4728 entry->vertex_color_clamp = GL_FALSE;
4730 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4733 /* Set the shader to allow uniform loading on it */
4734 GL_EXTCALL(glUseProgramObjectARB(programId));
4735 checkGLcall("glUseProgramObjectARB(programId)");
4737 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4738 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4739 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4740 * vertex shader with fixed function pixel processing is used we make sure that the card
4741 * supports enough samplers to allow the max number of vertex samplers with all possible
4742 * fixed function fragment processing setups. So once the program is linked these samplers
4745 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4746 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4748 /* If the local constants do not have to be loaded with the environment constants,
4749 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4752 if (pshader && !pshader->load_local_constsF)
4753 hardcode_local_constants(pshader, gl_info, programId, "ps");
4754 if (vshader && !vshader->load_local_constsF)
4755 hardcode_local_constants(vshader, gl_info, programId, "vs");
4758 /* GL locking is done by the caller */
4759 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
4761 GLhandleARB program_id;
4762 GLhandleARB vshader_id, pshader_id;
4763 const char *blt_pshader;
4765 static const char *blt_vshader =
4769 " gl_Position = gl_Vertex;\n"
4770 " gl_FrontColor = vec4(1.0);\n"
4771 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4774 static const char * const blt_pshaders_full[tex_type_count] =
4780 "uniform sampler2D sampler;\n"
4783 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4789 "uniform samplerCube sampler;\n"
4792 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4796 "#extension GL_ARB_texture_rectangle : enable\n"
4797 "uniform sampler2DRect sampler;\n"
4800 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4804 static const char * const blt_pshaders_masked[tex_type_count] =
4810 "uniform sampler2D sampler;\n"
4811 "uniform vec4 mask;\n"
4814 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4815 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4821 "uniform samplerCube sampler;\n"
4822 "uniform vec4 mask;\n"
4825 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4826 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4830 "#extension GL_ARB_texture_rectangle : enable\n"
4831 "uniform sampler2DRect sampler;\n"
4832 "uniform vec4 mask;\n"
4835 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4836 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4840 blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
4843 FIXME("tex_type %#x not supported\n", tex_type);
4847 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4848 shader_glsl_compile(gl_info, vshader_id, blt_vshader);
4850 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4851 shader_glsl_compile(gl_info, pshader_id, blt_pshader);
4853 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4854 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4855 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4856 GL_EXTCALL(glLinkProgramARB(program_id));
4858 shader_glsl_validate_link(gl_info, program_id);
4860 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4863 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4864 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4868 /* GL locking is done by the caller */
4869 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4871 const struct wined3d_gl_info *gl_info = context->gl_info;
4872 struct wined3d_device *device = context->swapchain->device;
4873 struct shader_glsl_priv *priv = device->shader_priv;
4874 GLhandleARB program_id = 0;
4875 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4877 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4879 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4880 else priv->glsl_program = NULL;
4882 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4884 if (old_vertex_color_clamp != current_vertex_color_clamp)
4886 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4888 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4889 checkGLcall("glClampColorARB");
4893 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4897 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4898 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4899 GL_EXTCALL(glUseProgramObjectARB(program_id));
4900 checkGLcall("glUseProgramObjectARB");
4902 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4903 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4904 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4905 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4907 shader_glsl_load_np2fixup_constants(priv, gl_info, &device->stateBlock->state);
4911 /* GL locking is done by the caller */
4912 static void shader_glsl_select_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info,
4913 enum tex_types tex_type, const SIZE *ds_mask_size)
4915 BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
4916 struct shader_glsl_priv *priv = shader_priv;
4917 GLhandleARB *blt_program;
4920 blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
4923 *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
4924 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4925 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4926 GL_EXTCALL(glUniform1iARB(loc, 0));
4930 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4935 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
4936 GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
4940 /* GL locking is done by the caller */
4941 static void shader_glsl_deselect_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info)
4943 struct shader_glsl_priv *priv = shader_priv;
4944 GLhandleARB program_id;
4946 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4947 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4949 GL_EXTCALL(glUseProgramObjectARB(program_id));
4950 checkGLcall("glUseProgramObjectARB");
4953 static void shader_glsl_destroy(struct wined3d_shader *shader)
4955 struct glsl_shader_private *shader_data = shader->backend_data;
4956 struct wined3d_device *device = shader->device;
4957 struct shader_glsl_priv *priv = device->shader_priv;
4958 const struct wined3d_gl_info *gl_info;
4959 const struct list *linked_programs;
4960 struct wined3d_context *context;
4962 if (!shader_data || !shader_data->num_gl_shaders)
4964 HeapFree(GetProcessHeap(), 0, shader_data);
4965 shader->backend_data = NULL;
4969 context = context_acquire(device, NULL);
4970 gl_info = context->gl_info;
4972 if (priv->glsl_program && (priv->glsl_program->vshader == shader
4973 || priv->glsl_program->pshader == shader))
4976 shader_glsl_select(context, FALSE, FALSE);
4980 TRACE("Deleting linked programs.\n");
4981 linked_programs = &shader->linked_programs;
4982 if (linked_programs->next)
4984 struct glsl_shader_prog_link *entry, *entry2;
4989 switch (shader->reg_maps.shader_version.type)
4991 case WINED3D_SHADER_TYPE_PIXEL:
4993 struct glsl_ps_compiled_shader *gl_shaders = shader_data->gl_shaders.ps;
4995 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs,
4996 struct glsl_shader_prog_link, pshader_entry)
4998 delete_glsl_program_entry(priv, gl_info, entry);
5001 for (i = 0; i < shader_data->num_gl_shaders; ++i)
5003 TRACE("Deleting pixel shader %u.\n", gl_shaders[i].prgId);
5004 GL_EXTCALL(glDeleteObjectARB(gl_shaders[i].prgId));
5005 checkGLcall("glDeleteObjectARB");
5007 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders.ps);
5012 case WINED3D_SHADER_TYPE_VERTEX:
5014 struct glsl_vs_compiled_shader *gl_shaders = shader_data->gl_shaders.vs;
5016 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs,
5017 struct glsl_shader_prog_link, vshader_entry)
5019 delete_glsl_program_entry(priv, gl_info, entry);
5022 for (i = 0; i < shader_data->num_gl_shaders; ++i)
5024 TRACE("Deleting vertex shader %u.\n", gl_shaders[i].prgId);
5025 GL_EXTCALL(glDeleteObjectARB(gl_shaders[i].prgId));
5026 checkGLcall("glDeleteObjectARB");
5028 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders.vs);
5034 ERR("Unhandled shader type %#x.\n", shader->reg_maps.shader_version.type);
5041 HeapFree(GetProcessHeap(), 0, shader->backend_data);
5042 shader->backend_data = NULL;
5044 context_release(context);
5047 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
5049 const struct glsl_program_key *k = key;
5050 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
5051 const struct glsl_shader_prog_link, program_lookup_entry);
5054 if (k->vshader > prog->vshader) return 1;
5055 else if (k->vshader < prog->vshader) return -1;
5057 if (k->pshader > prog->pshader) return 1;
5058 else if (k->pshader < prog->pshader) return -1;
5060 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
5061 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
5066 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
5068 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
5069 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
5073 ERR("Failed to allocate memory\n");
5077 heap->entries = mem;
5078 heap->entries[1].version = 0;
5079 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
5085 static void constant_heap_free(struct constant_heap *heap)
5087 HeapFree(GetProcessHeap(), 0, heap->entries);
5090 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
5095 glsl_program_key_compare,
5098 static HRESULT shader_glsl_alloc(struct wined3d_device *device)
5100 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5101 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
5102 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
5103 gl_info->limits.glsl_ps_float_constants)) + 1;
5105 if (!shader_buffer_init(&priv->shader_buffer))
5107 ERR("Failed to initialize shader buffer.\n");
5111 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
5114 ERR("Failed to allocate memory.\n");
5118 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
5120 ERR("Failed to initialize vertex shader constant heap\n");
5124 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
5126 ERR("Failed to initialize pixel shader constant heap\n");
5130 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
5132 ERR("Failed to initialize rbtree.\n");
5136 priv->next_constant_version = 1;
5138 device->shader_priv = priv;
5142 constant_heap_free(&priv->pconst_heap);
5143 constant_heap_free(&priv->vconst_heap);
5144 HeapFree(GetProcessHeap(), 0, priv->stack);
5145 shader_buffer_free(&priv->shader_buffer);
5146 HeapFree(GetProcessHeap(), 0, priv);
5147 return E_OUTOFMEMORY;
5150 /* Context activation is done by the caller. */
5151 static void shader_glsl_free(struct wined3d_device *device)
5153 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
5154 struct shader_glsl_priv *priv = device->shader_priv;
5158 for (i = 0; i < tex_type_count; ++i)
5160 if (priv->depth_blt_program_full[i])
5162 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
5164 if (priv->depth_blt_program_masked[i])
5166 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
5171 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
5172 constant_heap_free(&priv->pconst_heap);
5173 constant_heap_free(&priv->vconst_heap);
5174 HeapFree(GetProcessHeap(), 0, priv->stack);
5175 shader_buffer_free(&priv->shader_buffer);
5177 HeapFree(GetProcessHeap(), 0, device->shader_priv);
5178 device->shader_priv = NULL;
5181 static void shader_glsl_context_destroyed(void *shader_priv, const struct wined3d_context *context) {}
5183 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
5187 if (gl_info->supported[EXT_GPU_SHADER4] && gl_info->supported[ARB_SHADER_BIT_ENCODING]
5188 && gl_info->supported[ARB_GEOMETRY_SHADER4] && gl_info->glsl_version >= MAKEDWORD_VERSION(1, 50))
5190 /* ARB_shader_texture_lod or EXT_gpu_shader4 is required for the SM3
5191 * texldd and texldl instructions. */
5192 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] || gl_info->supported[EXT_GPU_SHADER4])
5196 TRACE("Shader model %u.\n", shader_model);
5198 caps->vs_version = shader_model;
5199 caps->gs_version = shader_model;
5200 caps->ps_version = shader_model;
5202 caps->vs_uniform_count = gl_info->limits.glsl_vs_float_constants;
5203 caps->ps_uniform_count = gl_info->limits.glsl_ps_float_constants;
5205 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
5206 * Direct3D minimum requirement.
5208 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
5209 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
5211 * The problem is that the refrast clamps temporary results in the shader to
5212 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
5213 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
5214 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
5215 * offer a way to query this.
5217 caps->ps_1x_max_value = 8.0;
5219 caps->vs_clipping = TRUE;
5222 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
5224 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
5226 TRACE("Checking support for fixup:\n");
5227 dump_color_fixup_desc(fixup);
5230 /* We support everything except YUV conversions. */
5231 if (!is_complex_fixup(fixup))
5237 TRACE("[FAILED]\n");
5241 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
5243 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
5244 /* WINED3DSIH_ADD */ shader_glsl_binop,
5245 /* WINED3DSIH_AND */ shader_glsl_binop,
5246 /* WINED3DSIH_BEM */ shader_glsl_bem,
5247 /* WINED3DSIH_BREAK */ shader_glsl_break,
5248 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
5249 /* WINED3DSIH_BREAKP */ shader_glsl_breakp,
5250 /* WINED3DSIH_CALL */ shader_glsl_call,
5251 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
5252 /* WINED3DSIH_CMP */ shader_glsl_cmp,
5253 /* WINED3DSIH_CND */ shader_glsl_cnd,
5254 /* WINED3DSIH_CRS */ shader_glsl_cross,
5255 /* WINED3DSIH_CUT */ shader_glsl_cut,
5256 /* WINED3DSIH_DCL */ shader_glsl_nop,
5257 /* WINED3DSIH_DCL_CONSTANT_BUFFER */ shader_glsl_nop,
5258 /* WINED3DSIH_DCL_INPUT_PRIMITIVE */ shader_glsl_nop,
5259 /* WINED3DSIH_DCL_OUTPUT_TOPOLOGY */ shader_glsl_nop,
5260 /* WINED3DSIH_DCL_VERTICES_OUT */ shader_glsl_nop,
5261 /* WINED3DSIH_DEF */ shader_glsl_nop,
5262 /* WINED3DSIH_DEFB */ shader_glsl_nop,
5263 /* WINED3DSIH_DEFI */ shader_glsl_nop,
5264 /* WINED3DSIH_DIV */ shader_glsl_binop,
5265 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
5266 /* WINED3DSIH_DP3 */ shader_glsl_dot,
5267 /* WINED3DSIH_DP4 */ shader_glsl_dot,
5268 /* WINED3DSIH_DST */ shader_glsl_dst,
5269 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
5270 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
5271 /* WINED3DSIH_ELSE */ shader_glsl_else,
5272 /* WINED3DSIH_EMIT */ shader_glsl_emit,
5273 /* WINED3DSIH_ENDIF */ shader_glsl_end,
5274 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5275 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5276 /* WINED3DSIH_EQ */ shader_glsl_relop,
5277 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5278 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5279 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5280 /* WINED3DSIH_FTOI */ NULL,
5281 /* WINED3DSIH_GE */ shader_glsl_relop,
5282 /* WINED3DSIH_IADD */ shader_glsl_binop,
5283 /* WINED3DSIH_IEQ */ NULL,
5284 /* WINED3DSIH_IF */ shader_glsl_if,
5285 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5286 /* WINED3DSIH_IGE */ shader_glsl_relop,
5287 /* WINED3DSIH_IMUL */ NULL,
5288 /* WINED3DSIH_ITOF */ NULL,
5289 /* WINED3DSIH_LABEL */ shader_glsl_label,
5290 /* WINED3DSIH_LD */ NULL,
5291 /* WINED3DSIH_LIT */ shader_glsl_lit,
5292 /* WINED3DSIH_LOG */ shader_glsl_log,
5293 /* WINED3DSIH_LOGP */ shader_glsl_log,
5294 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5295 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5296 /* WINED3DSIH_LT */ shader_glsl_relop,
5297 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5298 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5299 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5300 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5301 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5302 /* WINED3DSIH_MAD */ shader_glsl_mad,
5303 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5304 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5305 /* WINED3DSIH_MOV */ shader_glsl_mov,
5306 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5307 /* WINED3DSIH_MOVC */ NULL,
5308 /* WINED3DSIH_MUL */ shader_glsl_binop,
5309 /* WINED3DSIH_NOP */ shader_glsl_nop,
5310 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5311 /* WINED3DSIH_PHASE */ shader_glsl_nop,
5312 /* WINED3DSIH_POW */ shader_glsl_pow,
5313 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5314 /* WINED3DSIH_REP */ shader_glsl_rep,
5315 /* WINED3DSIH_RET */ shader_glsl_ret,
5316 /* WINED3DSIH_ROUND_NI */ NULL,
5317 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5318 /* WINED3DSIH_SAMPLE */ NULL,
5319 /* WINED3DSIH_SAMPLE_GRAD */ NULL,
5320 /* WINED3DSIH_SAMPLE_LOD */ NULL,
5321 /* WINED3DSIH_SETP */ NULL,
5322 /* WINED3DSIH_SGE */ shader_glsl_compare,
5323 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5324 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5325 /* WINED3DSIH_SLT */ shader_glsl_compare,
5326 /* WINED3DSIH_SQRT */ NULL,
5327 /* WINED3DSIH_SUB */ shader_glsl_binop,
5328 /* WINED3DSIH_TEX */ shader_glsl_tex,
5329 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5330 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5331 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5332 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5333 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5334 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5335 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5336 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5337 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5338 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5339 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5340 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5341 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5342 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5343 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5344 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5345 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5346 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5347 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5348 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5349 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5350 /* WINED3DSIH_UDIV */ NULL,
5351 /* WINED3DSIH_USHR */ NULL,
5352 /* WINED3DSIH_UTOF */ NULL,
5353 /* WINED3DSIH_XOR */ shader_glsl_binop,
5356 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5357 SHADER_HANDLER hw_fct;
5359 /* Select handler */
5360 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5362 /* Unhandled opcode */
5365 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5370 shader_glsl_add_instruction_modifiers(ins);
5373 const struct wined3d_shader_backend_ops glsl_shader_backend =
5375 shader_glsl_handle_instruction,
5377 shader_glsl_select_depth_blt,
5378 shader_glsl_deselect_depth_blt,
5379 shader_glsl_update_float_vertex_constants,
5380 shader_glsl_update_float_pixel_constants,
5381 shader_glsl_load_constants,
5382 shader_glsl_load_np2fixup_constants,
5383 shader_glsl_destroy,
5386 shader_glsl_context_destroyed,
5387 shader_glsl_get_caps,
5388 shader_glsl_color_fixup_supported,