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 WINED3D_GLSL_SAMPLE_PROJECTED 0x1
43 #define WINED3D_GLSL_SAMPLE_RECT 0x2
44 #define WINED3D_GLSL_SAMPLE_LOD 0x4
45 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
60 } glsl_sample_function_t;
64 HEAP_NODE_TRAVERSE_LEFT,
65 HEAP_NODE_TRAVERSE_RIGHT,
77 struct constant_entry *entries;
78 unsigned int *positions;
82 /* GLSL shader private data */
83 struct shader_glsl_priv {
84 struct wined3d_shader_buffer shader_buffer;
85 struct wine_rb_tree program_lookup;
86 struct glsl_shader_prog_link *glsl_program;
87 struct constant_heap vconst_heap;
88 struct constant_heap pconst_heap;
90 GLhandleARB depth_blt_program_full[tex_type_count];
91 GLhandleARB depth_blt_program_masked[tex_type_count];
92 UINT next_constant_version;
95 /* Struct to maintain data about a linked GLSL program */
96 struct glsl_shader_prog_link {
97 struct wine_rb_entry program_lookup_entry;
98 struct list vshader_entry;
99 struct list pshader_entry;
100 GLhandleARB programId;
101 GLint *vuniformF_locations;
102 GLint *puniformF_locations;
103 GLint vuniformI_locations[MAX_CONST_I];
104 GLint puniformI_locations[MAX_CONST_I];
105 GLint posFixup_location;
106 GLint np2Fixup_location;
107 GLint bumpenvmat_location[MAX_TEXTURES];
108 GLint luminancescale_location[MAX_TEXTURES];
109 GLint luminanceoffset_location[MAX_TEXTURES];
110 GLint ycorrection_location;
111 GLenum vertex_color_clamp;
112 IWineD3DVertexShader *vshader;
113 IWineD3DPixelShader *pshader;
114 struct vs_compile_args vs_args;
115 struct ps_compile_args ps_args;
116 UINT constant_version;
117 const struct ps_np2fixup_info *np2Fixup_info;
121 IWineD3DVertexShader *vshader;
122 IWineD3DPixelShader *pshader;
123 struct ps_compile_args ps_args;
124 struct vs_compile_args vs_args;
125 } glsl_program_key_t;
127 struct shader_glsl_ctx_priv {
128 const struct vs_compile_args *cur_vs_args;
129 const struct ps_compile_args *cur_ps_args;
130 struct ps_np2fixup_info *cur_np2fixup_info;
133 struct glsl_ps_compiled_shader
135 struct ps_compile_args args;
136 struct ps_np2fixup_info np2fixup;
140 struct glsl_pshader_private
142 struct glsl_ps_compiled_shader *gl_shaders;
143 UINT num_gl_shaders, shader_array_size;
146 struct glsl_vs_compiled_shader
148 struct vs_compile_args args;
152 struct glsl_vshader_private
154 struct glsl_vs_compiled_shader *gl_shaders;
155 UINT num_gl_shaders, shader_array_size;
158 static const char *debug_gl_shader_type(GLenum type)
162 #define WINED3D_TO_STR(u) case u: return #u
163 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
164 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
165 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
166 #undef WINED3D_TO_STR
168 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
172 /* Extract a line from the info log.
173 * Note that this modifies the source string. */
174 static char *get_info_log_line(char **ptr)
179 if (!(q = strstr(p, "\n")))
181 if (!*p) return NULL;
191 /** Prints the GLSL info log which will contain error messages if they exist */
192 /* GL locking is done by the caller */
193 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
195 int infologLength = 0;
200 static const char * const spam[] =
202 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
203 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx, with \n */
204 "Fragment shader was successfully compiled to run on hardware.", /* fglrx, no \n */
205 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \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. \n", /* fglrx, with \n */
210 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
211 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
212 "Fragment shader(s) linked, no vertex shader(s) defined. \n", /* fglrx, with \n */
213 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
216 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
218 GL_EXTCALL(glGetObjectParameterivARB(obj,
219 GL_OBJECT_INFO_LOG_LENGTH_ARB,
222 /* A size of 1 is just a null-terminated string, so the log should be bigger than
223 * that if there are errors. */
224 if (infologLength > 1)
228 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
229 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
231 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
232 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
235 for (i = 0; i < sizeof(spam) / sizeof(*spam); ++i)
237 if (!strcmp(infoLog, spam[i]))
247 TRACE("Spam received from GLSL shader #%u:\n", obj);
248 while ((line = get_info_log_line(&ptr))) TRACE(" %s\n", line);
252 FIXME("Error received from GLSL shader #%u:\n", obj);
253 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
255 HeapFree(GetProcessHeap(), 0, infoLog);
259 /* GL locking is done by the caller. */
260 static void shader_glsl_compile(const struct wined3d_gl_info *gl_info, GLhandleARB shader, const char *src)
262 TRACE("Compiling shader object %u.\n", shader);
263 GL_EXTCALL(glShaderSourceARB(shader, 1, &src, NULL));
264 checkGLcall("glShaderSourceARB");
265 GL_EXTCALL(glCompileShaderARB(shader));
266 checkGLcall("glCompileShaderARB");
267 print_glsl_info_log(gl_info, shader);
270 /* GL locking is done by the caller. */
271 static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
273 GLint i, object_count, source_size = -1;
274 GLhandleARB *objects;
277 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
278 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
281 ERR("Failed to allocate object array memory.\n");
285 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
286 for (i = 0; i < object_count; ++i)
291 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
293 if (source_size < tmp)
295 HeapFree(GetProcessHeap(), 0, source);
297 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
300 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
301 HeapFree(GetProcessHeap(), 0, objects);
307 FIXME("Object %u:\n", objects[i]);
308 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_SUBTYPE_ARB, &tmp));
309 FIXME(" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp));
310 GL_EXTCALL(glGetObjectParameterivARB(objects[i], GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
311 FIXME(" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp);
315 GL_EXTCALL(glGetShaderSourceARB(objects[i], source_size, NULL, source));
316 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
320 HeapFree(GetProcessHeap(), 0, source);
321 HeapFree(GetProcessHeap(), 0, objects);
324 /* GL locking is done by the caller. */
325 static void shader_glsl_validate_link(const struct wined3d_gl_info *gl_info, GLhandleARB program)
329 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
331 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
332 if (tmp == GL_PROGRAM_OBJECT_ARB)
334 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
337 FIXME("Program %u link status invalid.\n", program);
338 shader_glsl_dump_program_source(gl_info, program);
342 print_glsl_info_log(gl_info, program);
346 * Loads (pixel shader) samplers
348 /* GL locking is done by the caller */
349 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
350 DWORD *tex_unit_map, GLhandleARB programId)
354 char sampler_name[20];
356 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
357 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
358 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
359 if (name_loc != -1) {
360 DWORD mapped_unit = tex_unit_map[i];
361 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
363 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
364 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
365 checkGLcall("glUniform1iARB");
367 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
373 /* GL locking is done by the caller */
374 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
375 DWORD *tex_unit_map, GLhandleARB programId)
378 char sampler_name[20];
381 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
382 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
383 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
384 if (name_loc != -1) {
385 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
386 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
388 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
389 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
390 checkGLcall("glUniform1iARB");
392 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
398 /* GL locking is done by the caller */
399 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
400 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
403 unsigned int heap_idx = 1;
406 if (heap->entries[heap_idx].version <= version) return;
408 idx = heap->entries[heap_idx].idx;
409 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
410 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
412 while (stack_idx >= 0)
414 /* Note that we fall through to the next case statement. */
415 switch(stack[stack_idx])
417 case HEAP_NODE_TRAVERSE_LEFT:
419 unsigned int left_idx = heap_idx << 1;
420 if (left_idx < heap->size && heap->entries[left_idx].version > version)
423 idx = heap->entries[heap_idx].idx;
424 if (constant_locations[idx] != -1)
425 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
427 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
428 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
433 case HEAP_NODE_TRAVERSE_RIGHT:
435 unsigned int right_idx = (heap_idx << 1) + 1;
436 if (right_idx < heap->size && heap->entries[right_idx].version > version)
438 heap_idx = right_idx;
439 idx = heap->entries[heap_idx].idx;
440 if (constant_locations[idx] != -1)
441 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
443 stack[stack_idx++] = HEAP_NODE_POP;
444 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
457 checkGLcall("walk_constant_heap()");
460 /* GL locking is done by the caller */
461 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
463 GLfloat clamped_constant[4];
465 if (location == -1) return;
467 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
468 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
469 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
470 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
472 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
475 /* GL locking is done by the caller */
476 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
477 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
480 unsigned int heap_idx = 1;
483 if (heap->entries[heap_idx].version <= version) return;
485 idx = heap->entries[heap_idx].idx;
486 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
487 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
489 while (stack_idx >= 0)
491 /* Note that we fall through to the next case statement. */
492 switch(stack[stack_idx])
494 case HEAP_NODE_TRAVERSE_LEFT:
496 unsigned int left_idx = heap_idx << 1;
497 if (left_idx < heap->size && heap->entries[left_idx].version > version)
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_TRAVERSE_RIGHT;
504 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
509 case HEAP_NODE_TRAVERSE_RIGHT:
511 unsigned int right_idx = (heap_idx << 1) + 1;
512 if (right_idx < heap->size && heap->entries[right_idx].version > version)
514 heap_idx = right_idx;
515 idx = heap->entries[heap_idx].idx;
516 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
518 stack[stack_idx++] = HEAP_NODE_POP;
519 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
532 checkGLcall("walk_constant_heap_clamped()");
535 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
536 /* GL locking is done by the caller */
537 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
538 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
539 unsigned char *stack, UINT version)
541 const local_constant *lconst;
543 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
544 if (This->baseShader.reg_maps.shader_version.major == 1
545 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
546 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
548 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
550 if (!This->baseShader.load_local_constsF)
552 TRACE("No need to load local float constants for this shader\n");
556 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
557 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
559 GLint location = constant_locations[lconst->idx];
560 /* We found this uniform name in the program - go ahead and send the data */
561 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
563 checkGLcall("glUniform4fvARB()");
566 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
567 /* GL locking is done by the caller */
568 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
569 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
574 for (i = 0; constants_set; constants_set >>= 1, ++i)
576 if (!(constants_set & 1)) continue;
578 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
579 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
581 /* We found this uniform name in the program - go ahead and send the data */
582 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
583 checkGLcall("glUniform4ivARB");
586 /* Load immediate constants */
587 ptr = list_head(&This->baseShader.constantsI);
589 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
590 unsigned int idx = lconst->idx;
591 const GLint *values = (const GLint *)lconst->value;
593 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
594 values[0], values[1], values[2], values[3]);
596 /* We found this uniform name in the program - go ahead and send the data */
597 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
598 checkGLcall("glUniform4ivARB");
599 ptr = list_next(&This->baseShader.constantsI, ptr);
603 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
604 /* GL locking is done by the caller */
605 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
606 GLhandleARB programId, const BOOL *constants, WORD constants_set)
614 switch (This->baseShader.reg_maps.shader_version.type)
616 case WINED3D_SHADER_TYPE_VERTEX:
620 case WINED3D_SHADER_TYPE_GEOMETRY:
624 case WINED3D_SHADER_TYPE_PIXEL:
629 FIXME("Unknown shader type %#x.\n",
630 This->baseShader.reg_maps.shader_version.type);
635 /* TODO: Benchmark and see if it would be beneficial to store the
636 * locations of the constants to avoid looking up each time */
637 for (i = 0; constants_set; constants_set >>= 1, ++i)
639 if (!(constants_set & 1)) continue;
641 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
643 /* TODO: Benchmark and see if it would be beneficial to store the
644 * locations of the constants to avoid looking up each time */
645 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
646 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
649 /* We found this uniform name in the program - go ahead and send the data */
650 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
651 checkGLcall("glUniform1ivARB");
655 /* Load immediate constants */
656 ptr = list_head(&This->baseShader.constantsB);
658 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
659 unsigned int idx = lconst->idx;
660 const GLint *values = (const GLint *)lconst->value;
662 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
664 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
665 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
667 /* We found this uniform name in the program - go ahead and send the data */
668 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
669 checkGLcall("glUniform1ivARB");
671 ptr = list_next(&This->baseShader.constantsB, ptr);
675 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
677 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
681 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
683 /* GL locking is done by the caller (state handler) */
684 static void shader_glsl_load_np2fixup_constants(
685 IWineD3DDevice* device,
687 char useVertexShader) {
689 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
690 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
693 /* No GLSL program set - nothing to do. */
697 if (!usePixelShader) {
698 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
702 if (prog->ps_args.np2_fixup && -1 != prog->np2Fixup_location) {
703 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
704 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
706 UINT fixup = prog->ps_args.np2_fixup;
707 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
709 for (i = 0; fixup; fixup >>= 1, ++i) {
710 const unsigned char idx = prog->np2Fixup_info->idx[i];
711 const IWineD3DBaseTextureImpl *tex = stateBlock->state.textures[i];
712 GLfloat *tex_dim = &np2fixup_constants[(idx >> 1) * 4];
716 ERR("Nonexistent texture is flagged for NP2 texcoord fixup.\n");
721 tex_dim[2] = tex->baseTexture.pow2Matrix[0]; tex_dim[3] = tex->baseTexture.pow2Matrix[5];
723 tex_dim[0] = tex->baseTexture.pow2Matrix[0]; tex_dim[1] = tex->baseTexture.pow2Matrix[5];
727 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
732 * Loads the app-supplied constants into the currently set GLSL program.
734 /* GL locking is done by the caller (state handler) */
735 static void shader_glsl_load_constants(const struct wined3d_context *context,
736 char usePixelShader, char useVertexShader)
738 const struct wined3d_gl_info *gl_info = context->gl_info;
739 IWineD3DDeviceImpl *device = context->swapchain->device;
740 IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
741 struct shader_glsl_priv *priv = device->shader_priv;
743 GLhandleARB programId;
744 struct glsl_shader_prog_link *prog = priv->glsl_program;
745 UINT constant_version;
749 /* No GLSL program set - nothing to do. */
752 programId = prog->programId;
753 constant_version = prog->constant_version;
757 IWineD3DBaseShaderImpl *vshader = (IWineD3DBaseShaderImpl *)stateBlock->state.vertex_shader;
759 /* Load DirectX 9 float constants/uniforms for vertex shader */
760 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->state.vs_consts_f,
761 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
763 /* Load DirectX 9 integer constants/uniforms for vertex shader */
764 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->state.vs_consts_i,
765 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
767 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
768 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->state.vs_consts_b,
769 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
771 /* Upload the position fixup params */
772 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &device->posFixup[0]));
773 checkGLcall("glUniform4fvARB");
778 IWineD3DBaseShaderImpl *pshader = (IWineD3DBaseShaderImpl *)stateBlock->state.pixel_shader;
780 /* Load DirectX 9 float constants/uniforms for pixel shader */
781 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->state.ps_consts_f,
782 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
784 /* Load DirectX 9 integer constants/uniforms for pixel shader */
785 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->state.ps_consts_i,
786 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
788 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
789 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->state.ps_consts_b,
790 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
792 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
793 * It can't be 0 for a valid texbem instruction.
795 for(i = 0; i < MAX_TEXTURES; i++) {
798 if(prog->bumpenvmat_location[i] == -1) continue;
800 data = (const float *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVMAT00];
801 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
802 checkGLcall("glUniformMatrix2fvARB");
804 /* texbeml needs the luminance scale and offset too. If texbeml
805 * is used, needsbumpmat is set too, so we can check that in the
806 * needsbumpmat check. */
807 if (prog->luminancescale_location[i] != -1)
809 const GLfloat *scale = (const GLfloat *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVLSCALE];
810 const GLfloat *offset = (const GLfloat *)&stateBlock->state.texture_states[i][WINED3DTSS_BUMPENVLOFFSET];
812 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
813 checkGLcall("glUniform1fvARB");
814 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
815 checkGLcall("glUniform1fvARB");
819 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
820 float correction_params[4];
822 if (context->render_offscreen)
824 correction_params[0] = 0.0f;
825 correction_params[1] = 1.0f;
827 /* position is window relative, not viewport relative */
828 correction_params[0] = context->current_rt->currentDesc.Height;
829 correction_params[1] = -1.0f;
831 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
835 if (priv->next_constant_version == UINT_MAX)
837 TRACE("Max constant version reached, resetting to 0.\n");
838 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
839 priv->next_constant_version = 1;
843 prog->constant_version = priv->next_constant_version++;
847 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
848 unsigned int heap_idx, DWORD new_version)
850 struct constant_entry *entries = heap->entries;
851 unsigned int *positions = heap->positions;
852 unsigned int parent_idx;
856 parent_idx = heap_idx >> 1;
858 if (new_version <= entries[parent_idx].version) break;
860 entries[heap_idx] = entries[parent_idx];
861 positions[entries[parent_idx].idx] = heap_idx;
862 heap_idx = parent_idx;
865 entries[heap_idx].version = new_version;
866 entries[heap_idx].idx = idx;
867 positions[idx] = heap_idx;
870 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
872 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
873 struct shader_glsl_priv *priv = This->shader_priv;
874 struct constant_heap *heap = &priv->vconst_heap;
877 for (i = start; i < count + start; ++i)
879 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
880 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
882 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
886 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
888 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
889 struct shader_glsl_priv *priv = This->shader_priv;
890 struct constant_heap *heap = &priv->pconst_heap;
893 for (i = start; i < count + start; ++i)
895 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
896 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
898 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
902 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
904 unsigned int ret = gl_info->limits.glsl_varyings / 4;
905 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
906 if(shader_major > 3) return ret;
908 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
909 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
913 /** Generate the variable & register declarations for the GLSL output target */
914 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
915 struct wined3d_shader_buffer *buffer, IWineD3DBaseShader *iface,
916 const shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
918 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
919 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
920 const struct wined3d_state *state = &device->stateBlock->state;
921 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
922 const struct wined3d_gl_info *gl_info = context->gl_info;
923 unsigned int i, extra_constants_needed = 0;
924 const local_constant *lconst;
927 /* There are some minor differences between pixel and vertex shaders */
928 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
929 char prefix = pshader ? 'P' : 'V';
931 /* Prototype the subroutines */
932 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
934 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
937 /* Declare the constants (aka uniforms) */
938 if (This->baseShader.limits.constant_float > 0) {
939 unsigned max_constantsF;
940 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
941 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
942 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
943 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
944 * a dx9 card, as long as it doesn't also use all the other constants.
946 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
947 * declare only the amount that we're assured to have.
949 * Thus we run into problems in these two cases:
950 * 1) The shader really uses more uniforms than supported
951 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
955 /* No indirect addressing here. */
956 max_constantsF = gl_info->limits.glsl_ps_float_constants;
960 if(This->baseShader.reg_maps.usesrelconstF) {
961 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
962 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
963 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
964 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
966 * Writing gl_ClipVertex requires one uniform for each clipplane as well.
968 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
969 if(ctx_priv->cur_vs_args->clip_enabled)
971 max_constantsF -= gl_info->limits.clipplanes;
973 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
974 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
975 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
976 * for now take this into account when calculating the number of available constants
978 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
979 /* Set by driver quirks in directx.c */
980 max_constantsF -= gl_info->reserved_glsl_constants;
984 max_constantsF = gl_info->limits.glsl_vs_float_constants;
987 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
988 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
991 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
992 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
994 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
995 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
997 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
998 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
1002 shader_addline(buffer, "uniform vec4 posFixup;\n");
1003 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
1007 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1009 if (!(map & 1)) continue;
1011 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1013 if (reg_maps->luminanceparams & (1 << i))
1015 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1016 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1017 extra_constants_needed++;
1020 extra_constants_needed++;
1023 if (ps_args->srgb_correction)
1025 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1026 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1027 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1030 if (reg_maps->vpos || reg_maps->usesdsy)
1032 if (This->baseShader.limits.constant_float + extra_constants_needed
1033 + 1 < gl_info->limits.glsl_ps_float_constants)
1035 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1036 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
1037 extra_constants_needed++;
1039 /* This happens because we do not have proper tracking of the constant registers that are
1040 * actually used, only the max limit of the shader version
1042 FIXME("Cannot find a free uniform for vpos correction params\n");
1043 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1044 context->render_offscreen ? 0.0f : device->render_targets[0]->currentDesc.Height,
1045 context->render_offscreen ? 1.0f : -1.0f);
1047 shader_addline(buffer, "vec4 vpos;\n");
1051 /* Declare texture samplers */
1052 for (i = 0; i < This->baseShader.limits.sampler; i++) {
1053 if (reg_maps->sampler_type[i])
1055 IWineD3DBaseTextureImpl *texture;
1057 switch (reg_maps->sampler_type[i])
1060 if (pshader && ps_args->shadow & (1 << i))
1061 shader_addline(buffer, "uniform sampler1DShadow %csampler%u;\n", prefix, i);
1063 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1066 texture = state->textures[i];
1067 if (pshader && ps_args->shadow & (1 << i))
1069 if (texture && texture->baseTexture.target == GL_TEXTURE_RECTANGLE_ARB)
1070 shader_addline(buffer, "uniform sampler2DRectShadow %csampler%u;\n", prefix, i);
1072 shader_addline(buffer, "uniform sampler2DShadow %csampler%u;\n", prefix, i);
1076 if (texture && texture->baseTexture.target == GL_TEXTURE_RECTANGLE_ARB)
1077 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1079 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1082 case WINED3DSTT_CUBE:
1083 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported Cube shadow sampler.\n");
1084 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1086 case WINED3DSTT_VOLUME:
1087 if (pshader && ps_args->shadow & (1 << i)) FIXME("Unsupported 3D shadow sampler.\n");
1088 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1091 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1092 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1098 /* Declare uniforms for NP2 texcoord fixup:
1099 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1100 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1101 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1102 if (pshader && ps_args->np2_fixup) {
1104 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1107 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1108 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1109 * samplerNP2Fixup stores texture dimensions and is updated through
1110 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1112 for (i = 0; i < This->baseShader.limits.sampler; ++i) {
1113 if (reg_maps->sampler_type[i]) {
1114 if (!(ps_args->np2_fixup & (1 << i))) continue;
1116 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1117 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1121 fixup->idx[i] = cur++;
1125 fixup->num_consts = (cur + 1) >> 1;
1126 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1129 /* Declare address variables */
1130 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1132 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1135 /* Declare texture coordinate temporaries and initialize them */
1136 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1138 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1141 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1142 * helper function shader that is linked in at link time
1144 if (pshader && reg_maps->shader_version.major >= 3)
1148 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1150 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1151 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1152 * pixel shader that reads the fixed function color into the packed input registers.
1154 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1158 /* Declare output register temporaries */
1159 if(This->baseShader.limits.packed_output) {
1160 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
1163 /* Declare temporary variables */
1164 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1166 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1169 /* Declare attributes */
1170 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1172 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1174 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1178 /* Declare loop registers aLx */
1179 for (i = 0; i < reg_maps->loop_depth; i++) {
1180 shader_addline(buffer, "int aL%u;\n", i);
1181 shader_addline(buffer, "int tmpInt%u;\n", i);
1184 /* Temporary variables for matrix operations */
1185 shader_addline(buffer, "vec4 tmp0;\n");
1186 shader_addline(buffer, "vec4 tmp1;\n");
1188 /* Local constants use a different name so they can be loaded once at shader link time
1189 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1190 * float -> string conversion can cause precision loss.
1192 if(!This->baseShader.load_local_constsF) {
1193 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1194 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1198 /* Start the main program */
1199 shader_addline(buffer, "void main() {\n");
1200 if(pshader && reg_maps->vpos) {
1201 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1202 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1203 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1204 * precision troubles when we just substract 0.5.
1206 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1208 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1210 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1211 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1212 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1213 * correctly on drivers that returns integer values.
1215 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1219 /*****************************************************************************
1220 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1222 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1223 ****************************************************************************/
1226 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1227 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1229 /** Used for opcode modifiers - They multiply the result by the specified amount */
1230 static const char * const shift_glsl_tab[] = {
1232 "2.0 * ", /* 1 (x2) */
1233 "4.0 * ", /* 2 (x4) */
1234 "8.0 * ", /* 3 (x8) */
1235 "16.0 * ", /* 4 (x16) */
1236 "32.0 * ", /* 5 (x32) */
1243 "0.0625 * ", /* 12 (d16) */
1244 "0.125 * ", /* 13 (d8) */
1245 "0.25 * ", /* 14 (d4) */
1246 "0.5 * " /* 15 (d2) */
1249 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1250 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1254 switch (src_modifier)
1256 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1257 case WINED3DSPSM_DW:
1258 case WINED3DSPSM_NONE:
1259 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1261 case WINED3DSPSM_NEG:
1262 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1264 case WINED3DSPSM_NOT:
1265 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1267 case WINED3DSPSM_BIAS:
1268 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1270 case WINED3DSPSM_BIASNEG:
1271 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1273 case WINED3DSPSM_SIGN:
1274 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1276 case WINED3DSPSM_SIGNNEG:
1277 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1279 case WINED3DSPSM_COMP:
1280 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1282 case WINED3DSPSM_X2:
1283 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1285 case WINED3DSPSM_X2NEG:
1286 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1288 case WINED3DSPSM_ABS:
1289 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1291 case WINED3DSPSM_ABSNEG:
1292 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1295 FIXME("Unhandled modifier %u\n", src_modifier);
1296 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1300 /** Writes the GLSL variable name that corresponds to the register that the
1301 * DX opcode parameter is trying to access */
1302 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1303 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1305 /* oPos, oFog and oPts in D3D */
1306 static const char * const hwrastout_reg_names[] = {"OUT[10]", "OUT[11].x", "OUT[11].y"};
1308 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1309 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1310 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1316 case WINED3DSPR_TEMP:
1317 sprintf(register_name, "R%u", reg->idx);
1320 case WINED3DSPR_INPUT:
1321 /* vertex shaders */
1324 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1325 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1326 sprintf(register_name, "attrib%u", reg->idx);
1330 /* pixel shaders >= 3.0 */
1331 if (This->baseShader.reg_maps.shader_version.major >= 3)
1333 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1334 unsigned int in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1338 glsl_src_param_t rel_param;
1340 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1342 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1343 * operation there */
1346 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1348 sprintf(register_name,
1349 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1350 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1351 rel_param.param_str, idx);
1355 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1360 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1362 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1363 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1364 rel_param.param_str);
1368 sprintf(register_name, "IN[%s]", rel_param.param_str);
1374 if (idx == in_count) sprintf(register_name, "gl_Color");
1375 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1376 else sprintf(register_name, "IN[%u]", idx);
1381 if (!reg->idx) strcpy(register_name, "gl_Color");
1382 else strcpy(register_name, "gl_SecondaryColor");
1387 case WINED3DSPR_CONST:
1389 const char prefix = pshader ? 'P' : 'V';
1391 /* Relative addressing */
1394 glsl_src_param_t rel_param;
1395 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1396 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1397 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1401 if (shader_constant_is_local(This, reg->idx))
1402 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1404 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1409 case WINED3DSPR_CONSTINT:
1410 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1411 else sprintf(register_name, "VI[%u]", reg->idx);
1414 case WINED3DSPR_CONSTBOOL:
1415 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1416 else sprintf(register_name, "VB[%u]", reg->idx);
1419 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1420 if (pshader) sprintf(register_name, "T%u", reg->idx);
1421 else sprintf(register_name, "A%u", reg->idx);
1424 case WINED3DSPR_LOOP:
1425 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1428 case WINED3DSPR_SAMPLER:
1429 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1430 else sprintf(register_name, "Vsampler%u", reg->idx);
1433 case WINED3DSPR_COLOROUT:
1434 if (reg->idx >= gl_info->limits.buffers)
1435 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1437 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1440 case WINED3DSPR_RASTOUT:
1441 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1444 case WINED3DSPR_DEPTHOUT:
1445 sprintf(register_name, "gl_FragDepth");
1448 case WINED3DSPR_ATTROUT:
1449 if (!reg->idx) sprintf(register_name, "OUT[8]");
1450 else sprintf(register_name, "OUT[9]");
1453 case WINED3DSPR_TEXCRDOUT:
1454 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1455 sprintf(register_name, "OUT[%u]", reg->idx);
1458 case WINED3DSPR_MISCTYPE:
1462 sprintf(register_name, "vpos");
1464 else if (reg->idx == 1)
1466 /* Note that gl_FrontFacing is a bool, while vFace is
1467 * a float for which the sign determines front/back */
1468 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1472 FIXME("Unhandled misctype register %d\n", reg->idx);
1473 sprintf(register_name, "unrecognized_register");
1477 case WINED3DSPR_IMMCONST:
1478 switch (reg->immconst_type)
1480 case WINED3D_IMMCONST_FLOAT:
1481 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1484 case WINED3D_IMMCONST_FLOAT4:
1485 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1486 *(const float *)®->immconst_data[0], *(const float *)®->immconst_data[1],
1487 *(const float *)®->immconst_data[2], *(const float *)®->immconst_data[3]);
1491 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1492 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1497 FIXME("Unhandled register name Type(%d)\n", reg->type);
1498 sprintf(register_name, "unrecognized_register");
1503 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1506 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1507 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1508 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1509 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1513 /* Get the GLSL write mask for the destination register */
1514 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1516 DWORD mask = param->write_mask;
1518 if (shader_is_scalar(¶m->reg))
1520 mask = WINED3DSP_WRITEMASK_0;
1525 shader_glsl_write_mask_to_str(mask, write_mask);
1531 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1532 unsigned int size = 0;
1534 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1535 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1536 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1537 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1542 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1544 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1545 * but addressed as "rgba". To fix this we need to swap the register's x
1546 * and z components. */
1547 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1550 /* swizzle bits fields: wwzzyyxx */
1551 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1552 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1553 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1554 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1558 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1559 BOOL fixup, DWORD mask, char *swizzle_str)
1561 if (shader_is_scalar(¶m->reg))
1562 *swizzle_str = '\0';
1564 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1567 /* From a given parameter token, generate the corresponding GLSL string.
1568 * Also, return the actual register name and swizzle in case the
1569 * caller needs this information as well. */
1570 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1571 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1573 BOOL is_color = FALSE;
1574 char swizzle_str[6];
1576 glsl_src->reg_name[0] = '\0';
1577 glsl_src->param_str[0] = '\0';
1578 swizzle_str[0] = '\0';
1580 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1581 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1582 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1585 /* From a given parameter token, generate the corresponding GLSL string.
1586 * Also, return the actual register name and swizzle in case the
1587 * caller needs this information as well. */
1588 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1589 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1591 BOOL is_color = FALSE;
1593 glsl_dst->mask_str[0] = '\0';
1594 glsl_dst->reg_name[0] = '\0';
1596 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1597 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1600 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1601 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1602 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1604 glsl_dst_param_t glsl_dst;
1607 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1608 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1613 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1614 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1616 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1619 /** Process GLSL instruction modifiers */
1620 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1622 glsl_dst_param_t dst_param;
1625 if (!ins->dst_count) return;
1627 modifiers = ins->dst[0].modifiers;
1628 if (!modifiers) return;
1630 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1632 if (modifiers & WINED3DSPDM_SATURATE)
1634 /* _SAT means to clamp the value of the register to between 0 and 1 */
1635 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1636 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1639 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1641 FIXME("_centroid modifier not handled\n");
1644 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1646 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1650 static inline const char *shader_get_comp_op(DWORD op)
1653 case COMPARISON_GT: return ">";
1654 case COMPARISON_EQ: return "==";
1655 case COMPARISON_GE: return ">=";
1656 case COMPARISON_LT: return "<";
1657 case COMPARISON_NE: return "!=";
1658 case COMPARISON_LE: return "<=";
1660 FIXME("Unrecognized comparison value: %u\n", op);
1665 static void shader_glsl_get_sample_function(const struct wined3d_shader_context *ctx,
1666 DWORD sampler_idx, DWORD flags, glsl_sample_function_t *sample_function)
1668 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ctx->reg_maps->sampler_type[sampler_idx];
1669 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1670 BOOL shadow = shader_is_pshader_version(ctx->reg_maps->shader_version.type)
1671 && (((const struct shader_glsl_ctx_priv *)ctx->backend_data)->cur_ps_args->shadow & (1 << sampler_idx));
1672 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1673 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1674 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1675 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1677 /* Note that there's no such thing as a projected cube texture. */
1678 switch(sampler_type) {
1684 sample_function->name = projected ? "shadow1DProjLod" : "shadow1DLod";
1688 if (gl_info->supported[EXT_GPU_SHADER4])
1689 sample_function->name = projected ? "shadow1DProjGrad" : "shadow1DGrad";
1690 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1691 sample_function->name = projected ? "shadow1DProjGradARB" : "shadow1DGradARB";
1694 FIXME("Unsupported 1D shadow grad function.\n");
1695 sample_function->name = "unsupported1DGrad";
1700 sample_function->name = projected ? "shadow1DProj" : "shadow1D";
1702 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1708 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1712 if (gl_info->supported[EXT_GPU_SHADER4])
1713 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1714 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1715 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1718 FIXME("Unsupported 1D grad function.\n");
1719 sample_function->name = "unsupported1DGrad";
1724 sample_function->name = projected ? "texture1DProj" : "texture1D";
1726 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1737 sample_function->name = projected ? "shadow2DRectProjLod" : "shadow2DRectLod";
1741 if (gl_info->supported[EXT_GPU_SHADER4])
1742 sample_function->name = projected ? "shadow2DRectProjGrad" : "shadow2DRectGrad";
1743 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1744 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1747 FIXME("Unsupported RECT shadow grad function.\n");
1748 sample_function->name = "unsupported2DRectGrad";
1753 sample_function->name = projected ? "shadow2DRectProj" : "shadow2DRect";
1760 sample_function->name = projected ? "shadow2DProjLod" : "shadow2DLod";
1764 if (gl_info->supported[EXT_GPU_SHADER4])
1765 sample_function->name = projected ? "shadow2DProjGrad" : "shadow2DGrad";
1766 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1767 sample_function->name = projected ? "shadow2DProjGradARB" : "shadow2DGradARB";
1770 FIXME("Unsupported 2D shadow grad function.\n");
1771 sample_function->name = "unsupported2DGrad";
1776 sample_function->name = projected ? "shadow2DProj" : "shadow2D";
1779 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1787 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1791 if (gl_info->supported[EXT_GPU_SHADER4])
1792 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1793 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1794 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1797 FIXME("Unsupported RECT grad function.\n");
1798 sample_function->name = "unsupported2DRectGrad";
1803 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1810 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1814 if (gl_info->supported[EXT_GPU_SHADER4])
1815 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1816 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1817 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1820 FIXME("Unsupported 2D grad function.\n");
1821 sample_function->name = "unsupported2DGrad";
1826 sample_function->name = projected ? "texture2DProj" : "texture2D";
1829 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1833 case WINED3DSTT_CUBE:
1836 FIXME("Unsupported Cube shadow function.\n");
1837 sample_function->name = "unsupportedCubeShadow";
1838 sample_function->coord_mask = 0;
1844 sample_function->name = "textureCubeLod";
1848 if (gl_info->supported[EXT_GPU_SHADER4])
1849 sample_function->name = "textureCubeGrad";
1850 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1851 sample_function->name = "textureCubeGradARB";
1854 FIXME("Unsupported Cube grad function.\n");
1855 sample_function->name = "unsupportedCubeGrad";
1860 sample_function->name = "textureCube";
1862 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1866 case WINED3DSTT_VOLUME:
1869 FIXME("Unsupported 3D shadow function.\n");
1870 sample_function->name = "unsupported3DShadow";
1871 sample_function->coord_mask = 0;
1877 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1881 if (gl_info->supported[EXT_GPU_SHADER4])
1882 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1883 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1884 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1887 FIXME("Unsupported 3D grad function.\n");
1888 sample_function->name = "unsupported3DGrad";
1893 sample_function->name = projected ? "texture3DProj" : "texture3D";
1895 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1900 sample_function->name = "";
1901 sample_function->coord_mask = 0;
1902 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1907 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1908 BOOL sign_fixup, enum fixup_channel_source channel_source)
1910 switch(channel_source)
1912 case CHANNEL_SOURCE_ZERO:
1913 strcat(arguments, "0.0");
1916 case CHANNEL_SOURCE_ONE:
1917 strcat(arguments, "1.0");
1920 case CHANNEL_SOURCE_X:
1921 strcat(arguments, reg_name);
1922 strcat(arguments, ".x");
1925 case CHANNEL_SOURCE_Y:
1926 strcat(arguments, reg_name);
1927 strcat(arguments, ".y");
1930 case CHANNEL_SOURCE_Z:
1931 strcat(arguments, reg_name);
1932 strcat(arguments, ".z");
1935 case CHANNEL_SOURCE_W:
1936 strcat(arguments, reg_name);
1937 strcat(arguments, ".w");
1941 FIXME("Unhandled channel source %#x\n", channel_source);
1942 strcat(arguments, "undefined");
1946 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1949 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1951 struct wined3d_shader_dst_param dst;
1952 unsigned int mask_size, remaining;
1953 glsl_dst_param_t dst_param;
1954 char arguments[256];
1958 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1959 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1960 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1961 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1962 mask &= ins->dst[0].write_mask;
1964 if (!mask) return; /* Nothing to do */
1966 if (is_complex_fixup(fixup))
1968 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
1969 FIXME("Complex fixup (%#x) not supported\n",complex_fixup);
1973 mask_size = shader_glsl_get_write_mask_size(mask);
1976 dst.write_mask = mask;
1977 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1979 arguments[0] = '\0';
1980 remaining = mask_size;
1981 if (mask & WINED3DSP_WRITEMASK_0)
1983 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1984 if (--remaining) strcat(arguments, ", ");
1986 if (mask & WINED3DSP_WRITEMASK_1)
1988 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1989 if (--remaining) strcat(arguments, ", ");
1991 if (mask & WINED3DSP_WRITEMASK_2)
1993 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1994 if (--remaining) strcat(arguments, ", ");
1996 if (mask & WINED3DSP_WRITEMASK_3)
1998 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1999 if (--remaining) strcat(arguments, ", ");
2004 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
2005 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
2009 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
2013 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2014 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
2015 const char *dx, const char *dy,
2016 const char *bias, const char *coord_reg_fmt, ...)
2018 const char *sampler_base;
2019 char dst_swizzle[6];
2020 struct color_fixup_desc fixup;
2021 BOOL np2_fixup = FALSE;
2024 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2026 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2028 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2029 fixup = priv->cur_ps_args->color_fixup[sampler];
2030 sampler_base = "Psampler";
2032 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2034 FIXME("Biased sampling from NP2 textures is unsupported\n");
2040 sampler_base = "Vsampler";
2041 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2044 shader_glsl_append_dst(ins->ctx->buffer, ins);
2046 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2048 va_start(args, coord_reg_fmt);
2049 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2053 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2056 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2057 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2059 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2060 (idx % 2) ? "zw" : "xy", dst_swizzle);
2061 } else if(dx && dy) {
2062 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2064 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2068 if(!is_identity_fixup(fixup)) {
2069 shader_glsl_color_correction(ins, fixup);
2073 /*****************************************************************************
2074 * Begin processing individual instruction opcodes
2075 ****************************************************************************/
2077 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
2078 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
2080 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2081 glsl_src_param_t src0_param;
2082 glsl_src_param_t src1_param;
2086 /* Determine the GLSL operator to use based on the opcode */
2087 switch (ins->handler_idx)
2089 case WINED3DSIH_MUL: op = '*'; break;
2090 case WINED3DSIH_ADD: op = '+'; break;
2091 case WINED3DSIH_SUB: op = '-'; break;
2094 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2098 write_mask = shader_glsl_append_dst(buffer, ins);
2099 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2100 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2101 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2104 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2105 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2107 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2108 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2109 glsl_src_param_t src0_param;
2112 write_mask = shader_glsl_append_dst(buffer, ins);
2113 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2115 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2116 * shader versions WINED3DSIO_MOVA is used for this. */
2117 if (ins->ctx->reg_maps->shader_version.major == 1
2118 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2119 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2121 /* This is a simple floor() */
2122 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2123 if (mask_size > 1) {
2124 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2126 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2129 else if(ins->handler_idx == WINED3DSIH_MOVA)
2131 /* We need to *round* to the nearest int here. */
2132 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2134 if (gl_info->supported[EXT_GPU_SHADER4])
2137 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2139 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2144 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2145 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2147 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2148 src0_param.param_str, src0_param.param_str);
2153 shader_addline(buffer, "%s);\n", src0_param.param_str);
2157 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2158 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2160 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2161 glsl_src_param_t src0_param;
2162 glsl_src_param_t src1_param;
2163 DWORD dst_write_mask, src_write_mask;
2164 unsigned int dst_size = 0;
2166 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2167 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2169 /* dp3 works on vec3, dp4 on vec4 */
2170 if (ins->handler_idx == WINED3DSIH_DP4)
2172 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2174 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2177 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2178 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2181 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2183 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2187 /* Note that this instruction has some restrictions. The destination write mask
2188 * can't contain the w component, and the source swizzles have to be .xyzw */
2189 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2191 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2192 glsl_src_param_t src0_param;
2193 glsl_src_param_t src1_param;
2196 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2197 shader_glsl_append_dst(ins->ctx->buffer, ins);
2198 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2199 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2200 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2203 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2204 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2205 * GLSL uses the value as-is. */
2206 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2208 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2209 glsl_src_param_t src0_param;
2210 glsl_src_param_t src1_param;
2211 DWORD dst_write_mask;
2212 unsigned int dst_size;
2214 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2215 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2217 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2218 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2222 shader_addline(buffer, "vec%u(pow(abs(%s), %s)));\n",
2223 dst_size, src0_param.param_str, src1_param.param_str);
2227 shader_addline(buffer, "pow(abs(%s), %s));\n",
2228 src0_param.param_str, src1_param.param_str);
2232 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2233 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2234 * GLSL uses the value as-is. */
2235 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2237 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2238 glsl_src_param_t src0_param;
2239 DWORD dst_write_mask;
2240 unsigned int dst_size;
2242 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2243 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2245 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2249 shader_addline(buffer, "vec%u(log2(abs(%s))));\n",
2250 dst_size, src0_param.param_str);
2254 shader_addline(buffer, "log2(abs(%s)));\n",
2255 src0_param.param_str);
2259 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2260 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2262 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2263 glsl_src_param_t src_param;
2264 const char *instruction;
2268 /* Determine the GLSL function to use based on the opcode */
2269 /* TODO: Possibly make this a table for faster lookups */
2270 switch (ins->handler_idx)
2272 case WINED3DSIH_MIN: instruction = "min"; break;
2273 case WINED3DSIH_MAX: instruction = "max"; break;
2274 case WINED3DSIH_ABS: instruction = "abs"; break;
2275 case WINED3DSIH_FRC: instruction = "fract"; break;
2276 case WINED3DSIH_EXP: instruction = "exp2"; break;
2277 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2278 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2279 default: instruction = "";
2280 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2284 write_mask = shader_glsl_append_dst(buffer, ins);
2286 shader_addline(buffer, "%s(", instruction);
2290 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2291 shader_addline(buffer, "%s", src_param.param_str);
2292 for (i = 1; i < ins->src_count; ++i)
2294 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2295 shader_addline(buffer, ", %s", src_param.param_str);
2299 shader_addline(buffer, "));\n");
2302 static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2304 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2305 glsl_src_param_t src_param;
2306 unsigned int mask_size;
2310 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2311 mask_size = shader_glsl_get_write_mask_size(write_mask);
2312 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2314 shader_addline(buffer, "tmp0.x = length(%s);\n", src_param.param_str);
2315 shader_glsl_append_dst(buffer, ins);
2318 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s / tmp0.x));\n",
2319 mask_size, src_param.param_str);
2323 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s / tmp0.x));\n",
2324 src_param.param_str);
2328 /** Process the WINED3DSIO_EXPP instruction in GLSL:
2329 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2330 * dst.x = 2^(floor(src))
2331 * dst.y = src - floor(src)
2332 * dst.z = 2^src (partial precision is allowed, but optional)
2334 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2335 * dst = 2^src; (partial precision is allowed, but optional)
2337 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2339 glsl_src_param_t src_param;
2341 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2343 if (ins->ctx->reg_maps->shader_version.major < 2)
2347 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2348 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2349 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2350 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2352 shader_glsl_append_dst(ins->ctx->buffer, ins);
2353 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2354 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2357 unsigned int mask_size;
2359 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2360 mask_size = shader_glsl_get_write_mask_size(write_mask);
2362 if (mask_size > 1) {
2363 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2365 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2370 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2371 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2373 glsl_src_param_t src_param;
2375 unsigned int mask_size;
2377 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2378 mask_size = shader_glsl_get_write_mask_size(write_mask);
2379 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2383 shader_addline(ins->ctx->buffer, "vec%u(1.0 / %s));\n",
2384 mask_size, src_param.param_str);
2388 shader_addline(ins->ctx->buffer, "1.0 / %s);\n",
2389 src_param.param_str);
2393 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2395 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2396 glsl_src_param_t src_param;
2398 unsigned int mask_size;
2400 write_mask = shader_glsl_append_dst(buffer, ins);
2401 mask_size = shader_glsl_get_write_mask_size(write_mask);
2403 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2407 shader_addline(buffer, "vec%u(inversesqrt(abs(%s))));\n",
2408 mask_size, src_param.param_str);
2412 shader_addline(buffer, "inversesqrt(abs(%s)));\n",
2413 src_param.param_str);
2417 /** Process signed comparison opcodes in GLSL. */
2418 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2420 glsl_src_param_t src0_param;
2421 glsl_src_param_t src1_param;
2423 unsigned int mask_size;
2425 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2426 mask_size = shader_glsl_get_write_mask_size(write_mask);
2427 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2428 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2430 if (mask_size > 1) {
2431 const char *compare;
2433 switch(ins->handler_idx)
2435 case WINED3DSIH_SLT: compare = "lessThan"; break;
2436 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2437 default: compare = "";
2438 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2441 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2442 src0_param.param_str, src1_param.param_str);
2444 switch(ins->handler_idx)
2446 case WINED3DSIH_SLT:
2447 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2448 * to return 0.0 but step returns 1.0 because step is not < x
2449 * An alternative is a bvec compare padded with an unused second component.
2450 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2451 * issue. Playing with not() is not possible either because not() does not accept
2454 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2455 src0_param.param_str, src1_param.param_str);
2457 case WINED3DSIH_SGE:
2458 /* Here we can use the step() function and safe a conditional */
2459 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2462 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2468 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2469 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2471 glsl_src_param_t src0_param;
2472 glsl_src_param_t src1_param;
2473 glsl_src_param_t src2_param;
2474 DWORD write_mask, cmp_channel = 0;
2477 BOOL temp_destination = FALSE;
2479 if (shader_is_scalar(&ins->src[0].reg))
2481 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2483 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2484 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2485 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2487 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2488 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2490 DWORD dst_mask = ins->dst[0].write_mask;
2491 struct wined3d_shader_dst_param dst = ins->dst[0];
2493 /* Cycle through all source0 channels */
2494 for (i=0; i<4; i++) {
2496 /* Find the destination channels which use the current source0 channel */
2497 for (j=0; j<4; j++) {
2498 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2500 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2501 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2504 dst.write_mask = dst_mask & write_mask;
2506 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2507 * The first lines may overwrite source parameters of the following lines.
2508 * Deal with that by using a temporary destination register if needed
2510 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2511 && ins->src[0].reg.type == ins->dst[0].reg.type)
2512 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2513 && ins->src[1].reg.type == ins->dst[0].reg.type)
2514 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2515 && ins->src[2].reg.type == ins->dst[0].reg.type))
2517 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2518 if (!write_mask) continue;
2519 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2520 temp_destination = TRUE;
2522 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2523 if (!write_mask) continue;
2526 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2527 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2528 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2530 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2531 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2534 if(temp_destination) {
2535 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2536 shader_glsl_append_dst(ins->ctx->buffer, ins);
2537 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2543 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2544 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2545 * the compare is done per component of src0. */
2546 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2548 struct wined3d_shader_dst_param dst;
2549 glsl_src_param_t src0_param;
2550 glsl_src_param_t src1_param;
2551 glsl_src_param_t src2_param;
2552 DWORD write_mask, cmp_channel = 0;
2555 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2556 ins->ctx->reg_maps->shader_version.minor);
2558 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2560 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2561 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2562 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2563 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2565 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2568 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2570 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2571 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2575 /* Cycle through all source0 channels */
2576 dst_mask = ins->dst[0].write_mask;
2578 for (i=0; i<4; i++) {
2580 /* Find the destination channels which use the current source0 channel */
2581 for (j=0; j<4; j++) {
2582 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2584 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2585 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2589 dst.write_mask = dst_mask & write_mask;
2590 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2591 if (!write_mask) continue;
2593 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2594 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2595 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2597 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2598 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2602 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2603 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2605 glsl_src_param_t src0_param;
2606 glsl_src_param_t src1_param;
2607 glsl_src_param_t src2_param;
2610 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2611 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2612 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2613 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2614 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2615 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2618 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2619 Vertex shaders to GLSL codes */
2620 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2623 int nComponents = 0;
2624 struct wined3d_shader_dst_param tmp_dst = {{0}};
2625 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2626 struct wined3d_shader_instruction tmp_ins;
2628 memset(&tmp_ins, 0, sizeof(tmp_ins));
2630 /* Set constants for the temporary argument */
2631 tmp_ins.ctx = ins->ctx;
2632 tmp_ins.dst_count = 1;
2633 tmp_ins.dst = &tmp_dst;
2634 tmp_ins.src_count = 2;
2635 tmp_ins.src = tmp_src;
2637 switch(ins->handler_idx)
2639 case WINED3DSIH_M4x4:
2641 tmp_ins.handler_idx = WINED3DSIH_DP4;
2643 case WINED3DSIH_M4x3:
2645 tmp_ins.handler_idx = WINED3DSIH_DP4;
2647 case WINED3DSIH_M3x4:
2649 tmp_ins.handler_idx = WINED3DSIH_DP3;
2651 case WINED3DSIH_M3x3:
2653 tmp_ins.handler_idx = WINED3DSIH_DP3;
2655 case WINED3DSIH_M3x2:
2657 tmp_ins.handler_idx = WINED3DSIH_DP3;
2663 tmp_dst = ins->dst[0];
2664 tmp_src[0] = ins->src[0];
2665 tmp_src[1] = ins->src[1];
2666 for (i = 0; i < nComponents; ++i)
2668 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2669 shader_glsl_dot(&tmp_ins);
2670 ++tmp_src[1].reg.idx;
2675 The LRP instruction performs a component-wise linear interpolation
2676 between the second and third operands using the first operand as the
2677 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2678 This is equivalent to mix(src2, src1, src0);
2680 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2682 glsl_src_param_t src0_param;
2683 glsl_src_param_t src1_param;
2684 glsl_src_param_t src2_param;
2687 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2689 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2690 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2691 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2693 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2694 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2697 /** Process the WINED3DSIO_LIT instruction in GLSL:
2698 * dst.x = dst.w = 1.0
2699 * dst.y = (src0.x > 0) ? src0.x
2700 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2701 * where src.w is clamped at +- 128
2703 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2705 glsl_src_param_t src0_param;
2706 glsl_src_param_t src1_param;
2707 glsl_src_param_t src3_param;
2710 shader_glsl_append_dst(ins->ctx->buffer, ins);
2711 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2713 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2714 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2715 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2717 /* The sdk specifies the instruction like this
2719 * if(src.x > 0.0) dst.y = src.x
2721 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2725 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2726 * dst.x = 1.0 ... No further explanation needed
2727 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2728 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2729 * dst.w = 1.0. ... Nothing fancy.
2731 * So we still have one conditional in there. So do this:
2732 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2734 * 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),
2735 * 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.
2736 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2738 shader_addline(ins->ctx->buffer,
2739 "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",
2740 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2743 /** Process the WINED3DSIO_DST instruction in GLSL:
2745 * dst.y = src0.x * src0.y
2749 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2751 glsl_src_param_t src0y_param;
2752 glsl_src_param_t src0z_param;
2753 glsl_src_param_t src1y_param;
2754 glsl_src_param_t src1w_param;
2757 shader_glsl_append_dst(ins->ctx->buffer, ins);
2758 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2760 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2761 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2762 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2763 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2765 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2766 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2769 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2770 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2771 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2773 * dst.x = cos(src0.?)
2774 * dst.y = sin(src0.?)
2778 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2780 glsl_src_param_t src0_param;
2783 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2784 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2786 switch (write_mask) {
2787 case WINED3DSP_WRITEMASK_0:
2788 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2791 case WINED3DSP_WRITEMASK_1:
2792 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2795 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2796 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2800 ERR("Write mask should be .x, .y or .xy\n");
2805 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2806 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2807 * generate invalid code
2809 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2811 glsl_src_param_t src0_param;
2814 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2815 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2817 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2820 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2821 * Start a for() loop where src1.y is the initial value of aL,
2822 * increment aL by src1.z for a total of src1.x iterations.
2823 * Need to use a temporary variable for this operation.
2825 /* FIXME: I don't think nested loops will work correctly this way. */
2826 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2828 glsl_src_param_t src1_param;
2829 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2830 const DWORD *control_values = NULL;
2831 const local_constant *constant;
2833 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2835 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2836 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2837 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2840 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2842 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2843 if (constant->idx == ins->src[1].reg.idx)
2845 control_values = constant->value;
2853 struct wined3d_shader_loop_control loop_control;
2854 loop_control.count = control_values[0];
2855 loop_control.start = control_values[1];
2856 loop_control.step = (int)control_values[2];
2858 if (loop_control.step > 0)
2860 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2861 shader->baseShader.cur_loop_depth, loop_control.start,
2862 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2863 shader->baseShader.cur_loop_depth, loop_control.step);
2865 else if (loop_control.step < 0)
2867 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2868 shader->baseShader.cur_loop_depth, loop_control.start,
2869 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2870 shader->baseShader.cur_loop_depth, loop_control.step);
2874 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2875 shader->baseShader.cur_loop_depth, loop_control.start, shader->baseShader.cur_loop_depth,
2876 shader->baseShader.cur_loop_depth, loop_control.count,
2877 shader->baseShader.cur_loop_depth);
2880 shader_addline(ins->ctx->buffer,
2881 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2882 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2883 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2884 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2887 shader->baseShader.cur_loop_depth++;
2888 shader->baseShader.cur_loop_regno++;
2891 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2893 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2895 shader_addline(ins->ctx->buffer, "}\n");
2897 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2899 shader->baseShader.cur_loop_depth--;
2900 shader->baseShader.cur_loop_regno--;
2903 if (ins->handler_idx == WINED3DSIH_ENDREP)
2905 shader->baseShader.cur_loop_depth--;
2909 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2911 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2912 glsl_src_param_t src0_param;
2913 const DWORD *control_values = NULL;
2914 const local_constant *constant;
2916 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2917 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2919 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
2921 if (constant->idx == ins->src[0].reg.idx)
2923 control_values = constant->value;
2929 if(control_values) {
2930 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2931 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2932 control_values[0], shader->baseShader.cur_loop_depth);
2934 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2935 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2936 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2937 src0_param.param_str, shader->baseShader.cur_loop_depth);
2939 shader->baseShader.cur_loop_depth++;
2942 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2944 glsl_src_param_t src0_param;
2946 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2947 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2950 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2952 glsl_src_param_t src0_param;
2953 glsl_src_param_t src1_param;
2955 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2956 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2958 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2959 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2962 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2964 shader_addline(ins->ctx->buffer, "} else {\n");
2967 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2969 shader_addline(ins->ctx->buffer, "break;\n");
2972 /* FIXME: According to MSDN the compare is done per component. */
2973 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2975 glsl_src_param_t src0_param;
2976 glsl_src_param_t src1_param;
2978 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2979 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2981 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2982 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2985 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2987 shader_addline(ins->ctx->buffer, "}\n");
2988 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
2991 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2993 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2996 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2998 glsl_src_param_t src1_param;
3000 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3001 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
3004 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3006 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3007 * function only suppresses the unhandled instruction warning
3011 /*********************************************
3012 * Pixel Shader Specific Code begins here
3013 ********************************************/
3014 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3016 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3017 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device;
3018 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3019 ins->ctx->reg_maps->shader_version.minor);
3020 glsl_sample_function_t sample_function;
3021 IWineD3DBaseTextureImpl *texture;
3022 DWORD sample_flags = 0;
3024 DWORD mask = 0, swizzle;
3026 /* 1.0-1.4: Use destination register as sampler source.
3027 * 2.0+: Use provided sampler source. */
3028 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3029 else sampler_idx = ins->src[1].reg.idx;
3030 texture = deviceImpl->stateBlock->state.textures[sampler_idx];
3032 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3034 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3035 DWORD flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3036 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3037 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3039 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3040 if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
3041 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3042 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3043 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3044 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
3045 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
3046 case WINED3DTTFF_COUNT4:
3047 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
3051 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3053 DWORD src_mod = ins->src[0].modifiers;
3055 if (src_mod == WINED3DSPSM_DZ) {
3056 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3057 mask = WINED3DSP_WRITEMASK_2;
3058 } else if (src_mod == WINED3DSPSM_DW) {
3059 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3060 mask = WINED3DSP_WRITEMASK_3;
3063 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3065 /* ps 2.0 texldp instruction always divides by the fourth component. */
3066 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3067 mask = WINED3DSP_WRITEMASK_3;
3071 if (texture && texture->baseTexture.target == GL_TEXTURE_RECTANGLE_ARB)
3072 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3074 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3075 mask |= sample_function.coord_mask;
3077 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3078 else swizzle = ins->src[1].swizzle;
3080 /* 1.0-1.3: Use destination register as coordinate source.
3081 1.4+: Use provided coordinate source register. */
3082 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3085 shader_glsl_write_mask_to_str(mask, coord_mask);
3086 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3087 "T%u%s", sampler_idx, coord_mask);
3089 glsl_src_param_t coord_param;
3090 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3091 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3093 glsl_src_param_t bias;
3094 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3095 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3096 "%s", coord_param.param_str);
3098 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3099 "%s", coord_param.param_str);
3104 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3106 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3107 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3108 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3109 glsl_sample_function_t sample_function;
3110 glsl_src_param_t coord_param, dx_param, dy_param;
3111 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3113 DWORD swizzle = ins->src[1].swizzle;
3114 IWineD3DBaseTextureImpl *texture;
3116 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3118 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3119 shader_glsl_tex(ins);
3123 sampler_idx = ins->src[1].reg.idx;
3124 texture = deviceImpl->stateBlock->state.textures[sampler_idx];
3125 if (texture && texture->baseTexture.target == GL_TEXTURE_RECTANGLE_ARB)
3126 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3128 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3129 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3130 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3131 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3133 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3134 "%s", coord_param.param_str);
3137 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3139 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3140 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3141 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3142 glsl_sample_function_t sample_function;
3143 glsl_src_param_t coord_param, lod_param;
3144 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3146 DWORD swizzle = ins->src[1].swizzle;
3147 IWineD3DBaseTextureImpl *texture;
3149 sampler_idx = ins->src[1].reg.idx;
3150 texture = deviceImpl->stateBlock->state.textures[sampler_idx];
3151 if (texture && texture->baseTexture.target == GL_TEXTURE_RECTANGLE_ARB)
3152 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3154 shader_glsl_get_sample_function(ins->ctx, sampler_idx, sample_flags, &sample_function);
3155 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3157 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3159 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3160 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3162 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
3163 * However, they seem to work just fine in fragment shaders as well. */
3164 WARN("Using %s in fragment shader.\n", sample_function.name);
3166 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3167 "%s", coord_param.param_str);
3170 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3172 /* FIXME: Make this work for more than just 2D textures */
3173 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3174 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3176 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3180 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3181 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3182 ins->dst[0].reg.idx, dst_mask);
3184 DWORD reg = ins->src[0].reg.idx;
3185 DWORD src_mod = ins->src[0].modifiers;
3186 char dst_swizzle[6];
3188 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3190 if (src_mod == WINED3DSPSM_DZ) {
3191 glsl_src_param_t div_param;
3192 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3193 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3195 if (mask_size > 1) {
3196 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3198 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3200 } else if (src_mod == WINED3DSPSM_DW) {
3201 glsl_src_param_t div_param;
3202 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3203 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3205 if (mask_size > 1) {
3206 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3208 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3211 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3216 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3217 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3218 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3219 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3221 glsl_src_param_t src0_param;
3222 glsl_sample_function_t sample_function;
3223 DWORD sampler_idx = ins->dst[0].reg.idx;
3224 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3227 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3229 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3230 * scalar, and projected sampling would require 4.
3232 * It is a dependent read - not valid with conditional NP2 textures
3234 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3235 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3240 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3241 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3245 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3246 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3250 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3251 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3255 FIXME("Unexpected mask size %u\n", mask_size);
3260 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3261 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3262 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3264 glsl_src_param_t src0_param;
3265 DWORD dstreg = ins->dst[0].reg.idx;
3266 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3268 unsigned int mask_size;
3270 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3271 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3272 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3274 if (mask_size > 1) {
3275 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3277 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3281 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3282 * Calculate the depth as dst.x / dst.y */
3283 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3285 glsl_dst_param_t dst_param;
3287 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3289 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3290 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3291 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3292 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3295 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3296 dst_param.reg_name, dst_param.reg_name);
3299 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3300 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3301 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3302 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3304 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3306 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3307 DWORD dstreg = ins->dst[0].reg.idx;
3308 glsl_src_param_t src0_param;
3310 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3312 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3313 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3316 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3317 * Calculate the 1st of a 2-row matrix multiplication. */
3318 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3320 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3321 DWORD reg = ins->dst[0].reg.idx;
3322 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3323 glsl_src_param_t src0_param;
3325 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3326 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3329 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3330 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3331 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3333 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3334 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3335 DWORD reg = ins->dst[0].reg.idx;
3336 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3337 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3338 glsl_src_param_t src0_param;
3340 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3341 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
3342 current_state->texcoord_w[current_state->current_row++] = reg;
3345 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3347 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3348 DWORD reg = ins->dst[0].reg.idx;
3349 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3350 glsl_src_param_t src0_param;
3351 glsl_sample_function_t sample_function;
3353 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3354 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3356 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3358 /* Sample the texture using the calculated coordinates */
3359 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3362 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3363 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3364 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3366 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3367 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3368 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3369 glsl_src_param_t src0_param;
3370 DWORD reg = ins->dst[0].reg.idx;
3371 glsl_sample_function_t sample_function;
3373 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3374 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3376 /* Dependent read, not valid with conditional NP2 */
3377 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3379 /* Sample the texture using the calculated coordinates */
3380 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3382 current_state->current_row = 0;
3385 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3386 * Perform the 3rd row of a 3x3 matrix multiply */
3387 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3389 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3390 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3391 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3392 glsl_src_param_t src0_param;
3394 DWORD reg = ins->dst[0].reg.idx;
3396 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3398 shader_glsl_append_dst(ins->ctx->buffer, ins);
3399 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3400 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3402 current_state->current_row = 0;
3405 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3406 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3407 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3409 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3410 DWORD reg = ins->dst[0].reg.idx;
3411 glsl_src_param_t src0_param;
3412 glsl_src_param_t src1_param;
3413 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3414 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3415 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3416 glsl_sample_function_t sample_function;
3418 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3419 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3421 /* Perform the last matrix multiply operation */
3422 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3423 /* Reflection calculation */
3424 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3426 /* Dependent read, not valid with conditional NP2 */
3427 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3429 /* Sample the texture */
3430 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3432 current_state->current_row = 0;
3435 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3436 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3437 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3439 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3440 DWORD reg = ins->dst[0].reg.idx;
3441 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3442 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3443 glsl_src_param_t src0_param;
3444 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3445 glsl_sample_function_t sample_function;
3447 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3449 /* Perform the last matrix multiply operation */
3450 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3452 /* Construct the eye-ray vector from w coordinates */
3453 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3454 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
3455 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3457 /* Dependent read, not valid with conditional NP2 */
3458 shader_glsl_get_sample_function(ins->ctx, reg, 0, &sample_function);
3460 /* Sample the texture using the calculated coordinates */
3461 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3463 current_state->current_row = 0;
3466 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3467 * Apply a fake bump map transform.
3468 * texbem is pshader <= 1.3 only, this saves a few version checks
3470 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3472 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3473 glsl_sample_function_t sample_function;
3474 glsl_src_param_t coord_param;
3480 sampler_idx = ins->dst[0].reg.idx;
3481 flags = (priv->cur_ps_args->tex_transform >> sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT)
3482 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3484 /* Dependent read, not valid with conditional NP2 */
3485 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3486 mask = sample_function.coord_mask;
3488 shader_glsl_write_mask_to_str(mask, coord_mask);
3490 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3491 * so we can't let the GL handle this.
3493 if (flags & WINED3D_PSARGS_PROJECTED) {
3495 char coord_div_mask[3];
3496 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3497 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3498 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3499 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3500 case WINED3DTTFF_COUNT4:
3501 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3503 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3504 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3507 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3509 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3510 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3511 coord_param.param_str, coord_mask);
3513 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3515 glsl_src_param_t luminance_param;
3516 glsl_dst_param_t dst_param;
3518 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3519 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3521 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3522 dst_param.reg_name, dst_param.mask_str,
3523 luminance_param.param_str, sampler_idx, sampler_idx);
3527 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3529 glsl_src_param_t src0_param, src1_param;
3530 DWORD sampler_idx = ins->dst[0].reg.idx;
3532 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3533 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3535 shader_glsl_append_dst(ins->ctx->buffer, ins);
3536 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3537 src0_param.param_str, sampler_idx, src1_param.param_str);
3540 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3541 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3542 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3544 glsl_src_param_t src0_param;
3545 DWORD sampler_idx = ins->dst[0].reg.idx;
3546 glsl_sample_function_t sample_function;
3548 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3550 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3551 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3552 "%s.wx", src0_param.reg_name);
3555 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3556 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3557 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3559 glsl_src_param_t src0_param;
3560 DWORD sampler_idx = ins->dst[0].reg.idx;
3561 glsl_sample_function_t sample_function;
3563 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3565 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3566 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3567 "%s.yz", src0_param.reg_name);
3570 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3571 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3572 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3574 glsl_src_param_t src0_param;
3575 DWORD sampler_idx = ins->dst[0].reg.idx;
3576 glsl_sample_function_t sample_function;
3578 /* Dependent read, not valid with conditional NP2 */
3579 shader_glsl_get_sample_function(ins->ctx, sampler_idx, 0, &sample_function);
3580 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3582 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3583 "%s", src0_param.param_str);
3586 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3587 * If any of the first 3 components are < 0, discard this pixel */
3588 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3590 glsl_dst_param_t dst_param;
3592 /* The argument is a destination parameter, and no writemasks are allowed */
3593 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3594 if (ins->ctx->reg_maps->shader_version.major >= 2)
3596 /* 2.0 shaders compare all 4 components in texkill */
3597 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3599 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3600 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3601 * 4 components are defined, only the first 3 are used
3603 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3607 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3608 * dst = dot2(src0, src1) + src2 */
3609 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3611 glsl_src_param_t src0_param;
3612 glsl_src_param_t src1_param;
3613 glsl_src_param_t src2_param;
3615 unsigned int mask_size;
3617 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3618 mask_size = shader_glsl_get_write_mask_size(write_mask);
3620 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3621 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3622 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3624 if (mask_size > 1) {
3625 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3626 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3628 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3629 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3633 static void shader_glsl_input_pack(IWineD3DPixelShader *iface, struct wined3d_shader_buffer *buffer,
3634 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps,
3635 enum vertexprocessing_mode vertexprocessing)
3638 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3639 WORD map = reg_maps->input_registers;
3641 for (i = 0; map; map >>= 1, ++i)
3643 const char *semantic_name;
3648 if (!(map & 1)) continue;
3650 semantic_name = input_signature[i].semantic_name;
3651 semantic_idx = input_signature[i].semantic_idx;
3652 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3654 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3656 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3657 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3658 This->input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3660 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3661 This->input_reg_map[i], reg_mask, reg_mask);
3663 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3666 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3667 This->input_reg_map[i], reg_mask, reg_mask);
3668 else if (semantic_idx == 1)
3669 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3670 This->input_reg_map[i], reg_mask, reg_mask);
3672 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3673 This->input_reg_map[i], reg_mask, reg_mask);
3677 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3678 This->input_reg_map[i], reg_mask, reg_mask);
3683 /*********************************************
3684 * Vertex Shader Specific Code begins here
3685 ********************************************/
3687 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3688 glsl_program_key_t key;
3690 key.vshader = entry->vshader;
3691 key.pshader = entry->pshader;
3692 key.vs_args = entry->vs_args;
3693 key.ps_args = entry->ps_args;
3695 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3697 ERR("Failed to insert program entry.\n");
3701 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3702 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3703 struct ps_compile_args *ps_args) {
3704 struct wine_rb_entry *entry;
3705 glsl_program_key_t key;
3707 key.vshader = vshader;
3708 key.pshader = pshader;
3709 key.vs_args = *vs_args;
3710 key.ps_args = *ps_args;
3712 entry = wine_rb_get(&priv->program_lookup, &key);
3713 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3716 /* GL locking is done by the caller */
3717 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3718 struct glsl_shader_prog_link *entry)
3720 glsl_program_key_t key;
3722 key.vshader = entry->vshader;
3723 key.pshader = entry->pshader;
3724 key.vs_args = entry->vs_args;
3725 key.ps_args = entry->ps_args;
3726 wine_rb_remove(&priv->program_lookup, &key);
3728 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3729 if (entry->vshader) list_remove(&entry->vshader_entry);
3730 if (entry->pshader) list_remove(&entry->pshader_entry);
3731 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3732 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3733 HeapFree(GetProcessHeap(), 0, entry);
3736 static void handle_ps3_input(struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info, const DWORD *map,
3737 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3738 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3741 const char *semantic_name_in;
3742 UINT semantic_idx_in;
3745 unsigned int in_count = vec4_varyings(3, gl_info);
3747 char destination[50];
3748 WORD input_map, output_map;
3750 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3752 input_map = reg_maps_in->input_registers;
3753 for (i = 0; input_map; input_map >>= 1, ++i)
3755 if (!(input_map & 1)) continue;
3758 /* Declared, but not read register */
3759 if (in_idx == ~0U) continue;
3760 if (in_idx >= (in_count + 2))
3762 FIXME("More input varyings declared than supported, expect issues.\n");
3766 if (in_idx == in_count) {
3767 sprintf(destination, "gl_FrontColor");
3768 } else if (in_idx == in_count + 1) {
3769 sprintf(destination, "gl_FrontSecondaryColor");
3771 sprintf(destination, "IN[%u]", in_idx);
3774 semantic_name_in = input_signature[i].semantic_name;
3775 semantic_idx_in = input_signature[i].semantic_idx;
3778 output_map = reg_maps_out->output_registers;
3779 for (j = 0; output_map; output_map >>= 1, ++j)
3783 if (!(output_map & 1)
3784 || semantic_idx_in != output_signature[j].semantic_idx
3785 || strcmp(semantic_name_in, output_signature[j].semantic_name)
3786 || !(mask = input_signature[i].mask & output_signature[j].mask))
3790 shader_glsl_write_mask_to_str(mask, reg_mask);
3792 shader_addline(buffer, "%s%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3793 destination, reg_mask, j, reg_mask);
3797 for (i = 0; i < in_count + 2; ++i)
3801 if (!set[i] || set[i] == WINED3DSP_WRITEMASK_ALL)
3804 if (set[i] == ~0U) set[i] = 0;
3807 if (!(set[i] & WINED3DSP_WRITEMASK_0)) reg_mask[size++] = 'x';
3808 if (!(set[i] & WINED3DSP_WRITEMASK_1)) reg_mask[size++] = 'y';
3809 if (!(set[i] & WINED3DSP_WRITEMASK_2)) reg_mask[size++] = 'z';
3810 if (!(set[i] & WINED3DSP_WRITEMASK_3)) reg_mask[size++] = 'w';
3811 reg_mask[size] = '\0';
3813 if (i == in_count) sprintf(destination, "gl_FrontColor");
3814 else if (i == in_count + 1) sprintf(destination, "gl_FrontSecondaryColor");
3815 else sprintf(destination, "IN[%u]", i);
3817 if (size == 1) shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3818 else shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3821 HeapFree(GetProcessHeap(), 0, set);
3824 /* GL locking is done by the caller */
3825 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3826 IWineD3DVertexShader *vertexshader, IWineD3DPixelShader *pixelshader, const struct wined3d_gl_info *gl_info)
3828 GLhandleARB ret = 0;
3829 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3830 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3831 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
3833 const char *semantic_name;
3836 const struct wined3d_shader_signature_element *output_signature = vs->baseShader.output_signature;
3837 WORD map = vs->baseShader.reg_maps.output_registers;
3839 shader_buffer_clear(buffer);
3841 shader_addline(buffer, "#version 120\n");
3842 shader_addline(buffer, "const float FLT_MAX = 1e38;\n");
3846 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3848 for (i = 0; map; map >>= 1, ++i)
3852 if (!(map & 1)) continue;
3854 semantic_name = output_signature[i].semantic_name;
3855 semantic_idx = output_signature[i].semantic_idx;
3856 write_mask = output_signature[i].mask;
3857 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3859 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3862 shader_addline(buffer, "gl_FrontColor%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3863 reg_mask, i, reg_mask);
3864 else if (semantic_idx == 1)
3865 shader_addline(buffer, "gl_FrontSecondaryColor%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3866 reg_mask, i, reg_mask);
3868 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3870 shader_addline(buffer, "gl_Position%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3871 reg_mask, i, reg_mask);
3873 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3875 if (semantic_idx < 8)
3877 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3878 write_mask |= WINED3DSP_WRITEMASK_3;
3880 shader_addline(buffer, "gl_TexCoord[%u]%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3881 semantic_idx, reg_mask, i, reg_mask);
3882 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3883 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3886 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3888 shader_addline(buffer, "gl_PointSize = clamp(OUT[%u].%c, -FLT_MAX, FLT_MAX);\n", i, reg_mask[1]);
3890 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3892 shader_addline(buffer, "gl_FogFragCoord = clamp(OUT[%u].%c, -FLT_MAX, FLT_MAX);\n", i, reg_mask[1]);
3895 shader_addline(buffer, "}\n");
3900 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3901 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3902 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3904 /* First, sort out position and point size. Those are not passed to the pixel shader */
3905 for (i = 0; map; map >>= 1, ++i)
3907 if (!(map & 1)) continue;
3909 semantic_name = output_signature[i].semantic_name;
3910 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3912 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3914 shader_addline(buffer, "gl_Position%s = clamp(OUT[%u]%s, -FLT_MAX, FLT_MAX);\n",
3915 reg_mask, i, reg_mask);
3917 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3919 shader_addline(buffer, "gl_PointSize = clamp(OUT[%u].%c, -FLT_MAX, FLT_MAX);\n", i, reg_mask[1]);
3923 /* Then, fix the pixel shader input */
3924 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
3925 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
3927 shader_addline(buffer, "}\n");
3930 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3931 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3932 shader_glsl_compile(gl_info, ret, buffer->buffer);
3937 /* GL locking is done by the caller */
3938 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const struct wined3d_gl_info *gl_info,
3939 GLhandleARB programId, char prefix)
3941 const local_constant *lconst;
3946 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3947 value = (const float *)lconst->value;
3948 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3949 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3950 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3952 checkGLcall("Hardcoding local constants");
3955 /* GL locking is done by the caller */
3956 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
3957 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *This,
3958 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
3960 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3961 const struct wined3d_gl_info *gl_info = context->gl_info;
3962 CONST DWORD *function = This->baseShader.function;
3963 struct shader_glsl_ctx_priv priv_ctx;
3965 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3966 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3968 memset(&priv_ctx, 0, sizeof(priv_ctx));
3969 priv_ctx.cur_ps_args = args;
3970 priv_ctx.cur_np2fixup_info = np2fixup_info;
3972 shader_addline(buffer, "#version 120\n");
3974 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] && reg_maps->usestexldd)
3976 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3978 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
3980 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3981 * drivers write a warning if we don't do so
3983 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3985 if (gl_info->supported[EXT_GPU_SHADER4])
3987 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
3990 /* Base Declarations */
3991 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
3993 /* Pack 3.0 inputs */
3994 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
3996 shader_glsl_input_pack((IWineD3DPixelShader *) This, buffer,
3997 This->baseShader.input_signature, reg_maps, args->vp_mode);
4000 /* Base Shader Body */
4001 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
4003 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4004 if (reg_maps->shader_version.major < 2)
4006 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4007 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4010 if (args->srgb_correction)
4012 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4013 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4014 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4015 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4016 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4017 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4019 /* Pixel shader < 3.0 do not replace the fog stage.
4020 * This implements linear fog computation and blending.
4021 * TODO: non linear fog
4022 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4023 * -1/(e-s) and e/(e-s) respectively.
4025 if (reg_maps->shader_version.major < 3)
4028 case FOG_OFF: break;
4030 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4031 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4032 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4033 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4036 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4037 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4038 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4039 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4042 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4043 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4044 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4045 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4050 shader_addline(buffer, "}\n");
4052 TRACE("Compiling shader object %u\n", shader_obj);
4053 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4055 /* Store the shader object */
4059 /* GL locking is done by the caller */
4060 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4061 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *This,
4062 const struct vs_compile_args *args)
4064 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4065 const struct wined3d_gl_info *gl_info = context->gl_info;
4066 CONST DWORD *function = This->baseShader.function;
4067 struct shader_glsl_ctx_priv priv_ctx;
4069 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4070 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4072 shader_addline(buffer, "#version 120\n");
4074 if (gl_info->supported[EXT_GPU_SHADER4])
4076 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4079 memset(&priv_ctx, 0, sizeof(priv_ctx));
4080 priv_ctx.cur_vs_args = args;
4082 /* Base Declarations */
4083 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
4085 /* Base Shader Body */
4086 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
4088 /* Unpack outputs */
4089 shader_addline(buffer, "order_ps_input(OUT);\n");
4091 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4092 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4093 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4094 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4096 if(args->fog_src == VS_FOG_Z) {
4097 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4098 } else if (!reg_maps->fog) {
4099 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4102 /* Write the final position.
4104 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4105 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4106 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4107 * contains 1.0 to allow a mad.
4109 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4110 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4111 if(args->clip_enabled) {
4112 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4115 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4117 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4118 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4119 * which is the same as z = z * 2 - w.
4121 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4123 shader_addline(buffer, "}\n");
4125 TRACE("Compiling shader object %u\n", shader_obj);
4126 shader_glsl_compile(gl_info, shader_obj, buffer->buffer);
4131 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4132 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
4133 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
4135 struct wined3d_state *state = &((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->state;
4138 struct glsl_ps_compiled_shader *new_array;
4139 struct glsl_pshader_private *shader_data;
4140 struct ps_np2fixup_info *np2fixup = NULL;
4143 if (!shader->baseShader.backend_data)
4145 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4146 if (!shader->baseShader.backend_data)
4148 ERR("Failed to allocate backend data.\n");
4152 shader_data = shader->baseShader.backend_data;
4154 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4155 * so a linear search is more performant than a hashmap or a binary search
4156 * (cache coherency etc)
4158 for (i = 0; i < shader_data->num_gl_shaders; ++i)
4160 if (!memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)))
4162 if (args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
4163 return shader_data->gl_shaders[i].prgId;
4167 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4168 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4169 if (shader_data->num_gl_shaders)
4171 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4172 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4173 new_size * sizeof(*shader_data->gl_shaders));
4175 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4180 ERR("Out of memory\n");
4183 shader_data->gl_shaders = new_array;
4184 shader_data->shader_array_size = new_size;
4187 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4189 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4190 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4192 pixelshader_update_samplers(&shader->baseShader.reg_maps, (IWineD3DBaseTexture **)state->textures);
4194 shader_buffer_clear(buffer);
4195 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4196 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4197 *np2fixup_info = np2fixup;
4202 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4203 const DWORD use_map) {
4204 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4205 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4206 return stored->fog_src == new->fog_src;
4209 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4210 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
4211 const struct vs_compile_args *args)
4215 struct glsl_vs_compiled_shader *new_array;
4216 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
4217 struct glsl_vshader_private *shader_data;
4220 if (!shader->baseShader.backend_data)
4222 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4223 if (!shader->baseShader.backend_data)
4225 ERR("Failed to allocate backend data.\n");
4229 shader_data = shader->baseShader.backend_data;
4231 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4232 * so a linear search is more performant than a hashmap or a binary search
4233 * (cache coherency etc)
4235 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4236 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4237 return shader_data->gl_shaders[i].prgId;
4241 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4243 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4244 if (shader_data->num_gl_shaders)
4246 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4247 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4248 new_size * sizeof(*shader_data->gl_shaders));
4250 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4255 ERR("Out of memory\n");
4258 shader_data->gl_shaders = new_array;
4259 shader_data->shader_array_size = new_size;
4262 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4264 shader_buffer_clear(buffer);
4265 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4266 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4271 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4272 * It sets the programId on the current StateBlock (because it should be called
4273 * inside of the DrawPrimitive() part of the render loop).
4275 * If a program for the given combination does not exist, create one, and store
4276 * the program in the hash table. If it creates a program, it will link the
4277 * given objects, too.
4280 /* GL locking is done by the caller */
4281 static void set_glsl_shader_program(const struct wined3d_context *context,
4282 IWineD3DDeviceImpl *device, BOOL use_ps, BOOL use_vs)
4284 const struct wined3d_state *state = &device->stateBlock->state;
4285 IWineD3DVertexShader *vshader = use_vs ? (IWineD3DVertexShader *)state->vertex_shader : NULL;
4286 IWineD3DPixelShader *pshader = use_ps ? (IWineD3DPixelShader *)state->pixel_shader : NULL;
4287 const struct wined3d_gl_info *gl_info = context->gl_info;
4288 struct shader_glsl_priv *priv = device->shader_priv;
4289 struct glsl_shader_prog_link *entry = NULL;
4290 GLhandleARB programId = 0;
4291 GLhandleARB reorder_shader_id = 0;
4294 struct ps_compile_args ps_compile_args;
4295 struct vs_compile_args vs_compile_args;
4297 if (vshader) find_vs_compile_args(state, (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
4298 if (pshader) find_ps_compile_args(state, (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args);
4300 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4302 priv->glsl_program = entry;
4306 /* If we get to this point, then no matching program exists, so we create one */
4307 programId = GL_EXTCALL(glCreateProgramObjectARB());
4308 TRACE("Created new GLSL shader program %u\n", programId);
4310 /* Create the entry */
4311 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4312 entry->programId = programId;
4313 entry->vshader = vshader;
4314 entry->pshader = pshader;
4315 entry->vs_args = vs_compile_args;
4316 entry->ps_args = ps_compile_args;
4317 entry->constant_version = 0;
4318 entry->np2Fixup_info = NULL;
4319 /* Add the hash table entry */
4320 add_glsl_program_entry(priv, entry);
4322 /* Set the current program */
4323 priv->glsl_program = entry;
4325 /* Attach GLSL vshader */
4328 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer,
4329 (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
4330 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4333 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4334 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4335 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4336 checkGLcall("glAttachObjectARB");
4337 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4340 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4342 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4343 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4344 checkGLcall("glAttachObjectARB");
4346 /* Bind vertex attributes to a corresponding index number to match
4347 * the same index numbers as ARB_vertex_programs (makes loading
4348 * vertex attributes simpler). With this method, we can use the
4349 * exact same code to load the attributes later for both ARB and
4352 * We have to do this here because we need to know the Program ID
4353 * in order to make the bindings work, and it has to be done prior
4354 * to linking the GLSL program. */
4355 for (i = 0; map; map >>= 1, ++i)
4357 if (!(map & 1)) continue;
4359 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4360 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4362 checkGLcall("glBindAttribLocationARB");
4364 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4367 /* Attach GLSL pshader */
4370 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4371 (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args, &entry->np2Fixup_info);
4372 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4373 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4374 checkGLcall("glAttachObjectARB");
4376 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4379 /* Link the program */
4380 TRACE("Linking GLSL shader program %u\n", programId);
4381 GL_EXTCALL(glLinkProgramARB(programId));
4382 shader_glsl_validate_link(gl_info, programId);
4384 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4385 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4386 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4388 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4389 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4391 for (i = 0; i < MAX_CONST_I; ++i)
4393 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4394 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4396 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0,
4397 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4398 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4400 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4401 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4403 for (i = 0; i < MAX_CONST_I; ++i)
4405 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4406 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4412 for(i = 0; i < MAX_TEXTURES; i++) {
4413 sprintf(name, "bumpenvmat%u", i);
4414 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4415 sprintf(name, "luminancescale%u", i);
4416 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4417 sprintf(name, "luminanceoffset%u", i);
4418 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4421 if (ps_compile_args.np2_fixup) {
4422 if (entry->np2Fixup_info) {
4423 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4425 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4430 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4431 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4432 checkGLcall("Find glsl program uniform locations");
4435 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4436 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4438 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4439 entry->vertex_color_clamp = GL_FALSE;
4441 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4444 /* Set the shader to allow uniform loading on it */
4445 GL_EXTCALL(glUseProgramObjectARB(programId));
4446 checkGLcall("glUseProgramObjectARB(programId)");
4448 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4449 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4450 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4451 * vertex shader with fixed function pixel processing is used we make sure that the card
4452 * supports enough samplers to allow the max number of vertex samplers with all possible
4453 * fixed function fragment processing setups. So once the program is linked these samplers
4456 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4457 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4459 /* If the local constants do not have to be loaded with the environment constants,
4460 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4463 if (pshader && !((IWineD3DBaseShaderImpl *)pshader)->baseShader.load_local_constsF)
4465 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4467 if (vshader && !((IWineD3DBaseShaderImpl *)vshader)->baseShader.load_local_constsF)
4469 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4473 /* GL locking is done by the caller */
4474 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type, BOOL masked)
4476 GLhandleARB program_id;
4477 GLhandleARB vshader_id, pshader_id;
4478 const char *blt_pshader;
4480 static const char *blt_vshader =
4484 " gl_Position = gl_Vertex;\n"
4485 " gl_FrontColor = vec4(1.0);\n"
4486 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4489 static const char * const blt_pshaders_full[tex_type_count] =
4495 "uniform sampler2D sampler;\n"
4498 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4504 "uniform samplerCube sampler;\n"
4507 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4511 "#extension GL_ARB_texture_rectangle : enable\n"
4512 "uniform sampler2DRect sampler;\n"
4515 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4519 static const char * const blt_pshaders_masked[tex_type_count] =
4525 "uniform sampler2D sampler;\n"
4526 "uniform vec4 mask;\n"
4529 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4530 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4536 "uniform samplerCube sampler;\n"
4537 "uniform vec4 mask;\n"
4540 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4541 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4545 "#extension GL_ARB_texture_rectangle : enable\n"
4546 "uniform sampler2DRect sampler;\n"
4547 "uniform vec4 mask;\n"
4550 " if (all(lessThan(gl_FragCoord.xy, mask.zw))) discard;\n"
4551 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4555 blt_pshader = masked ? blt_pshaders_masked[tex_type] : blt_pshaders_full[tex_type];
4558 FIXME("tex_type %#x not supported\n", tex_type);
4562 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4563 shader_glsl_compile(gl_info, vshader_id, blt_vshader);
4565 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4566 shader_glsl_compile(gl_info, pshader_id, blt_pshader);
4568 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4569 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4570 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4571 GL_EXTCALL(glLinkProgramARB(program_id));
4573 shader_glsl_validate_link(gl_info, program_id);
4575 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4578 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4579 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4583 /* GL locking is done by the caller */
4584 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4586 const struct wined3d_gl_info *gl_info = context->gl_info;
4587 IWineD3DDeviceImpl *device = context->swapchain->device;
4588 struct shader_glsl_priv *priv = device->shader_priv;
4589 GLhandleARB program_id = 0;
4590 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4592 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4594 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4595 else priv->glsl_program = NULL;
4597 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4599 if (old_vertex_color_clamp != current_vertex_color_clamp)
4601 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4603 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4604 checkGLcall("glClampColorARB");
4608 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4612 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4613 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4614 GL_EXTCALL(glUseProgramObjectARB(program_id));
4615 checkGLcall("glUseProgramObjectARB");
4617 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4618 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4619 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4620 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4622 shader_glsl_load_np2fixup_constants((IWineD3DDevice *)device, usePS, useVS);
4626 /* GL locking is done by the caller */
4627 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface,
4628 enum tex_types tex_type, const SIZE *ds_mask_size)
4630 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4631 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4632 BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
4633 struct shader_glsl_priv *priv = This->shader_priv;
4634 GLhandleARB *blt_program;
4637 blt_program = masked ? &priv->depth_blt_program_masked[tex_type] : &priv->depth_blt_program_full[tex_type];
4640 *blt_program = create_glsl_blt_shader(gl_info, tex_type, masked);
4641 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4642 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4643 GL_EXTCALL(glUniform1iARB(loc, 0));
4647 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4652 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "mask"));
4653 GL_EXTCALL(glUniform4fARB(loc, 0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy));
4657 /* GL locking is done by the caller */
4658 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
4659 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4660 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4661 struct shader_glsl_priv *priv = This->shader_priv;
4662 GLhandleARB program_id;
4664 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4665 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4667 GL_EXTCALL(glUseProgramObjectARB(program_id));
4668 checkGLcall("glUseProgramObjectARB");
4671 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
4672 const struct list *linked_programs;
4673 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
4674 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
4675 struct shader_glsl_priv *priv = device->shader_priv;
4676 const struct wined3d_gl_info *gl_info;
4677 struct wined3d_context *context;
4679 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
4680 * can be called from IWineD3DBaseShader::Release
4682 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
4685 struct glsl_pshader_private *shader_data;
4686 shader_data = This->baseShader.backend_data;
4687 if (!shader_data || !shader_data->num_gl_shaders)
4689 HeapFree(GetProcessHeap(), 0, shader_data);
4690 This->baseShader.backend_data = NULL;
4694 context = context_acquire(device, NULL);
4695 gl_info = context->gl_info;
4697 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
4700 shader_glsl_select(context, FALSE, FALSE);
4704 struct glsl_vshader_private *shader_data;
4705 shader_data = This->baseShader.backend_data;
4706 if (!shader_data || !shader_data->num_gl_shaders)
4708 HeapFree(GetProcessHeap(), 0, shader_data);
4709 This->baseShader.backend_data = NULL;
4713 context = context_acquire(device, NULL);
4714 gl_info = context->gl_info;
4716 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
4719 shader_glsl_select(context, FALSE, FALSE);
4724 linked_programs = &This->baseShader.linked_programs;
4726 TRACE("Deleting linked programs\n");
4727 if (linked_programs->next) {
4728 struct glsl_shader_prog_link *entry, *entry2;
4732 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4733 delete_glsl_program_entry(priv, gl_info, entry);
4736 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4737 delete_glsl_program_entry(priv, gl_info, entry);
4745 struct glsl_pshader_private *shader_data = This->baseShader.backend_data;
4748 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4749 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4750 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4751 checkGLcall("glDeleteObjectARB");
4754 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4759 struct glsl_vshader_private *shader_data = This->baseShader.backend_data;
4762 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4763 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4764 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4765 checkGLcall("glDeleteObjectARB");
4768 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4771 HeapFree(GetProcessHeap(), 0, This->baseShader.backend_data);
4772 This->baseShader.backend_data = NULL;
4774 context_release(context);
4777 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4779 const glsl_program_key_t *k = key;
4780 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4781 const struct glsl_shader_prog_link, program_lookup_entry);
4784 if (k->vshader > prog->vshader) return 1;
4785 else if (k->vshader < prog->vshader) return -1;
4787 if (k->pshader > prog->pshader) return 1;
4788 else if (k->pshader < prog->pshader) return -1;
4790 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4791 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4796 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4798 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4799 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4803 ERR("Failed to allocate memory\n");
4807 heap->entries = mem;
4808 heap->entries[1].version = 0;
4809 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4815 static void constant_heap_free(struct constant_heap *heap)
4817 HeapFree(GetProcessHeap(), 0, heap->entries);
4820 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4825 glsl_program_key_compare,
4828 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
4829 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4830 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4831 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4832 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
4833 gl_info->limits.glsl_ps_float_constants)) + 1;
4835 if (!shader_buffer_init(&priv->shader_buffer))
4837 ERR("Failed to initialize shader buffer.\n");
4841 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4844 ERR("Failed to allocate memory.\n");
4848 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
4850 ERR("Failed to initialize vertex shader constant heap\n");
4854 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
4856 ERR("Failed to initialize pixel shader constant heap\n");
4860 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4862 ERR("Failed to initialize rbtree.\n");
4866 priv->next_constant_version = 1;
4868 This->shader_priv = priv;
4872 constant_heap_free(&priv->pconst_heap);
4873 constant_heap_free(&priv->vconst_heap);
4874 HeapFree(GetProcessHeap(), 0, priv->stack);
4875 shader_buffer_free(&priv->shader_buffer);
4876 HeapFree(GetProcessHeap(), 0, priv);
4877 return E_OUTOFMEMORY;
4880 /* Context activation is done by the caller. */
4881 static void shader_glsl_free(IWineD3DDevice *iface) {
4882 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4883 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4884 struct shader_glsl_priv *priv = This->shader_priv;
4888 for (i = 0; i < tex_type_count; ++i)
4890 if (priv->depth_blt_program_full[i])
4892 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_full[i]));
4894 if (priv->depth_blt_program_masked[i])
4896 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program_masked[i]));
4901 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4902 constant_heap_free(&priv->pconst_heap);
4903 constant_heap_free(&priv->vconst_heap);
4904 HeapFree(GetProcessHeap(), 0, priv->stack);
4905 shader_buffer_free(&priv->shader_buffer);
4907 HeapFree(GetProcessHeap(), 0, This->shader_priv);
4908 This->shader_priv = NULL;
4911 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
4912 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4916 static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *pCaps)
4918 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4919 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support based
4920 * on the version of NV_vertex_program.
4921 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4922 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4923 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4924 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4926 if ((gl_info->supported[NV_VERTEX_PROGRAM2] && !gl_info->supported[NV_VERTEX_PROGRAM3])
4927 || gl_info->limits.arb_ps_instructions <= 512)
4928 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4930 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4931 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4932 pCaps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
4934 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4935 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4936 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4937 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4938 * in max native instructions. Intel and others also offer the info in this extension but they
4939 * don't support GLSL (at least on Windows).
4941 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4942 * of instructions is 512 or less we have to do with ps2.0 hardware.
4943 * 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.
4945 if ((gl_info->supported[NV_FRAGMENT_PROGRAM] && !gl_info->supported[NV_FRAGMENT_PROGRAM2])
4946 || gl_info->limits.arb_ps_instructions <= 512)
4947 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4949 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4951 pCaps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
4953 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4954 * Direct3D minimum requirement.
4956 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4957 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4959 * The problem is that the refrast clamps temporary results in the shader to
4960 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4961 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4962 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4963 * offer a way to query this.
4965 pCaps->PixelShader1xMaxValue = 8.0;
4966 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4968 pCaps->VSClipping = TRUE;
4971 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4973 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4975 TRACE("Checking support for fixup:\n");
4976 dump_color_fixup_desc(fixup);
4979 /* We support everything except YUV conversions. */
4980 if (!is_complex_fixup(fixup))
4986 TRACE("[FAILED]\n");
4990 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4992 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4993 /* WINED3DSIH_ADD */ shader_glsl_arith,
4994 /* WINED3DSIH_BEM */ shader_glsl_bem,
4995 /* WINED3DSIH_BREAK */ shader_glsl_break,
4996 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4997 /* WINED3DSIH_BREAKP */ NULL,
4998 /* WINED3DSIH_CALL */ shader_glsl_call,
4999 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
5000 /* WINED3DSIH_CMP */ shader_glsl_cmp,
5001 /* WINED3DSIH_CND */ shader_glsl_cnd,
5002 /* WINED3DSIH_CRS */ shader_glsl_cross,
5003 /* WINED3DSIH_CUT */ NULL,
5004 /* WINED3DSIH_DCL */ NULL,
5005 /* WINED3DSIH_DEF */ NULL,
5006 /* WINED3DSIH_DEFB */ NULL,
5007 /* WINED3DSIH_DEFI */ NULL,
5008 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
5009 /* WINED3DSIH_DP3 */ shader_glsl_dot,
5010 /* WINED3DSIH_DP4 */ shader_glsl_dot,
5011 /* WINED3DSIH_DST */ shader_glsl_dst,
5012 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
5013 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
5014 /* WINED3DSIH_ELSE */ shader_glsl_else,
5015 /* WINED3DSIH_EMIT */ NULL,
5016 /* WINED3DSIH_ENDIF */ shader_glsl_end,
5017 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5018 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5019 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5020 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5021 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5022 /* WINED3DSIH_IADD */ NULL,
5023 /* WINED3DSIH_IF */ shader_glsl_if,
5024 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5025 /* WINED3DSIH_IGE */ NULL,
5026 /* WINED3DSIH_LABEL */ shader_glsl_label,
5027 /* WINED3DSIH_LIT */ shader_glsl_lit,
5028 /* WINED3DSIH_LOG */ shader_glsl_log,
5029 /* WINED3DSIH_LOGP */ shader_glsl_log,
5030 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5031 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5032 /* WINED3DSIH_LT */ NULL,
5033 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5034 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5035 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5036 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5037 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5038 /* WINED3DSIH_MAD */ shader_glsl_mad,
5039 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5040 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5041 /* WINED3DSIH_MOV */ shader_glsl_mov,
5042 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5043 /* WINED3DSIH_MUL */ shader_glsl_arith,
5044 /* WINED3DSIH_NOP */ NULL,
5045 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5046 /* WINED3DSIH_PHASE */ NULL,
5047 /* WINED3DSIH_POW */ shader_glsl_pow,
5048 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5049 /* WINED3DSIH_REP */ shader_glsl_rep,
5050 /* WINED3DSIH_RET */ shader_glsl_ret,
5051 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5052 /* WINED3DSIH_SETP */ NULL,
5053 /* WINED3DSIH_SGE */ shader_glsl_compare,
5054 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5055 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5056 /* WINED3DSIH_SLT */ shader_glsl_compare,
5057 /* WINED3DSIH_SUB */ shader_glsl_arith,
5058 /* WINED3DSIH_TEX */ shader_glsl_tex,
5059 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5060 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5061 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5062 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5063 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5064 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5065 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5066 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5067 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5068 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5069 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5070 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5071 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5072 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5073 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5074 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5075 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5076 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5077 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5078 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5079 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5082 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5083 SHADER_HANDLER hw_fct;
5085 /* Select handler */
5086 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5088 /* Unhandled opcode */
5091 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5096 shader_glsl_add_instruction_modifiers(ins);
5099 const shader_backend_t glsl_shader_backend = {
5100 shader_glsl_handle_instruction,
5102 shader_glsl_select_depth_blt,
5103 shader_glsl_deselect_depth_blt,
5104 shader_glsl_update_float_vertex_constants,
5105 shader_glsl_update_float_pixel_constants,
5106 shader_glsl_load_constants,
5107 shader_glsl_load_np2fixup_constants,
5108 shader_glsl_destroy,
5111 shader_glsl_dirty_const,
5112 shader_glsl_get_caps,
5113 shader_glsl_color_fixup_supported,