2 * GLSL pixel and vertex shader implementation
4 * Copyright 2006 Jason Green
5 * Copyright 2006-2007 Henri Verbeet
6 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
7 * Copyright 2009 Henri Verbeet for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 * D3D shader asm has swizzles on source parameters, and write masks for
26 * destination parameters. GLSL uses swizzles for both. The result of this is
27 * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
28 * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
29 * mask for the destination parameter into account.
35 #include "wined3d_private.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
40 WINE_DECLARE_DEBUG_CHANNEL(d3d);
42 #define GLINFO_LOCATION (*gl_info)
44 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
45 #define WINED3D_GLSL_SAMPLE_RECT 0x2
46 #define WINED3D_GLSL_SAMPLE_LOD 0x4
47 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
62 } glsl_sample_function_t;
66 HEAP_NODE_TRAVERSE_LEFT,
67 HEAP_NODE_TRAVERSE_RIGHT,
79 struct constant_entry *entries;
80 unsigned int *positions;
84 /* GLSL shader private data */
85 struct shader_glsl_priv {
86 struct wined3d_shader_buffer shader_buffer;
87 struct wine_rb_tree program_lookup;
88 struct glsl_shader_prog_link *glsl_program;
89 struct constant_heap vconst_heap;
90 struct constant_heap pconst_heap;
92 GLhandleARB depth_blt_program[tex_type_count];
93 UINT next_constant_version;
96 /* Struct to maintain data about a linked GLSL program */
97 struct glsl_shader_prog_link {
98 struct wine_rb_entry program_lookup_entry;
99 struct list vshader_entry;
100 struct list pshader_entry;
101 GLhandleARB programId;
102 GLint *vuniformF_locations;
103 GLint *puniformF_locations;
104 GLint vuniformI_locations[MAX_CONST_I];
105 GLint puniformI_locations[MAX_CONST_I];
106 GLint posFixup_location;
107 GLint np2Fixup_location;
108 GLint bumpenvmat_location[MAX_TEXTURES];
109 GLint luminancescale_location[MAX_TEXTURES];
110 GLint luminanceoffset_location[MAX_TEXTURES];
111 GLint ycorrection_location;
112 GLenum vertex_color_clamp;
113 IWineD3DVertexShader *vshader;
114 IWineD3DPixelShader *pshader;
115 struct vs_compile_args vs_args;
116 struct ps_compile_args ps_args;
117 UINT constant_version;
118 const struct ps_np2fixup_info *np2Fixup_info;
122 IWineD3DVertexShader *vshader;
123 IWineD3DPixelShader *pshader;
124 struct ps_compile_args ps_args;
125 struct vs_compile_args vs_args;
126 } glsl_program_key_t;
128 struct shader_glsl_ctx_priv {
129 const struct vs_compile_args *cur_vs_args;
130 const struct ps_compile_args *cur_ps_args;
131 struct ps_np2fixup_info *cur_np2fixup_info;
134 struct glsl_ps_compiled_shader
136 struct ps_compile_args args;
137 struct ps_np2fixup_info np2fixup;
141 struct glsl_pshader_private
143 struct glsl_ps_compiled_shader *gl_shaders;
144 UINT num_gl_shaders, shader_array_size;
147 struct glsl_vs_compiled_shader
149 struct vs_compile_args args;
153 struct glsl_vshader_private
155 struct glsl_vs_compiled_shader *gl_shaders;
156 UINT num_gl_shaders, shader_array_size;
159 static const char *debug_gl_shader_type(GLenum type)
163 #define WINED3D_TO_STR(u) case u: return #u
164 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
165 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
166 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
167 #undef WINED3D_TO_STR
169 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
173 /* Extract a line from the info log.
174 * Note that this modifies the source string. */
175 static char *get_info_log_line(char **ptr)
180 if (!(q = strstr(p, "\n")))
182 if (!*p) return NULL;
192 /** Prints the GLSL info log which will contain error messages if they exist */
193 /* GL locking is done by the caller */
194 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
196 int infologLength = 0;
201 static const char * const spam[] =
203 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
204 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx, with \n */
205 "Fragment shader was successfully compiled to run on hardware.", /* fglrx, no \n */
206 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
207 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
208 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
209 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
210 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
211 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
214 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
216 GL_EXTCALL(glGetObjectParameterivARB(obj,
217 GL_OBJECT_INFO_LOG_LENGTH_ARB,
220 /* A size of 1 is just a null-terminated string, so the log should be bigger than
221 * that if there are errors. */
222 if (infologLength > 1)
226 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
227 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
229 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
230 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
233 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
234 if(strcmp(infoLog, spam[i]) == 0) {
243 TRACE("Spam received from GLSL shader #%u:\n", obj);
244 while ((line = get_info_log_line(&ptr))) TRACE(" %s\n", line);
248 FIXME("Error received from GLSL shader #%u:\n", obj);
249 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
251 HeapFree(GetProcessHeap(), 0, infoLog);
255 /* GL locking is done by the caller. */
256 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
258 GLint i, object_count, source_size;
259 GLhandleARB *objects;
262 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
263 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
266 ERR("Failed to allocate object array memory.\n");
270 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
271 for (i = 0; i < object_count; ++i)
276 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
278 if (!source || source_size < tmp)
280 HeapFree(GetProcessHeap(), 0, source);
282 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
285 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
286 HeapFree(GetProcessHeap(), 0, objects);
292 FIXME("Object %u:\n", objects[i]);
293 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
294 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
295 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
296 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
300 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
301 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
305 HeapFree(GetProcessHeap(), 0, source);
306 HeapFree(GetProcessHeap(), 0, objects);
309 /* GL locking is done by the caller. */
310 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
314 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
316 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
317 if (tmp == GL_PROGRAM_OBJECT_ARB)
319 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
322 FIXME("Program %u link status invalid.\n", program);
323 shader_glsl_dump_program_source(gl_info, program);
327 print_glsl_info_log(gl_info, program);
331 * Loads (pixel shader) samplers
333 /* GL locking is done by the caller */
334 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
335 DWORD *tex_unit_map, GLhandleARB programId)
339 char sampler_name[20];
341 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
342 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
343 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
344 if (name_loc != -1) {
345 DWORD mapped_unit = tex_unit_map[i];
346 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
348 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
349 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
350 checkGLcall("glUniform1iARB");
352 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
358 /* GL locking is done by the caller */
359 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
360 DWORD *tex_unit_map, GLhandleARB programId)
363 char sampler_name[20];
366 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
367 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
368 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
369 if (name_loc != -1) {
370 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
371 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
373 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
374 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
375 checkGLcall("glUniform1iARB");
377 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
383 /* GL locking is done by the caller */
384 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
385 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
388 unsigned int heap_idx = 1;
391 if (heap->entries[heap_idx].version <= version) return;
393 idx = heap->entries[heap_idx].idx;
394 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
395 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
397 while (stack_idx >= 0)
399 /* Note that we fall through to the next case statement. */
400 switch(stack[stack_idx])
402 case HEAP_NODE_TRAVERSE_LEFT:
404 unsigned int left_idx = heap_idx << 1;
405 if (left_idx < heap->size && heap->entries[left_idx].version > version)
408 idx = heap->entries[heap_idx].idx;
409 if (constant_locations[idx] != -1)
410 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
412 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
413 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
418 case HEAP_NODE_TRAVERSE_RIGHT:
420 unsigned int right_idx = (heap_idx << 1) + 1;
421 if (right_idx < heap->size && heap->entries[right_idx].version > version)
423 heap_idx = right_idx;
424 idx = heap->entries[heap_idx].idx;
425 if (constant_locations[idx] != -1)
426 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
428 stack[stack_idx++] = HEAP_NODE_POP;
429 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
442 checkGLcall("walk_constant_heap()");
445 /* GL locking is done by the caller */
446 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
448 GLfloat clamped_constant[4];
450 if (location == -1) return;
452 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
453 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
454 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
455 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
457 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
460 /* GL locking is done by the caller */
461 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
462 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
465 unsigned int heap_idx = 1;
468 if (heap->entries[heap_idx].version <= version) return;
470 idx = heap->entries[heap_idx].idx;
471 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
472 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
474 while (stack_idx >= 0)
476 /* Note that we fall through to the next case statement. */
477 switch(stack[stack_idx])
479 case HEAP_NODE_TRAVERSE_LEFT:
481 unsigned int left_idx = heap_idx << 1;
482 if (left_idx < heap->size && heap->entries[left_idx].version > version)
485 idx = heap->entries[heap_idx].idx;
486 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
488 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
489 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
494 case HEAP_NODE_TRAVERSE_RIGHT:
496 unsigned int right_idx = (heap_idx << 1) + 1;
497 if (right_idx < heap->size && heap->entries[right_idx].version > version)
499 heap_idx = right_idx;
500 idx = heap->entries[heap_idx].idx;
501 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
503 stack[stack_idx++] = HEAP_NODE_POP;
504 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
517 checkGLcall("walk_constant_heap_clamped()");
520 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
521 /* GL locking is done by the caller */
522 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
523 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
524 unsigned char *stack, UINT version)
526 const local_constant *lconst;
528 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
529 if (This->baseShader.reg_maps.shader_version.major == 1
530 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
531 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
533 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
535 if (!This->baseShader.load_local_constsF)
537 TRACE("No need to load local float constants for this shader\n");
541 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
542 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
544 GLint location = constant_locations[lconst->idx];
545 /* We found this uniform name in the program - go ahead and send the data */
546 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
548 checkGLcall("glUniform4fvARB()");
551 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
552 /* GL locking is done by the caller */
553 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
554 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
559 for (i = 0; constants_set; constants_set >>= 1, ++i)
561 if (!(constants_set & 1)) continue;
563 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
564 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
566 /* We found this uniform name in the program - go ahead and send the data */
567 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
568 checkGLcall("glUniform4ivARB");
571 /* Load immediate constants */
572 ptr = list_head(&This->baseShader.constantsI);
574 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
575 unsigned int idx = lconst->idx;
576 const GLint *values = (const GLint *)lconst->value;
578 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
579 values[0], values[1], values[2], values[3]);
581 /* We found this uniform name in the program - go ahead and send the data */
582 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
583 checkGLcall("glUniform4ivARB");
584 ptr = list_next(&This->baseShader.constantsI, ptr);
588 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
589 /* GL locking is done by the caller */
590 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
591 GLhandleARB programId, const BOOL *constants, WORD constants_set)
599 switch (This->baseShader.reg_maps.shader_version.type)
601 case WINED3D_SHADER_TYPE_VERTEX:
605 case WINED3D_SHADER_TYPE_GEOMETRY:
609 case WINED3D_SHADER_TYPE_PIXEL:
614 FIXME("Unknown shader type %#x.\n",
615 This->baseShader.reg_maps.shader_version.type);
620 /* TODO: Benchmark and see if it would be beneficial to store the
621 * locations of the constants to avoid looking up each time */
622 for (i = 0; constants_set; constants_set >>= 1, ++i)
624 if (!(constants_set & 1)) continue;
626 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
628 /* TODO: Benchmark and see if it would be beneficial to store the
629 * locations of the constants to avoid looking up each time */
630 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
631 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
634 /* We found this uniform name in the program - go ahead and send the data */
635 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
636 checkGLcall("glUniform1ivARB");
640 /* Load immediate constants */
641 ptr = list_head(&This->baseShader.constantsB);
643 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
644 unsigned int idx = lconst->idx;
645 const GLint *values = (const GLint *)lconst->value;
647 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
649 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
650 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
652 /* We found this uniform name in the program - go ahead and send the data */
653 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
654 checkGLcall("glUniform1ivARB");
656 ptr = list_next(&This->baseShader.constantsB, ptr);
660 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
662 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
666 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
668 /* GL locking is done by the caller (state handler) */
669 static void shader_glsl_load_np2fixup_constants(
670 IWineD3DDevice* device,
672 char useVertexShader) {
674 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
675 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
678 /* No GLSL program set - nothing to do. */
682 if (!usePixelShader) {
683 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
687 if (prog->ps_args.np2_fixup && -1 != prog->np2Fixup_location) {
688 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
689 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
691 UINT fixup = prog->ps_args.np2_fixup;
692 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
694 for (i = 0; fixup; fixup >>= 1, ++i) {
695 const unsigned char idx = prog->np2Fixup_info->idx[i];
696 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
697 GLfloat* tex_dim = &np2fixup_constants[(idx >> 1) * 4];
700 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
705 tex_dim[2] = tex->baseTexture.pow2Matrix[0]; tex_dim[3] = tex->baseTexture.pow2Matrix[5];
707 tex_dim[0] = tex->baseTexture.pow2Matrix[0]; tex_dim[1] = tex->baseTexture.pow2Matrix[5];
711 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
716 * Loads the app-supplied constants into the currently set GLSL program.
718 /* GL locking is done by the caller (state handler) */
719 static void shader_glsl_load_constants(const struct wined3d_context *context,
720 char usePixelShader, char useVertexShader)
722 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
723 const struct wined3d_gl_info *gl_info = context->gl_info;
724 IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
725 struct shader_glsl_priv *priv = device->shader_priv;
727 GLhandleARB programId;
728 struct glsl_shader_prog_link *prog = priv->glsl_program;
729 UINT constant_version;
733 /* No GLSL program set - nothing to do. */
736 programId = prog->programId;
737 constant_version = prog->constant_version;
739 if (useVertexShader) {
740 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
742 /* Load DirectX 9 float constants/uniforms for vertex shader */
743 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
744 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
746 /* Load DirectX 9 integer constants/uniforms for vertex shader */
747 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
748 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
750 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
751 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
752 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
754 /* Upload the position fixup params */
755 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &device->posFixup[0]));
756 checkGLcall("glUniform4fvARB");
759 if (usePixelShader) {
761 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
763 /* Load DirectX 9 float constants/uniforms for pixel shader */
764 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
765 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
767 /* Load DirectX 9 integer constants/uniforms for pixel shader */
768 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
769 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
771 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
772 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
773 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
775 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
776 * It can't be 0 for a valid texbem instruction.
778 for(i = 0; i < MAX_TEXTURES; i++) {
781 if(prog->bumpenvmat_location[i] == -1) continue;
783 data = (const float *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVMAT00];
784 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
785 checkGLcall("glUniformMatrix2fvARB");
787 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
788 * is set too, so we can check that in the needsbumpmat check
790 if(prog->luminancescale_location[i] != -1) {
791 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLSCALE];
792 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLOFFSET];
794 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
795 checkGLcall("glUniform1fvARB");
796 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
797 checkGLcall("glUniform1fvARB");
801 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
802 float correction_params[4];
804 if (context->render_offscreen)
806 correction_params[0] = 0.0f;
807 correction_params[1] = 1.0f;
809 /* position is window relative, not viewport relative */
810 correction_params[0] = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
811 correction_params[1] = -1.0f;
813 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
817 if (priv->next_constant_version == UINT_MAX)
819 TRACE("Max constant version reached, resetting to 0.\n");
820 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
821 priv->next_constant_version = 1;
825 prog->constant_version = priv->next_constant_version++;
829 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
830 unsigned int heap_idx, DWORD new_version)
832 struct constant_entry *entries = heap->entries;
833 unsigned int *positions = heap->positions;
834 unsigned int parent_idx;
838 parent_idx = heap_idx >> 1;
840 if (new_version <= entries[parent_idx].version) break;
842 entries[heap_idx] = entries[parent_idx];
843 positions[entries[parent_idx].idx] = heap_idx;
844 heap_idx = parent_idx;
847 entries[heap_idx].version = new_version;
848 entries[heap_idx].idx = idx;
849 positions[idx] = heap_idx;
852 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
854 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
855 struct shader_glsl_priv *priv = This->shader_priv;
856 struct constant_heap *heap = &priv->vconst_heap;
859 for (i = start; i < count + start; ++i)
861 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
862 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
864 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
868 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
870 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
871 struct shader_glsl_priv *priv = This->shader_priv;
872 struct constant_heap *heap = &priv->pconst_heap;
875 for (i = start; i < count + start; ++i)
877 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
878 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
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, IWineD3DBaseShader *iface,
898 const shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
900 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
901 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
902 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
903 const struct wined3d_gl_info *gl_info = context->gl_info;
904 unsigned int i, extra_constants_needed = 0;
905 const local_constant *lconst;
908 /* There are some minor differences between pixel and vertex shaders */
909 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
910 char prefix = pshader ? 'P' : 'V';
912 /* Prototype the subroutines */
913 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
915 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
918 /* Declare the constants (aka uniforms) */
919 if (This->baseShader.limits.constant_float > 0) {
920 unsigned max_constantsF;
921 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
922 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
923 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
924 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
925 * a dx9 card, as long as it doesn't also use all the other constants.
927 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
928 * declare only the amount that we're assured to have.
930 * Thus we run into problems in these two cases:
931 * 1) The shader really uses more uniforms than supported
932 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
936 /* No indirect addressing here. */
937 max_constantsF = gl_info->limits.glsl_ps_float_constants;
941 if(This->baseShader.reg_maps.usesrelconstF) {
942 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
943 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
944 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
945 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
947 * Writing gl_ClipVertex requires one uniform for each clipplane as well.
949 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
950 if(ctx_priv->cur_vs_args->clip_enabled)
952 max_constantsF -= gl_info->limits.clipplanes;
954 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
955 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
956 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
957 * for now take this into account when calculating the number of available constants
959 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
960 /* Set by driver quirks in directx.c */
961 max_constantsF -= gl_info->reserved_glsl_constants;
965 max_constantsF = gl_info->limits.glsl_vs_float_constants;
968 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
969 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
972 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
973 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
975 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
976 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
978 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
979 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
982 shader_addline(buffer, "uniform vec4 posFixup;\n");
983 /* Predeclaration; This function is added at link time based on the pixel shader.
984 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
985 * that. We know the input to the reorder function at vertex shader compile time, so
986 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
987 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
988 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
989 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
990 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
993 if (reg_maps->shader_version.major >= 3)
995 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
997 shader_addline(buffer, "void order_ps_input();\n");
1000 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1002 if (!(map & 1)) continue;
1004 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1006 if (reg_maps->luminanceparams & (1 << i))
1008 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1009 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1010 extra_constants_needed++;
1013 extra_constants_needed++;
1016 if (ps_args->srgb_correction)
1018 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1019 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1020 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1023 if (reg_maps->vpos || reg_maps->usesdsy)
1025 if (This->baseShader.limits.constant_float + extra_constants_needed
1026 + 1 < gl_info->limits.glsl_ps_float_constants)
1028 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1029 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
1030 extra_constants_needed++;
1032 /* This happens because we do not have proper tracking of the constant registers that are
1033 * actually used, only the max limit of the shader version
1035 FIXME("Cannot find a free uniform for vpos correction params\n");
1036 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1037 context->render_offscreen ? 0.0f : ((IWineD3DSurfaceImpl *)device->render_targets[0])->currentDesc.Height,
1038 context->render_offscreen ? 1.0f : -1.0f);
1040 shader_addline(buffer, "vec4 vpos;\n");
1044 /* Declare texture samplers */
1045 for (i = 0; i < This->baseShader.limits.sampler; i++) {
1046 if (reg_maps->sampler_type[i])
1048 switch (reg_maps->sampler_type[i])
1051 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1054 if(device->stateBlock->textures[i] &&
1055 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
1056 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1058 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1061 case WINED3DSTT_CUBE:
1062 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1064 case WINED3DSTT_VOLUME:
1065 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1068 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1069 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1075 /* Declare uniforms for NP2 texcoord fixup:
1076 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1077 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1078 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1079 if (pshader && ps_args->np2_fixup) {
1081 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1084 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1085 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1086 * samplerNP2Fixup stores texture dimensions and is updated through
1087 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1089 for (i = 0; i < This->baseShader.limits.sampler; ++i) {
1090 if (reg_maps->sampler_type[i]) {
1091 if (!(ps_args->np2_fixup & (1 << i))) continue;
1093 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1094 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1098 fixup->idx[i] = cur++;
1102 fixup->num_consts = (cur + 1) >> 1;
1103 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1106 /* Declare address variables */
1107 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1109 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1112 /* Declare texture coordinate temporaries and initialize them */
1113 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1115 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1118 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1119 * helper function shader that is linked in at link time
1121 if (pshader && reg_maps->shader_version.major >= 3)
1123 if (use_vs(device->stateBlock))
1125 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1127 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1128 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1129 * pixel shader that reads the fixed function color into the packed input registers.
1131 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1135 /* Declare output register temporaries */
1136 if(This->baseShader.limits.packed_output) {
1137 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
1140 /* Declare temporary variables */
1141 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1143 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1146 /* Declare attributes */
1147 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1149 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1151 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1155 /* Declare loop registers aLx */
1156 for (i = 0; i < reg_maps->loop_depth; i++) {
1157 shader_addline(buffer, "int aL%u;\n", i);
1158 shader_addline(buffer, "int tmpInt%u;\n", i);
1161 /* Temporary variables for matrix operations */
1162 shader_addline(buffer, "vec4 tmp0;\n");
1163 shader_addline(buffer, "vec4 tmp1;\n");
1165 /* Local constants use a different name so they can be loaded once at shader link time
1166 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1167 * float -> string conversion can cause precision loss.
1169 if(!This->baseShader.load_local_constsF) {
1170 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1171 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1175 /* Start the main program */
1176 shader_addline(buffer, "void main() {\n");
1177 if(pshader && reg_maps->vpos) {
1178 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1179 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1180 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1181 * precision troubles when we just substract 0.5.
1183 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1185 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1187 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1188 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1189 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1190 * correctly on drivers that returns integer values.
1192 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1196 /*****************************************************************************
1197 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1199 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1200 ****************************************************************************/
1203 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1204 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1206 /** Used for opcode modifiers - They multiply the result by the specified amount */
1207 static const char * const shift_glsl_tab[] = {
1209 "2.0 * ", /* 1 (x2) */
1210 "4.0 * ", /* 2 (x4) */
1211 "8.0 * ", /* 3 (x8) */
1212 "16.0 * ", /* 4 (x16) */
1213 "32.0 * ", /* 5 (x32) */
1220 "0.0625 * ", /* 12 (d16) */
1221 "0.125 * ", /* 13 (d8) */
1222 "0.25 * ", /* 14 (d4) */
1223 "0.5 * " /* 15 (d2) */
1226 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1227 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1231 switch (src_modifier)
1233 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1234 case WINED3DSPSM_DW:
1235 case WINED3DSPSM_NONE:
1236 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1238 case WINED3DSPSM_NEG:
1239 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1241 case WINED3DSPSM_NOT:
1242 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1244 case WINED3DSPSM_BIAS:
1245 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1247 case WINED3DSPSM_BIASNEG:
1248 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1250 case WINED3DSPSM_SIGN:
1251 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1253 case WINED3DSPSM_SIGNNEG:
1254 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1256 case WINED3DSPSM_COMP:
1257 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1259 case WINED3DSPSM_X2:
1260 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1262 case WINED3DSPSM_X2NEG:
1263 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1265 case WINED3DSPSM_ABS:
1266 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1268 case WINED3DSPSM_ABSNEG:
1269 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1272 FIXME("Unhandled modifier %u\n", src_modifier);
1273 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1277 /** Writes the GLSL variable name that corresponds to the register that the
1278 * DX opcode parameter is trying to access */
1279 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1280 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1282 /* oPos, oFog and oPts in D3D */
1283 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1285 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1286 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1287 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1293 case WINED3DSPR_TEMP:
1294 sprintf(register_name, "R%u", reg->idx);
1297 case WINED3DSPR_INPUT:
1298 /* vertex shaders */
1301 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1302 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1303 sprintf(register_name, "attrib%u", reg->idx);
1307 /* pixel shaders >= 3.0 */
1308 if (This->baseShader.reg_maps.shader_version.major >= 3)
1310 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1311 unsigned int in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1315 glsl_src_param_t rel_param;
1317 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1319 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1320 * operation there */
1323 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1325 sprintf(register_name,
1326 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1327 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1328 rel_param.param_str, idx);
1332 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1337 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1339 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1340 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1341 rel_param.param_str);
1345 sprintf(register_name, "IN[%s]", rel_param.param_str);
1351 if (idx == in_count) sprintf(register_name, "gl_Color");
1352 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1353 else sprintf(register_name, "IN[%u]", idx);
1358 if (reg->idx == 0) strcpy(register_name, "gl_Color");
1359 else strcpy(register_name, "gl_SecondaryColor");
1364 case WINED3DSPR_CONST:
1366 const char prefix = pshader ? 'P' : 'V';
1368 /* Relative addressing */
1371 glsl_src_param_t rel_param;
1372 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1373 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1374 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1378 if (shader_constant_is_local(This, reg->idx))
1379 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1381 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1386 case WINED3DSPR_CONSTINT:
1387 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1388 else sprintf(register_name, "VI[%u]", reg->idx);
1391 case WINED3DSPR_CONSTBOOL:
1392 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1393 else sprintf(register_name, "VB[%u]", reg->idx);
1396 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1397 if (pshader) sprintf(register_name, "T%u", reg->idx);
1398 else sprintf(register_name, "A%u", reg->idx);
1401 case WINED3DSPR_LOOP:
1402 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1405 case WINED3DSPR_SAMPLER:
1406 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1407 else sprintf(register_name, "Vsampler%u", reg->idx);
1410 case WINED3DSPR_COLOROUT:
1411 if (reg->idx >= gl_info->limits.buffers)
1412 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1414 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1417 case WINED3DSPR_RASTOUT:
1418 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1421 case WINED3DSPR_DEPTHOUT:
1422 sprintf(register_name, "gl_FragDepth");
1425 case WINED3DSPR_ATTROUT:
1426 if (reg->idx == 0) sprintf(register_name, "gl_FrontColor");
1427 else sprintf(register_name, "gl_FrontSecondaryColor");
1430 case WINED3DSPR_TEXCRDOUT:
1431 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1432 if (This->baseShader.reg_maps.shader_version.major >= 3) sprintf(register_name, "OUT[%u]", reg->idx);
1433 else sprintf(register_name, "gl_TexCoord[%u]", reg->idx);
1436 case WINED3DSPR_MISCTYPE:
1440 sprintf(register_name, "vpos");
1442 else if (reg->idx == 1)
1444 /* Note that gl_FrontFacing is a bool, while vFace is
1445 * a float for which the sign determines front/back */
1446 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1450 FIXME("Unhandled misctype register %d\n", reg->idx);
1451 sprintf(register_name, "unrecognized_register");
1455 case WINED3DSPR_IMMCONST:
1456 switch (reg->immconst_type)
1458 case WINED3D_IMMCONST_FLOAT:
1459 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1462 case WINED3D_IMMCONST_FLOAT4:
1463 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1464 *(const float *)®->immconst_data[0], *(const float *)®->immconst_data[1],
1465 *(const float *)®->immconst_data[2], *(const float *)®->immconst_data[3]);
1469 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1470 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1475 FIXME("Unhandled register name Type(%d)\n", reg->type);
1476 sprintf(register_name, "unrecognized_register");
1481 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1484 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1485 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1486 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1487 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1491 /* Get the GLSL write mask for the destination register */
1492 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1494 DWORD mask = param->write_mask;
1496 if (shader_is_scalar(¶m->reg))
1498 mask = WINED3DSP_WRITEMASK_0;
1503 shader_glsl_write_mask_to_str(mask, write_mask);
1509 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1510 unsigned int size = 0;
1512 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1513 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1514 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1515 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1520 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1522 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1523 * but addressed as "rgba". To fix this we need to swap the register's x
1524 * and z components. */
1525 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1528 /* swizzle bits fields: wwzzyyxx */
1529 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1530 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1531 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1532 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1536 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1537 BOOL fixup, DWORD mask, char *swizzle_str)
1539 if (shader_is_scalar(¶m->reg))
1540 *swizzle_str = '\0';
1542 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1545 /* From a given parameter token, generate the corresponding GLSL string.
1546 * Also, return the actual register name and swizzle in case the
1547 * caller needs this information as well. */
1548 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1549 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1551 BOOL is_color = FALSE;
1552 char swizzle_str[6];
1554 glsl_src->reg_name[0] = '\0';
1555 glsl_src->param_str[0] = '\0';
1556 swizzle_str[0] = '\0';
1558 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1559 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1560 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1563 /* From a given parameter token, generate the corresponding GLSL string.
1564 * Also, return the actual register name and swizzle in case the
1565 * caller needs this information as well. */
1566 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1567 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1569 BOOL is_color = FALSE;
1571 glsl_dst->mask_str[0] = '\0';
1572 glsl_dst->reg_name[0] = '\0';
1574 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1575 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1578 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1579 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1580 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1582 glsl_dst_param_t glsl_dst;
1585 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1586 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1591 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1592 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1594 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1597 /** Process GLSL instruction modifiers */
1598 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1600 glsl_dst_param_t dst_param;
1603 if (!ins->dst_count) return;
1605 modifiers = ins->dst[0].modifiers;
1606 if (!modifiers) return;
1608 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1610 if (modifiers & WINED3DSPDM_SATURATE)
1612 /* _SAT means to clamp the value of the register to between 0 and 1 */
1613 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1614 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1617 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1619 FIXME("_centroid modifier not handled\n");
1622 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1624 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1628 static inline const char *shader_get_comp_op(DWORD op)
1631 case COMPARISON_GT: return ">";
1632 case COMPARISON_EQ: return "==";
1633 case COMPARISON_GE: return ">=";
1634 case COMPARISON_LT: return "<";
1635 case COMPARISON_NE: return "!=";
1636 case COMPARISON_LE: return "<=";
1638 FIXME("Unrecognized comparison value: %u\n", op);
1643 static void shader_glsl_get_sample_function(const struct wined3d_gl_info *gl_info,
1644 DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1646 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1647 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1648 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1649 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1651 /* Note that there's no such thing as a projected cube texture. */
1652 switch(sampler_type) {
1655 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1659 if (gl_info->supported[EXT_GPU_SHADER4])
1660 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1661 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1662 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1665 FIXME("Unsupported 1D grad function.\n");
1666 sample_function->name = "unsupported1DGrad";
1671 sample_function->name = projected ? "texture1DProj" : "texture1D";
1673 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1678 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1682 if (gl_info->supported[EXT_GPU_SHADER4])
1683 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1684 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1685 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1688 FIXME("Unsupported RECT grad function.\n");
1689 sample_function->name = "unsupported2DRectGrad";
1694 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1698 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1702 if (gl_info->supported[EXT_GPU_SHADER4])
1703 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1704 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1705 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1708 FIXME("Unsupported 2D grad function.\n");
1709 sample_function->name = "unsupported2DGrad";
1714 sample_function->name = projected ? "texture2DProj" : "texture2D";
1717 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1719 case WINED3DSTT_CUBE:
1721 sample_function->name = "textureCubeLod";
1725 if (gl_info->supported[EXT_GPU_SHADER4])
1726 sample_function->name = "textureCubeGrad";
1727 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1728 sample_function->name = "textureCubeGradARB";
1731 FIXME("Unsupported Cube grad function.\n");
1732 sample_function->name = "unsupportedCubeGrad";
1737 sample_function->name = "textureCube";
1739 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1741 case WINED3DSTT_VOLUME:
1743 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1747 if (gl_info->supported[EXT_GPU_SHADER4])
1748 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1749 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1750 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1753 FIXME("Unsupported 3D grad function.\n");
1754 sample_function->name = "unsupported3DGrad";
1759 sample_function->name = projected ? "texture3DProj" : "texture3D";
1761 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1764 sample_function->name = "";
1765 sample_function->coord_mask = 0;
1766 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1771 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1772 BOOL sign_fixup, enum fixup_channel_source channel_source)
1774 switch(channel_source)
1776 case CHANNEL_SOURCE_ZERO:
1777 strcat(arguments, "0.0");
1780 case CHANNEL_SOURCE_ONE:
1781 strcat(arguments, "1.0");
1784 case CHANNEL_SOURCE_X:
1785 strcat(arguments, reg_name);
1786 strcat(arguments, ".x");
1789 case CHANNEL_SOURCE_Y:
1790 strcat(arguments, reg_name);
1791 strcat(arguments, ".y");
1794 case CHANNEL_SOURCE_Z:
1795 strcat(arguments, reg_name);
1796 strcat(arguments, ".z");
1799 case CHANNEL_SOURCE_W:
1800 strcat(arguments, reg_name);
1801 strcat(arguments, ".w");
1805 FIXME("Unhandled channel source %#x\n", channel_source);
1806 strcat(arguments, "undefined");
1810 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1813 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1815 struct wined3d_shader_dst_param dst;
1816 unsigned int mask_size, remaining;
1817 glsl_dst_param_t dst_param;
1818 char arguments[256];
1822 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1823 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1824 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1825 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1826 mask &= ins->dst[0].write_mask;
1828 if (!mask) return; /* Nothing to do */
1830 if (is_yuv_fixup(fixup))
1832 enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1833 FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1837 mask_size = shader_glsl_get_write_mask_size(mask);
1840 dst.write_mask = mask;
1841 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1843 arguments[0] = '\0';
1844 remaining = mask_size;
1845 if (mask & WINED3DSP_WRITEMASK_0)
1847 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1848 if (--remaining) strcat(arguments, ", ");
1850 if (mask & WINED3DSP_WRITEMASK_1)
1852 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1853 if (--remaining) strcat(arguments, ", ");
1855 if (mask & WINED3DSP_WRITEMASK_2)
1857 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1858 if (--remaining) strcat(arguments, ", ");
1860 if (mask & WINED3DSP_WRITEMASK_3)
1862 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1863 if (--remaining) strcat(arguments, ", ");
1868 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1869 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1873 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1877 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
1878 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
1879 const char *dx, const char *dy,
1880 const char *bias, const char *coord_reg_fmt, ...)
1882 const char *sampler_base;
1883 char dst_swizzle[6];
1884 struct color_fixup_desc fixup;
1885 BOOL np2_fixup = FALSE;
1888 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
1890 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
1892 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1893 fixup = priv->cur_ps_args->color_fixup[sampler];
1894 sampler_base = "Psampler";
1896 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
1898 FIXME("Biased sampling from NP2 textures is unsupported\n");
1904 sampler_base = "Vsampler";
1905 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
1908 shader_glsl_append_dst(ins->ctx->buffer, ins);
1910 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
1912 va_start(args, coord_reg_fmt);
1913 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
1917 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
1920 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1921 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
1923 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
1924 (idx % 2) ? "zw" : "xy", dst_swizzle);
1925 } else if(dx && dy) {
1926 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
1928 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
1932 if(!is_identity_fixup(fixup)) {
1933 shader_glsl_color_correction(ins, fixup);
1937 /*****************************************************************************
1938 * Begin processing individual instruction opcodes
1939 ****************************************************************************/
1941 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1942 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
1944 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1945 glsl_src_param_t src0_param;
1946 glsl_src_param_t src1_param;
1950 /* Determine the GLSL operator to use based on the opcode */
1951 switch (ins->handler_idx)
1953 case WINED3DSIH_MUL: op = '*'; break;
1954 case WINED3DSIH_ADD: op = '+'; break;
1955 case WINED3DSIH_SUB: op = '-'; break;
1958 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1962 write_mask = shader_glsl_append_dst(buffer, ins);
1963 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1964 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1965 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1968 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1969 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
1971 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1972 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1973 glsl_src_param_t src0_param;
1976 write_mask = shader_glsl_append_dst(buffer, ins);
1977 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1979 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1980 * shader versions WINED3DSIO_MOVA is used for this. */
1981 if (ins->ctx->reg_maps->shader_version.major == 1
1982 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
1983 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
1985 /* This is a simple floor() */
1986 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1987 if (mask_size > 1) {
1988 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1990 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1993 else if(ins->handler_idx == WINED3DSIH_MOVA)
1995 /* We need to *round* to the nearest int here. */
1996 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1998 if (gl_info->supported[EXT_GPU_SHADER4])
2001 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2003 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2008 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2009 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2011 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2012 src0_param.param_str, src0_param.param_str);
2017 shader_addline(buffer, "%s);\n", src0_param.param_str);
2021 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2022 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2024 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2025 glsl_src_param_t src0_param;
2026 glsl_src_param_t src1_param;
2027 DWORD dst_write_mask, src_write_mask;
2028 unsigned int dst_size = 0;
2030 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2031 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2033 /* dp3 works on vec3, dp4 on vec4 */
2034 if (ins->handler_idx == WINED3DSIH_DP4)
2036 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2038 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2041 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2042 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2045 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2047 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2051 /* Note that this instruction has some restrictions. The destination write mask
2052 * can't contain the w component, and the source swizzles have to be .xyzw */
2053 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2055 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2056 glsl_src_param_t src0_param;
2057 glsl_src_param_t src1_param;
2060 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2061 shader_glsl_append_dst(ins->ctx->buffer, ins);
2062 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2063 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2064 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2067 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2068 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2069 * GLSL uses the value as-is. */
2070 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2072 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2073 glsl_src_param_t src0_param;
2074 glsl_src_param_t src1_param;
2075 DWORD dst_write_mask;
2076 unsigned int dst_size;
2078 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2079 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2081 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2082 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2085 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2087 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
2091 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2092 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2093 * GLSL uses the value as-is. */
2094 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2096 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2097 glsl_src_param_t src0_param;
2098 DWORD dst_write_mask;
2099 unsigned int dst_size;
2101 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2102 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2104 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2107 shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
2109 shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
2113 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2114 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2116 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2117 glsl_src_param_t src_param;
2118 const char *instruction;
2122 /* Determine the GLSL function to use based on the opcode */
2123 /* TODO: Possibly make this a table for faster lookups */
2124 switch (ins->handler_idx)
2126 case WINED3DSIH_MIN: instruction = "min"; break;
2127 case WINED3DSIH_MAX: instruction = "max"; break;
2128 case WINED3DSIH_ABS: instruction = "abs"; break;
2129 case WINED3DSIH_FRC: instruction = "fract"; break;
2130 case WINED3DSIH_NRM: instruction = "normalize"; break;
2131 case WINED3DSIH_EXP: instruction = "exp2"; break;
2132 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2133 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2134 default: instruction = "";
2135 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2139 write_mask = shader_glsl_append_dst(buffer, ins);
2141 shader_addline(buffer, "%s(", instruction);
2145 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2146 shader_addline(buffer, "%s", src_param.param_str);
2147 for (i = 1; i < ins->src_count; ++i)
2149 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2150 shader_addline(buffer, ", %s", src_param.param_str);
2154 shader_addline(buffer, "));\n");
2157 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2158 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2159 * dst.x = 2^(floor(src))
2160 * dst.y = src - floor(src)
2161 * dst.z = 2^src (partial precision is allowed, but optional)
2163 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2164 * dst = 2^src; (partial precision is allowed, but optional)
2166 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2168 glsl_src_param_t src_param;
2170 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2172 if (ins->ctx->reg_maps->shader_version.major < 2)
2176 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2177 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2178 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2179 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2181 shader_glsl_append_dst(ins->ctx->buffer, ins);
2182 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2183 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2186 unsigned int mask_size;
2188 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2189 mask_size = shader_glsl_get_write_mask_size(write_mask);
2191 if (mask_size > 1) {
2192 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2194 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2199 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2200 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2202 glsl_src_param_t src_param;
2204 unsigned int mask_size;
2206 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2207 mask_size = shader_glsl_get_write_mask_size(write_mask);
2208 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2210 if (mask_size > 1) {
2211 shader_addline(ins->ctx->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
2213 shader_addline(ins->ctx->buffer, "1.0 / %s);\n", src_param.param_str);
2217 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2219 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2220 glsl_src_param_t src_param;
2222 unsigned int mask_size;
2224 write_mask = shader_glsl_append_dst(buffer, ins);
2225 mask_size = shader_glsl_get_write_mask_size(write_mask);
2227 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2229 if (mask_size > 1) {
2230 shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
2232 shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
2236 /** Process signed comparison opcodes in GLSL. */
2237 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2239 glsl_src_param_t src0_param;
2240 glsl_src_param_t src1_param;
2242 unsigned int mask_size;
2244 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2245 mask_size = shader_glsl_get_write_mask_size(write_mask);
2246 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2247 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2249 if (mask_size > 1) {
2250 const char *compare;
2252 switch(ins->handler_idx)
2254 case WINED3DSIH_SLT: compare = "lessThan"; break;
2255 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2256 default: compare = "";
2257 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2260 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2261 src0_param.param_str, src1_param.param_str);
2263 switch(ins->handler_idx)
2265 case WINED3DSIH_SLT:
2266 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2267 * to return 0.0 but step returns 1.0 because step is not < x
2268 * An alternative is a bvec compare padded with an unused second component.
2269 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2270 * issue. Playing with not() is not possible either because not() does not accept
2273 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2274 src0_param.param_str, src1_param.param_str);
2276 case WINED3DSIH_SGE:
2277 /* Here we can use the step() function and safe a conditional */
2278 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2281 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2287 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2288 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2290 glsl_src_param_t src0_param;
2291 glsl_src_param_t src1_param;
2292 glsl_src_param_t src2_param;
2293 DWORD write_mask, cmp_channel = 0;
2296 BOOL temp_destination = FALSE;
2298 if (shader_is_scalar(&ins->src[0].reg))
2300 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2302 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2303 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2304 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2306 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2307 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2309 DWORD dst_mask = ins->dst[0].write_mask;
2310 struct wined3d_shader_dst_param dst = ins->dst[0];
2312 /* Cycle through all source0 channels */
2313 for (i=0; i<4; i++) {
2315 /* Find the destination channels which use the current source0 channel */
2316 for (j=0; j<4; j++) {
2317 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2319 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2320 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2323 dst.write_mask = dst_mask & write_mask;
2325 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2326 * The first lines may overwrite source parameters of the following lines.
2327 * Deal with that by using a temporary destination register if needed
2329 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2330 && ins->src[0].reg.type == ins->dst[0].reg.type)
2331 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2332 && ins->src[1].reg.type == ins->dst[0].reg.type)
2333 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2334 && ins->src[2].reg.type == ins->dst[0].reg.type))
2336 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2337 if (!write_mask) continue;
2338 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2339 temp_destination = TRUE;
2341 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2342 if (!write_mask) continue;
2345 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2346 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2347 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2349 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2350 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2353 if(temp_destination) {
2354 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2355 shader_glsl_append_dst(ins->ctx->buffer, ins);
2356 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2362 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2363 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2364 * the compare is done per component of src0. */
2365 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2367 struct wined3d_shader_dst_param dst;
2368 glsl_src_param_t src0_param;
2369 glsl_src_param_t src1_param;
2370 glsl_src_param_t src2_param;
2371 DWORD write_mask, cmp_channel = 0;
2374 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2375 ins->ctx->reg_maps->shader_version.minor);
2377 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2379 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2380 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2381 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2382 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2384 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2387 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2389 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2390 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2394 /* Cycle through all source0 channels */
2395 dst_mask = ins->dst[0].write_mask;
2397 for (i=0; i<4; i++) {
2399 /* Find the destination channels which use the current source0 channel */
2400 for (j=0; j<4; j++) {
2401 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2403 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2404 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2408 dst.write_mask = dst_mask & write_mask;
2409 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2410 if (!write_mask) continue;
2412 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2413 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2414 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2416 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2417 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2421 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2422 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2424 glsl_src_param_t src0_param;
2425 glsl_src_param_t src1_param;
2426 glsl_src_param_t src2_param;
2429 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2430 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2431 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2432 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2433 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2434 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2437 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2438 Vertex shaders to GLSL codes */
2439 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2442 int nComponents = 0;
2443 struct wined3d_shader_dst_param tmp_dst = {{0}};
2444 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2445 struct wined3d_shader_instruction tmp_ins;
2447 memset(&tmp_ins, 0, sizeof(tmp_ins));
2449 /* Set constants for the temporary argument */
2450 tmp_ins.ctx = ins->ctx;
2451 tmp_ins.dst_count = 1;
2452 tmp_ins.dst = &tmp_dst;
2453 tmp_ins.src_count = 2;
2454 tmp_ins.src = tmp_src;
2456 switch(ins->handler_idx)
2458 case WINED3DSIH_M4x4:
2460 tmp_ins.handler_idx = WINED3DSIH_DP4;
2462 case WINED3DSIH_M4x3:
2464 tmp_ins.handler_idx = WINED3DSIH_DP4;
2466 case WINED3DSIH_M3x4:
2468 tmp_ins.handler_idx = WINED3DSIH_DP3;
2470 case WINED3DSIH_M3x3:
2472 tmp_ins.handler_idx = WINED3DSIH_DP3;
2474 case WINED3DSIH_M3x2:
2476 tmp_ins.handler_idx = WINED3DSIH_DP3;
2482 tmp_dst = ins->dst[0];
2483 tmp_src[0] = ins->src[0];
2484 tmp_src[1] = ins->src[1];
2485 for (i = 0; i < nComponents; ++i)
2487 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2488 shader_glsl_dot(&tmp_ins);
2489 ++tmp_src[1].reg.idx;
2494 The LRP instruction performs a component-wise linear interpolation
2495 between the second and third operands using the first operand as the
2496 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2497 This is equivalent to mix(src2, src1, src0);
2499 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2501 glsl_src_param_t src0_param;
2502 glsl_src_param_t src1_param;
2503 glsl_src_param_t src2_param;
2506 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2508 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2509 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2510 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2512 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2513 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2516 /** Process the WINED3DSIO_LIT instruction in GLSL:
2517 * dst.x = dst.w = 1.0
2518 * dst.y = (src0.x > 0) ? src0.x
2519 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2520 * where src.w is clamped at +- 128
2522 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2524 glsl_src_param_t src0_param;
2525 glsl_src_param_t src1_param;
2526 glsl_src_param_t src3_param;
2529 shader_glsl_append_dst(ins->ctx->buffer, ins);
2530 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2532 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2533 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2534 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2536 /* The sdk specifies the instruction like this
2538 * if(src.x > 0.0) dst.y = src.x
2540 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2544 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2545 * dst.x = 1.0 ... No further explanation needed
2546 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2547 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2548 * dst.w = 1.0. ... Nothing fancy.
2550 * So we still have one conditional in there. So do this:
2551 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2553 * 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),
2554 * 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.
2555 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2557 shader_addline(ins->ctx->buffer,
2558 "vec4(1.0, max(%s, 0.0), pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
2559 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2562 /** Process the WINED3DSIO_DST instruction in GLSL:
2564 * dst.y = src0.x * src0.y
2568 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2570 glsl_src_param_t src0y_param;
2571 glsl_src_param_t src0z_param;
2572 glsl_src_param_t src1y_param;
2573 glsl_src_param_t src1w_param;
2576 shader_glsl_append_dst(ins->ctx->buffer, ins);
2577 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2579 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2580 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2581 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2582 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2584 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2585 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2588 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2589 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2590 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2592 * dst.x = cos(src0.?)
2593 * dst.y = sin(src0.?)
2597 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2599 glsl_src_param_t src0_param;
2602 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2603 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2605 switch (write_mask) {
2606 case WINED3DSP_WRITEMASK_0:
2607 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2610 case WINED3DSP_WRITEMASK_1:
2611 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2614 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2615 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2619 ERR("Write mask should be .x, .y or .xy\n");
2624 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2625 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2626 * generate invalid code
2628 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2630 glsl_src_param_t src0_param;
2633 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2634 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2636 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2639 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2640 * Start a for() loop where src1.y is the initial value of aL,
2641 * increment aL by src1.z for a total of src1.x iterations.
2642 * Need to use a temporary variable for this operation.
2644 /* FIXME: I don't think nested loops will work correctly this way. */
2645 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2647 glsl_src_param_t src1_param;
2648 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2649 const DWORD *control_values = NULL;
2650 const local_constant *constant;
2652 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2654 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2655 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2656 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2659 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2661 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2662 if (constant->idx == ins->src[1].reg.idx)
2664 control_values = constant->value;
2672 struct wined3d_shader_loop_control loop_control;
2673 loop_control.count = control_values[0];
2674 loop_control.start = control_values[1];
2675 loop_control.step = (int)control_values[2];
2677 if (loop_control.step > 0)
2679 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2680 shader->baseShader.cur_loop_depth, loop_control.start,
2681 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2682 shader->baseShader.cur_loop_depth, loop_control.step);
2684 else if (loop_control.step < 0)
2686 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2687 shader->baseShader.cur_loop_depth, loop_control.start,
2688 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2689 shader->baseShader.cur_loop_depth, loop_control.step);
2693 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2694 shader->baseShader.cur_loop_depth, loop_control.start, shader->baseShader.cur_loop_depth,
2695 shader->baseShader.cur_loop_depth, loop_control.count,
2696 shader->baseShader.cur_loop_depth);
2699 shader_addline(ins->ctx->buffer,
2700 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2701 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2702 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2703 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2706 shader->baseShader.cur_loop_depth++;
2707 shader->baseShader.cur_loop_regno++;
2710 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2712 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2714 shader_addline(ins->ctx->buffer, "}\n");
2716 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2718 shader->baseShader.cur_loop_depth--;
2719 shader->baseShader.cur_loop_regno--;
2722 if (ins->handler_idx == WINED3DSIH_ENDREP)
2724 shader->baseShader.cur_loop_depth--;
2728 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2730 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2731 glsl_src_param_t src0_param;
2732 const DWORD *control_values = NULL;
2733 const local_constant *constant;
2735 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2736 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2738 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
2740 if (constant->idx == ins->src[0].reg.idx)
2742 control_values = constant->value;
2748 if(control_values) {
2749 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2750 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2751 control_values[0], shader->baseShader.cur_loop_depth);
2753 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2754 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2755 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2756 src0_param.param_str, shader->baseShader.cur_loop_depth);
2758 shader->baseShader.cur_loop_depth++;
2761 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2763 glsl_src_param_t src0_param;
2765 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2766 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2769 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2771 glsl_src_param_t src0_param;
2772 glsl_src_param_t src1_param;
2774 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2775 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2777 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2778 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2781 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2783 shader_addline(ins->ctx->buffer, "} else {\n");
2786 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2788 shader_addline(ins->ctx->buffer, "break;\n");
2791 /* FIXME: According to MSDN the compare is done per component. */
2792 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2794 glsl_src_param_t src0_param;
2795 glsl_src_param_t src1_param;
2797 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2798 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2800 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2801 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2804 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2806 shader_addline(ins->ctx->buffer, "}\n");
2807 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
2810 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2812 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2815 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2817 glsl_src_param_t src1_param;
2819 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2820 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
2823 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
2825 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
2826 * function only suppresses the unhandled instruction warning
2830 /*********************************************
2831 * Pixel Shader Specific Code begins here
2832 ********************************************/
2833 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
2835 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2836 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device;
2837 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2838 ins->ctx->reg_maps->shader_version.minor);
2839 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2840 glsl_sample_function_t sample_function;
2841 DWORD sample_flags = 0;
2842 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
2844 DWORD mask = 0, swizzle;
2846 /* 1.0-1.4: Use destination register as sampler source.
2847 * 2.0+: Use provided sampler source. */
2848 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
2849 else sampler_idx = ins->src[1].reg.idx;
2850 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2852 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2854 DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2856 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
2857 if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
2858 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2859 switch (flags & ~WINED3DTTFF_PROJECTED) {
2860 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2861 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2862 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2863 case WINED3DTTFF_COUNT4:
2864 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2868 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
2870 DWORD src_mod = ins->src[0].modifiers;
2872 if (src_mod == WINED3DSPSM_DZ) {
2873 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2874 mask = WINED3DSP_WRITEMASK_2;
2875 } else if (src_mod == WINED3DSPSM_DW) {
2876 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2877 mask = WINED3DSP_WRITEMASK_3;
2880 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
2882 /* ps 2.0 texldp instruction always divides by the fourth component. */
2883 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2884 mask = WINED3DSP_WRITEMASK_3;
2888 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2889 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2890 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2893 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
2894 mask |= sample_function.coord_mask;
2896 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
2897 else swizzle = ins->src[1].swizzle;
2899 /* 1.0-1.3: Use destination register as coordinate source.
2900 1.4+: Use provided coordinate source register. */
2901 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2904 shader_glsl_write_mask_to_str(mask, coord_mask);
2905 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2906 "T%u%s", sampler_idx, coord_mask);
2908 glsl_src_param_t coord_param;
2909 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
2910 if (ins->flags & WINED3DSI_TEXLD_BIAS)
2912 glsl_src_param_t bias;
2913 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
2914 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
2915 "%s", coord_param.param_str);
2917 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2918 "%s", coord_param.param_str);
2923 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
2925 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2926 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2927 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2928 glsl_sample_function_t sample_function;
2929 glsl_src_param_t coord_param, dx_param, dy_param;
2930 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
2933 DWORD swizzle = ins->src[1].swizzle;
2935 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
2937 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
2938 return shader_glsl_tex(ins);
2941 sampler_idx = ins->src[1].reg.idx;
2942 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2943 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2944 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2945 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2948 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
2949 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2950 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
2951 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
2953 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
2954 "%s", coord_param.param_str);
2957 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
2959 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2960 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2961 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2962 glsl_sample_function_t sample_function;
2963 glsl_src_param_t coord_param, lod_param;
2964 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
2967 DWORD swizzle = ins->src[1].swizzle;
2969 sampler_idx = ins->src[1].reg.idx;
2970 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2971 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2972 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2973 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2975 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
2976 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2978 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
2980 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
2981 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2983 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2984 * However, they seem to work just fine in fragment shaders as well. */
2985 WARN("Using %s in fragment shader.\n", sample_function.name);
2987 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
2988 "%s", coord_param.param_str);
2991 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
2993 /* FIXME: Make this work for more than just 2D textures */
2994 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2995 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2997 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3001 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3002 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3003 ins->dst[0].reg.idx, dst_mask);
3005 DWORD reg = ins->src[0].reg.idx;
3006 DWORD src_mod = ins->src[0].modifiers;
3007 char dst_swizzle[6];
3009 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3011 if (src_mod == WINED3DSPSM_DZ) {
3012 glsl_src_param_t div_param;
3013 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3014 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3016 if (mask_size > 1) {
3017 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3019 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3021 } else if (src_mod == WINED3DSPSM_DW) {
3022 glsl_src_param_t div_param;
3023 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3024 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3026 if (mask_size > 1) {
3027 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3029 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3032 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3037 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3038 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3039 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3040 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3042 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3043 glsl_src_param_t src0_param;
3044 glsl_sample_function_t sample_function;
3045 DWORD sampler_idx = ins->dst[0].reg.idx;
3046 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3047 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3050 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3052 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3053 * scalar, and projected sampling would require 4.
3055 * It is a dependent read - not valid with conditional NP2 textures
3057 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3058 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3063 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3064 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3068 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3069 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3073 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3074 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3078 FIXME("Unexpected mask size %u\n", mask_size);
3083 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3084 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3085 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3087 glsl_src_param_t src0_param;
3088 DWORD dstreg = ins->dst[0].reg.idx;
3089 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3091 unsigned int mask_size;
3093 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3094 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3095 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3097 if (mask_size > 1) {
3098 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3100 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3104 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3105 * Calculate the depth as dst.x / dst.y */
3106 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3108 glsl_dst_param_t dst_param;
3110 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3112 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3113 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3114 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3115 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3118 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3119 dst_param.reg_name, dst_param.reg_name);
3122 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3123 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3124 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3125 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3127 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3129 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3130 DWORD dstreg = ins->dst[0].reg.idx;
3131 glsl_src_param_t src0_param;
3133 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3135 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3136 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3139 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3140 * Calculate the 1st of a 2-row matrix multiplication. */
3141 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3143 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3144 DWORD reg = ins->dst[0].reg.idx;
3145 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3146 glsl_src_param_t src0_param;
3148 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3149 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3152 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3153 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3154 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3156 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3157 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3158 DWORD reg = ins->dst[0].reg.idx;
3159 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3160 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3161 glsl_src_param_t src0_param;
3163 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3164 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
3165 current_state->texcoord_w[current_state->current_row++] = reg;
3168 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3170 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3171 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3172 DWORD reg = ins->dst[0].reg.idx;
3173 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3174 glsl_src_param_t src0_param;
3175 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3176 glsl_sample_function_t sample_function;
3178 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3179 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3181 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3183 /* Sample the texture using the calculated coordinates */
3184 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3187 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3188 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3189 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3191 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3192 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3193 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3194 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3195 glsl_src_param_t src0_param;
3196 DWORD reg = ins->dst[0].reg.idx;
3197 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3198 glsl_sample_function_t sample_function;
3200 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3201 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3203 /* Dependent read, not valid with conditional NP2 */
3204 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3206 /* Sample the texture using the calculated coordinates */
3207 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3209 current_state->current_row = 0;
3212 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3213 * Perform the 3rd row of a 3x3 matrix multiply */
3214 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3216 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3217 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3218 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3219 glsl_src_param_t src0_param;
3221 DWORD reg = ins->dst[0].reg.idx;
3223 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3225 shader_glsl_append_dst(ins->ctx->buffer, ins);
3226 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3227 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3229 current_state->current_row = 0;
3232 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3233 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3234 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3236 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3237 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3238 DWORD reg = ins->dst[0].reg.idx;
3239 glsl_src_param_t src0_param;
3240 glsl_src_param_t src1_param;
3241 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3242 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3243 WINED3DSAMPLER_TEXTURE_TYPE stype = ins->ctx->reg_maps->sampler_type[reg];
3244 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3245 glsl_sample_function_t sample_function;
3247 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3248 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3250 /* Perform the last matrix multiply operation */
3251 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3252 /* Reflection calculation */
3253 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3255 /* Dependent read, not valid with conditional NP2 */
3256 shader_glsl_get_sample_function(gl_info, stype, 0, &sample_function);
3258 /* Sample the texture */
3259 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3261 current_state->current_row = 0;
3264 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3265 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3266 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3268 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3269 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3270 DWORD reg = ins->dst[0].reg.idx;
3271 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3272 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3273 glsl_src_param_t src0_param;
3274 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3275 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3276 glsl_sample_function_t sample_function;
3278 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3280 /* Perform the last matrix multiply operation */
3281 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3283 /* Construct the eye-ray vector from w coordinates */
3284 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3285 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
3286 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3288 /* Dependent read, not valid with conditional NP2 */
3289 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3291 /* Sample the texture using the calculated coordinates */
3292 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3294 current_state->current_row = 0;
3297 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3298 * Apply a fake bump map transform.
3299 * texbem is pshader <= 1.3 only, this saves a few version checks
3301 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3303 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3304 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device;
3305 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3306 glsl_sample_function_t sample_function;
3307 glsl_src_param_t coord_param;
3308 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
3314 sampler_idx = ins->dst[0].reg.idx;
3315 flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
3317 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3318 /* Dependent read, not valid with conditional NP2 */
3319 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3320 mask = sample_function.coord_mask;
3322 shader_glsl_write_mask_to_str(mask, coord_mask);
3324 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3325 * so we can't let the GL handle this.
3327 if (flags & WINED3DTTFF_PROJECTED) {
3329 char coord_div_mask[3];
3330 switch (flags & ~WINED3DTTFF_PROJECTED) {
3331 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3332 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3333 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3334 case WINED3DTTFF_COUNT4:
3335 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3337 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3338 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3341 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3343 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3344 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3345 coord_param.param_str, coord_mask);
3347 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3349 glsl_src_param_t luminance_param;
3350 glsl_dst_param_t dst_param;
3352 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3353 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3355 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3356 dst_param.reg_name, dst_param.mask_str,
3357 luminance_param.param_str, sampler_idx, sampler_idx);
3361 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3363 glsl_src_param_t src0_param, src1_param;
3364 DWORD sampler_idx = ins->dst[0].reg.idx;
3366 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3367 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3369 shader_glsl_append_dst(ins->ctx->buffer, ins);
3370 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3371 src0_param.param_str, sampler_idx, src1_param.param_str);
3374 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3375 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3376 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3378 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3379 glsl_src_param_t src0_param;
3380 DWORD sampler_idx = ins->dst[0].reg.idx;
3381 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3382 glsl_sample_function_t sample_function;
3384 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3386 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3387 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3388 "%s.wx", src0_param.reg_name);
3391 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3392 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3393 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3395 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3396 glsl_src_param_t src0_param;
3397 DWORD sampler_idx = ins->dst[0].reg.idx;
3398 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3399 glsl_sample_function_t sample_function;
3401 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3403 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3404 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3405 "%s.yz", src0_param.reg_name);
3408 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3409 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3410 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3412 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3413 glsl_src_param_t src0_param;
3414 DWORD sampler_idx = ins->dst[0].reg.idx;
3415 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3416 glsl_sample_function_t sample_function;
3418 /* Dependent read, not valid with conditional NP2 */
3419 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3420 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3422 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3423 "%s", src0_param.param_str);
3426 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3427 * If any of the first 3 components are < 0, discard this pixel */
3428 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3430 glsl_dst_param_t dst_param;
3432 /* The argument is a destination parameter, and no writemasks are allowed */
3433 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3434 if (ins->ctx->reg_maps->shader_version.major >= 2)
3436 /* 2.0 shaders compare all 4 components in texkill */
3437 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3439 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3440 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3441 * 4 components are defined, only the first 3 are used
3443 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3447 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3448 * dst = dot2(src0, src1) + src2 */
3449 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3451 glsl_src_param_t src0_param;
3452 glsl_src_param_t src1_param;
3453 glsl_src_param_t src2_param;
3455 unsigned int mask_size;
3457 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3458 mask_size = shader_glsl_get_write_mask_size(write_mask);
3460 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3461 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3462 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3464 if (mask_size > 1) {
3465 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3466 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3468 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3469 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3473 static void shader_glsl_input_pack(IWineD3DPixelShader *iface, struct wined3d_shader_buffer *buffer,
3474 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps,
3475 enum vertexprocessing_mode vertexprocessing)
3478 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3479 WORD map = reg_maps->input_registers;
3481 for (i = 0; map; map >>= 1, ++i)
3483 const char *semantic_name;
3488 if (!(map & 1)) continue;
3490 semantic_name = input_signature[i].semantic_name;
3491 semantic_idx = input_signature[i].semantic_idx;
3492 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3494 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3496 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3497 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3498 This->input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3500 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3501 This->input_reg_map[i], reg_mask, reg_mask);
3503 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3505 if (semantic_idx == 0)
3506 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3507 This->input_reg_map[i], reg_mask, reg_mask);
3508 else if (semantic_idx == 1)
3509 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3510 This->input_reg_map[i], reg_mask, reg_mask);
3512 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3513 This->input_reg_map[i], reg_mask, reg_mask);
3517 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3518 This->input_reg_map[i], reg_mask, reg_mask);
3523 /*********************************************
3524 * Vertex Shader Specific Code begins here
3525 ********************************************/
3527 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3528 glsl_program_key_t key;
3530 key.vshader = entry->vshader;
3531 key.pshader = entry->pshader;
3532 key.vs_args = entry->vs_args;
3533 key.ps_args = entry->ps_args;
3535 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3537 ERR("Failed to insert program entry.\n");
3541 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3542 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3543 struct ps_compile_args *ps_args) {
3544 struct wine_rb_entry *entry;
3545 glsl_program_key_t key;
3547 key.vshader = vshader;
3548 key.pshader = pshader;
3549 key.vs_args = *vs_args;
3550 key.ps_args = *ps_args;
3552 entry = wine_rb_get(&priv->program_lookup, &key);
3553 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3556 /* GL locking is done by the caller */
3557 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3558 struct glsl_shader_prog_link *entry)
3560 glsl_program_key_t key;
3562 key.vshader = entry->vshader;
3563 key.pshader = entry->pshader;
3564 key.vs_args = entry->vs_args;
3565 key.ps_args = entry->ps_args;
3566 wine_rb_remove(&priv->program_lookup, &key);
3568 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3569 if (entry->vshader) list_remove(&entry->vshader_entry);
3570 if (entry->pshader) list_remove(&entry->pshader_entry);
3571 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3572 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3573 HeapFree(GetProcessHeap(), 0, entry);
3576 static void handle_ps3_input(struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info, const DWORD *map,
3577 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3578 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3581 const char *semantic_name_in, *semantic_name_out;
3582 UINT semantic_idx_in, semantic_idx_out;
3585 unsigned int in_count = vec4_varyings(3, gl_info);
3586 char reg_mask[6], reg_mask_out[6];
3587 char destination[50];
3588 WORD input_map, output_map;
3590 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3592 if (!output_signature)
3594 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3595 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3596 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3599 input_map = reg_maps_in->input_registers;
3600 for (i = 0; input_map; input_map >>= 1, ++i)
3602 if (!(input_map & 1)) continue;
3605 if (in_idx >= (in_count + 2)) {
3606 FIXME("More input varyings declared than supported, expect issues\n");
3609 else if (map[i] == ~0U)
3611 /* Declared, but not read register */
3615 if (in_idx == in_count) {
3616 sprintf(destination, "gl_FrontColor");
3617 } else if (in_idx == in_count + 1) {
3618 sprintf(destination, "gl_FrontSecondaryColor");
3620 sprintf(destination, "IN[%u]", in_idx);
3623 semantic_name_in = input_signature[i].semantic_name;
3624 semantic_idx_in = input_signature[i].semantic_idx;
3625 set[map[i]] = input_signature[i].mask;
3626 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3628 if (!output_signature)
3630 if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_COLOR))
3632 if (semantic_idx_in == 0)
3633 shader_addline(buffer, "%s%s = front_color%s;\n",
3634 destination, reg_mask, reg_mask);
3635 else if (semantic_idx_in == 1)
3636 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3637 destination, reg_mask, reg_mask);
3639 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3640 destination, reg_mask, reg_mask);
3642 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_TEXCOORD))
3644 if (semantic_idx_in < 8)
3646 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3647 destination, reg_mask, semantic_idx_in, reg_mask);
3651 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3652 destination, reg_mask, reg_mask);
3655 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_FOG))
3657 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3658 destination, reg_mask, reg_mask);
3662 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3663 destination, reg_mask, reg_mask);
3668 output_map = reg_maps_out->output_registers;
3669 for (j = 0; output_map; output_map >>= 1, ++j)
3671 if (!(output_map & 1)) continue;
3673 semantic_name_out = output_signature[j].semantic_name;
3674 semantic_idx_out = output_signature[j].semantic_idx;
3675 shader_glsl_write_mask_to_str(output_signature[j].mask, reg_mask_out);
3677 if (semantic_idx_in == semantic_idx_out
3678 && !strcmp(semantic_name_in, semantic_name_out))
3680 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3681 destination, reg_mask, j, reg_mask);
3686 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3687 destination, reg_mask, reg_mask);
3692 /* This is solely to make the compiler / linker happy and avoid warning about undefined
3693 * varyings. It shouldn't result in any real code executed on the GPU, since all read
3694 * input varyings are assigned above, if the optimizer works properly.
3696 for(i = 0; i < in_count + 2; i++) {
3697 if (set[i] && set[i] != WINED3DSP_WRITEMASK_ALL)
3699 unsigned int size = 0;
3700 memset(reg_mask, 0, sizeof(reg_mask));
3701 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3702 reg_mask[size] = 'x';
3705 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3706 reg_mask[size] = 'y';
3709 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3710 reg_mask[size] = 'z';
3713 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3714 reg_mask[size] = 'w';
3718 if (i == in_count) {
3719 sprintf(destination, "gl_FrontColor");
3720 } else if (i == in_count + 1) {
3721 sprintf(destination, "gl_FrontSecondaryColor");
3723 sprintf(destination, "IN[%u]", i);
3727 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3729 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3734 HeapFree(GetProcessHeap(), 0, set);
3737 /* GL locking is done by the caller */
3738 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3739 IWineD3DVertexShader *vertexshader, IWineD3DPixelShader *pixelshader, const struct wined3d_gl_info *gl_info)
3741 GLhandleARB ret = 0;
3742 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3743 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3744 IWineD3DDeviceImpl *device;
3745 DWORD vs_major = vs->baseShader.reg_maps.shader_version.major;
3746 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
3748 const char *semantic_name;
3751 const struct wined3d_shader_signature_element *output_signature;
3753 shader_buffer_clear(buffer);
3755 shader_addline(buffer, "#version 120\n");
3757 if(vs_major < 3 && ps_major < 3) {
3758 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3759 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3761 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3762 if ((gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W)
3763 && ps_major == 0 && vs_major > 0 && !device->frag_pipe->ffp_proj_control)
3765 shader_addline(buffer, "void order_ps_input() {\n");
3766 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3767 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3768 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3769 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3772 shader_addline(buffer, "}\n");
3774 shader_addline(buffer, "void order_ps_input() { /* do nothing */ }\n");
3776 } else if(ps_major < 3 && vs_major >= 3) {
3777 WORD map = vs->baseShader.reg_maps.output_registers;
3779 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3780 output_signature = vs->baseShader.output_signature;
3782 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3783 for (i = 0; map; map >>= 1, ++i)
3787 if (!(map & 1)) continue;
3789 semantic_name = output_signature[i].semantic_name;
3790 semantic_idx = output_signature[i].semantic_idx;
3791 write_mask = output_signature[i].mask;
3792 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3794 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3796 if (semantic_idx == 0)
3797 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3798 else if (semantic_idx == 1)
3799 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3801 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3803 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3805 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3807 if (semantic_idx < 8)
3809 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3810 write_mask |= WINED3DSP_WRITEMASK_3;
3812 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3813 semantic_idx, reg_mask, i, reg_mask);
3814 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3815 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3818 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3820 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
3822 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3824 shader_addline(buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3827 shader_addline(buffer, "}\n");
3829 } else if(ps_major >= 3 && vs_major >= 3) {
3830 WORD map = vs->baseShader.reg_maps.output_registers;
3832 output_signature = vs->baseShader.output_signature;
3834 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3835 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3836 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3838 /* First, sort out position and point size. Those are not passed to the pixel shader */
3839 for (i = 0; map; map >>= 1, ++i)
3841 if (!(map & 1)) continue;
3843 semantic_name = output_signature[i].semantic_name;
3844 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3846 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3848 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3850 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3852 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
3856 /* Then, fix the pixel shader input */
3857 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
3858 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
3860 shader_addline(buffer, "}\n");
3861 } else if(ps_major >= 3 && vs_major < 3) {
3862 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3863 shader_addline(buffer, "void order_ps_input() {\n");
3864 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3865 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3866 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3868 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
3869 &ps->baseShader.reg_maps, NULL, NULL);
3870 shader_addline(buffer, "}\n");
3872 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3875 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3876 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3877 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer->buffer, NULL));
3878 checkGLcall("glShaderSourceARB(ret, 1, &buffer->buffer, NULL)");
3879 GL_EXTCALL(glCompileShaderARB(ret));
3880 checkGLcall("glCompileShaderARB(ret)");
3885 /* GL locking is done by the caller */
3886 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const struct wined3d_gl_info *gl_info,
3887 GLhandleARB programId, char prefix)
3889 const local_constant *lconst;
3894 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3895 value = (const float *)lconst->value;
3896 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3897 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3898 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3900 checkGLcall("Hardcoding local constants");
3903 /* GL locking is done by the caller */
3904 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
3905 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *This,
3906 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
3908 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3909 const struct wined3d_gl_info *gl_info = context->gl_info;
3910 CONST DWORD *function = This->baseShader.function;
3911 struct shader_glsl_ctx_priv priv_ctx;
3913 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3914 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3916 memset(&priv_ctx, 0, sizeof(priv_ctx));
3917 priv_ctx.cur_ps_args = args;
3918 priv_ctx.cur_np2fixup_info = np2fixup_info;
3920 shader_addline(buffer, "#version 120\n");
3922 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] && reg_maps->usestexldd)
3924 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3926 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
3928 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3929 * drivers write a warning if we don't do so
3931 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3933 if (gl_info->supported[EXT_GPU_SHADER4])
3935 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
3938 /* Base Declarations */
3939 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
3941 /* Pack 3.0 inputs */
3942 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
3944 shader_glsl_input_pack((IWineD3DPixelShader *) This, buffer,
3945 This->baseShader.input_signature, reg_maps, args->vp_mode);
3948 /* Base Shader Body */
3949 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3951 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
3952 if (reg_maps->shader_version.major < 2)
3954 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
3955 shader_addline(buffer, "gl_FragData[0] = R0;\n");
3958 if (args->srgb_correction)
3960 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
3961 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
3962 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
3963 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
3964 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
3965 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
3967 /* Pixel shader < 3.0 do not replace the fog stage.
3968 * This implements linear fog computation and blending.
3969 * TODO: non linear fog
3970 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
3971 * -1/(e-s) and e/(e-s) respectively.
3973 if (reg_maps->shader_version.major < 3)
3976 case FOG_OFF: break;
3978 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
3979 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
3980 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
3981 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
3984 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
3985 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
3986 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3987 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
3990 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
3991 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
3992 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3993 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
3998 shader_addline(buffer, "}\n");
4000 TRACE("Compiling shader object %u\n", shader_obj);
4001 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4002 GL_EXTCALL(glCompileShaderARB(shader_obj));
4003 print_glsl_info_log(gl_info, shader_obj);
4005 /* Store the shader object */
4009 /* GL locking is done by the caller */
4010 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4011 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *This,
4012 const struct vs_compile_args *args)
4014 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4015 const struct wined3d_gl_info *gl_info = context->gl_info;
4016 CONST DWORD *function = This->baseShader.function;
4017 struct shader_glsl_ctx_priv priv_ctx;
4019 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4020 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4022 shader_addline(buffer, "#version 120\n");
4024 if (gl_info->supported[EXT_GPU_SHADER4])
4026 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4029 memset(&priv_ctx, 0, sizeof(priv_ctx));
4030 priv_ctx.cur_vs_args = args;
4032 /* Base Declarations */
4033 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
4035 /* Base Shader Body */
4036 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
4038 /* Unpack 3.0 outputs */
4039 if (reg_maps->shader_version.major >= 3) shader_addline(buffer, "order_ps_input(OUT);\n");
4040 else shader_addline(buffer, "order_ps_input();\n");
4042 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4043 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4044 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4045 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4047 if(args->fog_src == VS_FOG_Z) {
4048 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4049 } else if (!reg_maps->fog) {
4050 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4053 /* Write the final position.
4055 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4056 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4057 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4058 * contains 1.0 to allow a mad.
4060 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4061 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4062 if(args->clip_enabled) {
4063 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4066 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4068 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4069 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4070 * which is the same as z = z * 2 - w.
4072 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4074 shader_addline(buffer, "}\n");
4076 TRACE("Compiling shader object %u\n", shader_obj);
4077 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4078 GL_EXTCALL(glCompileShaderARB(shader_obj));
4079 print_glsl_info_log(gl_info, shader_obj);
4084 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4085 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
4086 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4090 struct glsl_ps_compiled_shader *new_array;
4091 struct glsl_pshader_private *shader_data;
4092 struct ps_np2fixup_info *np2fixup = NULL;
4095 if (!shader->baseShader.backend_data)
4097 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4098 if (!shader->baseShader.backend_data)
4100 ERR("Failed to allocate backend data.\n");
4104 shader_data = shader->baseShader.backend_data;
4106 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4107 * so a linear search is more performant than a hashmap or a binary search
4108 * (cache coherency etc)
4110 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4111 if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
4112 if(args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
4113 return shader_data->gl_shaders[i].prgId;
4117 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4118 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4119 if (shader_data->num_gl_shaders)
4121 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4122 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4123 new_size * sizeof(*shader_data->gl_shaders));
4125 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4130 ERR("Out of memory\n");
4133 shader_data->gl_shaders = new_array;
4134 shader_data->shader_array_size = new_size;
4137 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4139 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4140 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4142 pixelshader_update_samplers(&shader->baseShader.reg_maps,
4143 ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
4145 shader_buffer_clear(buffer);
4146 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4147 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4148 *np2fixup_info = np2fixup;
4153 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4154 const DWORD use_map) {
4155 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4156 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4157 return stored->fog_src == new->fog_src;
4160 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4161 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
4162 const struct vs_compile_args *args)
4166 struct glsl_vs_compiled_shader *new_array;
4167 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
4168 struct glsl_vshader_private *shader_data;
4171 if (!shader->baseShader.backend_data)
4173 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4174 if (!shader->baseShader.backend_data)
4176 ERR("Failed to allocate backend data.\n");
4180 shader_data = shader->baseShader.backend_data;
4182 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4183 * so a linear search is more performant than a hashmap or a binary search
4184 * (cache coherency etc)
4186 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4187 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4188 return shader_data->gl_shaders[i].prgId;
4192 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4194 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4195 if (shader_data->num_gl_shaders)
4197 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4198 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4199 new_size * sizeof(*shader_data->gl_shaders));
4201 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4206 ERR("Out of memory\n");
4209 shader_data->gl_shaders = new_array;
4210 shader_data->shader_array_size = new_size;
4213 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4215 shader_buffer_clear(buffer);
4216 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4217 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4222 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4223 * It sets the programId on the current StateBlock (because it should be called
4224 * inside of the DrawPrimitive() part of the render loop).
4226 * If a program for the given combination does not exist, create one, and store
4227 * the program in the hash table. If it creates a program, it will link the
4228 * given objects, too.
4231 /* GL locking is done by the caller */
4232 static void set_glsl_shader_program(const struct wined3d_context *context,
4233 IWineD3DDeviceImpl *device, BOOL use_ps, BOOL use_vs)
4235 IWineD3DVertexShader *vshader = use_vs ? device->stateBlock->vertexShader : NULL;
4236 IWineD3DPixelShader *pshader = use_ps ? device->stateBlock->pixelShader : NULL;
4237 const struct wined3d_gl_info *gl_info = context->gl_info;
4238 struct shader_glsl_priv *priv = device->shader_priv;
4239 struct glsl_shader_prog_link *entry = NULL;
4240 GLhandleARB programId = 0;
4241 GLhandleARB reorder_shader_id = 0;
4244 struct ps_compile_args ps_compile_args;
4245 struct vs_compile_args vs_compile_args;
4247 if (vshader) find_vs_compile_args((IWineD3DVertexShaderImpl *)vshader, device->stateBlock, &vs_compile_args);
4248 if (pshader) find_ps_compile_args((IWineD3DPixelShaderImpl *)pshader, device->stateBlock, &ps_compile_args);
4250 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4252 priv->glsl_program = entry;
4256 /* If we get to this point, then no matching program exists, so we create one */
4257 programId = GL_EXTCALL(glCreateProgramObjectARB());
4258 TRACE("Created new GLSL shader program %u\n", programId);
4260 /* Create the entry */
4261 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4262 entry->programId = programId;
4263 entry->vshader = vshader;
4264 entry->pshader = pshader;
4265 entry->vs_args = vs_compile_args;
4266 entry->ps_args = ps_compile_args;
4267 entry->constant_version = 0;
4268 entry->np2Fixup_info = NULL;
4269 /* Add the hash table entry */
4270 add_glsl_program_entry(priv, entry);
4272 /* Set the current program */
4273 priv->glsl_program = entry;
4275 /* Attach GLSL vshader */
4278 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer,
4279 (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
4280 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4283 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4284 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4285 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4286 checkGLcall("glAttachObjectARB");
4287 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4290 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4292 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4293 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4294 checkGLcall("glAttachObjectARB");
4296 /* Bind vertex attributes to a corresponding index number to match
4297 * the same index numbers as ARB_vertex_programs (makes loading
4298 * vertex attributes simpler). With this method, we can use the
4299 * exact same code to load the attributes later for both ARB and
4302 * We have to do this here because we need to know the Program ID
4303 * in order to make the bindings work, and it has to be done prior
4304 * to linking the GLSL program. */
4305 for (i = 0; map; map >>= 1, ++i)
4307 if (!(map & 1)) continue;
4309 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4310 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4312 checkGLcall("glBindAttribLocationARB");
4314 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4317 /* Attach GLSL pshader */
4320 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4321 (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args, &entry->np2Fixup_info);
4322 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4323 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4324 checkGLcall("glAttachObjectARB");
4326 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4329 /* Link the program */
4330 TRACE("Linking GLSL shader program %u\n", programId);
4331 GL_EXTCALL(glLinkProgramARB(programId));
4332 shader_glsl_validate_link(gl_info, programId);
4334 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4335 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4336 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4338 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4339 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4341 for (i = 0; i < MAX_CONST_I; ++i)
4343 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4344 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4346 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4347 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4348 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4350 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4351 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4353 for (i = 0; i < MAX_CONST_I; ++i)
4355 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4356 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4362 for(i = 0; i < MAX_TEXTURES; i++) {
4363 sprintf(name, "bumpenvmat%u", i);
4364 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4365 sprintf(name, "luminancescale%u", i);
4366 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4367 sprintf(name, "luminanceoffset%u", i);
4368 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4371 if (ps_compile_args.np2_fixup) {
4372 if (entry->np2Fixup_info) {
4373 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4375 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4380 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4381 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4382 checkGLcall("Find glsl program uniform locations");
4385 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4386 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4388 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4389 entry->vertex_color_clamp = GL_FALSE;
4391 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4394 /* Set the shader to allow uniform loading on it */
4395 GL_EXTCALL(glUseProgramObjectARB(programId));
4396 checkGLcall("glUseProgramObjectARB(programId)");
4398 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4399 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4400 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4401 * vertex shader with fixed function pixel processing is used we make sure that the card
4402 * supports enough samplers to allow the max number of vertex samplers with all possible
4403 * fixed function fragment processing setups. So once the program is linked these samplers
4406 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4407 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4409 /* If the local constants do not have to be loaded with the environment constants,
4410 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4413 if (pshader && !((IWineD3DBaseShaderImpl *)pshader)->baseShader.load_local_constsF)
4415 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4417 if (vshader && !((IWineD3DBaseShaderImpl *)vshader)->baseShader.load_local_constsF)
4419 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4423 /* GL locking is done by the caller */
4424 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type)
4426 GLhandleARB program_id;
4427 GLhandleARB vshader_id, pshader_id;
4428 static const char *blt_vshader[] =
4433 " gl_Position = gl_Vertex;\n"
4434 " gl_FrontColor = vec4(1.0);\n"
4435 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4439 static const char *blt_pshaders[tex_type_count] =
4445 "uniform sampler2D sampler;\n"
4448 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4454 "uniform samplerCube sampler;\n"
4457 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4461 "#extension GL_ARB_texture_rectangle : enable\n"
4462 "uniform sampler2DRect sampler;\n"
4465 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4469 if (!blt_pshaders[tex_type])
4471 FIXME("tex_type %#x not supported\n", tex_type);
4475 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4476 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
4477 GL_EXTCALL(glCompileShaderARB(vshader_id));
4479 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4480 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
4481 GL_EXTCALL(glCompileShaderARB(pshader_id));
4483 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4484 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4485 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4486 GL_EXTCALL(glLinkProgramARB(program_id));
4488 shader_glsl_validate_link(gl_info, program_id);
4490 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4493 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4494 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4498 /* GL locking is done by the caller */
4499 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4501 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
4502 const struct wined3d_gl_info *gl_info = context->gl_info;
4503 struct shader_glsl_priv *priv = device->shader_priv;
4504 GLhandleARB program_id = 0;
4505 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4507 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4509 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4510 else priv->glsl_program = NULL;
4512 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4514 if (old_vertex_color_clamp != current_vertex_color_clamp)
4516 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4518 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4519 checkGLcall("glClampColorARB");
4523 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4527 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4528 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4529 GL_EXTCALL(glUseProgramObjectARB(program_id));
4530 checkGLcall("glUseProgramObjectARB");
4532 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4533 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4534 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4535 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4537 shader_glsl_load_np2fixup_constants((IWineD3DDevice *)device, usePS, useVS);
4541 /* GL locking is done by the caller */
4542 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
4543 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4544 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4545 struct shader_glsl_priv *priv = This->shader_priv;
4546 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
4548 if (!*blt_program) {
4550 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
4551 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4552 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4553 GL_EXTCALL(glUniform1iARB(loc, 0));
4555 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4559 /* GL locking is done by the caller */
4560 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
4561 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4562 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4563 struct shader_glsl_priv *priv = This->shader_priv;
4564 GLhandleARB program_id;
4566 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4567 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4569 GL_EXTCALL(glUseProgramObjectARB(program_id));
4570 checkGLcall("glUseProgramObjectARB");
4573 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
4574 const struct list *linked_programs;
4575 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
4576 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
4577 struct shader_glsl_priv *priv = device->shader_priv;
4578 const struct wined3d_gl_info *gl_info;
4579 struct wined3d_context *context;
4581 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
4582 * can be called from IWineD3DBaseShader::Release
4584 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
4587 struct glsl_pshader_private *shader_data;
4588 shader_data = This->baseShader.backend_data;
4589 if(!shader_data || shader_data->num_gl_shaders == 0)
4591 HeapFree(GetProcessHeap(), 0, shader_data);
4592 This->baseShader.backend_data = NULL;
4596 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
4597 gl_info = context->gl_info;
4599 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
4602 shader_glsl_select(context, FALSE, FALSE);
4606 struct glsl_vshader_private *shader_data;
4607 shader_data = This->baseShader.backend_data;
4608 if(!shader_data || shader_data->num_gl_shaders == 0)
4610 HeapFree(GetProcessHeap(), 0, shader_data);
4611 This->baseShader.backend_data = NULL;
4615 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
4616 gl_info = context->gl_info;
4618 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
4621 shader_glsl_select(context, FALSE, FALSE);
4626 linked_programs = &This->baseShader.linked_programs;
4628 TRACE("Deleting linked programs\n");
4629 if (linked_programs->next) {
4630 struct glsl_shader_prog_link *entry, *entry2;
4634 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4635 delete_glsl_program_entry(priv, gl_info, entry);
4638 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4639 delete_glsl_program_entry(priv, gl_info, entry);
4647 struct glsl_pshader_private *shader_data = This->baseShader.backend_data;
4650 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4651 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4652 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4653 checkGLcall("glDeleteObjectARB");
4656 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4661 struct glsl_vshader_private *shader_data = This->baseShader.backend_data;
4664 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4665 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4666 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4667 checkGLcall("glDeleteObjectARB");
4670 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4673 HeapFree(GetProcessHeap(), 0, This->baseShader.backend_data);
4674 This->baseShader.backend_data = NULL;
4676 context_release(context);
4679 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4681 const glsl_program_key_t *k = key;
4682 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4683 const struct glsl_shader_prog_link, program_lookup_entry);
4686 if (k->vshader > prog->vshader) return 1;
4687 else if (k->vshader < prog->vshader) return -1;
4689 if (k->pshader > prog->pshader) return 1;
4690 else if (k->pshader < prog->pshader) return -1;
4692 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4693 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4698 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4700 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4701 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4705 ERR("Failed to allocate memory\n");
4709 heap->entries = mem;
4710 heap->entries[1].version = 0;
4711 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4717 static void constant_heap_free(struct constant_heap *heap)
4719 HeapFree(GetProcessHeap(), 0, heap->entries);
4722 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4727 glsl_program_key_compare,
4730 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
4731 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4732 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4733 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4734 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4735 gl_info->limits.glsl_ps_float_constants)) + 1;
4737 if (!shader_buffer_init(&priv->shader_buffer))
4739 ERR("Failed to initialize shader buffer.\n");
4743 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4746 ERR("Failed to allocate memory.\n");
4750 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4752 ERR("Failed to initialize vertex shader constant heap\n");
4756 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4758 ERR("Failed to initialize pixel shader constant heap\n");
4762 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4764 ERR("Failed to initialize rbtree.\n");
4768 priv->next_constant_version = 1;
4770 This->shader_priv = priv;
4774 constant_heap_free(&priv->pconst_heap);
4775 constant_heap_free(&priv->vconst_heap);
4776 HeapFree(GetProcessHeap(), 0, priv->stack);
4777 shader_buffer_free(&priv->shader_buffer);
4778 HeapFree(GetProcessHeap(), 0, priv);
4779 return E_OUTOFMEMORY;
4782 /* Context activation is done by the caller. */
4783 static void shader_glsl_free(IWineD3DDevice *iface) {
4784 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4785 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4786 struct shader_glsl_priv *priv = This->shader_priv;
4790 for (i = 0; i < tex_type_count; ++i)
4792 if (priv->depth_blt_program[i])
4794 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
4799 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4800 constant_heap_free(&priv->pconst_heap);
4801 constant_heap_free(&priv->vconst_heap);
4802 HeapFree(GetProcessHeap(), 0, priv->stack);
4803 shader_buffer_free(&priv->shader_buffer);
4805 HeapFree(GetProcessHeap(), 0, This->shader_priv);
4806 This->shader_priv = NULL;
4809 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
4810 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4814 static void shader_glsl_get_caps(WINED3DDEVTYPE devtype,
4815 const struct wined3d_gl_info *gl_info, struct shader_caps *pCaps)
4817 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4818 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support based
4819 * on the version of NV_vertex_program.
4820 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4821 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4822 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4823 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4825 if ((gl_info->supported[NV_VERTEX_PROGRAM2] && !gl_info->supported[NV_VERTEX_PROGRAM3])
4826 || gl_info->limits.arb_ps_instructions <= 512)
4827 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4829 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4830 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4831 pCaps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4833 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4834 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4835 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4836 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4837 * in max native instructions. Intel and others also offer the info in this extension but they
4838 * don't support GLSL (at least on Windows).
4840 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4841 * of instructions is 512 or less we have to do with ps2.0 hardware.
4842 * NOTE: ps3.0 hardware requires 512 or more instructions but ati and nvidia offer 'enough' (1024 vs 4096) on their most basic ps3.0 hardware.
4844 if ((gl_info->supported[NV_FRAGMENT_PROGRAM] && !gl_info->supported[NV_FRAGMENT_PROGRAM2])
4845 || gl_info->limits.arb_ps_instructions <= 512)
4846 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4848 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4850 pCaps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4852 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4853 * Direct3D minimum requirement.
4855 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4856 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4858 * The problem is that the refrast clamps temporary results in the shader to
4859 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4860 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4861 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4862 * offer a way to query this.
4864 pCaps->PixelShader1xMaxValue = 8.0;
4865 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4867 pCaps->VSClipping = TRUE;
4870 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4872 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4874 TRACE("Checking support for fixup:\n");
4875 dump_color_fixup_desc(fixup);
4878 /* We support everything except YUV conversions. */
4879 if (!is_yuv_fixup(fixup))
4885 TRACE("[FAILED]\n");
4889 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4891 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4892 /* WINED3DSIH_ADD */ shader_glsl_arith,
4893 /* WINED3DSIH_BEM */ shader_glsl_bem,
4894 /* WINED3DSIH_BREAK */ shader_glsl_break,
4895 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4896 /* WINED3DSIH_BREAKP */ NULL,
4897 /* WINED3DSIH_CALL */ shader_glsl_call,
4898 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4899 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4900 /* WINED3DSIH_CND */ shader_glsl_cnd,
4901 /* WINED3DSIH_CRS */ shader_glsl_cross,
4902 /* WINED3DSIH_CUT */ NULL,
4903 /* WINED3DSIH_DCL */ NULL,
4904 /* WINED3DSIH_DEF */ NULL,
4905 /* WINED3DSIH_DEFB */ NULL,
4906 /* WINED3DSIH_DEFI */ NULL,
4907 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
4908 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4909 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4910 /* WINED3DSIH_DST */ shader_glsl_dst,
4911 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4912 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4913 /* WINED3DSIH_ELSE */ shader_glsl_else,
4914 /* WINED3DSIH_EMIT */ NULL,
4915 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4916 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
4917 /* WINED3DSIH_ENDREP */ shader_glsl_end,
4918 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
4919 /* WINED3DSIH_EXPP */ shader_glsl_expp,
4920 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
4921 /* WINED3DSIH_IADD */ NULL,
4922 /* WINED3DSIH_IF */ shader_glsl_if,
4923 /* WINED3DSIH_IFC */ shader_glsl_ifc,
4924 /* WINED3DSIH_IGE */ NULL,
4925 /* WINED3DSIH_LABEL */ shader_glsl_label,
4926 /* WINED3DSIH_LIT */ shader_glsl_lit,
4927 /* WINED3DSIH_LOG */ shader_glsl_log,
4928 /* WINED3DSIH_LOGP */ shader_glsl_log,
4929 /* WINED3DSIH_LOOP */ shader_glsl_loop,
4930 /* WINED3DSIH_LRP */ shader_glsl_lrp,
4931 /* WINED3DSIH_LT */ NULL,
4932 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
4933 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
4934 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
4935 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
4936 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
4937 /* WINED3DSIH_MAD */ shader_glsl_mad,
4938 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
4939 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
4940 /* WINED3DSIH_MOV */ shader_glsl_mov,
4941 /* WINED3DSIH_MOVA */ shader_glsl_mov,
4942 /* WINED3DSIH_MUL */ shader_glsl_arith,
4943 /* WINED3DSIH_NOP */ NULL,
4944 /* WINED3DSIH_NRM */ shader_glsl_map2gl,
4945 /* WINED3DSIH_PHASE */ NULL,
4946 /* WINED3DSIH_POW */ shader_glsl_pow,
4947 /* WINED3DSIH_RCP */ shader_glsl_rcp,
4948 /* WINED3DSIH_REP */ shader_glsl_rep,
4949 /* WINED3DSIH_RET */ shader_glsl_ret,
4950 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
4951 /* WINED3DSIH_SETP */ NULL,
4952 /* WINED3DSIH_SGE */ shader_glsl_compare,
4953 /* WINED3DSIH_SGN */ shader_glsl_sgn,
4954 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
4955 /* WINED3DSIH_SLT */ shader_glsl_compare,
4956 /* WINED3DSIH_SUB */ shader_glsl_arith,
4957 /* WINED3DSIH_TEX */ shader_glsl_tex,
4958 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
4959 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
4960 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
4961 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
4962 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
4963 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
4964 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
4965 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
4966 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
4967 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
4968 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
4969 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
4970 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
4971 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
4972 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
4973 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
4974 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
4975 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
4976 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
4977 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
4978 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
4981 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
4982 SHADER_HANDLER hw_fct;
4984 /* Select handler */
4985 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
4987 /* Unhandled opcode */
4990 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
4995 shader_glsl_add_instruction_modifiers(ins);
4998 const shader_backend_t glsl_shader_backend = {
4999 shader_glsl_handle_instruction,
5001 shader_glsl_select_depth_blt,
5002 shader_glsl_deselect_depth_blt,
5003 shader_glsl_update_float_vertex_constants,
5004 shader_glsl_update_float_pixel_constants,
5005 shader_glsl_load_constants,
5006 shader_glsl_load_np2fixup_constants,
5007 shader_glsl_destroy,
5010 shader_glsl_dirty_const,
5011 shader_glsl_get_caps,
5012 shader_glsl_color_fixup_supported,