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_pshader_private
149 struct glsl_ps_compiled_shader *gl_shaders;
150 UINT num_gl_shaders, shader_array_size;
153 struct glsl_vs_compiled_shader
155 struct vs_compile_args args;
159 struct glsl_vshader_private
161 struct glsl_vs_compiled_shader *gl_shaders;
162 UINT num_gl_shaders, shader_array_size;
165 static const char *debug_gl_shader_type(GLenum type)
169 #define WINED3D_TO_STR(u) case u: return #u
170 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
171 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
172 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
173 #undef WINED3D_TO_STR
175 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
179 /* Extract a line from the info log.
180 * Note that this modifies the source string. */
181 static char *get_info_log_line(char **ptr)
186 if (!(q = strstr(p, "\n")))
188 if (!*p) return NULL;
198 /** Prints the GLSL info log which will contain error messages if they exist */
199 /* GL locking is done by the caller */
200 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
202 int infologLength = 0;
205 if (!WARN_ON(d3d_shader) && !FIXME_ON(d3d_shader))
208 GL_EXTCALL(glGetObjectParameterivARB(obj,
209 GL_OBJECT_INFO_LOG_LENGTH_ARB,
212 /* A size of 1 is just a null-terminated string, so the log should be bigger than
213 * that if there are errors. */
214 if (infologLength > 1)
218 infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
219 /* The info log is supposed to be zero-terminated, but at least some
220 * versions of fglrx don't terminate the string properly. The reported
221 * length does include the terminator, so explicitly set it to zero
223 infoLog[infologLength - 1] = 0;
224 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
227 if (gl_info->quirks & WINED3D_QUIRK_INFO_LOG_SPAM)
229 WARN("Info log received from GLSL shader #%u:\n", obj);
230 while ((line = get_info_log_line(&ptr))) WARN(" %s\n", line);
234 FIXME("Info log received from GLSL shader #%u:\n", obj);
235 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
237 HeapFree(GetProcessHeap(), 0, infoLog);
241 /* GL locking is done by the caller. */
242 static void shader_glsl_compile(const struct wined3d_gl_info *gl_info, GLhandleARB shader, const char *src)
244 TRACE("Compiling shader object %u.\n", shader);
245 GL_EXTCALL(glShaderSourceARB(shader, 1, &src, NULL));
246 checkGLcall("glShaderSourceARB");
247 GL_EXTCALL(glCompileShaderARB(shader));
248 checkGLcall("glCompileShaderARB");
249 print_glsl_info_log(gl_info, shader);
252 /* GL locking is done by the caller. */
253 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
255 GLint i, object_count, source_size = -1;
256 GLhandleARB *objects;
259 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
260 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
263 ERR("Failed to allocate object array memory.\n");
267 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
268 for (i = 0; i < object_count; ++i)
273 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
275 if (source_size < tmp)
277 HeapFree(GetProcessHeap(), 0, source);
279 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
282 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
283 HeapFree(GetProcessHeap(), 0, objects);
289 FIXME("Object %u:\n", objects[i]);
290 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
291 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
292 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
293 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
297 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
298 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
302 HeapFree(GetProcessHeap(), 0, source);
303 HeapFree(GetProcessHeap(), 0, objects);
306 /* GL locking is done by the caller. */
307 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
311 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
313 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
314 if (tmp == GL_PROGRAM_OBJECT_ARB)
316 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
319 FIXME("Program %u link status invalid.\n", program);
320 shader_glsl_dump_program_source(gl_info, program);
324 print_glsl_info_log(gl_info, program);
328 * Loads (pixel shader) samplers
330 /* GL locking is done by the caller */
331 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
332 const DWORD *tex_unit_map, GLhandleARB programId)
336 char sampler_name[20];
338 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
339 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
340 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
341 if (name_loc != -1) {
342 DWORD mapped_unit = tex_unit_map[i];
343 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
345 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
346 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
347 checkGLcall("glUniform1iARB");
349 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
355 /* GL locking is done by the caller */
356 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
357 const DWORD *tex_unit_map, GLhandleARB programId)
360 char sampler_name[20];
363 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
364 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
365 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
366 if (name_loc != -1) {
367 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
368 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
370 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
371 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
372 checkGLcall("glUniform1iARB");
374 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
380 /* GL locking is done by the caller */
381 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
382 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
385 unsigned int heap_idx = 1;
388 if (heap->entries[heap_idx].version <= version) return;
390 idx = heap->entries[heap_idx].idx;
391 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
392 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
394 while (stack_idx >= 0)
396 /* Note that we fall through to the next case statement. */
397 switch(stack[stack_idx])
399 case HEAP_NODE_TRAVERSE_LEFT:
401 unsigned int left_idx = heap_idx << 1;
402 if (left_idx < heap->size && heap->entries[left_idx].version > version)
405 idx = heap->entries[heap_idx].idx;
406 if (constant_locations[idx] != -1)
407 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
409 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
410 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
415 case HEAP_NODE_TRAVERSE_RIGHT:
417 unsigned int right_idx = (heap_idx << 1) + 1;
418 if (right_idx < heap->size && heap->entries[right_idx].version > version)
420 heap_idx = right_idx;
421 idx = heap->entries[heap_idx].idx;
422 if (constant_locations[idx] != -1)
423 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
425 stack[stack_idx++] = HEAP_NODE_POP;
426 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
437 checkGLcall("walk_constant_heap()");
440 /* GL locking is done by the caller */
441 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
443 GLfloat clamped_constant[4];
445 if (location == -1) return;
447 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
448 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
449 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
450 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
452 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
455 /* GL locking is done by the caller */
456 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
457 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
460 unsigned int heap_idx = 1;
463 if (heap->entries[heap_idx].version <= version) return;
465 idx = heap->entries[heap_idx].idx;
466 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
467 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
469 while (stack_idx >= 0)
471 /* Note that we fall through to the next case statement. */
472 switch(stack[stack_idx])
474 case HEAP_NODE_TRAVERSE_LEFT:
476 unsigned int left_idx = heap_idx << 1;
477 if (left_idx < heap->size && heap->entries[left_idx].version > version)
480 idx = heap->entries[heap_idx].idx;
481 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
483 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
484 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
489 case HEAP_NODE_TRAVERSE_RIGHT:
491 unsigned int right_idx = (heap_idx << 1) + 1;
492 if (right_idx < heap->size && heap->entries[right_idx].version > version)
494 heap_idx = right_idx;
495 idx = heap->entries[heap_idx].idx;
496 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
498 stack[stack_idx++] = HEAP_NODE_POP;
499 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
510 checkGLcall("walk_constant_heap_clamped()");
513 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
514 /* GL locking is done by the caller */
515 static void shader_glsl_load_constantsF(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
516 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
517 unsigned char *stack, UINT version)
519 const struct wined3d_shader_lconst *lconst;
521 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
522 if (shader->reg_maps.shader_version.major == 1
523 && shader_is_pshader_version(shader->reg_maps.shader_version.type))
524 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
526 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
528 if (!shader->load_local_constsF)
530 TRACE("No need to load local float constants for this shader\n");
534 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
535 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
537 GLint location = constant_locations[lconst->idx];
538 /* We found this uniform name in the program - go ahead and send the data */
539 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
541 checkGLcall("glUniform4fvARB()");
544 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
545 /* GL locking is done by the caller */
546 static void shader_glsl_load_constantsI(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
547 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
552 for (i = 0; constants_set; constants_set >>= 1, ++i)
554 if (!(constants_set & 1)) continue;
556 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
557 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
559 /* We found this uniform name in the program - go ahead and send the data */
560 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
561 checkGLcall("glUniform4ivARB");
564 /* Load immediate constants */
565 ptr = list_head(&shader->constantsI);
568 const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
569 unsigned int idx = lconst->idx;
570 const GLint *values = (const GLint *)lconst->value;
572 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
573 values[0], values[1], values[2], values[3]);
575 /* We found this uniform name in the program - go ahead and send the data */
576 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
577 checkGLcall("glUniform4ivARB");
578 ptr = list_next(&shader->constantsI, ptr);
582 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
583 /* GL locking is done by the caller */
584 static void shader_glsl_load_constantsB(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
585 GLhandleARB programId, const BOOL *constants, WORD constants_set)
593 switch (shader->reg_maps.shader_version.type)
595 case WINED3D_SHADER_TYPE_VERTEX:
599 case WINED3D_SHADER_TYPE_GEOMETRY:
603 case WINED3D_SHADER_TYPE_PIXEL:
608 FIXME("Unknown shader type %#x.\n",
609 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[%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[%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;
907 /* There are some minor differences between pixel and vertex shaders */
908 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
909 char prefix = pshader ? 'P' : 'V';
911 /* Prototype the subroutines */
912 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
914 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
917 /* Declare the constants (aka uniforms) */
918 if (shader->limits.constant_float > 0)
920 unsigned max_constantsF;
921 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
922 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
923 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
924 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
925 * a dx9 card, as long as it doesn't also use all the other constants.
927 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
928 * declare only the amount that we're assured to have.
930 * Thus we run into problems in these two cases:
931 * 1) The shader really uses more uniforms than supported
932 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
936 /* No indirect addressing here. */
937 max_constantsF = gl_info->limits.glsl_ps_float_constants;
941 if (reg_maps->usesrelconstF)
943 /* Subtract the other potential uniforms from the max
944 * available (bools, ints, and 1 row of projection matrix).
945 * Subtract another uniform for immediate values, which have
946 * to be loaded via uniform by the driver as well. The shader
947 * code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex
948 * shader code, so one vec4 should be enough. (Unfortunately
949 * the Nvidia driver doesn't store 128 and -128 in one float).
951 * Writing gl_ClipVertex requires one uniform for each
952 * clipplane as well. */
953 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
954 if(ctx_priv->cur_vs_args->clip_enabled)
956 max_constantsF -= gl_info->limits.clipplanes;
958 max_constantsF -= count_bits(reg_maps->integer_constants);
959 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
960 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
961 * for now take this into account when calculating the number of available constants
963 max_constantsF -= count_bits(reg_maps->boolean_constants);
964 /* Set by driver quirks in directx.c */
965 max_constantsF -= gl_info->reserved_glsl_constants;
967 if (max_constantsF < shader->limits.constant_float)
969 static unsigned int once;
972 ERR_(winediag)("The hardware does not support enough uniform components to run this shader,"
973 " it may not render correctly.\n");
975 WARN("The hardware does not support enough uniform components to run this shader.\n");
980 max_constantsF = gl_info->limits.glsl_vs_float_constants;
983 max_constantsF = min(shader->limits.constant_float, max_constantsF);
984 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
987 /* Always declare the full set of constants, the compiler can remove the
988 * unused ones because d3d doesn't (yet) support indirect int and bool
989 * constant addressing. This avoids problems if the app uses e.g. i0 and i9. */
990 if (shader->limits.constant_int > 0 && reg_maps->integer_constants)
991 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, shader->limits.constant_int);
993 if (shader->limits.constant_bool > 0 && reg_maps->boolean_constants)
994 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, shader->limits.constant_bool);
998 shader_addline(buffer, "uniform vec4 posFixup;\n");
999 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
1003 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1005 if (!(map & 1)) continue;
1007 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1009 if (reg_maps->luminanceparams & (1 << i))
1011 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1012 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1013 extra_constants_needed++;
1016 extra_constants_needed++;
1019 if (ps_args->srgb_correction)
1021 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1022 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1023 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1026 if (reg_maps->vpos || reg_maps->usesdsy)
1028 if (shader->limits.constant_float + extra_constants_needed
1029 + 1 < gl_info->limits.glsl_ps_float_constants)
1031 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1032 extra_constants_needed++;
1036 /* This happens because we do not have proper tracking of the constant registers that are
1037 * actually used, only the max limit of the shader version
1039 FIXME("Cannot find a free uniform for vpos correction params\n");
1040 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1041 context->render_offscreen ? 0.0f : fb->render_targets[0]->resource.height,
1042 context->render_offscreen ? 1.0f : -1.0f);
1044 shader_addline(buffer, "vec4 vpos;\n");
1048 /* Declare texture samplers */
1049 for (i = 0; i < shader->limits.sampler; ++i)
1051 if (reg_maps->sampler_type[i])
1053 const struct wined3d_texture *texture;
1055 switch (reg_maps->sampler_type[i])
1058 if (pshader && ps_args->shadow & (1 << i))
1059 shader_addline(buffer, "uniform sampler1DShadow %csampler%u;\n", prefix, i);
1061 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1064 texture = state->textures[i];
1065 if (pshader && ps_args->shadow & (1 << i))
1067 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1068 shader_addline(buffer, "uniform sampler2DRectShadow %csampler%u;\n", prefix, i);
1070 shader_addline(buffer, "uniform sampler2DShadow %csampler%u;\n", prefix, i);
1074 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1075 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1077 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1080 case WINED3DSTT_CUBE:
1081 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported Cube shadow sampler.\n");
1082 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1084 case WINED3DSTT_VOLUME:
1085 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported 3D shadow sampler.\n");
1086 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1089 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1090 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1096 /* Declare uniforms for NP2 texcoord fixup:
1097 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1098 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1099 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1100 if (pshader && ps_args->np2_fixup) {
1102 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1105 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1106 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1107 * samplerNP2Fixup stores texture dimensions and is updated through
1108 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1110 for (i = 0; i < shader->limits.sampler; ++i)
1112 if (reg_maps->sampler_type[i])
1114 if (!(ps_args->np2_fixup & (1 << i))) continue;
1116 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1117 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1121 fixup->idx[i] = cur++;
1125 fixup->num_consts = (cur + 1) >> 1;
1126 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1129 /* Declare address variables */
1130 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1132 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1135 /* Declare texture coordinate temporaries and initialize them */
1136 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1138 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1141 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1142 * helper function shader that is linked in at link time
1144 if (pshader && reg_maps->shader_version.major >= 3)
1146 UINT in_count = min(vec4_varyings(reg_maps->shader_version.major, gl_info), shader->limits.packed_input);
1149 shader_addline(buffer, "varying vec4 IN[%u];\n", in_count);
1151 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1152 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1153 * pixel shader that reads the fixed function color into the packed input registers. */
1154 shader_addline(buffer, "vec4 IN[%u];\n", in_count);
1157 /* Declare output register temporaries */
1158 if (shader->limits.packed_output)
1159 shader_addline(buffer, "vec4 OUT[%u];\n", shader->limits.packed_output);
1161 /* Declare temporary variables */
1162 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1164 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1167 /* Declare attributes */
1168 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1170 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1172 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1176 /* Declare loop registers aLx */
1177 for (i = 0; i < reg_maps->loop_depth; i++) {
1178 shader_addline(buffer, "int aL%u;\n", i);
1179 shader_addline(buffer, "int tmpInt%u;\n", i);
1182 /* Temporary variables for matrix operations */
1183 shader_addline(buffer, "vec4 tmp0;\n");
1184 shader_addline(buffer, "vec4 tmp1;\n");
1186 /* Local constants use a different name so they can be loaded once at shader link time
1187 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1188 * float -> string conversion can cause precision loss.
1190 if (!shader->load_local_constsF)
1192 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
1194 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1198 /* Start the main program */
1199 shader_addline(buffer, "void main() {\n");
1200 if(pshader && reg_maps->vpos) {
1201 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1202 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1203 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1204 * precision troubles when we just subtract 0.5.
1206 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1208 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1210 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1211 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1212 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1213 * correctly on drivers that returns integer values.
1215 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1219 /*****************************************************************************
1220 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1222 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1223 ****************************************************************************/
1226 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1227 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src);
1229 /** Used for opcode modifiers - They multiply the result by the specified amount */
1230 static const char * const shift_glsl_tab[] = {
1232 "2.0 * ", /* 1 (x2) */
1233 "4.0 * ", /* 2 (x4) */
1234 "8.0 * ", /* 3 (x8) */
1235 "16.0 * ", /* 4 (x16) */
1236 "32.0 * ", /* 5 (x32) */
1243 "0.0625 * ", /* 12 (d16) */
1244 "0.125 * ", /* 13 (d8) */
1245 "0.25 * ", /* 14 (d4) */
1246 "0.5 * " /* 15 (d2) */
1249 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1250 static void shader_glsl_gen_modifier(enum wined3d_shader_src_modifier src_modifier,
1251 const char *in_reg, const char *in_regswizzle, char *out_str)
1255 switch (src_modifier)
1257 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1258 case WINED3DSPSM_DW:
1259 case WINED3DSPSM_NONE:
1260 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1262 case WINED3DSPSM_NEG:
1263 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1265 case WINED3DSPSM_NOT:
1266 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1268 case WINED3DSPSM_BIAS:
1269 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1271 case WINED3DSPSM_BIASNEG:
1272 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1274 case WINED3DSPSM_SIGN:
1275 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1277 case WINED3DSPSM_SIGNNEG:
1278 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1280 case WINED3DSPSM_COMP:
1281 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1283 case WINED3DSPSM_X2:
1284 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1286 case WINED3DSPSM_X2NEG:
1287 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1289 case WINED3DSPSM_ABS:
1290 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1292 case WINED3DSPSM_ABSNEG:
1293 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1296 FIXME("Unhandled modifier %u\n", src_modifier);
1297 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1301 /** Writes the GLSL variable name that corresponds to the register that the
1302 * DX opcode parameter is trying to access */
1303 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1304 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1306 /* oPos, oFog and oPts in D3D */
1307 static const char * const hwrastout_reg_names[] = {"OUT[10]", "OUT[11].x", "OUT[11].y"};
1309 const struct wined3d_shader *shader = ins->ctx->shader;
1310 const struct wined3d_shader_reg_maps *reg_maps = ins->ctx->reg_maps;
1311 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1312 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
1318 case WINED3DSPR_TEMP:
1319 sprintf(register_name, "R%u", reg->idx);
1322 case WINED3DSPR_INPUT:
1323 /* vertex shaders */
1326 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1327 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1328 sprintf(register_name, "attrib%u", reg->idx);
1332 /* pixel shaders >= 3.0 */
1333 if (reg_maps->shader_version.major >= 3)
1335 DWORD idx = shader->u.ps.input_reg_map[reg->idx];
1336 unsigned int in_count = vec4_varyings(reg_maps->shader_version.major, gl_info);
1340 struct glsl_src_param rel_param;
1342 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1344 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1345 * operation there */
1348 if (shader->u.ps.declared_in_count > in_count)
1350 sprintf(register_name,
1351 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1352 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1353 rel_param.param_str, idx);
1357 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1362 if (shader->u.ps.declared_in_count > in_count)
1364 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1365 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1366 rel_param.param_str);
1370 sprintf(register_name, "IN[%s]", rel_param.param_str);
1376 if (idx == in_count) sprintf(register_name, "gl_Color");
1377 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1378 else sprintf(register_name, "IN[%u]", idx);
1383 if (!reg->idx) strcpy(register_name, "gl_Color");
1384 else strcpy(register_name, "gl_SecondaryColor");
1389 case WINED3DSPR_CONST:
1391 const char prefix = pshader ? 'P' : 'V';
1393 /* Relative addressing */
1396 struct glsl_src_param rel_param;
1397 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1398 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1399 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1403 if (shader_constant_is_local(shader, reg->idx))
1404 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1406 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1411 case WINED3DSPR_CONSTINT:
1412 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1413 else sprintf(register_name, "VI[%u]", reg->idx);
1416 case WINED3DSPR_CONSTBOOL:
1417 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1418 else sprintf(register_name, "VB[%u]", reg->idx);
1421 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1422 if (pshader) sprintf(register_name, "T%u", reg->idx);
1423 else sprintf(register_name, "A%u", reg->idx);
1426 case WINED3DSPR_LOOP:
1427 sprintf(register_name, "aL%u", ins->ctx->loop_state->current_reg - 1);
1430 case WINED3DSPR_SAMPLER:
1431 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1432 else sprintf(register_name, "Vsampler%u", reg->idx);
1435 case WINED3DSPR_COLOROUT:
1436 if (reg->idx >= gl_info->limits.buffers)
1437 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1439 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1442 case WINED3DSPR_RASTOUT:
1443 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1446 case WINED3DSPR_DEPTHOUT:
1447 sprintf(register_name, "gl_FragDepth");
1450 case WINED3DSPR_ATTROUT:
1451 if (!reg->idx) sprintf(register_name, "OUT[8]");
1452 else sprintf(register_name, "OUT[9]");
1455 case WINED3DSPR_TEXCRDOUT:
1456 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1457 sprintf(register_name, "OUT[%u]", reg->idx);
1460 case WINED3DSPR_MISCTYPE:
1464 sprintf(register_name, "vpos");
1466 else if (reg->idx == 1)
1468 /* Note that gl_FrontFacing is a bool, while vFace is
1469 * a float for which the sign determines front/back */
1470 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1474 FIXME("Unhandled misctype register %d\n", reg->idx);
1475 sprintf(register_name, "unrecognized_register");
1479 case WINED3DSPR_IMMCONST:
1480 switch (reg->immconst_type)
1482 case WINED3D_IMMCONST_SCALAR:
1483 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1486 case WINED3D_IMMCONST_VEC4:
1487 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1488 *(const float *)®->immconst_data[0], *(const float *)®->immconst_data[1],
1489 *(const float *)®->immconst_data[2], *(const float *)®->immconst_data[3]);
1493 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1494 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1499 FIXME("Unhandled register name Type(%d)\n", reg->type);
1500 sprintf(register_name, "unrecognized_register");
1505 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1508 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1509 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1510 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1511 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1515 /* Get the GLSL write mask for the destination register */
1516 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1518 DWORD mask = param->write_mask;
1520 if (shader_is_scalar(¶m->reg))
1522 mask = WINED3DSP_WRITEMASK_0;
1527 shader_glsl_write_mask_to_str(mask, write_mask);
1533 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1534 unsigned int size = 0;
1536 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1537 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1538 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1539 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1544 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1546 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1547 * but addressed as "rgba". To fix this we need to swap the register's x
1548 * and z components. */
1549 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1552 /* swizzle bits fields: wwzzyyxx */
1553 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1554 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1555 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1556 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1560 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1561 BOOL fixup, DWORD mask, char *swizzle_str)
1563 if (shader_is_scalar(¶m->reg))
1564 *swizzle_str = '\0';
1566 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1569 /* From a given parameter token, generate the corresponding GLSL string.
1570 * Also, return the actual register name and swizzle in case the
1571 * caller needs this information as well. */
1572 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1573 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src)
1575 BOOL is_color = FALSE;
1576 char swizzle_str[6];
1578 glsl_src->reg_name[0] = '\0';
1579 glsl_src->param_str[0] = '\0';
1580 swizzle_str[0] = '\0';
1582 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1583 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1584 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1587 /* From a given parameter token, generate the corresponding GLSL string.
1588 * Also, return the actual register name and swizzle in case the
1589 * caller needs this information as well. */
1590 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1591 const struct wined3d_shader_dst_param *wined3d_dst, struct glsl_dst_param *glsl_dst)
1593 BOOL is_color = FALSE;
1595 glsl_dst->mask_str[0] = '\0';
1596 glsl_dst->reg_name[0] = '\0';
1598 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1599 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1602 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1603 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1604 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1606 struct glsl_dst_param glsl_dst;
1609 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1610 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1615 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1616 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1618 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1621 /** Process GLSL instruction modifiers */
1622 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1624 struct glsl_dst_param dst_param;
1627 if (!ins->dst_count) return;
1629 modifiers = ins->dst[0].modifiers;
1630 if (!modifiers) return;
1632 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1634 if (modifiers & WINED3DSPDM_SATURATE)
1636 /* _SAT means to clamp the value of the register to between 0 and 1 */
1637 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1638 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1641 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1643 FIXME("_centroid modifier not handled\n");
1646 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1648 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1652 static const char *shader_glsl_get_rel_op(enum wined3d_shader_rel_op op)
1656 case WINED3D_SHADER_REL_OP_GT: return ">";
1657 case WINED3D_SHADER_REL_OP_EQ: return "==";
1658 case WINED3D_SHADER_REL_OP_GE: return ">=";
1659 case WINED3D_SHADER_REL_OP_LT: return "<";
1660 case WINED3D_SHADER_REL_OP_NE: return "!=";
1661 case WINED3D_SHADER_REL_OP_LE: return "<=";
1663 FIXME("Unrecognized operator %#x.\n", op);
1668 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1669 DWORD sampler_idx, DWORD flags, struct glsl_sample_function *sample_function)
1671 enum wined3d_sampler_texture_type sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1672 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1673 BOOL shadow = shader_is_pshader_version(ctx->reg_maps->shader_version.type)
1674 && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1675 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1676 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1677 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1678 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1680 /* Note that there's no such thing as a projected cube texture. */
1681 switch(sampler_type) {
1687 sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1691 if (gl_info->supported[EXT_GPU_SHADER4])
1692 sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1693 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1694 sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1697 FIXME("Unsupported 1D shadow grad function.\n");
1698 sample_function->name = "unsupported1DGrad";
1703 sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1705 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1711 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1715 if (gl_info->supported[EXT_GPU_SHADER4])
1716 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1717 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1718 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1721 FIXME("Unsupported 1D grad function.\n");
1722 sample_function->name = "unsupported1DGrad";
1727 sample_function->name = projected ? "texture1DProj" : "texture1D";
1729 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1740 sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1744 if (gl_info->supported[EXT_GPU_SHADER4])
1745 sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1746 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1747 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1750 FIXME("Unsupported RECT shadow grad function.\n");
1751 sample_function->name = "unsupported2DRectGrad";
1756 sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1763 sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1767 if (gl_info->supported[EXT_GPU_SHADER4])
1768 sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1769 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1770 sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1773 FIXME("Unsupported 2D shadow grad function.\n");
1774 sample_function->name = "unsupported2DGrad";
1779 sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1782 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1790 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1794 if (gl_info->supported[EXT_GPU_SHADER4])
1795 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1796 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1797 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1800 FIXME("Unsupported RECT grad function.\n");
1801 sample_function->name = "unsupported2DRectGrad";
1806 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1813 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1817 if (gl_info->supported[EXT_GPU_SHADER4])
1818 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1819 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1820 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1823 FIXME("Unsupported 2D grad function.\n");
1824 sample_function->name = "unsupported2DGrad";
1829 sample_function->name = projected ? "texture2DProj" : "texture2D";
1832 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1836 case WINED3DSTT_CUBE:
1839 FIXME("Unsupported Cube shadow function.\n");
1840 sample_function->name = "unsupportedCubeShadow";
1841 sample_function->coord_mask = 0;
1847 sample_function->name = "textureCubeLod";
1851 if (gl_info->supported[EXT_GPU_SHADER4])
1852 sample_function->name = "textureCubeGrad";
1853 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1854 sample_function->name = "textureCubeGradARB";
1857 FIXME("Unsupported Cube grad function.\n");
1858 sample_function->name = "unsupportedCubeGrad";
1863 sample_function->name = "textureCube";
1865 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1869 case WINED3DSTT_VOLUME:
1872 FIXME("Unsupported 3D shadow function.\n");
1873 sample_function->name = "unsupported3DShadow";
1874 sample_function->coord_mask = 0;
1880 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1884 if (gl_info->supported[EXT_GPU_SHADER4])
1885 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1886 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1887 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1890 FIXME("Unsupported 3D grad function.\n");
1891 sample_function->name = "unsupported3DGrad";
1896 sample_function->name = projected ? "texture3DProj" : "texture3D";
1898 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1903 sample_function->name = "";
1904 sample_function->coord_mask = 0;
1905 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1910 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1911 BOOL sign_fixup, enum fixup_channel_source channel_source)
1913 switch(channel_source)
1915 case CHANNEL_SOURCE_ZERO:
1916 strcat(arguments, "0.0");
1919 case CHANNEL_SOURCE_ONE:
1920 strcat(arguments, "1.0");
1923 case CHANNEL_SOURCE_X:
1924 strcat(arguments, reg_name);
1925 strcat(arguments, ".x");
1928 case CHANNEL_SOURCE_Y:
1929 strcat(arguments, reg_name);
1930 strcat(arguments, ".y");
1933 case CHANNEL_SOURCE_Z:
1934 strcat(arguments, reg_name);
1935 strcat(arguments, ".z");
1938 case CHANNEL_SOURCE_W:
1939 strcat(arguments, reg_name);
1940 strcat(arguments, ".w");
1944 FIXME("Unhandled channel source %#x\n", channel_source);
1945 strcat(arguments, "undefined");
1949 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1952 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1954 struct wined3d_shader_dst_param dst;
1955 unsigned int mask_size, remaining;
1956 struct glsl_dst_param dst_param;
1957 char arguments[256];
1961 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1962 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1963 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1964 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1965 mask &= ins->dst[0].write_mask;
1967 if (!mask) return; /* Nothing to do */
1969 if (is_complex_fixup(fixup))
1971 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
1972 FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
1976 mask_size = shader_glsl_get_write_mask_size(mask);
1979 dst.write_mask = mask;
1980 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1982 arguments[0] = '\0';
1983 remaining = mask_size;
1984 if (mask & WINED3DSP_WRITEMASK_0)
1986 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1987 if (--remaining) strcat(arguments, ", ");
1989 if (mask & WINED3DSP_WRITEMASK_1)
1991 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1992 if (--remaining) strcat(arguments, ", ");
1994 if (mask & WINED3DSP_WRITEMASK_2)
1996 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1997 if (--remaining) strcat(arguments, ", ");
1999 if (mask & WINED3DSP_WRITEMASK_3)
2001 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
2002 if (--remaining) strcat(arguments, ", ");
2007 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
2008 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
2012 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
2016 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2017 DWORD sampler, const struct glsl_sample_function *sample_function, DWORD swizzle,
2018 const char *dx, const char *dy, const char *bias, const char *coord_reg_fmt, ...)
2020 const char *sampler_base;
2021 char dst_swizzle[6];
2022 struct color_fixup_desc fixup;
2023 BOOL np2_fixup = FALSE;
2026 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2028 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2030 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2031 fixup = priv->cur_ps_args->color_fixup[sampler];
2032 sampler_base = "Psampler";
2034 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2036 FIXME("Biased sampling from NP2 textures is unsupported\n");
2042 sampler_base = "Vsampler";
2043 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2046 shader_glsl_append_dst(ins->ctx->buffer, ins);
2048 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2050 va_start(args, coord_reg_fmt);
2051 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2055 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2058 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2059 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2061 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2062 (idx % 2) ? "zw" : "xy", dst_swizzle);
2063 } else if(dx && dy) {
2064 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2066 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2070 if(!is_identity_fixup(fixup)) {
2071 shader_glsl_color_correction(ins, fixup);
2075 /*****************************************************************************
2076 * Begin processing individual instruction opcodes
2077 ****************************************************************************/
2079 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
2080 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
2082 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2083 struct glsl_src_param src0_param;
2084 struct glsl_src_param src1_param;
2088 /* Determine the GLSL operator to use based on the opcode */
2089 switch (ins->handler_idx)
2091 case WINED3DSIH_MUL: op = '*'; break;
2092 case WINED3DSIH_ADD: op = '+'; break;
2093 case WINED3DSIH_SUB: op = '-'; break;
2096 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2100 write_mask = shader_glsl_append_dst(buffer, ins);
2101 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2102 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2103 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2106 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2107 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2109 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2110 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2111 struct glsl_src_param src0_param;
2114 write_mask = shader_glsl_append_dst(buffer, ins);
2115 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2117 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2118 * shader versions WINED3DSIO_MOVA is used for this. */
2119 if (ins->ctx->reg_maps->shader_version.major == 1
2120 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2121 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2123 /* This is a simple floor() */
2124 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2125 if (mask_size > 1) {
2126 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2128 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2131 else if(ins->handler_idx == WINED3DSIH_MOVA)
2133 /* We need to *round* to the nearest int here. */
2134 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2136 if (gl_info->supported[EXT_GPU_SHADER4])
2139 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2141 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2146 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2147 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2149 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2150 src0_param.param_str, src0_param.param_str);
2155 shader_addline(buffer, "%s);\n", src0_param.param_str);
2159 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2160 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2162 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2163 struct glsl_src_param src0_param;
2164 struct glsl_src_param src1_param;
2165 DWORD dst_write_mask, src_write_mask;
2166 unsigned int dst_size = 0;
2168 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2169 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2171 /* dp3 works on vec3, dp4 on vec4 */
2172 if (ins->handler_idx == WINED3DSIH_DP4)
2174 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2176 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2179 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2180 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2183 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2185 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2189 /* Note that this instruction has some restrictions. The destination write mask
2190 * can't contain the w component, and the source swizzles have to be .xyzw */
2191 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2193 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2194 struct glsl_src_param src0_param;
2195 struct glsl_src_param src1_param;
2198 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2199 shader_glsl_append_dst(ins->ctx->buffer, ins);
2200 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2201 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2202 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2205 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2206 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2207 * GLSL uses the value as-is. */
2208 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2210 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2211 struct glsl_src_param src0_param;
2212 struct glsl_src_param src1_param;
2213 DWORD dst_write_mask;
2214 unsigned int dst_size;
2216 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2217 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2219 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2220 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2224 shader_addline(buffer, "vec%u(%s == 0.0 ? 1.0 : pow(abs(%s), %s)));\n",
2225 dst_size, src1_param.param_str, src0_param.param_str, src1_param.param_str);
2229 shader_addline(buffer, "%s == 0.0 ? 1.0 : pow(abs(%s), %s));\n",
2230 src1_param.param_str, src0_param.param_str, src1_param.param_str);
2234 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2235 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2236 * GLSL uses the value as-is. */
2237 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2239 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2240 struct glsl_src_param src0_param;
2241 DWORD dst_write_mask;
2242 unsigned int dst_size;
2244 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2245 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2247 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2251 shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2252 dst_size, src0_param.param_str);
2256 shader_addline(buffer, "log2(abs(%s)));\n",
2257 src0_param.param_str);
2261 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2262 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2264 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2265 struct glsl_src_param src_param;
2266 const char *instruction;
2270 /* Determine the GLSL function to use based on the opcode */
2271 /* TODO: Possibly make this a table for faster lookups */
2272 switch (ins->handler_idx)
2274 case WINED3DSIH_MIN: instruction = "min"; break;
2275 case WINED3DSIH_MAX: instruction = "max"; break;
2276 case WINED3DSIH_ABS: instruction = "abs"; break;
2277 case WINED3DSIH_FRC: instruction = "fract"; break;
2278 case WINED3DSIH_EXP: instruction = "exp2"; break;
2279 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2280 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2281 default: instruction = "";
2282 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2286 write_mask = shader_glsl_append_dst(buffer, ins);
2288 shader_addline(buffer, "%s(", instruction);
2292 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2293 shader_addline(buffer, "%s", src_param.param_str);
2294 for (i = 1; i < ins->src_count; ++i)
2296 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2297 shader_addline(buffer, ", %s", src_param.param_str);
2301 shader_addline(buffer, "));\n");
2304 static void shader_glsl_nop(const struct wined3d_shader_instruction *ins) {}
2306 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2308 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2309 struct glsl_src_param src_param;
2310 unsigned int mask_size;
2314 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2315 mask_size = shader_glsl_get_write_mask_size(write_mask);
2316 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2318 shader_addline(buffer, "tmp0.x = dot(%s, %s);\n",
2319 src_param.param_str, src_param.param_str);
2320 shader_glsl_append_dst(buffer, ins);
2324 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s * inversesqrt(tmp0.x)));\n",
2325 mask_size, src_param.param_str);
2329 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s * inversesqrt(tmp0.x)));\n",
2330 src_param.param_str);
2334 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2335 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2336 * dst.x = 2^(floor(src))
2337 * dst.y = src - floor(src)
2338 * dst.z = 2^src (partial precision is allowed, but optional)
2340 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2341 * dst = 2^src; (partial precision is allowed, but optional)
2343 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2345 struct glsl_src_param src_param;
2347 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2349 if (ins->ctx->reg_maps->shader_version.major < 2)
2353 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2354 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2355 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2356 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2358 shader_glsl_append_dst(ins->ctx->buffer, ins);
2359 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2360 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2363 unsigned int mask_size;
2365 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2366 mask_size = shader_glsl_get_write_mask_size(write_mask);
2368 if (mask_size > 1) {
2369 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2371 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2376 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2377 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2379 struct glsl_src_param src_param;
2381 unsigned int mask_size;
2383 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2384 mask_size = shader_glsl_get_write_mask_size(write_mask);
2385 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2389 shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2390 mask_size, src_param.param_str);
2394 shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2395 src_param.param_str);
2399 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2401 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2402 struct glsl_src_param src_param;
2404 unsigned int mask_size;
2406 write_mask = shader_glsl_append_dst(buffer, ins);
2407 mask_size = shader_glsl_get_write_mask_size(write_mask);
2409 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2413 shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2414 mask_size, src_param.param_str);
2418 shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2419 src_param.param_str);
2423 /** Process signed comparison opcodes in GLSL. */
2424 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2426 struct glsl_src_param src0_param;
2427 struct glsl_src_param src1_param;
2429 unsigned int mask_size;
2431 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2432 mask_size = shader_glsl_get_write_mask_size(write_mask);
2433 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2434 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2436 if (mask_size > 1) {
2437 const char *compare;
2439 switch(ins->handler_idx)
2441 case WINED3DSIH_SLT: compare = "lessThan"; break;
2442 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2443 default: compare = "";
2444 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2447 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2448 src0_param.param_str, src1_param.param_str);
2450 switch(ins->handler_idx)
2452 case WINED3DSIH_SLT:
2453 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2454 * to return 0.0 but step returns 1.0 because step is not < x
2455 * An alternative is a bvec compare padded with an unused second component.
2456 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2457 * issue. Playing with not() is not possible either because not() does not accept
2460 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2461 src0_param.param_str, src1_param.param_str);
2463 case WINED3DSIH_SGE:
2464 /* Here we can use the step() function and safe a conditional */
2465 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2468 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2474 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2475 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2477 struct glsl_src_param src0_param;
2478 struct glsl_src_param src1_param;
2479 struct glsl_src_param src2_param;
2480 DWORD write_mask, cmp_channel = 0;
2483 BOOL temp_destination = FALSE;
2485 if (shader_is_scalar(&ins->src[0].reg))
2487 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2489 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2490 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2491 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2493 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2494 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2496 DWORD dst_mask = ins->dst[0].write_mask;
2497 struct wined3d_shader_dst_param dst = ins->dst[0];
2499 /* Cycle through all source0 channels */
2500 for (i=0; i<4; i++) {
2502 /* Find the destination channels which use the current source0 channel */
2503 for (j=0; j<4; j++) {
2504 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2506 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2507 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2510 dst.write_mask = dst_mask & write_mask;
2512 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2513 * The first lines may overwrite source parameters of the following lines.
2514 * Deal with that by using a temporary destination register if needed
2516 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2517 && ins->src[0].reg.type == ins->dst[0].reg.type)
2518 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2519 && ins->src[1].reg.type == ins->dst[0].reg.type)
2520 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2521 && ins->src[2].reg.type == ins->dst[0].reg.type))
2523 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2524 if (!write_mask) continue;
2525 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2526 temp_destination = TRUE;
2528 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2529 if (!write_mask) continue;
2532 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2533 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2534 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2536 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2537 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2540 if(temp_destination) {
2541 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2542 shader_glsl_append_dst(ins->ctx->buffer, ins);
2543 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2549 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2550 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2551 * the compare is done per component of src0. */
2552 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2554 struct wined3d_shader_dst_param dst;
2555 struct glsl_src_param src0_param;
2556 struct glsl_src_param src1_param;
2557 struct glsl_src_param src2_param;
2558 DWORD write_mask, cmp_channel = 0;
2561 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2562 ins->ctx->reg_maps->shader_version.minor);
2564 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2566 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2567 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2568 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2569 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2571 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2574 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2576 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2577 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2581 /* Cycle through all source0 channels */
2582 dst_mask = ins->dst[0].write_mask;
2584 for (i=0; i<4; i++) {
2586 /* Find the destination channels which use the current source0 channel */
2587 for (j=0; j<4; j++) {
2588 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2590 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2591 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2595 dst.write_mask = dst_mask & write_mask;
2596 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2597 if (!write_mask) continue;
2599 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2600 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2601 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2603 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2604 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2608 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2609 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2611 struct glsl_src_param src0_param;
2612 struct glsl_src_param src1_param;
2613 struct glsl_src_param src2_param;
2616 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2617 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2618 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2619 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2620 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2621 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2624 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2625 Vertex shaders to GLSL codes */
2626 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2629 int nComponents = 0;
2630 struct wined3d_shader_dst_param tmp_dst = {{0}};
2631 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2632 struct wined3d_shader_instruction tmp_ins;
2634 memset(&tmp_ins, 0, sizeof(tmp_ins));
2636 /* Set constants for the temporary argument */
2637 tmp_ins.ctx = ins->ctx;
2638 tmp_ins.dst_count = 1;
2639 tmp_ins.dst = &tmp_dst;
2640 tmp_ins.src_count = 2;
2641 tmp_ins.src = tmp_src;
2643 switch(ins->handler_idx)
2645 case WINED3DSIH_M4x4:
2647 tmp_ins.handler_idx = WINED3DSIH_DP4;
2649 case WINED3DSIH_M4x3:
2651 tmp_ins.handler_idx = WINED3DSIH_DP4;
2653 case WINED3DSIH_M3x4:
2655 tmp_ins.handler_idx = WINED3DSIH_DP3;
2657 case WINED3DSIH_M3x3:
2659 tmp_ins.handler_idx = WINED3DSIH_DP3;
2661 case WINED3DSIH_M3x2:
2663 tmp_ins.handler_idx = WINED3DSIH_DP3;
2669 tmp_dst = ins->dst[0];
2670 tmp_src[0] = ins->src[0];
2671 tmp_src[1] = ins->src[1];
2672 for (i = 0; i < nComponents; ++i)
2674 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2675 shader_glsl_dot(&tmp_ins);
2676 ++tmp_src[1].reg.idx;
2681 The LRP instruction performs a component-wise linear interpolation
2682 between the second and third operands using the first operand as the
2683 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2684 This is equivalent to mix(src2, src1, src0);
2686 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2688 struct glsl_src_param src0_param;
2689 struct glsl_src_param src1_param;
2690 struct glsl_src_param src2_param;
2693 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2695 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2696 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2697 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2699 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2700 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2703 /** Process the WINED3DSIO_LIT instruction in GLSL:
2704 * dst.x = dst.w = 1.0
2705 * dst.y = (src0.x > 0) ? src0.x
2706 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2707 * where src.w is clamped at +- 128
2709 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2711 struct glsl_src_param src0_param;
2712 struct glsl_src_param src1_param;
2713 struct glsl_src_param src3_param;
2716 shader_glsl_append_dst(ins->ctx->buffer, ins);
2717 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2719 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2720 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2721 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2723 /* The sdk specifies the instruction like this
2725 * if(src.x > 0.0) dst.y = src.x
2727 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2730 * (where power = src.w clamped between -128 and 128)
2732 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2733 * dst.x = 1.0 ... No further explanation needed
2734 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2735 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2736 * dst.w = 1.0. ... Nothing fancy.
2738 * So we still have one conditional in there. So do this:
2739 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2741 * 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),
2742 * 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.
2743 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to.
2745 * Unfortunately pow(0.0 ^ 0.0) returns NaN on most GPUs, but lit with src.y = 0 and src.w = 0 returns
2746 * a non-NaN value in dst.z. What we return doesn't matter, as long as it is not NaN. Return 0, which is
2747 * what all Windows HW drivers and GL_ARB_vertex_program's LIT do.
2749 shader_addline(ins->ctx->buffer,
2750 "vec4(1.0, max(%s, 0.0), %s == 0.0 ? 0.0 : "
2751 "pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
2752 src0_param.param_str, src3_param.param_str, src1_param.param_str,
2753 src0_param.param_str, src3_param.param_str, dst_mask);
2756 /** Process the WINED3DSIO_DST instruction in GLSL:
2758 * dst.y = src0.x * src0.y
2762 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2764 struct glsl_src_param src0y_param;
2765 struct glsl_src_param src0z_param;
2766 struct glsl_src_param src1y_param;
2767 struct glsl_src_param src1w_param;
2770 shader_glsl_append_dst(ins->ctx->buffer, ins);
2771 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2773 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2774 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2775 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2776 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2778 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2779 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2782 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2783 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2784 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2786 * dst.x = cos(src0.?)
2787 * dst.y = sin(src0.?)
2791 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2793 struct glsl_src_param src0_param;
2796 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2797 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2799 switch (write_mask) {
2800 case WINED3DSP_WRITEMASK_0:
2801 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2804 case WINED3DSP_WRITEMASK_1:
2805 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2808 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2809 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2813 ERR("Write mask should be .x, .y or .xy\n");
2818 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2819 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2820 * generate invalid code
2822 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2824 struct glsl_src_param src0_param;
2827 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2828 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2830 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2833 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2834 * Start a for() loop where src1.y is the initial value of aL,
2835 * increment aL by src1.z for a total of src1.x iterations.
2836 * Need to use a temporary variable for this operation.
2838 /* FIXME: I don't think nested loops will work correctly this way. */
2839 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2841 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2842 const struct wined3d_shader *shader = ins->ctx->shader;
2843 const struct wined3d_shader_lconst *constant;
2844 struct glsl_src_param src1_param;
2845 const DWORD *control_values = NULL;
2847 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2849 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2850 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2851 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2854 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2856 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
2858 if (constant->idx == ins->src[1].reg.idx)
2860 control_values = constant->value;
2868 struct wined3d_shader_loop_control loop_control;
2869 loop_control.count = control_values[0];
2870 loop_control.start = control_values[1];
2871 loop_control.step = (int)control_values[2];
2873 if (loop_control.step > 0)
2875 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2876 loop_state->current_depth, loop_control.start,
2877 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2878 loop_state->current_depth, loop_control.step);
2880 else if (loop_control.step < 0)
2882 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2883 loop_state->current_depth, loop_control.start,
2884 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2885 loop_state->current_depth, loop_control.step);
2889 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2890 loop_state->current_depth, loop_control.start, loop_state->current_depth,
2891 loop_state->current_depth, loop_control.count,
2892 loop_state->current_depth);
2895 shader_addline(ins->ctx->buffer,
2896 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2897 loop_state->current_depth, loop_state->current_reg,
2898 src1_param.reg_name, loop_state->current_depth, src1_param.reg_name,
2899 loop_state->current_depth, loop_state->current_reg, src1_param.reg_name);
2902 ++loop_state->current_depth;
2903 ++loop_state->current_reg;
2906 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2908 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2910 shader_addline(ins->ctx->buffer, "}\n");
2912 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2914 --loop_state->current_depth;
2915 --loop_state->current_reg;
2918 if (ins->handler_idx == WINED3DSIH_ENDREP)
2920 --loop_state->current_depth;
2924 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2926 const struct wined3d_shader *shader = ins->ctx->shader;
2927 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2928 const struct wined3d_shader_lconst *constant;
2929 struct glsl_src_param src0_param;
2930 const DWORD *control_values = NULL;
2932 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2933 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2935 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
2937 if (constant->idx == ins->src[0].reg.idx)
2939 control_values = constant->value;
2947 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2948 loop_state->current_depth, loop_state->current_depth,
2949 control_values[0], loop_state->current_depth);
2953 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2954 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2955 loop_state->current_depth, loop_state->current_depth,
2956 src0_param.param_str, loop_state->current_depth);
2959 ++loop_state->current_depth;
2962 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2964 struct glsl_src_param src0_param;
2966 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2967 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2970 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2972 struct glsl_src_param src0_param;
2973 struct glsl_src_param src1_param;
2975 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2976 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2978 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2979 src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
2982 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2984 shader_addline(ins->ctx->buffer, "} else {\n");
2987 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2989 shader_addline(ins->ctx->buffer, "break;\n");
2992 /* FIXME: According to MSDN the compare is done per component. */
2993 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2995 struct glsl_src_param src0_param;
2996 struct glsl_src_param src1_param;
2998 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2999 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3001 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
3002 src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
3005 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
3007 shader_addline(ins->ctx->buffer, "}\n");
3008 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
3011 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
3013 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
3016 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
3018 struct glsl_src_param src1_param;
3020 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3021 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
3024 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3026 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3027 * function only suppresses the unhandled instruction warning
3031 /*********************************************
3032 * Pixel Shader Specific Code begins here
3033 ********************************************/
3034 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3036 const struct wined3d_shader *shader = ins->ctx->shader;
3037 struct wined3d_device *device = shader->device;
3038 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3039 ins->ctx->reg_maps->shader_version.minor);
3040 struct glsl_sample_function sample_function;
3041 const struct wined3d_texture *texture;
3042 DWORD sample_flags = 0;
3044 DWORD mask = 0, swizzle;
3046 /* 1.0-1.4: Use destination register as sampler source.
3047 * 2.0+: Use provided sampler source. */
3048 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3049 else sampler_idx = ins->src[1].reg.idx;
3050 texture = device->stateBlock->state.textures[sampler_idx];
3052 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3054 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3055 DWORD flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3056 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3057 enum wined3d_sampler_texture_type sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3059 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3060 if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE)
3062 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3063 switch (flags & ~WINED3D_PSARGS_PROJECTED)
3065 case WINED3D_TTFF_COUNT1:
3066 FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3068 case WINED3D_TTFF_COUNT2:
3069 mask = WINED3DSP_WRITEMASK_1;
3071 case WINED3D_TTFF_COUNT3:
3072 mask = WINED3DSP_WRITEMASK_2;
3074 case WINED3D_TTFF_COUNT4:
3075 case WINED3D_TTFF_DISABLE:
3076 mask = WINED3DSP_WRITEMASK_3;
3081 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3083 enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3085 if (src_mod == WINED3DSPSM_DZ) {
3086 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3087 mask = WINED3DSP_WRITEMASK_2;
3088 } else if (src_mod == WINED3DSPSM_DW) {
3089 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3090 mask = WINED3DSP_WRITEMASK_3;
3093 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3095 /* ps 2.0 texldp instruction always divides by the fourth component. */
3096 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3097 mask = WINED3DSP_WRITEMASK_3;
3101 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3102 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3104 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3105 mask |= sample_function.coord_mask;
3107 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3108 else swizzle = ins->src[1].swizzle;
3110 /* 1.0-1.3: Use destination register as coordinate source.
3111 1.4+: Use provided coordinate source register. */
3112 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3115 shader_glsl_write_mask_to_str(mask, coord_mask);
3116 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3117 "T%u%s", sampler_idx, coord_mask);
3121 struct glsl_src_param coord_param;
3122 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3123 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3125 struct glsl_src_param bias;
3126 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3127 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3128 "%s", coord_param.param_str);
3130 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3131 "%s", coord_param.param_str);
3136 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3138 const struct wined3d_shader *shader = ins->ctx->shader;
3139 struct wined3d_device *device = shader->device;
3140 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3141 struct glsl_src_param coord_param, dx_param, dy_param;
3142 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3143 struct glsl_sample_function sample_function;
3145 DWORD swizzle = ins->src[1].swizzle;
3146 const struct wined3d_texture *texture;
3148 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3150 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3151 shader_glsl_tex(ins);
3155 sampler_idx = ins->src[1].reg.idx;
3156 texture = device->stateBlock->state.textures[sampler_idx];
3157 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3158 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3160 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3161 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3162 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3163 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3165 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3166 "%s", coord_param.param_str);
3169 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3171 const struct wined3d_shader *shader = ins->ctx->shader;
3172 struct wined3d_device *device = shader->device;
3173 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3174 struct glsl_src_param coord_param, lod_param;
3175 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3176 struct glsl_sample_function sample_function;
3178 DWORD swizzle = ins->src[1].swizzle;
3179 const struct wined3d_texture *texture;
3181 sampler_idx = ins->src[1].reg.idx;
3182 texture = device->stateBlock->state.textures[sampler_idx];
3183 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3184 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3186 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3187 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3189 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3191 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3192 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3194 /* Plain GLSL only supports Lod sampling functions in vertex shaders.
3195 * However, the NVIDIA drivers allow them in fragment shaders as well,
3196 * even without the appropriate extension. */
3197 WARN("Using %s in fragment shader.\n", sample_function.name);
3199 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3200 "%s", coord_param.param_str);
3203 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3205 /* FIXME: Make this work for more than just 2D textures */
3206 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3207 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3209 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3213 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3214 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3215 ins->dst[0].reg.idx, dst_mask);
3219 enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3220 DWORD reg = ins->src[0].reg.idx;
3221 char dst_swizzle[6];
3223 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3225 if (src_mod == WINED3DSPSM_DZ)
3227 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3228 struct glsl_src_param div_param;
3230 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3232 if (mask_size > 1) {
3233 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3235 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3238 else if (src_mod == WINED3DSPSM_DW)
3240 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3241 struct glsl_src_param div_param;
3243 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3245 if (mask_size > 1) {
3246 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3248 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3251 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3256 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3257 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3258 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3259 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3261 DWORD sampler_idx = ins->dst[0].reg.idx;
3262 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3263 struct glsl_sample_function sample_function;
3264 struct glsl_src_param src0_param;
3267 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3269 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3270 * scalar, and projected sampling would require 4.
3272 * It is a dependent read - not valid with conditional NP2 textures
3274 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3275 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3280 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3281 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3285 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3286 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3290 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3291 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3295 FIXME("Unexpected mask size %u\n", mask_size);
3300 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3301 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3302 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3304 DWORD dstreg = ins->dst[0].reg.idx;
3305 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3306 struct glsl_src_param src0_param;
3308 unsigned int mask_size;
3310 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3311 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3312 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3314 if (mask_size > 1) {
3315 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3317 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3321 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3322 * Calculate the depth as dst.x / dst.y */
3323 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3325 struct glsl_dst_param dst_param;
3327 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3329 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3330 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3331 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3332 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3335 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3336 dst_param.reg_name, dst_param.reg_name);
3339 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3340 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3341 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3342 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3344 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3346 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3347 DWORD dstreg = ins->dst[0].reg.idx;
3348 struct glsl_src_param src0_param;
3350 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3352 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3353 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3356 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3357 * Calculate the 1st of a 2-row matrix multiplication. */
3358 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3360 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3361 DWORD reg = ins->dst[0].reg.idx;
3362 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3363 struct glsl_src_param src0_param;
3365 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3366 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3369 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3370 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3371 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3373 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3374 DWORD reg = ins->dst[0].reg.idx;
3375 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3376 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3377 struct glsl_src_param src0_param;
3379 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3380 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + tex_mx->current_row, reg, src0_param.param_str);
3381 tex_mx->texcoord_w[tex_mx->current_row++] = reg;
3384 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3386 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3387 DWORD reg = ins->dst[0].reg.idx;
3388 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3389 struct glsl_sample_function sample_function;
3390 struct glsl_src_param src0_param;
3392 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3393 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3395 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3397 /* Sample the texture using the calculated coordinates */
3398 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3401 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3402 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3403 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3405 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3406 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3407 struct glsl_sample_function sample_function;
3408 struct glsl_src_param src0_param;
3409 DWORD reg = ins->dst[0].reg.idx;
3411 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3412 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3414 /* Dependent read, not valid with conditional NP2 */
3415 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3417 /* Sample the texture using the calculated coordinates */
3418 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3420 tex_mx->current_row = 0;
3423 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3424 * Perform the 3rd row of a 3x3 matrix multiply */
3425 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3427 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3428 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3429 struct glsl_src_param src0_param;
3431 DWORD reg = ins->dst[0].reg.idx;
3433 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3435 shader_glsl_append_dst(ins->ctx->buffer, ins);
3436 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3437 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3439 tex_mx->current_row = 0;
3442 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3443 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3444 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3446 struct glsl_src_param src0_param;
3447 struct glsl_src_param src1_param;
3448 DWORD reg = ins->dst[0].reg.idx;
3449 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3450 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3451 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3452 struct glsl_sample_function sample_function;
3455 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3456 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3458 /* Perform the last matrix multiply operation */
3459 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3460 /* Reflection calculation */
3461 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3463 /* Dependent read, not valid with conditional NP2 */
3464 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3465 shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3467 /* Sample the texture */
3468 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3469 NULL, NULL, NULL, "tmp0%s", coord_mask);
3471 tex_mx->current_row = 0;
3474 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3475 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3476 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3478 DWORD reg = ins->dst[0].reg.idx;
3479 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3480 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3481 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3482 struct glsl_sample_function sample_function;
3483 struct glsl_src_param src0_param;
3486 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3488 /* Perform the last matrix multiply operation */
3489 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3491 /* Construct the eye-ray vector from w coordinates */
3492 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3493 tex_mx->texcoord_w[0], tex_mx->texcoord_w[1], reg);
3494 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3496 /* Dependent read, not valid with conditional NP2 */
3497 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3498 shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3500 /* Sample the texture using the calculated coordinates */
3501 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3502 NULL, NULL, NULL, "tmp0%s", coord_mask);
3504 tex_mx->current_row = 0;
3507 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3508 * Apply a fake bump map transform.
3509 * texbem is pshader <= 1.3 only, this saves a few version checks
3511 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3513 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3514 struct glsl_sample_function sample_function;
3515 struct glsl_src_param coord_param;
3521 sampler_idx = ins->dst[0].reg.idx;
3522 flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3523 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3525 /* Dependent read, not valid with conditional NP2 */
3526 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3527 mask = sample_function.coord_mask;
3529 shader_glsl_write_mask_to_str(mask, coord_mask);
3531 /* With projected textures, texbem only divides the static texture coord,
3532 * not the displacement, so we can't let GL handle this. */
3533 if (flags & WINED3D_PSARGS_PROJECTED)
3536 char coord_div_mask[3];
3537 switch (flags & ~WINED3D_PSARGS_PROJECTED)
3539 case WINED3D_TTFF_COUNT1:
3540 FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3542 case WINED3D_TTFF_COUNT2:
3543 div_mask = WINED3DSP_WRITEMASK_1;
3545 case WINED3D_TTFF_COUNT3:
3546 div_mask = WINED3DSP_WRITEMASK_2;
3548 case WINED3D_TTFF_COUNT4:
3549 case WINED3D_TTFF_DISABLE:
3550 div_mask = WINED3DSP_WRITEMASK_3;
3553 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3554 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3557 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3559 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3560 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3561 coord_param.param_str, coord_mask);
3563 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3565 struct glsl_src_param luminance_param;
3566 struct glsl_dst_param dst_param;
3568 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3569 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3571 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3572 dst_param.reg_name, dst_param.mask_str,
3573 luminance_param.param_str, sampler_idx, sampler_idx);
3577 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3579 struct glsl_src_param src0_param, src1_param;
3580 DWORD sampler_idx = ins->dst[0].reg.idx;
3582 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3583 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3585 shader_glsl_append_dst(ins->ctx->buffer, ins);
3586 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3587 src0_param.param_str, sampler_idx, src1_param.param_str);
3590 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3591 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3592 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3594 struct glsl_sample_function sample_function;
3595 struct glsl_src_param src0_param;
3596 DWORD sampler_idx = ins->dst[0].reg.idx;
3598 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3600 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3601 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3602 "%s.wx", src0_param.reg_name);
3605 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3606 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3607 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3609 struct glsl_sample_function sample_function;
3610 struct glsl_src_param src0_param;
3611 DWORD sampler_idx = ins->dst[0].reg.idx;
3613 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3615 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3616 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3617 "%s.yz", src0_param.reg_name);
3620 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3621 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3622 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3624 struct glsl_sample_function sample_function;
3625 struct glsl_src_param src0_param;
3626 DWORD sampler_idx = ins->dst[0].reg.idx;
3628 /* Dependent read, not valid with conditional NP2 */
3629 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3630 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3632 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3633 "%s", src0_param.param_str);
3636 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3637 * If any of the first 3 components are < 0, discard this pixel */
3638 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3640 struct glsl_dst_param dst_param;
3642 /* The argument is a destination parameter, and no writemasks are allowed */
3643 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3644 if (ins->ctx->reg_maps->shader_version.major >= 2)
3646 /* 2.0 shaders compare all 4 components in texkill */
3647 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3649 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3650 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3651 * 4 components are defined, only the first 3 are used
3653 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3657 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3658 * dst = dot2(src0, src1) + src2 */
3659 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3661 struct glsl_src_param src0_param;
3662 struct glsl_src_param src1_param;
3663 struct glsl_src_param src2_param;
3665 unsigned int mask_size;
3667 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3668 mask_size = shader_glsl_get_write_mask_size(write_mask);
3670 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3671 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3672 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3674 if (mask_size > 1) {
3675 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3676 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3678 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3679 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3683 static void shader_glsl_input_pack(const struct wined3d_shader *shader, struct wined3d_shader_buffer *buffer,
3684 const struct wined3d_shader_signature_element *input_signature,
3685 const struct wined3d_shader_reg_maps *reg_maps,
3686 enum vertexprocessing_mode vertexprocessing)
3688 WORD map = reg_maps->input_registers;
3691 for (i = 0; map; map >>= 1, ++i)
3693 const char *semantic_name;
3698 if (!(map & 1)) continue;
3700 semantic_name = input_signature[i].semantic_name;
3701 semantic_idx = input_signature[i].semantic_idx;
3702 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3704 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
3706 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3707 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3708 shader->u.ps.input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3710 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3711 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3713 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
3716 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3717 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3718 else if (semantic_idx == 1)
3719 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3720 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3722 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3723 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3727 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3728 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3733 /*********************************************
3734 * Vertex Shader Specific Code begins here
3735 ********************************************/
3737 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry)
3739 struct glsl_program_key key;
3741 key.vshader = entry->vshader;
3742 key.pshader = entry->pshader;
3743 key.vs_args = entry->vs_args;
3744 key.ps_args = entry->ps_args;
3746 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3748 ERR("Failed to insert program entry.\n");
3752 static struct glsl_shader_prog_link *get_glsl_program_entry(const struct shader_glsl_priv *priv,
3753 const struct wined3d_shader *vshader, const struct wined3d_shader *pshader,
3754 const struct vs_compile_args *vs_args, const struct ps_compile_args *ps_args)
3756 struct wine_rb_entry *entry;
3757 struct glsl_program_key key;
3759 key.vshader = vshader;
3760 key.pshader = pshader;
3761 key.vs_args = *vs_args;
3762 key.ps_args = *ps_args;
3764 entry = wine_rb_get(&priv->program_lookup, &key);
3765 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3768 /* GL locking is done by the caller */
3769 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3770 struct glsl_shader_prog_link *entry)
3772 struct glsl_program_key key;
3774 key.vshader = entry->vshader;
3775 key.pshader = entry->pshader;
3776 key.vs_args = entry->vs_args;
3777 key.ps_args = entry->ps_args;
3778 wine_rb_remove(&priv->program_lookup, &key);
3780 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3781 if (entry->vshader) list_remove(&entry->vshader_entry);
3782 if (entry->pshader) list_remove(&entry->pshader_entry);
3783 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3784 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3785 HeapFree(GetProcessHeap(), 0, entry);
3788 static void handle_ps3_input(struct wined3d_shader_buffer *buffer,
3789 const struct wined3d_gl_info *gl_info, const DWORD *map,
3790 const struct wined3d_shader_signature_element *input_signature,
3791 const struct wined3d_shader_reg_maps *reg_maps_in,
3792 const struct wined3d_shader_signature_element *output_signature,
3793 const struct wined3d_shader_reg_maps *reg_maps_out)
3796 const char *semantic_name_in;
3797 UINT semantic_idx_in;
3800 unsigned int in_count = vec4_varyings(3, gl_info);
3802 char destination[50];
3803 WORD input_map, output_map;
3805 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3807 input_map = reg_maps_in->input_registers;
3808 for (i = 0; input_map; input_map >>= 1, ++i)
3810 if (!(input_map & 1)) continue;
3813 /* Declared, but not read register */
3814 if (in_idx == ~0U) continue;
3815 if (in_idx >= (in_count + 2))
3817 FIXME("More input varyings declared than supported, expect issues.\n");
3821 if (in_idx == in_count) {
3822 sprintf(destination, "gl_FrontColor");
3823 } else if (in_idx == in_count + 1) {
3824 sprintf(destination, "gl_FrontSecondaryColor");
3826 sprintf(destination, "IN[%u]", in_idx);
3829 semantic_name_in = input_signature[i].semantic_name;
3830 semantic_idx_in = input_signature[i].semantic_idx;
3833 output_map = reg_maps_out->output_registers;
3834 for (j = 0; output_map; output_map >>= 1, ++j)
3838 if (!(output_map & 1)
3839 || semantic_idx_in != output_signature[j].semantic_idx
3840 || strcmp(semantic_name_in, output_signature[j].semantic_name)
3841 || !(mask = input_signature[i].mask & output_signature[j].mask))
3845 shader_glsl_write_mask_to_str(mask, reg_mask);
3847 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3848 destination, reg_mask, j, reg_mask);
3852 for (i = 0; i < in_count + 2; ++i)
3856 if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
3859 if (set[i] == ~0U) set[i] = 0;
3862 if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
3863 if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
3864 if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
3865 if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
3866 reg_mask[size] = '\0';
3868 if (i == in_count) sprintf(destination, "gl_FrontColor");
3869 else if (i == in_count + 1) sprintf(destination, "gl_FrontSecondaryColor");
3870 else sprintf(destination, "IN[%u]", i);
3872 if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3873 else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3876 HeapFree(GetProcessHeap(), 0, set);
3879 /* GL locking is done by the caller */
3880 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3881 const struct wined3d_shader *vs, const struct wined3d_shader *ps,
3882 const struct wined3d_gl_info *gl_info)
3884 GLhandleARB ret = 0;
3885 DWORD ps_major = ps ? ps->reg_maps.shader_version.major : 0;
3887 const char *semantic_name;
3890 const struct wined3d_shader_signature_element *output_signature = vs->output_signature;
3891 WORD map = vs->reg_maps.output_registers;
3893 shader_buffer_clear(buffer);
3895 shader_addline(buffer, "#version 120\n");
3899 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3901 for (i = 0; map; map >>= 1, ++i)
3905 if (!(map & 1)) continue;
3907 semantic_name = output_signature[i].semantic_name;
3908 semantic_idx = output_signature[i].semantic_idx;
3909 write_mask = output_signature[i].mask;
3910 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3912 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
3915 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n",
3916 reg_mask, i, reg_mask);
3917 else if (semantic_idx == 1)
3918 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n",
3919 reg_mask, i, reg_mask);
3921 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
3923 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3924 reg_mask, i, reg_mask);
3926 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
3928 if (semantic_idx < 8)
3930 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3931 write_mask |= WINED3DSP_WRITEMASK_3;
3933 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3934 semantic_idx, reg_mask, i, reg_mask);
3935 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3936 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3939 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
3941 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3943 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_FOG))
3945 shader_addline(buffer, "gl_FogFragCoord = clamp(OUT[%u].%c, 0.0, 1.0);\n", i, reg_mask[1]);
3948 shader_addline(buffer, "}\n");
3952 UINT in_count = min(vec4_varyings(ps_major, gl_info), ps->limits.packed_input);
3953 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3954 shader_addline(buffer, "varying vec4 IN[%u];\n", in_count);
3955 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3957 /* First, sort out position and point size. Those are not passed to the pixel shader */
3958 for (i = 0; map; map >>= 1, ++i)
3960 if (!(map & 1)) continue;
3962 semantic_name = output_signature[i].semantic_name;
3963 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3965 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
3967 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3968 reg_mask, i, reg_mask);
3970 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
3972 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3976 /* Then, fix the pixel shader input */
3977 handle_ps3_input(buffer, gl_info, ps->u.ps.input_reg_map, ps->input_signature,
3978 &ps->reg_maps, output_signature, &vs->reg_maps);
3980 shader_addline(buffer, "}\n");
3983 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3984 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3985 shader_glsl_compile(gl_info, ret, buffer->buffer);
3990 /* GL locking is done by the caller */
3991 static void hardcode_local_constants(const struct wined3d_shader *shader,
3992 const struct wined3d_gl_info *gl_info, GLhandleARB programId, char prefix)
3994 const struct wined3d_shader_lconst *lconst;
3999 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
4001 value = (const float *)lconst->value;
4002 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
4003 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4004 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
4006 checkGLcall("Hardcoding local constants");
4009 /* GL locking is done by the caller */
4010 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
4011 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4012 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
4014 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4015 const struct wined3d_gl_info *gl_info = context->gl_info;
4016 const DWORD *function = shader->function;
4017 struct shader_glsl_ctx_priv priv_ctx;
4019 /* Create the hw GLSL shader object and assign it as the shader->prgId */
4020 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4022 memset(&priv_ctx, 0, sizeof(priv_ctx));
4023 priv_ctx.cur_ps_args = args;
4024 priv_ctx.cur_np2fixup_info = np2fixup_info;
4026 shader_addline(buffer, "#version 120\n");
4028 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
4030 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
4032 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4034 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
4035 * drivers write a warning if we don't do so
4037 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4039 if (gl_info->supported[EXT_GPU_SHADER4])
4041 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4044 /* Base Declarations */
4045 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4047 /* Pack 3.0 inputs */
4048 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4049 shader_glsl_input_pack(shader, buffer, shader->input_signature, reg_maps, args->vp_mode);
4051 /* Base Shader Body */
4052 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4054 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4055 if (reg_maps->shader_version.major < 2)
4057 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4058 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4061 if (args->srgb_correction)
4063 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4064 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4065 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4066 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4067 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4068 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4070 /* Pixel shader < 3.0 do not replace the fog stage.
4071 * This implements linear fog computation and blending.
4072 * TODO: non linear fog
4073 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4074 * -1/(e-s) and e/(e-s) respectively.
4076 if (reg_maps->shader_version.major < 3)
4079 case FOG_OFF: break;
4081 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4082 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4083 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4084 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4087 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4088 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4089 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4090 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4093 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4094 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4095 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4096 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4101 shader_addline(buffer, "}\n");
4103 TRACE("Compiling shader object %u\n", shader_obj);
4104 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4106 /* Store the shader object */
4110 /* GL locking is done by the caller */
4111 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4112 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4113 const struct vs_compile_args *args)
4115 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4116 const struct wined3d_gl_info *gl_info = context->gl_info;
4117 const DWORD *function = shader->function;
4118 struct shader_glsl_ctx_priv priv_ctx;
4120 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4121 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4123 shader_addline(buffer, "#version 120\n");
4125 if (gl_info->supported[EXT_GPU_SHADER4])
4126 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4128 memset(&priv_ctx, 0, sizeof(priv_ctx));
4129 priv_ctx.cur_vs_args = args;
4131 /* Base Declarations */
4132 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4134 /* Base Shader Body */
4135 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4137 /* Unpack outputs */
4138 shader_addline(buffer, "order_ps_input(OUT);\n");
4140 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4141 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4142 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4143 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4145 if (args->fog_src == VS_FOG_Z)
4146 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4147 else if (!reg_maps->fog)
4148 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4150 /* We always store the clipplanes without y inversion */
4151 if (args->clip_enabled)
4152 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4154 /* Write the final position.
4156 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4157 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4158 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4159 * contains 1.0 to allow a mad.
4161 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4162 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4164 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4166 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4167 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4168 * which is the same as z = z * 2 - w.
4170 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4172 shader_addline(buffer, "}\n");
4174 TRACE("Compiling shader object %u\n", shader_obj);
4175 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4180 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4181 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4182 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4184 struct wined3d_state *state = &shader->device->stateBlock->state;
4187 struct glsl_ps_compiled_shader *new_array;
4188 struct glsl_pshader_private *shader_data;
4189 struct ps_np2fixup_info *np2fixup = NULL;
4192 if (!shader->backend_data)
4194 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4195 if (!shader->backend_data)
4197 ERR("Failed to allocate backend data.\n");
4201 shader_data = shader->backend_data;
4203 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4204 * so a linear search is more performant than a hashmap or a binary search
4205 * (cache coherency etc)
4207 for (i = 0; i < shader_data->num_gl_shaders; ++i)
4209 if (!memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)))
4211 if (args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
4212 return shader_data->gl_shaders[i].prgId;
4216 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4217 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4218 if (shader_data->num_gl_shaders)
4220 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4221 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4222 new_size * sizeof(*shader_data->gl_shaders));
4224 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4229 ERR("Out of memory\n");
4232 shader_data->gl_shaders = new_array;
4233 shader_data->shader_array_size = new_size;
4236 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4238 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4239 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4241 pixelshader_update_samplers(&shader->reg_maps, state->textures);
4243 shader_buffer_clear(buffer);
4244 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4245 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4246 *np2fixup_info = np2fixup;
4251 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4252 const DWORD use_map) {
4253 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4254 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4255 return stored->fog_src == new->fog_src;
4258 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4259 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4260 const struct vs_compile_args *args)
4264 struct glsl_vs_compiled_shader *new_array;
4265 DWORD use_map = shader->device->strided_streams.use_map;
4266 struct glsl_vshader_private *shader_data;
4269 if (!shader->backend_data)
4271 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4272 if (!shader->backend_data)
4274 ERR("Failed to allocate backend data.\n");
4278 shader_data = shader->backend_data;
4280 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4281 * so a linear search is more performant than a hashmap or a binary search
4282 * (cache coherency etc)
4284 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4285 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4286 return shader_data->gl_shaders[i].prgId;
4290 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4292 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4293 if (shader_data->num_gl_shaders)
4295 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4296 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4297 new_size * sizeof(*shader_data->gl_shaders));
4299 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4304 ERR("Out of memory\n");
4307 shader_data->gl_shaders = new_array;
4308 shader_data->shader_array_size = new_size;
4311 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4313 shader_buffer_clear(buffer);
4314 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4315 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4320 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4321 * It sets the programId on the current StateBlock (because it should be called
4322 * inside of the DrawPrimitive() part of the render loop).
4324 * If a program for the given combination does not exist, create one, and store
4325 * the program in the hash table. If it creates a program, it will link the
4326 * given objects, too.
4329 /* GL locking is done by the caller */
4330 static void set_glsl_shader_program(const struct wined3d_context *context,
4331 struct wined3d_device *device, BOOL use_ps, BOOL use_vs)
4333 const struct wined3d_state *state = &device->stateBlock->state;
4334 struct wined3d_shader *vshader = use_vs ? state->vertex_shader : NULL;
4335 struct wined3d_shader *pshader = use_ps ? state->pixel_shader : NULL;
4336 const struct wined3d_gl_info *gl_info = context->gl_info;
4337 struct shader_glsl_priv *priv = device->shader_priv;
4338 struct glsl_shader_prog_link *entry = NULL;
4339 GLhandleARB programId = 0;
4340 GLhandleARB reorder_shader_id = 0;
4343 struct ps_compile_args ps_compile_args;
4344 struct vs_compile_args vs_compile_args;
4346 if (vshader) find_vs_compile_args(state, vshader, &vs_compile_args);
4347 if (pshader) find_ps_compile_args(state, pshader, &ps_compile_args);
4349 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4352 priv->glsl_program = entry;
4356 /* If we get to this point, then no matching program exists, so we create one */
4357 programId = GL_EXTCALL(glCreateProgramObjectARB());
4358 TRACE("Created new GLSL shader program %u\n", programId);
4360 /* Create the entry */
4361 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4362 entry->programId = programId;
4363 entry->vshader = vshader;
4364 entry->pshader = pshader;
4365 entry->vs_args = vs_compile_args;
4366 entry->ps_args = ps_compile_args;
4367 entry->constant_version = 0;
4368 entry->np2Fixup_info = NULL;
4369 /* Add the hash table entry */
4370 add_glsl_program_entry(priv, entry);
4372 /* Set the current program */
4373 priv->glsl_program = entry;
4375 /* Attach GLSL vshader */
4378 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer, vshader, &vs_compile_args);
4379 WORD map = vshader->reg_maps.input_registers;
4382 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4383 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4384 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4385 checkGLcall("glAttachObjectARB");
4386 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4389 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4391 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4392 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4393 checkGLcall("glAttachObjectARB");
4395 /* Bind vertex attributes to a corresponding index number to match
4396 * the same index numbers as ARB_vertex_programs (makes loading
4397 * vertex attributes simpler). With this method, we can use the
4398 * exact same code to load the attributes later for both ARB and
4401 * We have to do this here because we need to know the Program ID
4402 * in order to make the bindings work, and it has to be done prior
4403 * to linking the GLSL program. */
4404 for (i = 0; map; map >>= 1, ++i)
4406 if (!(map & 1)) continue;
4408 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4409 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4411 checkGLcall("glBindAttribLocationARB");
4413 list_add_head(&vshader->linked_programs, &entry->vshader_entry);
4416 /* Attach GLSL pshader */
4419 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4420 pshader, &ps_compile_args, &entry->np2Fixup_info);
4421 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4422 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4423 checkGLcall("glAttachObjectARB");
4425 list_add_head(&pshader->linked_programs, &entry->pshader_entry);
4428 /* Link the program */
4429 TRACE("Linking GLSL shader program %u\n", programId);
4430 GL_EXTCALL(glLinkProgramARB(programId));
4431 shader_glsl_validate_link(gl_info, programId);
4433 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4434 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4435 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4437 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4438 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4440 for (i = 0; i < MAX_CONST_I; ++i)
4442 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4443 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4445 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4446 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4447 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4449 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4450 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4452 for (i = 0; i < MAX_CONST_I; ++i)
4454 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4455 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4461 for(i = 0; i < MAX_TEXTURES; i++) {
4462 sprintf(name, "bumpenvmat%u", i);
4463 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4464 sprintf(name, "luminancescale%u", i);
4465 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4466 sprintf(name, "luminanceoffset%u", i);
4467 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4470 if (ps_compile_args.np2_fixup) {
4471 if (entry->np2Fixup_info) {
4472 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4474 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4479 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4480 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4481 checkGLcall("Find glsl program uniform locations");
4483 if (pshader && pshader->reg_maps.shader_version.major >= 3
4484 && pshader->u.ps.declared_in_count > vec4_varyings(3, gl_info))
4486 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4487 entry->vertex_color_clamp = GL_FALSE;
4489 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4492 /* Set the shader to allow uniform loading on it */
4493 GL_EXTCALL(glUseProgramObjectARB(programId));
4494 checkGLcall("glUseProgramObjectARB(programId)");
4496 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4497 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4498 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4499 * vertex shader with fixed function pixel processing is used we make sure that the card
4500 * supports enough samplers to allow the max number of vertex samplers with all possible
4501 * fixed function fragment processing setups. So once the program is linked these samplers
4504 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4505 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4507 /* If the local constants do not have to be loaded with the environment constants,
4508 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4511 if (pshader && !pshader->load_local_constsF)
4512 hardcode_local_constants(pshader, gl_info, programId, 'P');
4513 if (vshader && !vshader->load_local_constsF)
4514 hardcode_local_constants(vshader, gl_info, programId, 'V');
4517 /* GL locking is done by the caller */
4518 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
4520 GLhandleARB program_id;
4521 GLhandleARB vshader_id, pshader_id;
4522 const char *blt_pshader;
4524 static const char *blt_vshader =
4528 " gl_Position = gl_Vertex;\n"
4529 " gl_FrontColor = vec4(1.0);\n"
4530 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4533 static const char * const blt_pshaders_full[tex_type_count] =
4539 "uniform sampler2D sampler;\n"
4542 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4548 "uniform samplerCube sampler;\n"
4551 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4555 "#extension GL_ARB_texture_rectangle : enable\n"
4556 "uniform sampler2DRect sampler;\n"
4559 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4563 static const char * const blt_pshaders_masked[tex_type_count] =
4569 "uniform sampler2D sampler;\n"
4570 "uniform vec4 mask;\n"
4573 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4574 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4580 "uniform samplerCube sampler;\n"
4581 "uniform vec4 mask;\n"
4584 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4585 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4589 "#extension GL_ARB_texture_rectangle : enable\n"
4590 "uniform sampler2DRect sampler;\n"
4591 "uniform vec4 mask;\n"
4594 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4595 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4599 blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
4602 FIXME("tex_type %#x not supported\n", tex_type);
4606 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4607 shader_glsl_compile(gl_info, vshader_id, blt_vshader);
4609 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4610 shader_glsl_compile(gl_info, pshader_id, blt_pshader);
4612 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4613 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4614 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4615 GL_EXTCALL(glLinkProgramARB(program_id));
4617 shader_glsl_validate_link(gl_info, program_id);
4619 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4622 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4623 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4627 /* GL locking is done by the caller */
4628 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4630 const struct wined3d_gl_info *gl_info = context->gl_info;
4631 struct wined3d_device *device = context->swapchain->device;
4632 struct shader_glsl_priv *priv = device->shader_priv;
4633 GLhandleARB program_id = 0;
4634 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4636 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4638 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4639 else priv->glsl_program = NULL;
4641 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4643 if (old_vertex_color_clamp != current_vertex_color_clamp)
4645 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4647 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4648 checkGLcall("glClampColorARB");
4652 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4656 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4657 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4658 GL_EXTCALL(glUseProgramObjectARB(program_id));
4659 checkGLcall("glUseProgramObjectARB");
4661 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4662 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4663 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4664 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4666 shader_glsl_load_np2fixup_constants(priv, gl_info, &device->stateBlock->state);
4670 /* GL locking is done by the caller */
4671 static void shader_glsl_select_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info,
4672 enum tex_types tex_type, const SIZE *ds_mask_size)
4674 BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
4675 struct shader_glsl_priv *priv = shader_priv;
4676 GLhandleARB *blt_program;
4679 blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
4682 *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
4683 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4684 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4685 GL_EXTCALL(glUniform1iARB(loc, 0));
4689 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4694 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
4695 GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
4699 /* GL locking is done by the caller */
4700 static void shader_glsl_deselect_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info)
4702 struct shader_glsl_priv *priv = shader_priv;
4703 GLhandleARB program_id;
4705 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4706 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4708 GL_EXTCALL(glUseProgramObjectARB(program_id));
4709 checkGLcall("glUseProgramObjectARB");
4712 static void shader_glsl_destroy(struct wined3d_shader *shader)
4714 struct wined3d_device *device = shader->device;
4715 struct shader_glsl_priv *priv = device->shader_priv;
4716 const struct wined3d_gl_info *gl_info;
4717 const struct list *linked_programs;
4718 struct wined3d_context *context;
4720 char pshader = shader_is_pshader_version(shader->reg_maps.shader_version.type);
4724 struct glsl_pshader_private *shader_data = shader->backend_data;
4726 if (!shader_data || !shader_data->num_gl_shaders)
4728 HeapFree(GetProcessHeap(), 0, shader_data);
4729 shader->backend_data = NULL;
4733 context = context_acquire(device, NULL);
4734 gl_info = context->gl_info;
4736 if (priv->glsl_program && priv->glsl_program->pshader == shader)
4739 shader_glsl_select(context, FALSE, FALSE);
4745 struct glsl_vshader_private *shader_data = shader->backend_data;
4747 if (!shader_data || !shader_data->num_gl_shaders)
4749 HeapFree(GetProcessHeap(), 0, shader_data);
4750 shader->backend_data = NULL;
4754 context = context_acquire(device, NULL);
4755 gl_info = context->gl_info;
4757 if (priv->glsl_program && priv->glsl_program->vshader == shader)
4760 shader_glsl_select(context, FALSE, FALSE);
4765 linked_programs = &shader->linked_programs;
4767 TRACE("Deleting linked programs\n");
4768 if (linked_programs->next) {
4769 struct glsl_shader_prog_link *entry, *entry2;
4773 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4774 delete_glsl_program_entry(priv, gl_info, entry);
4777 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4778 delete_glsl_program_entry(priv, gl_info, entry);
4786 struct glsl_pshader_private *shader_data = shader->backend_data;
4790 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4791 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4792 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4793 checkGLcall("glDeleteObjectARB");
4796 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4800 struct glsl_vshader_private *shader_data = shader->backend_data;
4804 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4805 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4806 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4807 checkGLcall("glDeleteObjectARB");
4810 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4813 HeapFree(GetProcessHeap(), 0, shader->backend_data);
4814 shader->backend_data = NULL;
4816 context_release(context);
4819 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4821 const struct glsl_program_key *k = key;
4822 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4823 const struct glsl_shader_prog_link, program_lookup_entry);
4826 if (k->vshader > prog->vshader) return 1;
4827 else if (k->vshader < prog->vshader) return -1;
4829 if (k->pshader > prog->pshader) return 1;
4830 else if (k->pshader < prog->pshader) return -1;
4832 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4833 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4838 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4840 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4841 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4845 ERR("Failed to allocate memory\n");
4849 heap->entries = mem;
4850 heap->entries[1].version = 0;
4851 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4857 static void constant_heap_free(struct constant_heap *heap)
4859 HeapFree(GetProcessHeap(), 0, heap->entries);
4862 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4867 glsl_program_key_compare,
4870 static HRESULT shader_glsl_alloc(struct wined3d_device *device)
4872 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4873 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4874 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4875 gl_info->limits.glsl_ps_float_constants)) + 1;
4877 if (!shader_buffer_init(&priv->shader_buffer))
4879 ERR("Failed to initialize shader buffer.\n");
4883 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4886 ERR("Failed to allocate memory.\n");
4890 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4892 ERR("Failed to initialize vertex shader constant heap\n");
4896 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4898 ERR("Failed to initialize pixel shader constant heap\n");
4902 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4904 ERR("Failed to initialize rbtree.\n");
4908 priv->next_constant_version = 1;
4910 device->shader_priv = priv;
4914 constant_heap_free(&priv->pconst_heap);
4915 constant_heap_free(&priv->vconst_heap);
4916 HeapFree(GetProcessHeap(), 0, priv->stack);
4917 shader_buffer_free(&priv->shader_buffer);
4918 HeapFree(GetProcessHeap(), 0, priv);
4919 return E_OUTOFMEMORY;
4922 /* Context activation is done by the caller. */
4923 static void shader_glsl_free(struct wined3d_device *device)
4925 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4926 struct shader_glsl_priv *priv = device->shader_priv;
4930 for (i = 0; i < tex_type_count; ++i)
4932 if (priv->depth_blt_program_full[i])
4934 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
4936 if (priv->depth_blt_program_masked[i])
4938 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
4943 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4944 constant_heap_free(&priv->pconst_heap);
4945 constant_heap_free(&priv->vconst_heap);
4946 HeapFree(GetProcessHeap(), 0, priv->stack);
4947 shader_buffer_free(&priv->shader_buffer);
4949 HeapFree(GetProcessHeap(), 0, device->shader_priv);
4950 device->shader_priv = NULL;
4953 static void shader_glsl_context_destroyed(void *shader_priv, const struct wined3d_context *context) {}
4955 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
4957 if (gl_info->supported[EXT_GPU_SHADER4] && gl_info->supported[ARB_GEOMETRY_SHADER4]
4958 && gl_info->glsl_version >= MAKEDWORD_VERSION(1, 50))
4960 caps->VertexShaderVersion = 4;
4961 caps->PixelShaderVersion = 4;
4963 /* ARB_shader_texture_lod or EXT_gpu_shader4 is required for the SM3
4964 * texldd and texldl instructions. */
4965 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] || gl_info->supported[EXT_GPU_SHADER4])
4967 caps->VertexShaderVersion = 3;
4968 caps->PixelShaderVersion = 3;
4972 caps->VertexShaderVersion = 2;
4973 caps->PixelShaderVersion = 2;
4976 caps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4977 caps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4979 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4980 * Direct3D minimum requirement.
4982 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4983 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4985 * The problem is that the refrast clamps temporary results in the shader to
4986 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4987 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4988 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4989 * offer a way to query this.
4991 caps->PixelShader1xMaxValue = 8.0;
4993 caps->VSClipping = TRUE;
4995 TRACE("Hardware vertex shader version %u enabled (GLSL).\n", caps->VertexShaderVersion);
4996 TRACE("Hardware pixel shader version %u enabled (GLSL).\n", caps->PixelShaderVersion);
4999 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
5001 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
5003 TRACE("Checking support for fixup:\n");
5004 dump_color_fixup_desc(fixup);
5007 /* We support everything except YUV conversions. */
5008 if (!is_complex_fixup(fixup))
5014 TRACE("[FAILED]\n");
5018 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
5020 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
5021 /* WINED3DSIH_ADD */ shader_glsl_arith,
5022 /* WINED3DSIH_AND */ NULL,
5023 /* WINED3DSIH_BEM */ shader_glsl_bem,
5024 /* WINED3DSIH_BREAK */ shader_glsl_break,
5025 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
5026 /* WINED3DSIH_BREAKP */ NULL,
5027 /* WINED3DSIH_CALL */ shader_glsl_call,
5028 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
5029 /* WINED3DSIH_CMP */ shader_glsl_cmp,
5030 /* WINED3DSIH_CND */ shader_glsl_cnd,
5031 /* WINED3DSIH_CRS */ shader_glsl_cross,
5032 /* WINED3DSIH_CUT */ NULL,
5033 /* WINED3DSIH_DCL */ shader_glsl_nop,
5034 /* WINED3DSIH_DCL_INPUT_PRIMITIVE */ shader_glsl_nop,
5035 /* WINED3DSIH_DCL_OUTPUT_TOPOLOGY */ shader_glsl_nop,
5036 /* WINED3DSIH_DCL_VERTICES_OUT */ shader_glsl_nop,
5037 /* WINED3DSIH_DEF */ shader_glsl_nop,
5038 /* WINED3DSIH_DEFB */ shader_glsl_nop,
5039 /* WINED3DSIH_DEFI */ shader_glsl_nop,
5040 /* WINED3DSIH_DIV */ NULL,
5041 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
5042 /* WINED3DSIH_DP3 */ shader_glsl_dot,
5043 /* WINED3DSIH_DP4 */ shader_glsl_dot,
5044 /* WINED3DSIH_DST */ shader_glsl_dst,
5045 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
5046 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
5047 /* WINED3DSIH_ELSE */ shader_glsl_else,
5048 /* WINED3DSIH_EMIT */ NULL,
5049 /* WINED3DSIH_ENDIF */ shader_glsl_end,
5050 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5051 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5052 /* WINED3DSIH_EQ */ NULL,
5053 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5054 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5055 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5056 /* WINED3DSIH_FTOI */ NULL,
5057 /* WINED3DSIH_GE */ NULL,
5058 /* WINED3DSIH_IADD */ NULL,
5059 /* WINED3DSIH_IEQ */ NULL,
5060 /* WINED3DSIH_IF */ shader_glsl_if,
5061 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5062 /* WINED3DSIH_IGE */ NULL,
5063 /* WINED3DSIH_IMUL */ NULL,
5064 /* WINED3DSIH_ITOF */ NULL,
5065 /* WINED3DSIH_LABEL */ shader_glsl_label,
5066 /* WINED3DSIH_LD */ NULL,
5067 /* WINED3DSIH_LIT */ shader_glsl_lit,
5068 /* WINED3DSIH_LOG */ shader_glsl_log,
5069 /* WINED3DSIH_LOGP */ shader_glsl_log,
5070 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5071 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5072 /* WINED3DSIH_LT */ NULL,
5073 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5074 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5075 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5076 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5077 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5078 /* WINED3DSIH_MAD */ shader_glsl_mad,
5079 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5080 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5081 /* WINED3DSIH_MOV */ shader_glsl_mov,
5082 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5083 /* WINED3DSIH_MOVC */ NULL,
5084 /* WINED3DSIH_MUL */ shader_glsl_arith,
5085 /* WINED3DSIH_NOP */ shader_glsl_nop,
5086 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5087 /* WINED3DSIH_PHASE */ shader_glsl_nop,
5088 /* WINED3DSIH_POW */ shader_glsl_pow,
5089 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5090 /* WINED3DSIH_REP */ shader_glsl_rep,
5091 /* WINED3DSIH_RET */ shader_glsl_ret,
5092 /* WINED3DSIH_ROUND_NI */ NULL,
5093 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5094 /* WINED3DSIH_SAMPLE */ NULL,
5095 /* WINED3DSIH_SAMPLE_GRAD */ NULL,
5096 /* WINED3DSIH_SAMPLE_LOD */ NULL,
5097 /* WINED3DSIH_SETP */ NULL,
5098 /* WINED3DSIH_SGE */ shader_glsl_compare,
5099 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5100 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5101 /* WINED3DSIH_SLT */ shader_glsl_compare,
5102 /* WINED3DSIH_SQRT */ NULL,
5103 /* WINED3DSIH_SUB */ shader_glsl_arith,
5104 /* WINED3DSIH_TEX */ shader_glsl_tex,
5105 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5106 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5107 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5108 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5109 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5110 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5111 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5112 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5113 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5114 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5115 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5116 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5117 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5118 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5119 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5120 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5121 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5122 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5123 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5124 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5125 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5126 /* WINED3DSIH_UDIV */ NULL,
5127 /* WINED3DSIH_USHR */ NULL,
5128 /* WINED3DSIH_UTOF */ NULL,
5129 /* WINED3DSIH_XOR */ NULL,
5132 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5133 SHADER_HANDLER hw_fct;
5135 /* Select handler */
5136 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5138 /* Unhandled opcode */
5141 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5146 shader_glsl_add_instruction_modifiers(ins);
5149 const struct wined3d_shader_backend_ops glsl_shader_backend =
5151 shader_glsl_handle_instruction,
5153 shader_glsl_select_depth_blt,
5154 shader_glsl_deselect_depth_blt,
5155 shader_glsl_update_float_vertex_constants,
5156 shader_glsl_update_float_pixel_constants,
5157 shader_glsl_load_constants,
5158 shader_glsl_load_np2fixup_constants,
5159 shader_glsl_destroy,
5162 shader_glsl_context_destroyed,
5163 shader_glsl_get_caps,
5164 shader_glsl_color_fixup_supported,