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_caps);
43 WINE_DECLARE_DEBUG_CHANNEL(d3d);
44 WINE_DECLARE_DEBUG_CHANNEL(winediag);
46 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
47 #define WINED3D_GLSL_SAMPLE_RECT 0x2
48 #define WINED3D_GLSL_SAMPLE_LOD 0x4
49 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
63 struct glsl_sample_function
71 HEAP_NODE_TRAVERSE_LEFT,
72 HEAP_NODE_TRAVERSE_RIGHT,
84 struct constant_entry *entries;
85 unsigned int *positions;
89 /* GLSL shader private data */
90 struct shader_glsl_priv {
91 struct wined3d_shader_buffer shader_buffer;
92 struct wine_rb_tree program_lookup;
93 struct glsl_shader_prog_link *glsl_program;
94 struct constant_heap vconst_heap;
95 struct constant_heap pconst_heap;
97 GLhandleARB depth_blt_program_full[tex_type_count];
98 GLhandleARB depth_blt_program_masked[tex_type_count];
99 UINT next_constant_version;
102 /* Struct to maintain data about a linked GLSL program */
103 struct glsl_shader_prog_link {
104 struct wine_rb_entry program_lookup_entry;
105 struct list vshader_entry;
106 struct list pshader_entry;
107 GLhandleARB programId;
108 GLint *vuniformF_locations;
109 GLint *puniformF_locations;
110 GLint vuniformI_locations[MAX_CONST_I];
111 GLint puniformI_locations[MAX_CONST_I];
112 GLint posFixup_location;
113 GLint np2Fixup_location;
114 GLint bumpenvmat_location[MAX_TEXTURES];
115 GLint luminancescale_location[MAX_TEXTURES];
116 GLint luminanceoffset_location[MAX_TEXTURES];
117 GLint ycorrection_location;
118 GLenum vertex_color_clamp;
119 const struct wined3d_shader *vshader;
120 const struct wined3d_shader *pshader;
121 struct vs_compile_args vs_args;
122 struct ps_compile_args ps_args;
123 UINT constant_version;
124 const struct ps_np2fixup_info *np2Fixup_info;
127 struct glsl_program_key
129 const struct wined3d_shader *vshader;
130 const struct wined3d_shader *pshader;
131 struct ps_compile_args ps_args;
132 struct vs_compile_args vs_args;
135 struct shader_glsl_ctx_priv {
136 const struct vs_compile_args *cur_vs_args;
137 const struct ps_compile_args *cur_ps_args;
138 struct ps_np2fixup_info *cur_np2fixup_info;
141 struct glsl_ps_compiled_shader
143 struct ps_compile_args args;
144 struct ps_np2fixup_info np2fixup;
148 struct glsl_pshader_private
150 struct glsl_ps_compiled_shader *gl_shaders;
151 UINT num_gl_shaders, shader_array_size;
154 struct glsl_vs_compiled_shader
156 struct vs_compile_args args;
160 struct glsl_vshader_private
162 struct glsl_vs_compiled_shader *gl_shaders;
163 UINT num_gl_shaders, shader_array_size;
166 static const char *debug_gl_shader_type(GLenum type)
170 #define WINED3D_TO_STR(u) case u: return #u
171 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
172 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
173 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
174 #undef WINED3D_TO_STR
176 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
180 /* Extract a line from the info log.
181 * Note that this modifies the source string. */
182 static char *get_info_log_line(char **ptr)
187 if (!(q = strstr(p, "\n")))
189 if (!*p) return NULL;
199 /** Prints the GLSL info log which will contain error messages if they exist */
200 /* GL locking is done by the caller */
201 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
203 int infologLength = 0;
206 if (!WARN_ON(d3d_shader) && !FIXME_ON(d3d_shader))
209 GL_EXTCALL(glGetObjectParameterivARB(obj,
210 GL_OBJECT_INFO_LOG_LENGTH_ARB,
213 /* A size of 1 is just a null-terminated string, so the log should be bigger than
214 * that if there are errors. */
215 if (infologLength > 1)
219 infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
220 /* The info log is supposed to be zero-terminated, but at least some
221 * versions of fglrx don't terminate the string properly. The reported
222 * length does include the terminator, so explicitly set it to zero
224 infoLog[infologLength - 1] = 0;
225 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
228 if (gl_info->quirks & WINED3D_QUIRK_INFO_LOG_SPAM)
230 WARN("Info log received from GLSL shader #%u:\n", obj);
231 while ((line = get_info_log_line(&ptr))) WARN(" %s\n", line);
235 FIXME("Info log received from GLSL shader #%u:\n", obj);
236 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
238 HeapFree(GetProcessHeap(), 0, infoLog);
242 /* GL locking is done by the caller. */
243 static void shader_glsl_compile(const struct wined3d_gl_info *gl_info, GLhandleARB shader, const char *src)
245 TRACE("Compiling shader object %u.\n", shader);
246 GL_EXTCALL(glShaderSourceARB(shader, 1, &src, NULL));
247 checkGLcall("glShaderSourceARB");
248 GL_EXTCALL(glCompileShaderARB(shader));
249 checkGLcall("glCompileShaderARB");
250 print_glsl_info_log(gl_info, shader);
253 /* GL locking is done by the caller. */
254 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
256 GLint i, object_count, source_size = -1;
257 GLhandleARB *objects;
260 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
261 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
264 ERR("Failed to allocate object array memory.\n");
268 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
269 for (i = 0; i < object_count; ++i)
274 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
276 if (source_size < tmp)
278 HeapFree(GetProcessHeap(), 0, source);
280 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
283 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
284 HeapFree(GetProcessHeap(), 0, objects);
290 FIXME("Object %u:\n", objects[i]);
291 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
292 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
293 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
294 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
298 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
299 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
303 HeapFree(GetProcessHeap(), 0, source);
304 HeapFree(GetProcessHeap(), 0, objects);
307 /* GL locking is done by the caller. */
308 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
312 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
314 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
315 if (tmp == GL_PROGRAM_OBJECT_ARB)
317 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
320 FIXME("Program %u link status invalid.\n", program);
321 shader_glsl_dump_program_source(gl_info, program);
325 print_glsl_info_log(gl_info, program);
329 * Loads (pixel shader) samplers
331 /* GL locking is done by the caller */
332 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
333 const DWORD *tex_unit_map, GLhandleARB programId)
337 char sampler_name[20];
339 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
340 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
341 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
342 if (name_loc != -1) {
343 DWORD mapped_unit = tex_unit_map[i];
344 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
346 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
347 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
348 checkGLcall("glUniform1iARB");
350 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
356 /* GL locking is done by the caller */
357 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
358 const DWORD *tex_unit_map, GLhandleARB programId)
361 char sampler_name[20];
364 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
365 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
366 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
367 if (name_loc != -1) {
368 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
369 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
371 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
372 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
373 checkGLcall("glUniform1iARB");
375 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
381 /* GL locking is done by the caller */
382 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
383 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
386 unsigned int heap_idx = 1;
389 if (heap->entries[heap_idx].version <= version) return;
391 idx = heap->entries[heap_idx].idx;
392 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
393 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
395 while (stack_idx >= 0)
397 /* Note that we fall through to the next case statement. */
398 switch(stack[stack_idx])
400 case HEAP_NODE_TRAVERSE_LEFT:
402 unsigned int left_idx = heap_idx << 1;
403 if (left_idx < heap->size && heap->entries[left_idx].version > version)
406 idx = heap->entries[heap_idx].idx;
407 if (constant_locations[idx] != -1)
408 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
410 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
411 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
416 case HEAP_NODE_TRAVERSE_RIGHT:
418 unsigned int right_idx = (heap_idx << 1) + 1;
419 if (right_idx < heap->size && heap->entries[right_idx].version > version)
421 heap_idx = right_idx;
422 idx = heap->entries[heap_idx].idx;
423 if (constant_locations[idx] != -1)
424 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
426 stack[stack_idx++] = HEAP_NODE_POP;
427 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
438 checkGLcall("walk_constant_heap()");
441 /* GL locking is done by the caller */
442 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
444 GLfloat clamped_constant[4];
446 if (location == -1) return;
448 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
449 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
450 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
451 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
453 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
456 /* GL locking is done by the caller */
457 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
458 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
461 unsigned int heap_idx = 1;
464 if (heap->entries[heap_idx].version <= version) return;
466 idx = heap->entries[heap_idx].idx;
467 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
468 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
470 while (stack_idx >= 0)
472 /* Note that we fall through to the next case statement. */
473 switch(stack[stack_idx])
475 case HEAP_NODE_TRAVERSE_LEFT:
477 unsigned int left_idx = heap_idx << 1;
478 if (left_idx < heap->size && heap->entries[left_idx].version > version)
481 idx = heap->entries[heap_idx].idx;
482 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
484 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
485 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
490 case HEAP_NODE_TRAVERSE_RIGHT:
492 unsigned int right_idx = (heap_idx << 1) + 1;
493 if (right_idx < heap->size && heap->entries[right_idx].version > version)
495 heap_idx = right_idx;
496 idx = heap->entries[heap_idx].idx;
497 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
499 stack[stack_idx++] = HEAP_NODE_POP;
500 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
511 checkGLcall("walk_constant_heap_clamped()");
514 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
515 /* GL locking is done by the caller */
516 static void shader_glsl_load_constantsF(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
517 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
518 unsigned char *stack, UINT version)
520 const struct wined3d_shader_lconst *lconst;
522 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
523 if (shader->reg_maps.shader_version.major == 1
524 && shader_is_pshader_version(shader->reg_maps.shader_version.type))
525 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
527 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
529 if (!shader->load_local_constsF)
531 TRACE("No need to load local float constants for this shader\n");
535 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
536 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
538 GLint location = constant_locations[lconst->idx];
539 /* We found this uniform name in the program - go ahead and send the data */
540 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
542 checkGLcall("glUniform4fvARB()");
545 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
546 /* GL locking is done by the caller */
547 static void shader_glsl_load_constantsI(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
548 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
553 for (i = 0; constants_set; constants_set >>= 1, ++i)
555 if (!(constants_set & 1)) continue;
557 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
558 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
560 /* We found this uniform name in the program - go ahead and send the data */
561 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
562 checkGLcall("glUniform4ivARB");
565 /* Load immediate constants */
566 ptr = list_head(&shader->constantsI);
569 const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
570 unsigned int idx = lconst->idx;
571 const GLint *values = (const GLint *)lconst->value;
573 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
574 values[0], values[1], values[2], values[3]);
576 /* We found this uniform name in the program - go ahead and send the data */
577 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
578 checkGLcall("glUniform4ivARB");
579 ptr = list_next(&shader->constantsI, ptr);
583 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
584 /* GL locking is done by the caller */
585 static void shader_glsl_load_constantsB(const struct wined3d_shader *shader, const struct wined3d_gl_info *gl_info,
586 GLhandleARB programId, const BOOL *constants, WORD constants_set)
594 switch (shader->reg_maps.shader_version.type)
596 case WINED3D_SHADER_TYPE_VERTEX:
600 case WINED3D_SHADER_TYPE_GEOMETRY:
604 case WINED3D_SHADER_TYPE_PIXEL:
609 FIXME("Unknown shader type %#x.\n",
610 shader->reg_maps.shader_version.type);
615 /* TODO: Benchmark and see if it would be beneficial to store the
616 * locations of the constants to avoid looking up each time */
617 for (i = 0; constants_set; constants_set >>= 1, ++i)
619 if (!(constants_set & 1)) continue;
621 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
623 /* TODO: Benchmark and see if it would be beneficial to store the
624 * locations of the constants to avoid looking up each time */
625 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
626 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
629 /* We found this uniform name in the program - go ahead and send the data */
630 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
631 checkGLcall("glUniform1ivARB");
635 /* Load immediate constants */
636 ptr = list_head(&shader->constantsB);
639 const struct wined3d_shader_lconst *lconst = LIST_ENTRY(ptr, const struct wined3d_shader_lconst, entry);
640 unsigned int idx = lconst->idx;
641 const GLint *values = (const GLint *)lconst->value;
643 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
645 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
646 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
648 /* We found this uniform name in the program - go ahead and send the data */
649 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
650 checkGLcall("glUniform1ivARB");
652 ptr = list_next(&shader->constantsB, ptr);
656 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
658 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
662 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
664 /* GL locking is done by the caller (state handler) */
665 static void shader_glsl_load_np2fixup_constants(void *shader_priv,
666 const struct wined3d_gl_info *gl_info, const struct wined3d_state *state)
668 struct shader_glsl_priv *glsl_priv = shader_priv;
669 const struct glsl_shader_prog_link *prog = glsl_priv->glsl_program;
671 /* No GLSL program set - nothing to do. */
674 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
675 if (!use_ps(state)) return;
677 if (prog->ps_args.np2_fixup && prog->np2Fixup_location != -1)
680 UINT fixup = prog->ps_args.np2_fixup;
681 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
683 for (i = 0; fixup; fixup >>= 1, ++i)
685 const struct wined3d_texture *tex = state->textures[i];
686 const unsigned char idx = prog->np2Fixup_info->idx[i];
687 GLfloat *tex_dim = &np2fixup_constants[(idx >> 1) * 4];
691 ERR("Nonexistent texture is flagged for NP2 texcoord fixup.\n");
697 tex_dim[2] = tex->pow2_matrix[0];
698 tex_dim[3] = tex->pow2_matrix[5];
702 tex_dim[0] = tex->pow2_matrix[0];
703 tex_dim[1] = tex->pow2_matrix[5];
707 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
712 * Loads the app-supplied constants into the currently set GLSL program.
714 /* GL locking is done by the caller (state handler) */
715 static void shader_glsl_load_constants(const struct wined3d_context *context,
716 char usePixelShader, char useVertexShader)
718 const struct wined3d_gl_info *gl_info = context->gl_info;
719 struct wined3d_device *device = context->swapchain->device;
720 struct wined3d_stateblock *stateBlock = device->stateBlock;
721 const struct wined3d_state *state = &stateBlock->state;
722 struct shader_glsl_priv *priv = device->shader_priv;
723 float position_fixup[4];
725 GLhandleARB programId;
726 struct glsl_shader_prog_link *prog = priv->glsl_program;
727 UINT constant_version;
731 /* No GLSL program set - nothing to do. */
734 programId = prog->programId;
735 constant_version = prog->constant_version;
739 const struct wined3d_shader *vshader = state->vertex_shader;
741 /* Load DirectX 9 float constants/uniforms for vertex shader */
742 shader_glsl_load_constantsF(vshader, gl_info, state->vs_consts_f,
743 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
745 /* Load DirectX 9 integer constants/uniforms for vertex shader */
746 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, state->vs_consts_i,
747 stateBlock->changed.vertexShaderConstantsI & vshader->reg_maps.integer_constants);
749 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
750 shader_glsl_load_constantsB(vshader, gl_info, programId, state->vs_consts_b,
751 stateBlock->changed.vertexShaderConstantsB & vshader->reg_maps.boolean_constants);
753 /* Upload the position fixup params */
754 shader_get_position_fixup(context, state, position_fixup);
755 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, position_fixup));
756 checkGLcall("glUniform4fvARB");
761 const struct wined3d_shader *pshader = state->pixel_shader;
763 /* Load DirectX 9 float constants/uniforms for pixel shader */
764 shader_glsl_load_constantsF(pshader, gl_info, state->ps_consts_f,
765 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
767 /* Load DirectX 9 integer constants/uniforms for pixel shader */
768 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, state->ps_consts_i,
769 stateBlock->changed.pixelShaderConstantsI & pshader->reg_maps.integer_constants);
771 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
772 shader_glsl_load_constantsB(pshader, gl_info, programId, state->ps_consts_b,
773 stateBlock->changed.pixelShaderConstantsB & pshader->reg_maps.boolean_constants);
775 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
776 * It can't be 0 for a valid texbem instruction.
778 for(i = 0; i < MAX_TEXTURES; i++) {
781 if(prog->bumpenvmat_location[i] == -1) continue;
783 data = (const float *)&state->texture_states[i][WINED3D_TSS_BUMPENV_MAT00];
784 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
785 checkGLcall("glUniformMatrix2fvARB");
787 /* texbeml needs the luminance scale and offset too. If texbeml
788 * is used, needsbumpmat is set too, so we can check that in the
789 * needsbumpmat check. */
790 if (prog->luminancescale_location[i] != -1)
792 const GLfloat *scale = (const GLfloat *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LSCALE];
793 const GLfloat *offset = (const GLfloat *)&state->texture_states[i][WINED3D_TSS_BUMPENV_LOFFSET];
795 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
796 checkGLcall("glUniform1fvARB");
797 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
798 checkGLcall("glUniform1fvARB");
802 if (prog->ycorrection_location != -1)
804 float correction_params[4];
806 if (context->render_offscreen)
808 correction_params[0] = 0.0f;
809 correction_params[1] = 1.0f;
811 /* position is window relative, not viewport relative */
812 correction_params[0] = (float) context->current_rt->resource.height;
813 correction_params[1] = -1.0f;
815 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
819 if (priv->next_constant_version == UINT_MAX)
821 TRACE("Max constant version reached, resetting to 0.\n");
822 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
823 priv->next_constant_version = 1;
827 prog->constant_version = priv->next_constant_version++;
831 static void update_heap_entry(const struct constant_heap *heap, unsigned int idx,
832 unsigned int heap_idx, DWORD new_version)
834 struct constant_entry *entries = heap->entries;
835 unsigned int *positions = heap->positions;
836 unsigned int parent_idx;
840 parent_idx = heap_idx >> 1;
842 if (new_version <= entries[parent_idx].version) break;
844 entries[heap_idx] = entries[parent_idx];
845 positions[entries[parent_idx].idx] = heap_idx;
846 heap_idx = parent_idx;
849 entries[heap_idx].version = new_version;
850 entries[heap_idx].idx = idx;
851 positions[idx] = heap_idx;
854 static void shader_glsl_update_float_vertex_constants(struct wined3d_device *device, UINT start, UINT count)
856 struct shader_glsl_priv *priv = device->shader_priv;
857 struct constant_heap *heap = &priv->vconst_heap;
860 for (i = start; i < count + start; ++i)
862 if (!device->stateBlock->changed.vertexShaderConstantsF[i])
863 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
865 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
869 static void shader_glsl_update_float_pixel_constants(struct wined3d_device *device, UINT start, UINT count)
871 struct shader_glsl_priv *priv = device->shader_priv;
872 struct constant_heap *heap = &priv->pconst_heap;
875 for (i = start; i < count + start; ++i)
877 if (!device->stateBlock->changed.pixelShaderConstantsF[i])
878 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
880 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
884 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
886 unsigned int ret = gl_info->limits.glsl_varyings / 4;
887 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
888 if(shader_major > 3) return ret;
890 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
891 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
895 /** Generate the variable & register declarations for the GLSL output target */
896 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
897 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
898 const struct wined3d_shader_reg_maps *reg_maps, const struct shader_glsl_ctx_priv *ctx_priv)
900 const struct wined3d_state *state = &shader->device->stateBlock->state;
901 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
902 const struct wined3d_gl_info *gl_info = context->gl_info;
903 const struct wined3d_fb_state *fb = &shader->device->fb;
904 unsigned int i, extra_constants_needed = 0;
905 const struct wined3d_shader_lconst *lconst;
908 /* There are some minor differences between pixel and vertex shaders */
909 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
910 char prefix = pshader ? 'P' : 'V';
912 /* Prototype the subroutines */
913 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
915 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
918 /* Declare the constants (aka uniforms) */
919 if (shader->limits.constant_float > 0)
921 unsigned max_constantsF;
922 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
923 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
924 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
925 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
926 * a dx9 card, as long as it doesn't also use all the other constants.
928 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
929 * declare only the amount that we're assured to have.
931 * Thus we run into problems in these two cases:
932 * 1) The shader really uses more uniforms than supported
933 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
937 /* No indirect addressing here. */
938 max_constantsF = gl_info->limits.glsl_ps_float_constants;
942 if (reg_maps->usesrelconstF)
944 /* Subtract the other potential uniforms from the max
945 * available (bools, ints, and 1 row of projection matrix).
946 * Subtract another uniform for immediate values, which have
947 * to be loaded via uniform by the driver as well. The shader
948 * code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex
949 * shader code, so one vec4 should be enough. (Unfortunately
950 * the Nvidia driver doesn't store 128 and -128 in one float).
952 * Writing gl_ClipVertex requires one uniform for each
953 * clipplane as well. */
954 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
955 if(ctx_priv->cur_vs_args->clip_enabled)
957 max_constantsF -= gl_info->limits.clipplanes;
959 max_constantsF -= count_bits(reg_maps->integer_constants);
960 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
961 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
962 * for now take this into account when calculating the number of available constants
964 max_constantsF -= count_bits(reg_maps->boolean_constants);
965 /* Set by driver quirks in directx.c */
966 max_constantsF -= gl_info->reserved_glsl_constants;
968 if (max_constantsF < shader->limits.constant_float)
970 static unsigned int once;
973 ERR_(winediag)("The hardware does not support enough uniform components to run this shader,"
974 " it may not render correctly.\n");
976 WARN("The hardware does not support enough uniform components to run this shader.\n");
981 max_constantsF = gl_info->limits.glsl_vs_float_constants;
984 max_constantsF = min(shader->limits.constant_float, max_constantsF);
985 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
988 /* Always declare the full set of constants, the compiler can remove the
989 * unused ones because d3d doesn't (yet) support indirect int and bool
990 * constant addressing. This avoids problems if the app uses e.g. i0 and i9. */
991 if (shader->limits.constant_int > 0 && reg_maps->integer_constants)
992 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, shader->limits.constant_int);
994 if (shader->limits.constant_bool > 0 && reg_maps->boolean_constants)
995 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, shader->limits.constant_bool);
999 shader_addline(buffer, "uniform vec4 posFixup;\n");
1000 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
1004 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1006 if (!(map & 1)) continue;
1008 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1010 if (reg_maps->luminanceparams & (1 << i))
1012 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1013 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1014 extra_constants_needed++;
1017 extra_constants_needed++;
1020 if (ps_args->srgb_correction)
1022 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1023 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1024 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1027 if (reg_maps->vpos || reg_maps->usesdsy)
1029 if (shader->limits.constant_float + extra_constants_needed
1030 + 1 < gl_info->limits.glsl_ps_float_constants)
1032 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1033 extra_constants_needed++;
1037 /* This happens because we do not have proper tracking of the constant registers that are
1038 * actually used, only the max limit of the shader version
1040 FIXME("Cannot find a free uniform for vpos correction params\n");
1041 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1042 context->render_offscreen ? 0.0f : fb->render_targets[0]->resource.height,
1043 context->render_offscreen ? 1.0f : -1.0f);
1045 shader_addline(buffer, "vec4 vpos;\n");
1049 /* Declare texture samplers */
1050 for (i = 0; i < shader->limits.sampler; ++i)
1052 if (reg_maps->sampler_type[i])
1054 const struct wined3d_texture *texture;
1056 switch (reg_maps->sampler_type[i])
1059 if (pshader && ps_args->shadow & (1 << i))
1060 shader_addline(buffer, "uniform sampler1DShadow %csampler%u;\n", prefix, i);
1062 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1065 texture = state->textures[i];
1066 if (pshader && ps_args->shadow & (1 << i))
1068 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1069 shader_addline(buffer, "uniform sampler2DRectShadow %csampler%u;\n", prefix, i);
1071 shader_addline(buffer, "uniform sampler2DShadow %csampler%u;\n", prefix, i);
1075 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
1076 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1078 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1081 case WINED3DSTT_CUBE:
1082 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported Cube shadow sampler.\n");
1083 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1085 case WINED3DSTT_VOLUME:
1086 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported 3D shadow sampler.\n");
1087 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1090 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1091 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1097 /* Declare uniforms for NP2 texcoord fixup:
1098 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1099 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1100 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1101 if (pshader && ps_args->np2_fixup) {
1103 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1106 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1107 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1108 * samplerNP2Fixup stores texture dimensions and is updated through
1109 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1111 for (i = 0; i < shader->limits.sampler; ++i)
1113 if (reg_maps->sampler_type[i])
1115 if (!(ps_args->np2_fixup & (1 << i))) continue;
1117 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1118 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1122 fixup->idx[i] = cur++;
1126 fixup->num_consts = (cur + 1) >> 1;
1127 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1130 /* Declare address variables */
1131 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1133 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1136 /* Declare texture coordinate temporaries and initialize them */
1137 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1139 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1142 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1143 * helper function shader that is linked in at link time
1145 if (pshader && reg_maps->shader_version.major >= 3)
1147 UINT in_count = min(vec4_varyings(reg_maps->shader_version.major, gl_info), shader->limits.packed_input);
1150 shader_addline(buffer, "varying vec4 IN[%u];\n", in_count);
1152 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1153 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1154 * pixel shader that reads the fixed function color into the packed input registers. */
1155 shader_addline(buffer, "vec4 IN[%u];\n", in_count);
1158 /* Declare output register temporaries */
1159 if (shader->limits.packed_output)
1160 shader_addline(buffer, "vec4 OUT[%u];\n", shader->limits.packed_output);
1162 /* Declare temporary variables */
1163 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1165 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1168 /* Declare attributes */
1169 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1171 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1173 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1177 /* Declare loop registers aLx */
1178 for (i = 0; i < reg_maps->loop_depth; i++) {
1179 shader_addline(buffer, "int aL%u;\n", i);
1180 shader_addline(buffer, "int tmpInt%u;\n", i);
1183 /* Temporary variables for matrix operations */
1184 shader_addline(buffer, "vec4 tmp0;\n");
1185 shader_addline(buffer, "vec4 tmp1;\n");
1187 /* Local constants use a different name so they can be loaded once at shader link time
1188 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1189 * float -> string conversion can cause precision loss.
1191 if (!shader->load_local_constsF)
1193 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
1195 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1199 /* Start the main program */
1200 shader_addline(buffer, "void main() {\n");
1201 if(pshader && reg_maps->vpos) {
1202 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1203 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1204 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1205 * precision troubles when we just subtract 0.5.
1207 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1209 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1211 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1212 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1213 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1214 * correctly on drivers that returns integer values.
1216 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1220 /*****************************************************************************
1221 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1223 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1224 ****************************************************************************/
1227 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1228 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src);
1230 /** Used for opcode modifiers - They multiply the result by the specified amount */
1231 static const char * const shift_glsl_tab[] = {
1233 "2.0 * ", /* 1 (x2) */
1234 "4.0 * ", /* 2 (x4) */
1235 "8.0 * ", /* 3 (x8) */
1236 "16.0 * ", /* 4 (x16) */
1237 "32.0 * ", /* 5 (x32) */
1244 "0.0625 * ", /* 12 (d16) */
1245 "0.125 * ", /* 13 (d8) */
1246 "0.25 * ", /* 14 (d4) */
1247 "0.5 * " /* 15 (d2) */
1250 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1251 static void shader_glsl_gen_modifier(enum wined3d_shader_src_modifier src_modifier,
1252 const char *in_reg, const char *in_regswizzle, char *out_str)
1256 switch (src_modifier)
1258 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1259 case WINED3DSPSM_DW:
1260 case WINED3DSPSM_NONE:
1261 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1263 case WINED3DSPSM_NEG:
1264 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1266 case WINED3DSPSM_NOT:
1267 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1269 case WINED3DSPSM_BIAS:
1270 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1272 case WINED3DSPSM_BIASNEG:
1273 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1275 case WINED3DSPSM_SIGN:
1276 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1278 case WINED3DSPSM_SIGNNEG:
1279 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1281 case WINED3DSPSM_COMP:
1282 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1284 case WINED3DSPSM_X2:
1285 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1287 case WINED3DSPSM_X2NEG:
1288 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1290 case WINED3DSPSM_ABS:
1291 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1293 case WINED3DSPSM_ABSNEG:
1294 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1297 FIXME("Unhandled modifier %u\n", src_modifier);
1298 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1302 /** Writes the GLSL variable name that corresponds to the register that the
1303 * DX opcode parameter is trying to access */
1304 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1305 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1307 /* oPos, oFog and oPts in D3D */
1308 static const char * const hwrastout_reg_names[] = {"OUT[10]", "OUT[11].x", "OUT[11].y"};
1310 const struct wined3d_shader *shader = ins->ctx->shader;
1311 const struct wined3d_shader_reg_maps *reg_maps = ins->ctx->reg_maps;
1312 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1313 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
1319 case WINED3DSPR_TEMP:
1320 sprintf(register_name, "R%u", reg->idx);
1323 case WINED3DSPR_INPUT:
1324 /* vertex shaders */
1327 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1328 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1329 sprintf(register_name, "attrib%u", reg->idx);
1333 /* pixel shaders >= 3.0 */
1334 if (reg_maps->shader_version.major >= 3)
1336 DWORD idx = shader->u.ps.input_reg_map[reg->idx];
1337 unsigned int in_count = vec4_varyings(reg_maps->shader_version.major, gl_info);
1341 struct glsl_src_param rel_param;
1343 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1345 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1346 * operation there */
1349 if (shader->u.ps.declared_in_count > in_count)
1351 sprintf(register_name,
1352 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1353 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1354 rel_param.param_str, idx);
1358 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1363 if (shader->u.ps.declared_in_count > in_count)
1365 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1366 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1367 rel_param.param_str);
1371 sprintf(register_name, "IN[%s]", rel_param.param_str);
1377 if (idx == in_count) sprintf(register_name, "gl_Color");
1378 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1379 else sprintf(register_name, "IN[%u]", idx);
1384 if (!reg->idx) strcpy(register_name, "gl_Color");
1385 else strcpy(register_name, "gl_SecondaryColor");
1390 case WINED3DSPR_CONST:
1392 const char prefix = pshader ? 'P' : 'V';
1394 /* Relative addressing */
1397 struct glsl_src_param rel_param;
1398 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1399 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1400 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1404 if (shader_constant_is_local(shader, reg->idx))
1405 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1407 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1412 case WINED3DSPR_CONSTINT:
1413 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1414 else sprintf(register_name, "VI[%u]", reg->idx);
1417 case WINED3DSPR_CONSTBOOL:
1418 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1419 else sprintf(register_name, "VB[%u]", reg->idx);
1422 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1423 if (pshader) sprintf(register_name, "T%u", reg->idx);
1424 else sprintf(register_name, "A%u", reg->idx);
1427 case WINED3DSPR_LOOP:
1428 sprintf(register_name, "aL%u", ins->ctx->loop_state->current_reg - 1);
1431 case WINED3DSPR_SAMPLER:
1432 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1433 else sprintf(register_name, "Vsampler%u", reg->idx);
1436 case WINED3DSPR_COLOROUT:
1437 if (reg->idx >= gl_info->limits.buffers)
1438 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1440 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1443 case WINED3DSPR_RASTOUT:
1444 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1447 case WINED3DSPR_DEPTHOUT:
1448 sprintf(register_name, "gl_FragDepth");
1451 case WINED3DSPR_ATTROUT:
1452 if (!reg->idx) sprintf(register_name, "OUT[8]");
1453 else sprintf(register_name, "OUT[9]");
1456 case WINED3DSPR_TEXCRDOUT:
1457 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1458 sprintf(register_name, "OUT[%u]", reg->idx);
1461 case WINED3DSPR_MISCTYPE:
1465 sprintf(register_name, "vpos");
1467 else if (reg->idx == 1)
1469 /* Note that gl_FrontFacing is a bool, while vFace is
1470 * a float for which the sign determines front/back */
1471 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1475 FIXME("Unhandled misctype register %d\n", reg->idx);
1476 sprintf(register_name, "unrecognized_register");
1480 case WINED3DSPR_IMMCONST:
1481 switch (reg->immconst_type)
1483 case WINED3D_IMMCONST_SCALAR:
1484 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1487 case WINED3D_IMMCONST_VEC4:
1488 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1489 *(const float *)®->immconst_data[0], *(const float *)®->immconst_data[1],
1490 *(const float *)®->immconst_data[2], *(const float *)®->immconst_data[3]);
1494 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1495 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1500 FIXME("Unhandled register name Type(%d)\n", reg->type);
1501 sprintf(register_name, "unrecognized_register");
1506 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1509 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1510 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1511 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1512 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1516 /* Get the GLSL write mask for the destination register */
1517 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1519 DWORD mask = param->write_mask;
1521 if (shader_is_scalar(¶m->reg))
1523 mask = WINED3DSP_WRITEMASK_0;
1528 shader_glsl_write_mask_to_str(mask, write_mask);
1534 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1535 unsigned int size = 0;
1537 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1538 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1539 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1540 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1545 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1547 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1548 * but addressed as "rgba". To fix this we need to swap the register's x
1549 * and z components. */
1550 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1553 /* swizzle bits fields: wwzzyyxx */
1554 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1555 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1556 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1557 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1561 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1562 BOOL fixup, DWORD mask, char *swizzle_str)
1564 if (shader_is_scalar(¶m->reg))
1565 *swizzle_str = '\0';
1567 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1570 /* From a given parameter token, generate the corresponding GLSL string.
1571 * Also, return the actual register name and swizzle in case the
1572 * caller needs this information as well. */
1573 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1574 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, struct glsl_src_param *glsl_src)
1576 BOOL is_color = FALSE;
1577 char swizzle_str[6];
1579 glsl_src->reg_name[0] = '\0';
1580 glsl_src->param_str[0] = '\0';
1581 swizzle_str[0] = '\0';
1583 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1584 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1585 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1588 /* From a given parameter token, generate the corresponding GLSL string.
1589 * Also, return the actual register name and swizzle in case the
1590 * caller needs this information as well. */
1591 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1592 const struct wined3d_shader_dst_param *wined3d_dst, struct glsl_dst_param *glsl_dst)
1594 BOOL is_color = FALSE;
1596 glsl_dst->mask_str[0] = '\0';
1597 glsl_dst->reg_name[0] = '\0';
1599 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1600 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1603 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1604 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1605 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1607 struct glsl_dst_param glsl_dst;
1610 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1611 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1616 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1617 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1619 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1622 /** Process GLSL instruction modifiers */
1623 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1625 struct glsl_dst_param dst_param;
1628 if (!ins->dst_count) return;
1630 modifiers = ins->dst[0].modifiers;
1631 if (!modifiers) return;
1633 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1635 if (modifiers & WINED3DSPDM_SATURATE)
1637 /* _SAT means to clamp the value of the register to between 0 and 1 */
1638 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1639 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1642 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1644 FIXME("_centroid modifier not handled\n");
1647 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1649 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1653 static const char *shader_glsl_get_rel_op(enum wined3d_shader_rel_op op)
1657 case WINED3D_SHADER_REL_OP_GT: return ">";
1658 case WINED3D_SHADER_REL_OP_EQ: return "==";
1659 case WINED3D_SHADER_REL_OP_GE: return ">=";
1660 case WINED3D_SHADER_REL_OP_LT: return "<";
1661 case WINED3D_SHADER_REL_OP_NE: return "!=";
1662 case WINED3D_SHADER_REL_OP_LE: return "<=";
1664 FIXME("Unrecognized operator %#x.\n", op);
1669 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1670 DWORD sampler_idx, DWORD flags, struct glsl_sample_function *sample_function)
1672 enum wined3d_sampler_texture_type sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1673 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1674 BOOL shadow = shader_is_pshader_version(ctx->reg_maps->shader_version.type)
1675 && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1676 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1677 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1678 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1679 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1681 /* Note that there's no such thing as a projected cube texture. */
1682 switch(sampler_type) {
1688 sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1692 if (gl_info->supported[EXT_GPU_SHADER4])
1693 sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1694 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1695 sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1698 FIXME("Unsupported 1D shadow grad function.\n");
1699 sample_function->name = "unsupported1DGrad";
1704 sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1706 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1712 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1716 if (gl_info->supported[EXT_GPU_SHADER4])
1717 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1718 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1719 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1722 FIXME("Unsupported 1D grad function.\n");
1723 sample_function->name = "unsupported1DGrad";
1728 sample_function->name = projected ? "texture1DProj" : "texture1D";
1730 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1741 sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1745 if (gl_info->supported[EXT_GPU_SHADER4])
1746 sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1747 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1748 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1751 FIXME("Unsupported RECT shadow grad function.\n");
1752 sample_function->name = "unsupported2DRectGrad";
1757 sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1764 sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1768 if (gl_info->supported[EXT_GPU_SHADER4])
1769 sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1770 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1771 sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1774 FIXME("Unsupported 2D shadow grad function.\n");
1775 sample_function->name = "unsupported2DGrad";
1780 sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1783 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1791 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1795 if (gl_info->supported[EXT_GPU_SHADER4])
1796 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1797 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1798 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1801 FIXME("Unsupported RECT grad function.\n");
1802 sample_function->name = "unsupported2DRectGrad";
1807 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1814 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1818 if (gl_info->supported[EXT_GPU_SHADER4])
1819 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1820 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1821 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1824 FIXME("Unsupported 2D grad function.\n");
1825 sample_function->name = "unsupported2DGrad";
1830 sample_function->name = projected ? "texture2DProj" : "texture2D";
1833 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1837 case WINED3DSTT_CUBE:
1840 FIXME("Unsupported Cube shadow function.\n");
1841 sample_function->name = "unsupportedCubeShadow";
1842 sample_function->coord_mask = 0;
1848 sample_function->name = "textureCubeLod";
1852 if (gl_info->supported[EXT_GPU_SHADER4])
1853 sample_function->name = "textureCubeGrad";
1854 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1855 sample_function->name = "textureCubeGradARB";
1858 FIXME("Unsupported Cube grad function.\n");
1859 sample_function->name = "unsupportedCubeGrad";
1864 sample_function->name = "textureCube";
1866 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1870 case WINED3DSTT_VOLUME:
1873 FIXME("Unsupported 3D shadow function.\n");
1874 sample_function->name = "unsupported3DShadow";
1875 sample_function->coord_mask = 0;
1881 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1885 if (gl_info->supported[EXT_GPU_SHADER4])
1886 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1887 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1888 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1891 FIXME("Unsupported 3D grad function.\n");
1892 sample_function->name = "unsupported3DGrad";
1897 sample_function->name = projected ? "texture3DProj" : "texture3D";
1899 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1904 sample_function->name = "";
1905 sample_function->coord_mask = 0;
1906 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1911 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1912 BOOL sign_fixup, enum fixup_channel_source channel_source)
1914 switch(channel_source)
1916 case CHANNEL_SOURCE_ZERO:
1917 strcat(arguments, "0.0");
1920 case CHANNEL_SOURCE_ONE:
1921 strcat(arguments, "1.0");
1924 case CHANNEL_SOURCE_X:
1925 strcat(arguments, reg_name);
1926 strcat(arguments, ".x");
1929 case CHANNEL_SOURCE_Y:
1930 strcat(arguments, reg_name);
1931 strcat(arguments, ".y");
1934 case CHANNEL_SOURCE_Z:
1935 strcat(arguments, reg_name);
1936 strcat(arguments, ".z");
1939 case CHANNEL_SOURCE_W:
1940 strcat(arguments, reg_name);
1941 strcat(arguments, ".w");
1945 FIXME("Unhandled channel source %#x\n", channel_source);
1946 strcat(arguments, "undefined");
1950 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1953 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1955 struct wined3d_shader_dst_param dst;
1956 unsigned int mask_size, remaining;
1957 struct glsl_dst_param dst_param;
1958 char arguments[256];
1962 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1963 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1964 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1965 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1966 mask &= ins->dst[0].write_mask;
1968 if (!mask) return; /* Nothing to do */
1970 if (is_complex_fixup(fixup))
1972 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
1973 FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
1977 mask_size = shader_glsl_get_write_mask_size(mask);
1980 dst.write_mask = mask;
1981 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1983 arguments[0] = '\0';
1984 remaining = mask_size;
1985 if (mask & WINED3DSP_WRITEMASK_0)
1987 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1988 if (--remaining) strcat(arguments, ", ");
1990 if (mask & WINED3DSP_WRITEMASK_1)
1992 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1993 if (--remaining) strcat(arguments, ", ");
1995 if (mask & WINED3DSP_WRITEMASK_2)
1997 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1998 if (--remaining) strcat(arguments, ", ");
2000 if (mask & WINED3DSP_WRITEMASK_3)
2002 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
2003 if (--remaining) strcat(arguments, ", ");
2008 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
2009 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
2013 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
2017 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2018 DWORD sampler, const struct glsl_sample_function *sample_function, DWORD swizzle,
2019 const char *dx, const char *dy, const char *bias, const char *coord_reg_fmt, ...)
2021 const char *sampler_base;
2022 char dst_swizzle[6];
2023 struct color_fixup_desc fixup;
2024 BOOL np2_fixup = FALSE;
2027 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2029 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2031 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2032 fixup = priv->cur_ps_args->color_fixup[sampler];
2033 sampler_base = "Psampler";
2035 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2037 FIXME("Biased sampling from NP2 textures is unsupported\n");
2043 sampler_base = "Vsampler";
2044 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2047 shader_glsl_append_dst(ins->ctx->buffer, ins);
2049 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2051 va_start(args, coord_reg_fmt);
2052 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2056 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2059 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2060 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2062 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2063 (idx % 2) ? "zw" : "xy", dst_swizzle);
2064 } else if(dx && dy) {
2065 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2067 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2071 if(!is_identity_fixup(fixup)) {
2072 shader_glsl_color_correction(ins, fixup);
2076 /*****************************************************************************
2077 * Begin processing individual instruction opcodes
2078 ****************************************************************************/
2080 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
2081 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
2083 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2084 struct glsl_src_param src0_param;
2085 struct glsl_src_param src1_param;
2089 /* Determine the GLSL operator to use based on the opcode */
2090 switch (ins->handler_idx)
2092 case WINED3DSIH_MUL: op = '*'; break;
2093 case WINED3DSIH_ADD: op = '+'; break;
2094 case WINED3DSIH_SUB: op = '-'; break;
2097 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2101 write_mask = shader_glsl_append_dst(buffer, ins);
2102 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2103 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2104 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2107 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2108 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2110 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2111 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2112 struct glsl_src_param src0_param;
2115 write_mask = shader_glsl_append_dst(buffer, ins);
2116 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2118 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2119 * shader versions WINED3DSIO_MOVA is used for this. */
2120 if (ins->ctx->reg_maps->shader_version.major == 1
2121 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2122 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2124 /* This is a simple floor() */
2125 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2126 if (mask_size > 1) {
2127 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2129 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2132 else if(ins->handler_idx == WINED3DSIH_MOVA)
2134 /* We need to *round* to the nearest int here. */
2135 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2137 if (gl_info->supported[EXT_GPU_SHADER4])
2140 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2142 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2147 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2148 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2150 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2151 src0_param.param_str, src0_param.param_str);
2156 shader_addline(buffer, "%s);\n", src0_param.param_str);
2160 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2161 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2163 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2164 struct glsl_src_param src0_param;
2165 struct glsl_src_param src1_param;
2166 DWORD dst_write_mask, src_write_mask;
2167 unsigned int dst_size = 0;
2169 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2170 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2172 /* dp3 works on vec3, dp4 on vec4 */
2173 if (ins->handler_idx == WINED3DSIH_DP4)
2175 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2177 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2180 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2181 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2184 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2186 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2190 /* Note that this instruction has some restrictions. The destination write mask
2191 * can't contain the w component, and the source swizzles have to be .xyzw */
2192 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2194 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2195 struct glsl_src_param src0_param;
2196 struct glsl_src_param src1_param;
2199 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2200 shader_glsl_append_dst(ins->ctx->buffer, ins);
2201 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2202 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2203 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2206 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2207 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2208 * GLSL uses the value as-is. */
2209 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2211 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2212 struct glsl_src_param src0_param;
2213 struct glsl_src_param src1_param;
2214 DWORD dst_write_mask;
2215 unsigned int dst_size;
2217 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2218 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2220 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2221 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2225 shader_addline(buffer, "vec%u(%s == 0.0 ? 1.0 : pow(abs(%s), %s)));\n",
2226 dst_size, src1_param.param_str, src0_param.param_str, src1_param.param_str);
2230 shader_addline(buffer, "%s == 0.0 ? 1.0 : pow(abs(%s), %s));\n",
2231 src1_param.param_str, src0_param.param_str, src1_param.param_str);
2235 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2236 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2237 * GLSL uses the value as-is. */
2238 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2240 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2241 struct glsl_src_param src0_param;
2242 DWORD dst_write_mask;
2243 unsigned int dst_size;
2245 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2246 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2248 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2252 shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2253 dst_size, src0_param.param_str);
2257 shader_addline(buffer, "log2(abs(%s)));\n",
2258 src0_param.param_str);
2262 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2263 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2265 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2266 struct glsl_src_param src_param;
2267 const char *instruction;
2271 /* Determine the GLSL function to use based on the opcode */
2272 /* TODO: Possibly make this a table for faster lookups */
2273 switch (ins->handler_idx)
2275 case WINED3DSIH_MIN: instruction = "min"; break;
2276 case WINED3DSIH_MAX: instruction = "max"; break;
2277 case WINED3DSIH_ABS: instruction = "abs"; break;
2278 case WINED3DSIH_FRC: instruction = "fract"; break;
2279 case WINED3DSIH_EXP: instruction = "exp2"; break;
2280 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2281 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2282 default: instruction = "";
2283 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2287 write_mask = shader_glsl_append_dst(buffer, ins);
2289 shader_addline(buffer, "%s(", instruction);
2293 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2294 shader_addline(buffer, "%s", src_param.param_str);
2295 for (i = 1; i < ins->src_count; ++i)
2297 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2298 shader_addline(buffer, ", %s", src_param.param_str);
2302 shader_addline(buffer, "));\n");
2305 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2307 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2308 struct glsl_src_param src_param;
2309 unsigned int mask_size;
2313 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2314 mask_size = shader_glsl_get_write_mask_size(write_mask);
2315 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2317 shader_addline(buffer, "tmp0.x = dot(%s, %s);\n",
2318 src_param.param_str, src_param.param_str);
2319 shader_glsl_append_dst(buffer, ins);
2323 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s * inversesqrt(tmp0.x)));\n",
2324 mask_size, src_param.param_str);
2328 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s * inversesqrt(tmp0.x)));\n",
2329 src_param.param_str);
2333 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2334 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2335 * dst.x = 2^(floor(src))
2336 * dst.y = src - floor(src)
2337 * dst.z = 2^src (partial precision is allowed, but optional)
2339 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2340 * dst = 2^src; (partial precision is allowed, but optional)
2342 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2344 struct glsl_src_param src_param;
2346 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2348 if (ins->ctx->reg_maps->shader_version.major < 2)
2352 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2353 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2354 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2355 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2357 shader_glsl_append_dst(ins->ctx->buffer, ins);
2358 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2359 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2362 unsigned int mask_size;
2364 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2365 mask_size = shader_glsl_get_write_mask_size(write_mask);
2367 if (mask_size > 1) {
2368 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2370 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2375 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2376 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2378 struct glsl_src_param src_param;
2380 unsigned int mask_size;
2382 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2383 mask_size = shader_glsl_get_write_mask_size(write_mask);
2384 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2388 shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2389 mask_size, src_param.param_str);
2393 shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2394 src_param.param_str);
2398 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2400 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2401 struct glsl_src_param src_param;
2403 unsigned int mask_size;
2405 write_mask = shader_glsl_append_dst(buffer, ins);
2406 mask_size = shader_glsl_get_write_mask_size(write_mask);
2408 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2412 shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2413 mask_size, src_param.param_str);
2417 shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2418 src_param.param_str);
2422 /** Process signed comparison opcodes in GLSL. */
2423 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2425 struct glsl_src_param src0_param;
2426 struct glsl_src_param src1_param;
2428 unsigned int mask_size;
2430 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2431 mask_size = shader_glsl_get_write_mask_size(write_mask);
2432 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2433 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2435 if (mask_size > 1) {
2436 const char *compare;
2438 switch(ins->handler_idx)
2440 case WINED3DSIH_SLT: compare = "lessThan"; break;
2441 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2442 default: compare = "";
2443 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2446 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2447 src0_param.param_str, src1_param.param_str);
2449 switch(ins->handler_idx)
2451 case WINED3DSIH_SLT:
2452 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2453 * to return 0.0 but step returns 1.0 because step is not < x
2454 * An alternative is a bvec compare padded with an unused second component.
2455 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2456 * issue. Playing with not() is not possible either because not() does not accept
2459 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2460 src0_param.param_str, src1_param.param_str);
2462 case WINED3DSIH_SGE:
2463 /* Here we can use the step() function and safe a conditional */
2464 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2467 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2473 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2474 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2476 struct glsl_src_param src0_param;
2477 struct glsl_src_param src1_param;
2478 struct glsl_src_param src2_param;
2479 DWORD write_mask, cmp_channel = 0;
2482 BOOL temp_destination = FALSE;
2484 if (shader_is_scalar(&ins->src[0].reg))
2486 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2488 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2489 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2490 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2492 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2493 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2495 DWORD dst_mask = ins->dst[0].write_mask;
2496 struct wined3d_shader_dst_param dst = ins->dst[0];
2498 /* Cycle through all source0 channels */
2499 for (i=0; i<4; i++) {
2501 /* Find the destination channels which use the current source0 channel */
2502 for (j=0; j<4; j++) {
2503 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2505 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2506 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2509 dst.write_mask = dst_mask & write_mask;
2511 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2512 * The first lines may overwrite source parameters of the following lines.
2513 * Deal with that by using a temporary destination register if needed
2515 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2516 && ins->src[0].reg.type == ins->dst[0].reg.type)
2517 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2518 && ins->src[1].reg.type == ins->dst[0].reg.type)
2519 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2520 && ins->src[2].reg.type == ins->dst[0].reg.type))
2522 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2523 if (!write_mask) continue;
2524 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2525 temp_destination = TRUE;
2527 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2528 if (!write_mask) continue;
2531 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2532 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2533 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2535 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2536 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2539 if(temp_destination) {
2540 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2541 shader_glsl_append_dst(ins->ctx->buffer, ins);
2542 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2548 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2549 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2550 * the compare is done per component of src0. */
2551 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2553 struct wined3d_shader_dst_param dst;
2554 struct glsl_src_param src0_param;
2555 struct glsl_src_param src1_param;
2556 struct glsl_src_param src2_param;
2557 DWORD write_mask, cmp_channel = 0;
2560 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2561 ins->ctx->reg_maps->shader_version.minor);
2563 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2565 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2566 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2567 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2568 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2570 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2573 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2575 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2576 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2580 /* Cycle through all source0 channels */
2581 dst_mask = ins->dst[0].write_mask;
2583 for (i=0; i<4; i++) {
2585 /* Find the destination channels which use the current source0 channel */
2586 for (j=0; j<4; j++) {
2587 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2589 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2590 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2594 dst.write_mask = dst_mask & write_mask;
2595 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2596 if (!write_mask) continue;
2598 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2599 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2600 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2602 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2603 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2607 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2608 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2610 struct glsl_src_param src0_param;
2611 struct glsl_src_param src1_param;
2612 struct glsl_src_param src2_param;
2615 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2616 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2617 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2618 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2619 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2620 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2623 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2624 Vertex shaders to GLSL codes */
2625 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2628 int nComponents = 0;
2629 struct wined3d_shader_dst_param tmp_dst = {{0}};
2630 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2631 struct wined3d_shader_instruction tmp_ins;
2633 memset(&tmp_ins, 0, sizeof(tmp_ins));
2635 /* Set constants for the temporary argument */
2636 tmp_ins.ctx = ins->ctx;
2637 tmp_ins.dst_count = 1;
2638 tmp_ins.dst = &tmp_dst;
2639 tmp_ins.src_count = 2;
2640 tmp_ins.src = tmp_src;
2642 switch(ins->handler_idx)
2644 case WINED3DSIH_M4x4:
2646 tmp_ins.handler_idx = WINED3DSIH_DP4;
2648 case WINED3DSIH_M4x3:
2650 tmp_ins.handler_idx = WINED3DSIH_DP4;
2652 case WINED3DSIH_M3x4:
2654 tmp_ins.handler_idx = WINED3DSIH_DP3;
2656 case WINED3DSIH_M3x3:
2658 tmp_ins.handler_idx = WINED3DSIH_DP3;
2660 case WINED3DSIH_M3x2:
2662 tmp_ins.handler_idx = WINED3DSIH_DP3;
2668 tmp_dst = ins->dst[0];
2669 tmp_src[0] = ins->src[0];
2670 tmp_src[1] = ins->src[1];
2671 for (i = 0; i < nComponents; ++i)
2673 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2674 shader_glsl_dot(&tmp_ins);
2675 ++tmp_src[1].reg.idx;
2680 The LRP instruction performs a component-wise linear interpolation
2681 between the second and third operands using the first operand as the
2682 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2683 This is equivalent to mix(src2, src1, src0);
2685 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2687 struct glsl_src_param src0_param;
2688 struct glsl_src_param src1_param;
2689 struct glsl_src_param src2_param;
2692 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2694 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2695 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2696 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2698 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2699 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2702 /** Process the WINED3DSIO_LIT instruction in GLSL:
2703 * dst.x = dst.w = 1.0
2704 * dst.y = (src0.x > 0) ? src0.x
2705 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2706 * where src.w is clamped at +- 128
2708 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2710 struct glsl_src_param src0_param;
2711 struct glsl_src_param src1_param;
2712 struct glsl_src_param src3_param;
2715 shader_glsl_append_dst(ins->ctx->buffer, ins);
2716 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2718 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2719 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2720 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2722 /* The sdk specifies the instruction like this
2724 * if(src.x > 0.0) dst.y = src.x
2726 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2729 * (where power = src.w clamped between -128 and 128)
2731 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2732 * dst.x = 1.0 ... No further explanation needed
2733 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2734 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2735 * dst.w = 1.0. ... Nothing fancy.
2737 * So we still have one conditional in there. So do this:
2738 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2740 * 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),
2741 * 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.
2742 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to.
2744 * Unfortunately pow(0.0 ^ 0.0) returns NaN on most GPUs, but lit with src.y = 0 and src.w = 0 returns
2745 * a non-NaN value in dst.z. What we return doesn't matter, as long as it is not NaN. Return 0, which is
2746 * what all Windows HW drivers and GL_ARB_vertex_program's LIT do.
2748 shader_addline(ins->ctx->buffer,
2749 "vec4(1.0, max(%s, 0.0), %s == 0.0 ? 0.0 : "
2750 "pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
2751 src0_param.param_str, src3_param.param_str, src1_param.param_str,
2752 src0_param.param_str, src3_param.param_str, dst_mask);
2755 /** Process the WINED3DSIO_DST instruction in GLSL:
2757 * dst.y = src0.x * src0.y
2761 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2763 struct glsl_src_param src0y_param;
2764 struct glsl_src_param src0z_param;
2765 struct glsl_src_param src1y_param;
2766 struct glsl_src_param src1w_param;
2769 shader_glsl_append_dst(ins->ctx->buffer, ins);
2770 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2772 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2773 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2774 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2775 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2777 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2778 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2781 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2782 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2783 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2785 * dst.x = cos(src0.?)
2786 * dst.y = sin(src0.?)
2790 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2792 struct glsl_src_param src0_param;
2795 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2796 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2798 switch (write_mask) {
2799 case WINED3DSP_WRITEMASK_0:
2800 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2803 case WINED3DSP_WRITEMASK_1:
2804 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2807 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2808 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2812 ERR("Write mask should be .x, .y or .xy\n");
2817 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2818 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2819 * generate invalid code
2821 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2823 struct glsl_src_param src0_param;
2826 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2827 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2829 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2832 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2833 * Start a for() loop where src1.y is the initial value of aL,
2834 * increment aL by src1.z for a total of src1.x iterations.
2835 * Need to use a temporary variable for this operation.
2837 /* FIXME: I don't think nested loops will work correctly this way. */
2838 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2840 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2841 const struct wined3d_shader *shader = ins->ctx->shader;
2842 const struct wined3d_shader_lconst *constant;
2843 struct glsl_src_param src1_param;
2844 const DWORD *control_values = NULL;
2846 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2848 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2849 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2850 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2853 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2855 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
2857 if (constant->idx == ins->src[1].reg.idx)
2859 control_values = constant->value;
2867 struct wined3d_shader_loop_control loop_control;
2868 loop_control.count = control_values[0];
2869 loop_control.start = control_values[1];
2870 loop_control.step = (int)control_values[2];
2872 if (loop_control.step > 0)
2874 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2875 loop_state->current_depth, loop_control.start,
2876 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2877 loop_state->current_depth, loop_control.step);
2879 else if (loop_control.step < 0)
2881 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2882 loop_state->current_depth, loop_control.start,
2883 loop_state->current_depth, loop_control.count, loop_control.step, loop_control.start,
2884 loop_state->current_depth, loop_control.step);
2888 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2889 loop_state->current_depth, loop_control.start, loop_state->current_depth,
2890 loop_state->current_depth, loop_control.count,
2891 loop_state->current_depth);
2894 shader_addline(ins->ctx->buffer,
2895 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2896 loop_state->current_depth, loop_state->current_reg,
2897 src1_param.reg_name, loop_state->current_depth, src1_param.reg_name,
2898 loop_state->current_depth, loop_state->current_reg, src1_param.reg_name);
2901 ++loop_state->current_depth;
2902 ++loop_state->current_reg;
2905 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2907 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2909 shader_addline(ins->ctx->buffer, "}\n");
2911 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2913 --loop_state->current_depth;
2914 --loop_state->current_reg;
2917 if (ins->handler_idx == WINED3DSIH_ENDREP)
2919 --loop_state->current_depth;
2923 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2925 const struct wined3d_shader *shader = ins->ctx->shader;
2926 struct wined3d_shader_loop_state *loop_state = ins->ctx->loop_state;
2927 const struct wined3d_shader_lconst *constant;
2928 struct glsl_src_param src0_param;
2929 const DWORD *control_values = NULL;
2931 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2932 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2934 LIST_FOR_EACH_ENTRY(constant, &shader->constantsI, struct wined3d_shader_lconst, entry)
2936 if (constant->idx == ins->src[0].reg.idx)
2938 control_values = constant->value;
2946 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2947 loop_state->current_depth, loop_state->current_depth,
2948 control_values[0], loop_state->current_depth);
2952 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2953 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2954 loop_state->current_depth, loop_state->current_depth,
2955 src0_param.param_str, loop_state->current_depth);
2958 ++loop_state->current_depth;
2961 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2963 struct glsl_src_param src0_param;
2965 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2966 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2969 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2971 struct glsl_src_param src0_param;
2972 struct glsl_src_param src1_param;
2974 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2975 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2977 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2978 src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
2981 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2983 shader_addline(ins->ctx->buffer, "} else {\n");
2986 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2988 shader_addline(ins->ctx->buffer, "break;\n");
2991 /* FIXME: According to MSDN the compare is done per component. */
2992 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2994 struct glsl_src_param src0_param;
2995 struct glsl_src_param src1_param;
2997 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2998 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3000 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
3001 src0_param.param_str, shader_glsl_get_rel_op(ins->flags), src1_param.param_str);
3004 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
3006 shader_addline(ins->ctx->buffer, "}\n");
3007 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
3010 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
3012 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
3015 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
3017 struct glsl_src_param src1_param;
3019 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3020 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
3023 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3025 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3026 * function only suppresses the unhandled instruction warning
3030 /*********************************************
3031 * Pixel Shader Specific Code begins here
3032 ********************************************/
3033 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3035 const struct wined3d_shader *shader = ins->ctx->shader;
3036 struct wined3d_device *device = shader->device;
3037 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3038 ins->ctx->reg_maps->shader_version.minor);
3039 struct glsl_sample_function sample_function;
3040 const struct wined3d_texture *texture;
3041 DWORD sample_flags = 0;
3043 DWORD mask = 0, swizzle;
3045 /* 1.0-1.4: Use destination register as sampler source.
3046 * 2.0+: Use provided sampler source. */
3047 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3048 else sampler_idx = ins->src[1].reg.idx;
3049 texture = device->stateBlock->state.textures[sampler_idx];
3051 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3053 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3054 DWORD flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3055 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3056 enum wined3d_sampler_texture_type sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3058 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3059 if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE)
3061 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3062 switch (flags & ~WINED3D_PSARGS_PROJECTED)
3064 case WINED3D_TTFF_COUNT1:
3065 FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3067 case WINED3D_TTFF_COUNT2:
3068 mask = WINED3DSP_WRITEMASK_1;
3070 case WINED3D_TTFF_COUNT3:
3071 mask = WINED3DSP_WRITEMASK_2;
3073 case WINED3D_TTFF_COUNT4:
3074 case WINED3D_TTFF_DISABLE:
3075 mask = WINED3DSP_WRITEMASK_3;
3080 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3082 enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3084 if (src_mod == WINED3DSPSM_DZ) {
3085 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3086 mask = WINED3DSP_WRITEMASK_2;
3087 } else if (src_mod == WINED3DSPSM_DW) {
3088 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3089 mask = WINED3DSP_WRITEMASK_3;
3092 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3094 /* ps 2.0 texldp instruction always divides by the fourth component. */
3095 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3096 mask = WINED3DSP_WRITEMASK_3;
3100 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3101 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3103 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3104 mask |= sample_function.coord_mask;
3106 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3107 else swizzle = ins->src[1].swizzle;
3109 /* 1.0-1.3: Use destination register as coordinate source.
3110 1.4+: Use provided coordinate source register. */
3111 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3114 shader_glsl_write_mask_to_str(mask, coord_mask);
3115 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3116 "T%u%s", sampler_idx, coord_mask);
3120 struct glsl_src_param coord_param;
3121 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3122 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3124 struct glsl_src_param bias;
3125 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3126 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3127 "%s", coord_param.param_str);
3129 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3130 "%s", coord_param.param_str);
3135 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3137 const struct wined3d_shader *shader = ins->ctx->shader;
3138 struct wined3d_device *device = shader->device;
3139 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3140 struct glsl_src_param coord_param, dx_param, dy_param;
3141 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3142 struct glsl_sample_function sample_function;
3144 DWORD swizzle = ins->src[1].swizzle;
3145 const struct wined3d_texture *texture;
3147 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3149 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3150 shader_glsl_tex(ins);
3154 sampler_idx = ins->src[1].reg.idx;
3155 texture = device->stateBlock->state.textures[sampler_idx];
3156 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3157 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3159 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3160 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3161 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3162 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3164 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3165 "%s", coord_param.param_str);
3168 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3170 const struct wined3d_shader *shader = ins->ctx->shader;
3171 struct wined3d_device *device = shader->device;
3172 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3173 struct glsl_src_param coord_param, lod_param;
3174 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3175 struct glsl_sample_function sample_function;
3177 DWORD swizzle = ins->src[1].swizzle;
3178 const struct wined3d_texture *texture;
3180 sampler_idx = ins->src[1].reg.idx;
3181 texture = device->stateBlock->state.textures[sampler_idx];
3182 if (texture && texture->target == GL_TEXTURE_RECTANGLE_ARB)
3183 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3185 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3186 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3188 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3190 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3191 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3193 /* Plain GLSL only supports Lod sampling functions in vertex shaders.
3194 * However, the NVIDIA drivers allow them in fragment shaders as well,
3195 * even without the appropriate extension. */
3196 WARN("Using %s in fragment shader.\n", sample_function.name);
3198 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3199 "%s", coord_param.param_str);
3202 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3204 /* FIXME: Make this work for more than just 2D textures */
3205 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3206 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3208 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3212 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3213 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3214 ins->dst[0].reg.idx, dst_mask);
3218 enum wined3d_shader_src_modifier src_mod = ins->src[0].modifiers;
3219 DWORD reg = ins->src[0].reg.idx;
3220 char dst_swizzle[6];
3222 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3224 if (src_mod == WINED3DSPSM_DZ)
3226 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3227 struct glsl_src_param div_param;
3229 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3231 if (mask_size > 1) {
3232 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3234 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3237 else if (src_mod == WINED3DSPSM_DW)
3239 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3240 struct glsl_src_param div_param;
3242 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3244 if (mask_size > 1) {
3245 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3247 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3250 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3255 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3256 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3257 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3258 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3260 DWORD sampler_idx = ins->dst[0].reg.idx;
3261 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3262 struct glsl_sample_function sample_function;
3263 struct glsl_src_param src0_param;
3266 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3268 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3269 * scalar, and projected sampling would require 4.
3271 * It is a dependent read - not valid with conditional NP2 textures
3273 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3274 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3279 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3280 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3284 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3285 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3289 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3290 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3294 FIXME("Unexpected mask size %u\n", mask_size);
3299 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3300 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3301 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3303 DWORD dstreg = ins->dst[0].reg.idx;
3304 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3305 struct glsl_src_param src0_param;
3307 unsigned int mask_size;
3309 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3310 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3311 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3313 if (mask_size > 1) {
3314 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3316 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3320 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3321 * Calculate the depth as dst.x / dst.y */
3322 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3324 struct glsl_dst_param dst_param;
3326 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3328 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3329 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3330 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3331 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3334 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3335 dst_param.reg_name, dst_param.reg_name);
3338 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3339 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3340 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3341 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3343 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3345 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3346 DWORD dstreg = ins->dst[0].reg.idx;
3347 struct glsl_src_param src0_param;
3349 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3351 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3352 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3355 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3356 * Calculate the 1st of a 2-row matrix multiplication. */
3357 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3359 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3360 DWORD reg = ins->dst[0].reg.idx;
3361 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3362 struct glsl_src_param src0_param;
3364 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3365 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3368 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3369 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3370 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3372 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3373 DWORD reg = ins->dst[0].reg.idx;
3374 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3375 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3376 struct glsl_src_param src0_param;
3378 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3379 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + tex_mx->current_row, reg, src0_param.param_str);
3380 tex_mx->texcoord_w[tex_mx->current_row++] = reg;
3383 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3385 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3386 DWORD reg = ins->dst[0].reg.idx;
3387 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3388 struct glsl_sample_function sample_function;
3389 struct glsl_src_param src0_param;
3391 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3392 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3394 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3396 /* Sample the texture using the calculated coordinates */
3397 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3400 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3401 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3402 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3404 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3405 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3406 struct glsl_sample_function sample_function;
3407 struct glsl_src_param src0_param;
3408 DWORD reg = ins->dst[0].reg.idx;
3410 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3411 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3413 /* Dependent read, not valid with conditional NP2 */
3414 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3416 /* Sample the texture using the calculated coordinates */
3417 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3419 tex_mx->current_row = 0;
3422 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3423 * Perform the 3rd row of a 3x3 matrix multiply */
3424 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3426 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3427 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3428 struct glsl_src_param src0_param;
3430 DWORD reg = ins->dst[0].reg.idx;
3432 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3434 shader_glsl_append_dst(ins->ctx->buffer, ins);
3435 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3436 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3438 tex_mx->current_row = 0;
3441 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3442 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3443 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3445 struct glsl_src_param src0_param;
3446 struct glsl_src_param src1_param;
3447 DWORD reg = ins->dst[0].reg.idx;
3448 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3449 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3450 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3451 struct glsl_sample_function sample_function;
3454 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3455 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3457 /* Perform the last matrix multiply operation */
3458 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3459 /* Reflection calculation */
3460 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3462 /* Dependent read, not valid with conditional NP2 */
3463 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3464 shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3466 /* Sample the texture */
3467 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3468 NULL, NULL, NULL, "tmp0%s", coord_mask);
3470 tex_mx->current_row = 0;
3473 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3474 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3475 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3477 DWORD reg = ins->dst[0].reg.idx;
3478 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3479 struct wined3d_shader_tex_mx *tex_mx = ins->ctx->tex_mx;
3480 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3481 struct glsl_sample_function sample_function;
3482 struct glsl_src_param src0_param;
3485 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3487 /* Perform the last matrix multiply operation */
3488 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3490 /* Construct the eye-ray vector from w coordinates */
3491 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3492 tex_mx->texcoord_w[0], tex_mx->texcoord_w[1], reg);
3493 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3495 /* Dependent read, not valid with conditional NP2 */
3496 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3497 shader_glsl_write_mask_to_str(sample_function.coord_mask, coord_mask);
3499 /* Sample the texture using the calculated coordinates */
3500 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE,
3501 NULL, NULL, NULL, "tmp0%s", coord_mask);
3503 tex_mx->current_row = 0;
3506 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3507 * Apply a fake bump map transform.
3508 * texbem is pshader <= 1.3 only, this saves a few version checks
3510 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3512 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3513 struct glsl_sample_function sample_function;
3514 struct glsl_src_param coord_param;
3520 sampler_idx = ins->dst[0].reg.idx;
3521 flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3522 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3524 /* Dependent read, not valid with conditional NP2 */
3525 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3526 mask = sample_function.coord_mask;
3528 shader_glsl_write_mask_to_str(mask, coord_mask);
3530 /* With projected textures, texbem only divides the static texture coord,
3531 * not the displacement, so we can't let GL handle this. */
3532 if (flags & WINED3D_PSARGS_PROJECTED)
3535 char coord_div_mask[3];
3536 switch (flags & ~WINED3D_PSARGS_PROJECTED)
3538 case WINED3D_TTFF_COUNT1:
3539 FIXME("WINED3D_TTFF_PROJECTED with WINED3D_TTFF_COUNT1?\n");
3541 case WINED3D_TTFF_COUNT2:
3542 div_mask = WINED3DSP_WRITEMASK_1;
3544 case WINED3D_TTFF_COUNT3:
3545 div_mask = WINED3DSP_WRITEMASK_2;
3547 case WINED3D_TTFF_COUNT4:
3548 case WINED3D_TTFF_DISABLE:
3549 div_mask = WINED3DSP_WRITEMASK_3;
3552 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3553 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3556 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3558 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3559 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3560 coord_param.param_str, coord_mask);
3562 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3564 struct glsl_src_param luminance_param;
3565 struct glsl_dst_param dst_param;
3567 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3568 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3570 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3571 dst_param.reg_name, dst_param.mask_str,
3572 luminance_param.param_str, sampler_idx, sampler_idx);
3576 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3578 struct glsl_src_param src0_param, src1_param;
3579 DWORD sampler_idx = ins->dst[0].reg.idx;
3581 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3582 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3584 shader_glsl_append_dst(ins->ctx->buffer, ins);
3585 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3586 src0_param.param_str, sampler_idx, src1_param.param_str);
3589 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3590 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3591 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3593 struct glsl_sample_function sample_function;
3594 struct glsl_src_param src0_param;
3595 DWORD sampler_idx = ins->dst[0].reg.idx;
3597 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3599 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3600 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3601 "%s.wx", src0_param.reg_name);
3604 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3605 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3606 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3608 struct glsl_sample_function sample_function;
3609 struct glsl_src_param src0_param;
3610 DWORD sampler_idx = ins->dst[0].reg.idx;
3612 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3614 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3615 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3616 "%s.yz", src0_param.reg_name);
3619 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3620 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3621 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3623 struct glsl_sample_function sample_function;
3624 struct glsl_src_param src0_param;
3625 DWORD sampler_idx = ins->dst[0].reg.idx;
3627 /* Dependent read, not valid with conditional NP2 */
3628 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3629 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3631 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3632 "%s", src0_param.param_str);
3635 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3636 * If any of the first 3 components are < 0, discard this pixel */
3637 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3639 struct glsl_dst_param dst_param;
3641 /* The argument is a destination parameter, and no writemasks are allowed */
3642 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3643 if (ins->ctx->reg_maps->shader_version.major >= 2)
3645 /* 2.0 shaders compare all 4 components in texkill */
3646 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3648 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3649 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3650 * 4 components are defined, only the first 3 are used
3652 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3656 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3657 * dst = dot2(src0, src1) + src2 */
3658 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3660 struct glsl_src_param src0_param;
3661 struct glsl_src_param src1_param;
3662 struct glsl_src_param src2_param;
3664 unsigned int mask_size;
3666 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3667 mask_size = shader_glsl_get_write_mask_size(write_mask);
3669 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3670 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3671 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3673 if (mask_size > 1) {
3674 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3675 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3677 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3678 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3682 static void shader_glsl_input_pack(const struct wined3d_shader *shader, struct wined3d_shader_buffer *buffer,
3683 const struct wined3d_shader_signature_element *input_signature,
3684 const struct wined3d_shader_reg_maps *reg_maps,
3685 enum vertexprocessing_mode vertexprocessing)
3687 WORD map = reg_maps->input_registers;
3690 for (i = 0; map; map >>= 1, ++i)
3692 const char *semantic_name;
3697 if (!(map & 1)) continue;
3699 semantic_name = input_signature[i].semantic_name;
3700 semantic_idx = input_signature[i].semantic_idx;
3701 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3703 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
3705 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3706 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3707 shader->u.ps.input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3709 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3710 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3712 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
3715 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3716 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3717 else if (semantic_idx == 1)
3718 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3719 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3721 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3722 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3726 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3727 shader->u.ps.input_reg_map[i], reg_mask, reg_mask);
3732 /*********************************************
3733 * Vertex Shader Specific Code begins here
3734 ********************************************/
3736 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry)
3738 struct glsl_program_key key;
3740 key.vshader = entry->vshader;
3741 key.pshader = entry->pshader;
3742 key.vs_args = entry->vs_args;
3743 key.ps_args = entry->ps_args;
3745 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3747 ERR("Failed to insert program entry.\n");
3751 static struct glsl_shader_prog_link *get_glsl_program_entry(const struct shader_glsl_priv *priv,
3752 const struct wined3d_shader *vshader, const struct wined3d_shader *pshader,
3753 const struct vs_compile_args *vs_args, const struct ps_compile_args *ps_args)
3755 struct wine_rb_entry *entry;
3756 struct glsl_program_key key;
3758 key.vshader = vshader;
3759 key.pshader = pshader;
3760 key.vs_args = *vs_args;
3761 key.ps_args = *ps_args;
3763 entry = wine_rb_get(&priv->program_lookup, &key);
3764 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3767 /* GL locking is done by the caller */
3768 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3769 struct glsl_shader_prog_link *entry)
3771 struct glsl_program_key key;
3773 key.vshader = entry->vshader;
3774 key.pshader = entry->pshader;
3775 key.vs_args = entry->vs_args;
3776 key.ps_args = entry->ps_args;
3777 wine_rb_remove(&priv->program_lookup, &key);
3779 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3780 if (entry->vshader) list_remove(&entry->vshader_entry);
3781 if (entry->pshader) list_remove(&entry->pshader_entry);
3782 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3783 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3784 HeapFree(GetProcessHeap(), 0, entry);
3787 static void handle_ps3_input(struct wined3d_shader_buffer *buffer,
3788 const struct wined3d_gl_info *gl_info, const DWORD *map,
3789 const struct wined3d_shader_signature_element *input_signature,
3790 const struct wined3d_shader_reg_maps *reg_maps_in,
3791 const struct wined3d_shader_signature_element *output_signature,
3792 const struct wined3d_shader_reg_maps *reg_maps_out)
3795 const char *semantic_name_in;
3796 UINT semantic_idx_in;
3799 unsigned int in_count = vec4_varyings(3, gl_info);
3801 char destination[50];
3802 WORD input_map, output_map;
3804 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3806 input_map = reg_maps_in->input_registers;
3807 for (i = 0; input_map; input_map >>= 1, ++i)
3809 if (!(input_map & 1)) continue;
3812 /* Declared, but not read register */
3813 if (in_idx == ~0U) continue;
3814 if (in_idx >= (in_count + 2))
3816 FIXME("More input varyings declared than supported, expect issues.\n");
3820 if (in_idx == in_count) {
3821 sprintf(destination, "gl_FrontColor");
3822 } else if (in_idx == in_count + 1) {
3823 sprintf(destination, "gl_FrontSecondaryColor");
3825 sprintf(destination, "IN[%u]", in_idx);
3828 semantic_name_in = input_signature[i].semantic_name;
3829 semantic_idx_in = input_signature[i].semantic_idx;
3832 output_map = reg_maps_out->output_registers;
3833 for (j = 0; output_map; output_map >>= 1, ++j)
3837 if (!(output_map & 1)
3838 || semantic_idx_in != output_signature[j].semantic_idx
3839 || strcmp(semantic_name_in, output_signature[j].semantic_name)
3840 || !(mask = input_signature[i].mask & output_signature[j].mask))
3844 shader_glsl_write_mask_to_str(mask, reg_mask);
3846 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3847 destination, reg_mask, j, reg_mask);
3851 for (i = 0; i < in_count + 2; ++i)
3855 if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
3858 if (set[i] == ~0U) set[i] = 0;
3861 if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
3862 if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
3863 if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
3864 if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
3865 reg_mask[size] = '\0';
3867 if (i == in_count) sprintf(destination, "gl_FrontColor");
3868 else if (i == in_count + 1) sprintf(destination, "gl_FrontSecondaryColor");
3869 else sprintf(destination, "IN[%u]", i);
3871 if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3872 else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3875 HeapFree(GetProcessHeap(), 0, set);
3878 /* GL locking is done by the caller */
3879 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3880 const struct wined3d_shader *vs, const struct wined3d_shader *ps,
3881 const struct wined3d_gl_info *gl_info)
3883 GLhandleARB ret = 0;
3884 DWORD ps_major = ps ? ps->reg_maps.shader_version.major : 0;
3886 const char *semantic_name;
3889 const struct wined3d_shader_signature_element *output_signature = vs->output_signature;
3890 WORD map = vs->reg_maps.output_registers;
3892 shader_buffer_clear(buffer);
3894 shader_addline(buffer, "#version 120\n");
3898 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3900 for (i = 0; map; map >>= 1, ++i)
3904 if (!(map & 1)) continue;
3906 semantic_name = output_signature[i].semantic_name;
3907 semantic_idx = output_signature[i].semantic_idx;
3908 write_mask = output_signature[i].mask;
3909 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3911 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_COLOR))
3914 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n",
3915 reg_mask, i, reg_mask);
3916 else if (semantic_idx == 1)
3917 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n",
3918 reg_mask, i, reg_mask);
3920 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
3922 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3923 reg_mask, i, reg_mask);
3925 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_TEXCOORD))
3927 if (semantic_idx < 8)
3929 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3930 write_mask |= WINED3DSP_WRITEMASK_3;
3932 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3933 semantic_idx, reg_mask, i, reg_mask);
3934 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3935 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3938 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
3940 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3942 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_FOG))
3944 shader_addline(buffer, "gl_FogFragCoord = clamp(OUT[%u].%c, 0.0, 1.0);\n", i, reg_mask[1]);
3947 shader_addline(buffer, "}\n");
3951 UINT in_count = min(vec4_varyings(ps_major, gl_info), ps->limits.packed_input);
3952 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3953 shader_addline(buffer, "varying vec4 IN[%u];\n", in_count);
3954 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3956 /* First, sort out position and point size. Those are not passed to the pixel shader */
3957 for (i = 0; map; map >>= 1, ++i)
3959 if (!(map & 1)) continue;
3961 semantic_name = output_signature[i].semantic_name;
3962 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3964 if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_POSITION))
3966 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n",
3967 reg_mask, i, reg_mask);
3969 else if (shader_match_semantic(semantic_name, WINED3D_DECL_USAGE_PSIZE))
3971 shader_addline(buffer, "gl_PointSize = OUT[%u].%c;\n", i, reg_mask[1]);
3975 /* Then, fix the pixel shader input */
3976 handle_ps3_input(buffer, gl_info, ps->u.ps.input_reg_map, ps->input_signature,
3977 &ps->reg_maps, output_signature, &vs->reg_maps);
3979 shader_addline(buffer, "}\n");
3982 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3983 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3984 shader_glsl_compile(gl_info, ret, buffer->buffer);
3989 /* GL locking is done by the caller */
3990 static void hardcode_local_constants(const struct wined3d_shader *shader,
3991 const struct wined3d_gl_info *gl_info, GLhandleARB programId, char prefix)
3993 const struct wined3d_shader_lconst *lconst;
3998 LIST_FOR_EACH_ENTRY(lconst, &shader->constantsF, struct wined3d_shader_lconst, entry)
4000 value = (const float *)lconst->value;
4001 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
4002 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4003 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
4005 checkGLcall("Hardcoding local constants");
4008 /* GL locking is done by the caller */
4009 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
4010 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4011 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
4013 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4014 const struct wined3d_gl_info *gl_info = context->gl_info;
4015 const DWORD *function = shader->function;
4016 struct shader_glsl_ctx_priv priv_ctx;
4018 /* Create the hw GLSL shader object and assign it as the shader->prgId */
4019 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4021 memset(&priv_ctx, 0, sizeof(priv_ctx));
4022 priv_ctx.cur_ps_args = args;
4023 priv_ctx.cur_np2fixup_info = np2fixup_info;
4025 shader_addline(buffer, "#version 120\n");
4027 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
4029 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
4031 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4033 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
4034 * drivers write a warning if we don't do so
4036 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4038 if (gl_info->supported[EXT_GPU_SHADER4])
4040 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4043 /* Base Declarations */
4044 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4046 /* Pack 3.0 inputs */
4047 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4048 shader_glsl_input_pack(shader, buffer, shader->input_signature, reg_maps, args->vp_mode);
4050 /* Base Shader Body */
4051 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4053 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4054 if (reg_maps->shader_version.major < 2)
4056 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4057 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4060 if (args->srgb_correction)
4062 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4063 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4064 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4065 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4066 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4067 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4069 /* Pixel shader < 3.0 do not replace the fog stage.
4070 * This implements linear fog computation and blending.
4071 * TODO: non linear fog
4072 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4073 * -1/(e-s) and e/(e-s) respectively.
4075 if (reg_maps->shader_version.major < 3)
4078 case FOG_OFF: break;
4080 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4081 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4082 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4083 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4086 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4087 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4088 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4089 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4092 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4093 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4094 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4095 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4100 shader_addline(buffer, "}\n");
4102 TRACE("Compiling shader object %u\n", shader_obj);
4103 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4105 /* Store the shader object */
4109 /* GL locking is done by the caller */
4110 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4111 struct wined3d_shader_buffer *buffer, const struct wined3d_shader *shader,
4112 const struct vs_compile_args *args)
4114 const struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
4115 const struct wined3d_gl_info *gl_info = context->gl_info;
4116 const DWORD *function = shader->function;
4117 struct shader_glsl_ctx_priv priv_ctx;
4119 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4120 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4122 shader_addline(buffer, "#version 120\n");
4124 if (gl_info->supported[EXT_GPU_SHADER4])
4125 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4127 memset(&priv_ctx, 0, sizeof(priv_ctx));
4128 priv_ctx.cur_vs_args = args;
4130 /* Base Declarations */
4131 shader_generate_glsl_declarations(context, buffer, shader, reg_maps, &priv_ctx);
4133 /* Base Shader Body */
4134 shader_generate_main(shader, buffer, reg_maps, function, &priv_ctx);
4136 /* Unpack outputs */
4137 shader_addline(buffer, "order_ps_input(OUT);\n");
4139 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4140 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4141 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4142 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4144 if (args->fog_src == VS_FOG_Z)
4145 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4146 else if (!reg_maps->fog)
4147 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4149 /* We always store the clipplanes without y inversion */
4150 if (args->clip_enabled)
4151 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4153 /* Write the final position.
4155 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4156 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4157 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4158 * contains 1.0 to allow a mad.
4160 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4161 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4163 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4165 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4166 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4167 * which is the same as z = z * 2 - w.
4169 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4171 shader_addline(buffer, "}\n");
4173 TRACE("Compiling shader object %u\n", shader_obj);
4174 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4179 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4180 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4181 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4183 struct wined3d_state *state = &shader->device->stateBlock->state;
4186 struct glsl_ps_compiled_shader *new_array;
4187 struct glsl_pshader_private *shader_data;
4188 struct ps_np2fixup_info *np2fixup = NULL;
4191 if (!shader->backend_data)
4193 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4194 if (!shader->backend_data)
4196 ERR("Failed to allocate backend data.\n");
4200 shader_data = shader->backend_data;
4202 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4203 * so a linear search is more performant than a hashmap or a binary search
4204 * (cache coherency etc)
4206 for (i = 0; i < shader_data->num_gl_shaders; ++i)
4208 if (!memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)))
4210 if (args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
4211 return shader_data->gl_shaders[i].prgId;
4215 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4216 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4217 if (shader_data->num_gl_shaders)
4219 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4220 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4221 new_size * sizeof(*shader_data->gl_shaders));
4223 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4228 ERR("Out of memory\n");
4231 shader_data->gl_shaders = new_array;
4232 shader_data->shader_array_size = new_size;
4235 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4237 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4238 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4240 pixelshader_update_samplers(&shader->reg_maps, state->textures);
4242 shader_buffer_clear(buffer);
4243 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4244 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4245 *np2fixup_info = np2fixup;
4250 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4251 const DWORD use_map) {
4252 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4253 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4254 return stored->fog_src == new->fog_src;
4257 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4258 struct wined3d_shader_buffer *buffer, struct wined3d_shader *shader,
4259 const struct vs_compile_args *args)
4263 struct glsl_vs_compiled_shader *new_array;
4264 DWORD use_map = shader->device->strided_streams.use_map;
4265 struct glsl_vshader_private *shader_data;
4268 if (!shader->backend_data)
4270 shader->backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4271 if (!shader->backend_data)
4273 ERR("Failed to allocate backend data.\n");
4277 shader_data = shader->backend_data;
4279 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4280 * so a linear search is more performant than a hashmap or a binary search
4281 * (cache coherency etc)
4283 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4284 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4285 return shader_data->gl_shaders[i].prgId;
4289 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4291 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4292 if (shader_data->num_gl_shaders)
4294 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4295 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4296 new_size * sizeof(*shader_data->gl_shaders));
4298 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4303 ERR("Out of memory\n");
4306 shader_data->gl_shaders = new_array;
4307 shader_data->shader_array_size = new_size;
4310 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4312 shader_buffer_clear(buffer);
4313 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4314 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4319 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4320 * It sets the programId on the current StateBlock (because it should be called
4321 * inside of the DrawPrimitive() part of the render loop).
4323 * If a program for the given combination does not exist, create one, and store
4324 * the program in the hash table. If it creates a program, it will link the
4325 * given objects, too.
4328 /* GL locking is done by the caller */
4329 static void set_glsl_shader_program(const struct wined3d_context *context,
4330 struct wined3d_device *device, BOOL use_ps, BOOL use_vs)
4332 const struct wined3d_state *state = &device->stateBlock->state;
4333 struct wined3d_shader *vshader = use_vs ? state->vertex_shader : NULL;
4334 struct wined3d_shader *pshader = use_ps ? state->pixel_shader : NULL;
4335 const struct wined3d_gl_info *gl_info = context->gl_info;
4336 struct shader_glsl_priv *priv = device->shader_priv;
4337 struct glsl_shader_prog_link *entry = NULL;
4338 GLhandleARB programId = 0;
4339 GLhandleARB reorder_shader_id = 0;
4342 struct ps_compile_args ps_compile_args;
4343 struct vs_compile_args vs_compile_args;
4345 if (vshader) find_vs_compile_args(state, vshader, &vs_compile_args);
4346 if (pshader) find_ps_compile_args(state, pshader, &ps_compile_args);
4348 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4351 priv->glsl_program = entry;
4355 /* If we get to this point, then no matching program exists, so we create one */
4356 programId = GL_EXTCALL(glCreateProgramObjectARB());
4357 TRACE("Created new GLSL shader program %u\n", programId);
4359 /* Create the entry */
4360 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4361 entry->programId = programId;
4362 entry->vshader = vshader;
4363 entry->pshader = pshader;
4364 entry->vs_args = vs_compile_args;
4365 entry->ps_args = ps_compile_args;
4366 entry->constant_version = 0;
4367 entry->np2Fixup_info = NULL;
4368 /* Add the hash table entry */
4369 add_glsl_program_entry(priv, entry);
4371 /* Set the current program */
4372 priv->glsl_program = entry;
4374 /* Attach GLSL vshader */
4377 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer, vshader, &vs_compile_args);
4378 WORD map = vshader->reg_maps.input_registers;
4381 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4382 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4383 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4384 checkGLcall("glAttachObjectARB");
4385 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4388 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4390 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4391 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4392 checkGLcall("glAttachObjectARB");
4394 /* Bind vertex attributes to a corresponding index number to match
4395 * the same index numbers as ARB_vertex_programs (makes loading
4396 * vertex attributes simpler). With this method, we can use the
4397 * exact same code to load the attributes later for both ARB and
4400 * We have to do this here because we need to know the Program ID
4401 * in order to make the bindings work, and it has to be done prior
4402 * to linking the GLSL program. */
4403 for (i = 0; map; map >>= 1, ++i)
4405 if (!(map & 1)) continue;
4407 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4408 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4410 checkGLcall("glBindAttribLocationARB");
4412 list_add_head(&vshader->linked_programs, &entry->vshader_entry);
4415 /* Attach GLSL pshader */
4418 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4419 pshader, &ps_compile_args, &entry->np2Fixup_info);
4420 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4421 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4422 checkGLcall("glAttachObjectARB");
4424 list_add_head(&pshader->linked_programs, &entry->pshader_entry);
4427 /* Link the program */
4428 TRACE("Linking GLSL shader program %u\n", programId);
4429 GL_EXTCALL(glLinkProgramARB(programId));
4430 shader_glsl_validate_link(gl_info, programId);
4432 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4433 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4434 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4436 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4437 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4439 for (i = 0; i < MAX_CONST_I; ++i)
4441 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4442 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4444 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4445 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4446 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4448 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4449 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4451 for (i = 0; i < MAX_CONST_I; ++i)
4453 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4454 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4460 for(i = 0; i < MAX_TEXTURES; i++) {
4461 sprintf(name, "bumpenvmat%u", i);
4462 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4463 sprintf(name, "luminancescale%u", i);
4464 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4465 sprintf(name, "luminanceoffset%u", i);
4466 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4469 if (ps_compile_args.np2_fixup) {
4470 if (entry->np2Fixup_info) {
4471 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4473 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4478 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4479 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4480 checkGLcall("Find glsl program uniform locations");
4482 if (pshader && pshader->reg_maps.shader_version.major >= 3
4483 && pshader->u.ps.declared_in_count > vec4_varyings(3, gl_info))
4485 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4486 entry->vertex_color_clamp = GL_FALSE;
4488 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4491 /* Set the shader to allow uniform loading on it */
4492 GL_EXTCALL(glUseProgramObjectARB(programId));
4493 checkGLcall("glUseProgramObjectARB(programId)");
4495 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4496 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4497 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4498 * vertex shader with fixed function pixel processing is used we make sure that the card
4499 * supports enough samplers to allow the max number of vertex samplers with all possible
4500 * fixed function fragment processing setups. So once the program is linked these samplers
4503 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4504 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4506 /* If the local constants do not have to be loaded with the environment constants,
4507 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4510 if (pshader && !pshader->load_local_constsF)
4511 hardcode_local_constants(pshader, gl_info, programId, 'P');
4512 if (vshader && !vshader->load_local_constsF)
4513 hardcode_local_constants(vshader, gl_info, programId, 'V');
4516 /* GL locking is done by the caller */
4517 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
4519 GLhandleARB program_id;
4520 GLhandleARB vshader_id, pshader_id;
4521 const char *blt_pshader;
4523 static const char *blt_vshader =
4527 " gl_Position = gl_Vertex;\n"
4528 " gl_FrontColor = vec4(1.0);\n"
4529 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4532 static const char * const blt_pshaders_full[tex_type_count] =
4538 "uniform sampler2D sampler;\n"
4541 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4547 "uniform samplerCube sampler;\n"
4550 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4554 "#extension GL_ARB_texture_rectangle : enable\n"
4555 "uniform sampler2DRect sampler;\n"
4558 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4562 static const char * const blt_pshaders_masked[tex_type_count] =
4568 "uniform sampler2D sampler;\n"
4569 "uniform vec4 mask;\n"
4572 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4573 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4579 "uniform samplerCube sampler;\n"
4580 "uniform vec4 mask;\n"
4583 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4584 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4588 "#extension GL_ARB_texture_rectangle : enable\n"
4589 "uniform sampler2DRect sampler;\n"
4590 "uniform vec4 mask;\n"
4593 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4594 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4598 blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
4601 FIXME("tex_type %#x not supported\n", tex_type);
4605 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4606 shader_glsl_compile(gl_info, vshader_id, blt_vshader);
4608 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4609 shader_glsl_compile(gl_info, pshader_id, blt_pshader);
4611 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4612 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4613 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4614 GL_EXTCALL(glLinkProgramARB(program_id));
4616 shader_glsl_validate_link(gl_info, program_id);
4618 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4621 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4622 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4626 /* GL locking is done by the caller */
4627 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4629 const struct wined3d_gl_info *gl_info = context->gl_info;
4630 struct wined3d_device *device = context->swapchain->device;
4631 struct shader_glsl_priv *priv = device->shader_priv;
4632 GLhandleARB program_id = 0;
4633 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4635 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4637 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4638 else priv->glsl_program = NULL;
4640 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4642 if (old_vertex_color_clamp != current_vertex_color_clamp)
4644 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4646 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4647 checkGLcall("glClampColorARB");
4651 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4655 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4656 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4657 GL_EXTCALL(glUseProgramObjectARB(program_id));
4658 checkGLcall("glUseProgramObjectARB");
4660 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4661 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4662 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4663 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4665 shader_glsl_load_np2fixup_constants(priv, gl_info, &device->stateBlock->state);
4669 /* GL locking is done by the caller */
4670 static void shader_glsl_select_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info,
4671 enum tex_types tex_type, const SIZE *ds_mask_size)
4673 BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
4674 struct shader_glsl_priv *priv = shader_priv;
4675 GLhandleARB *blt_program;
4678 blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
4681 *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
4682 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4683 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4684 GL_EXTCALL(glUniform1iARB(loc, 0));
4688 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4693 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
4694 GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
4698 /* GL locking is done by the caller */
4699 static void shader_glsl_deselect_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info)
4701 struct shader_glsl_priv *priv = shader_priv;
4702 GLhandleARB program_id;
4704 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4705 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4707 GL_EXTCALL(glUseProgramObjectARB(program_id));
4708 checkGLcall("glUseProgramObjectARB");
4711 static void shader_glsl_destroy(struct wined3d_shader *shader)
4713 struct wined3d_device *device = shader->device;
4714 struct shader_glsl_priv *priv = device->shader_priv;
4715 const struct wined3d_gl_info *gl_info;
4716 const struct list *linked_programs;
4717 struct wined3d_context *context;
4719 char pshader = shader_is_pshader_version(shader->reg_maps.shader_version.type);
4723 struct glsl_pshader_private *shader_data = shader->backend_data;
4725 if (!shader_data || !shader_data->num_gl_shaders)
4727 HeapFree(GetProcessHeap(), 0, shader_data);
4728 shader->backend_data = NULL;
4732 context = context_acquire(device, NULL);
4733 gl_info = context->gl_info;
4735 if (priv->glsl_program && priv->glsl_program->pshader == shader)
4738 shader_glsl_select(context, FALSE, FALSE);
4744 struct glsl_vshader_private *shader_data = shader->backend_data;
4746 if (!shader_data || !shader_data->num_gl_shaders)
4748 HeapFree(GetProcessHeap(), 0, shader_data);
4749 shader->backend_data = NULL;
4753 context = context_acquire(device, NULL);
4754 gl_info = context->gl_info;
4756 if (priv->glsl_program && priv->glsl_program->vshader == shader)
4759 shader_glsl_select(context, FALSE, FALSE);
4764 linked_programs = &shader->linked_programs;
4766 TRACE("Deleting linked programs\n");
4767 if (linked_programs->next) {
4768 struct glsl_shader_prog_link *entry, *entry2;
4772 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4773 delete_glsl_program_entry(priv, gl_info, entry);
4776 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4777 delete_glsl_program_entry(priv, gl_info, entry);
4785 struct glsl_pshader_private *shader_data = shader->backend_data;
4789 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4790 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4791 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4792 checkGLcall("glDeleteObjectARB");
4795 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4799 struct glsl_vshader_private *shader_data = shader->backend_data;
4803 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4804 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4805 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4806 checkGLcall("glDeleteObjectARB");
4809 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4812 HeapFree(GetProcessHeap(), 0, shader->backend_data);
4813 shader->backend_data = NULL;
4815 context_release(context);
4818 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4820 const struct glsl_program_key *k = key;
4821 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4822 const struct glsl_shader_prog_link, program_lookup_entry);
4825 if (k->vshader > prog->vshader) return 1;
4826 else if (k->vshader < prog->vshader) return -1;
4828 if (k->pshader > prog->pshader) return 1;
4829 else if (k->pshader < prog->pshader) return -1;
4831 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4832 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4837 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4839 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4840 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4844 ERR("Failed to allocate memory\n");
4848 heap->entries = mem;
4849 heap->entries[1].version = 0;
4850 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4856 static void constant_heap_free(struct constant_heap *heap)
4858 HeapFree(GetProcessHeap(), 0, heap->entries);
4861 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4866 glsl_program_key_compare,
4869 static HRESULT shader_glsl_alloc(struct wined3d_device *device)
4871 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4872 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4873 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4874 gl_info->limits.glsl_ps_float_constants)) + 1;
4876 if (!shader_buffer_init(&priv->shader_buffer))
4878 ERR("Failed to initialize shader buffer.\n");
4882 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4885 ERR("Failed to allocate memory.\n");
4889 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4891 ERR("Failed to initialize vertex shader constant heap\n");
4895 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4897 ERR("Failed to initialize pixel shader constant heap\n");
4901 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4903 ERR("Failed to initialize rbtree.\n");
4907 priv->next_constant_version = 1;
4909 device->shader_priv = priv;
4913 constant_heap_free(&priv->pconst_heap);
4914 constant_heap_free(&priv->vconst_heap);
4915 HeapFree(GetProcessHeap(), 0, priv->stack);
4916 shader_buffer_free(&priv->shader_buffer);
4917 HeapFree(GetProcessHeap(), 0, priv);
4918 return E_OUTOFMEMORY;
4921 /* Context activation is done by the caller. */
4922 static void shader_glsl_free(struct wined3d_device *device)
4924 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4925 struct shader_glsl_priv *priv = device->shader_priv;
4929 for (i = 0; i < tex_type_count; ++i)
4931 if (priv->depth_blt_program_full[i])
4933 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
4935 if (priv->depth_blt_program_masked[i])
4937 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
4942 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4943 constant_heap_free(&priv->pconst_heap);
4944 constant_heap_free(&priv->vconst_heap);
4945 HeapFree(GetProcessHeap(), 0, priv->stack);
4946 shader_buffer_free(&priv->shader_buffer);
4948 HeapFree(GetProcessHeap(), 0, device->shader_priv);
4949 device->shader_priv = NULL;
4952 static void shader_glsl_context_destroyed(void *shader_priv, const struct wined3d_context *context) {}
4954 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
4956 if (gl_info->supported[EXT_GPU_SHADER4] && gl_info->supported[ARB_GEOMETRY_SHADER4]
4957 && gl_info->glsl_version >= MAKEDWORD_VERSION(1, 50))
4959 caps->VertexShaderVersion = 4;
4960 caps->PixelShaderVersion = 4;
4962 /* ARB_shader_texture_lod or EXT_gpu_shader4 is required for the SM3
4963 * texldd and texldl instructions. */
4964 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] || gl_info->supported[EXT_GPU_SHADER4])
4966 caps->VertexShaderVersion = 3;
4967 caps->PixelShaderVersion = 3;
4971 caps->VertexShaderVersion = 2;
4972 caps->PixelShaderVersion = 2;
4975 caps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4976 caps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4978 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4979 * Direct3D minimum requirement.
4981 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4982 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4984 * The problem is that the refrast clamps temporary results in the shader to
4985 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4986 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4987 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4988 * offer a way to query this.
4990 caps->PixelShader1xMaxValue = 8.0;
4992 caps->VSClipping = TRUE;
4994 TRACE_(d3d_caps)("Hardware vertex shader version %u enabled (GLSL).\n",
4995 caps->VertexShaderVersion);
4996 TRACE_(d3d_caps)("Hardware pixel shader version %u enabled (GLSL).\n",
4997 caps->PixelShaderVersion);
5000 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
5002 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
5004 TRACE("Checking support for fixup:\n");
5005 dump_color_fixup_desc(fixup);
5008 /* We support everything except YUV conversions. */
5009 if (!is_complex_fixup(fixup))
5015 TRACE("[FAILED]\n");
5019 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
5021 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
5022 /* WINED3DSIH_ADD */ shader_glsl_arith,
5023 /* WINED3DSIH_AND */ NULL,
5024 /* WINED3DSIH_BEM */ shader_glsl_bem,
5025 /* WINED3DSIH_BREAK */ shader_glsl_break,
5026 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
5027 /* WINED3DSIH_BREAKP */ NULL,
5028 /* WINED3DSIH_CALL */ shader_glsl_call,
5029 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
5030 /* WINED3DSIH_CMP */ shader_glsl_cmp,
5031 /* WINED3DSIH_CND */ shader_glsl_cnd,
5032 /* WINED3DSIH_CRS */ shader_glsl_cross,
5033 /* WINED3DSIH_CUT */ NULL,
5034 /* WINED3DSIH_DCL */ NULL,
5035 /* WINED3DSIH_DEF */ NULL,
5036 /* WINED3DSIH_DEFB */ NULL,
5037 /* WINED3DSIH_DEFI */ NULL,
5038 /* WINED3DSIH_DIV */ NULL,
5039 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
5040 /* WINED3DSIH_DP3 */ shader_glsl_dot,
5041 /* WINED3DSIH_DP4 */ shader_glsl_dot,
5042 /* WINED3DSIH_DST */ shader_glsl_dst,
5043 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
5044 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
5045 /* WINED3DSIH_ELSE */ shader_glsl_else,
5046 /* WINED3DSIH_EMIT */ NULL,
5047 /* WINED3DSIH_ENDIF */ shader_glsl_end,
5048 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5049 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5050 /* WINED3DSIH_EQ */ NULL,
5051 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5052 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5053 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5054 /* WINED3DSIH_FTOI */ NULL,
5055 /* WINED3DSIH_GE */ NULL,
5056 /* WINED3DSIH_IADD */ NULL,
5057 /* WINED3DSIH_IEQ */ NULL,
5058 /* WINED3DSIH_IF */ shader_glsl_if,
5059 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5060 /* WINED3DSIH_IGE */ NULL,
5061 /* WINED3DSIH_IMUL */ NULL,
5062 /* WINED3DSIH_ITOF */ NULL,
5063 /* WINED3DSIH_LABEL */ shader_glsl_label,
5064 /* WINED3DSIH_LD */ NULL,
5065 /* WINED3DSIH_LIT */ shader_glsl_lit,
5066 /* WINED3DSIH_LOG */ shader_glsl_log,
5067 /* WINED3DSIH_LOGP */ shader_glsl_log,
5068 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5069 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5070 /* WINED3DSIH_LT */ NULL,
5071 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5072 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5073 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5074 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5075 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5076 /* WINED3DSIH_MAD */ shader_glsl_mad,
5077 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5078 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5079 /* WINED3DSIH_MOV */ shader_glsl_mov,
5080 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5081 /* WINED3DSIH_MOVC */ NULL,
5082 /* WINED3DSIH_MUL */ shader_glsl_arith,
5083 /* WINED3DSIH_NOP */ NULL,
5084 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5085 /* WINED3DSIH_PHASE */ NULL,
5086 /* WINED3DSIH_POW */ shader_glsl_pow,
5087 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5088 /* WINED3DSIH_REP */ shader_glsl_rep,
5089 /* WINED3DSIH_RET */ shader_glsl_ret,
5090 /* WINED3DSIH_ROUND_NI */ NULL,
5091 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5092 /* WINED3DSIH_SAMPLE */ NULL,
5093 /* WINED3DSIH_SAMPLE_GRAD */ NULL,
5094 /* WINED3DSIH_SAMPLE_LOD */ NULL,
5095 /* WINED3DSIH_SETP */ NULL,
5096 /* WINED3DSIH_SGE */ shader_glsl_compare,
5097 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5098 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5099 /* WINED3DSIH_SLT */ shader_glsl_compare,
5100 /* WINED3DSIH_SQRT */ NULL,
5101 /* WINED3DSIH_SUB */ shader_glsl_arith,
5102 /* WINED3DSIH_TEX */ shader_glsl_tex,
5103 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5104 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5105 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5106 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5107 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5108 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5109 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5110 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5111 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5112 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5113 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5114 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5115 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5116 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5117 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5118 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5119 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5120 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5121 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5122 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5123 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5124 /* WINED3DSIH_UDIV */ NULL,
5125 /* WINED3DSIH_USHR */ NULL,
5126 /* WINED3DSIH_UTOF */ NULL,
5127 /* WINED3DSIH_XOR */ NULL,
5130 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5131 SHADER_HANDLER hw_fct;
5133 /* Select handler */
5134 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5136 /* Unhandled opcode */
5139 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5144 shader_glsl_add_instruction_modifiers(ins);
5147 const struct wined3d_shader_backend_ops glsl_shader_backend =
5149 shader_glsl_handle_instruction,
5151 shader_glsl_select_depth_blt,
5152 shader_glsl_deselect_depth_blt,
5153 shader_glsl_update_float_vertex_constants,
5154 shader_glsl_update_float_pixel_constants,
5155 shader_glsl_load_constants,
5156 shader_glsl_load_np2fixup_constants,
5157 shader_glsl_destroy,
5160 shader_glsl_context_destroyed,
5161 shader_glsl_get_caps,
5162 shader_glsl_color_fixup_supported,