2 * GLSL pixel and vertex shader implementation
4 * Copyright 2006 Jason Green
5 * Copyright 2006-2007 Henri Verbeet
6 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
7 * Copyright 2009 Henri Verbeet for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 * D3D shader asm has swizzles on source parameters, and write masks for
26 * destination parameters. GLSL uses swizzles for both. The result of this is
27 * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
28 * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
29 * mask for the destination parameter into account.
35 #include "wined3d_private.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
40 WINE_DECLARE_DEBUG_CHANNEL(d3d);
42 #define GLINFO_LOCATION (*gl_info)
44 #define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
45 #define WINED3D_GLSL_SAMPLE_RECT 0x2
46 #define WINED3D_GLSL_SAMPLE_LOD 0x4
47 #define WINED3D_GLSL_SAMPLE_GRAD 0x8
62 } glsl_sample_function_t;
66 HEAP_NODE_TRAVERSE_LEFT,
67 HEAP_NODE_TRAVERSE_RIGHT,
79 struct constant_entry *entries;
80 unsigned int *positions;
84 /* GLSL shader private data */
85 struct shader_glsl_priv {
86 struct wined3d_shader_buffer shader_buffer;
87 struct wine_rb_tree program_lookup;
88 struct glsl_shader_prog_link *glsl_program;
89 struct constant_heap vconst_heap;
90 struct constant_heap pconst_heap;
92 GLhandleARB depth_blt_program[tex_type_count];
93 UINT next_constant_version;
96 /* Struct to maintain data about a linked GLSL program */
97 struct glsl_shader_prog_link {
98 struct wine_rb_entry program_lookup_entry;
99 struct list vshader_entry;
100 struct list pshader_entry;
101 GLhandleARB programId;
102 GLint *vuniformF_locations;
103 GLint *puniformF_locations;
104 GLint vuniformI_locations[MAX_CONST_I];
105 GLint puniformI_locations[MAX_CONST_I];
106 GLint posFixup_location;
107 GLint np2Fixup_location;
108 GLint bumpenvmat_location[MAX_TEXTURES];
109 GLint luminancescale_location[MAX_TEXTURES];
110 GLint luminanceoffset_location[MAX_TEXTURES];
111 GLint ycorrection_location;
112 GLenum vertex_color_clamp;
113 IWineD3DVertexShader *vshader;
114 IWineD3DPixelShader *pshader;
115 struct vs_compile_args vs_args;
116 struct ps_compile_args ps_args;
117 UINT constant_version;
118 const struct ps_np2fixup_info *np2Fixup_info;
122 IWineD3DVertexShader *vshader;
123 IWineD3DPixelShader *pshader;
124 struct ps_compile_args ps_args;
125 struct vs_compile_args vs_args;
126 } glsl_program_key_t;
128 struct shader_glsl_ctx_priv {
129 const struct vs_compile_args *cur_vs_args;
130 const struct ps_compile_args *cur_ps_args;
131 struct ps_np2fixup_info *cur_np2fixup_info;
134 struct glsl_ps_compiled_shader
136 struct ps_compile_args args;
137 struct ps_np2fixup_info np2fixup;
141 struct glsl_pshader_private
143 struct glsl_ps_compiled_shader *gl_shaders;
144 UINT num_gl_shaders, shader_array_size;
147 struct glsl_vs_compiled_shader
149 struct vs_compile_args args;
153 struct glsl_vshader_private
155 struct glsl_vs_compiled_shader *gl_shaders;
156 UINT num_gl_shaders, shader_array_size;
159 /* Extract a line from the info log.
160 * Note that this modifies the source string. */
161 static char *get_info_log_line(char **ptr)
166 if (!(q = strstr(p, "\n")))
168 if (!*p) return NULL;
178 /** Prints the GLSL info log which will contain error messages if they exist */
179 /* GL locking is done by the caller */
180 static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
182 int infologLength = 0;
187 static const char * const spam[] =
189 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
190 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx, with \n */
191 "Fragment shader was successfully compiled to run on hardware.", /* fglrx, no \n */
192 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
193 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
194 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
195 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
196 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
197 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
200 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
202 GL_EXTCALL(glGetObjectParameterivARB(obj,
203 GL_OBJECT_INFO_LOG_LENGTH_ARB,
206 /* A size of 1 is just a null-terminated string, so the log should be bigger than
207 * that if there are errors. */
208 if (infologLength > 1)
212 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
213 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
215 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
216 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
219 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
220 if(strcmp(infoLog, spam[i]) == 0) {
229 TRACE("Spam received from GLSL shader #%u:\n", obj);
230 while ((line = get_info_log_line(&ptr))) TRACE(" %s\n", line);
234 FIXME("Error received from GLSL shader #%u:\n", obj);
235 while ((line = get_info_log_line(&ptr))) FIXME(" %s\n", line);
237 HeapFree(GetProcessHeap(), 0, infoLog);
242 * Loads (pixel shader) samplers
244 /* GL locking is done by the caller */
245 static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
246 DWORD *tex_unit_map, GLhandleARB programId)
250 char sampler_name[20];
252 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
253 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
254 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
255 if (name_loc != -1) {
256 DWORD mapped_unit = tex_unit_map[i];
257 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->max_fragment_samplers)
259 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
260 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
261 checkGLcall("glUniform1iARB");
263 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
269 /* GL locking is done by the caller */
270 static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
271 DWORD *tex_unit_map, GLhandleARB programId)
274 char sampler_name[20];
277 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
278 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
279 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
280 if (name_loc != -1) {
281 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
282 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->max_combined_samplers)
284 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
285 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
286 checkGLcall("glUniform1iARB");
288 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
294 /* GL locking is done by the caller */
295 static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
296 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
299 unsigned int heap_idx = 1;
302 if (heap->entries[heap_idx].version <= version) return;
304 idx = heap->entries[heap_idx].idx;
305 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
306 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
308 while (stack_idx >= 0)
310 /* Note that we fall through to the next case statement. */
311 switch(stack[stack_idx])
313 case HEAP_NODE_TRAVERSE_LEFT:
315 unsigned int left_idx = heap_idx << 1;
316 if (left_idx < heap->size && heap->entries[left_idx].version > version)
319 idx = heap->entries[heap_idx].idx;
320 if (constant_locations[idx] != -1)
321 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
323 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
324 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
329 case HEAP_NODE_TRAVERSE_RIGHT:
331 unsigned int right_idx = (heap_idx << 1) + 1;
332 if (right_idx < heap->size && heap->entries[right_idx].version > version)
334 heap_idx = right_idx;
335 idx = heap->entries[heap_idx].idx;
336 if (constant_locations[idx] != -1)
337 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
339 stack[stack_idx++] = HEAP_NODE_POP;
340 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
353 checkGLcall("walk_constant_heap()");
356 /* GL locking is done by the caller */
357 static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
359 GLfloat clamped_constant[4];
361 if (location == -1) return;
363 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
364 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
365 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
366 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
368 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
371 /* GL locking is done by the caller */
372 static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
373 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
376 unsigned int heap_idx = 1;
379 if (heap->entries[heap_idx].version <= version) return;
381 idx = heap->entries[heap_idx].idx;
382 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
383 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
385 while (stack_idx >= 0)
387 /* Note that we fall through to the next case statement. */
388 switch(stack[stack_idx])
390 case HEAP_NODE_TRAVERSE_LEFT:
392 unsigned int left_idx = heap_idx << 1;
393 if (left_idx < heap->size && heap->entries[left_idx].version > version)
396 idx = heap->entries[heap_idx].idx;
397 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
399 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
400 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
405 case HEAP_NODE_TRAVERSE_RIGHT:
407 unsigned int right_idx = (heap_idx << 1) + 1;
408 if (right_idx < heap->size && heap->entries[right_idx].version > version)
410 heap_idx = right_idx;
411 idx = heap->entries[heap_idx].idx;
412 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
414 stack[stack_idx++] = HEAP_NODE_POP;
415 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
428 checkGLcall("walk_constant_heap_clamped()");
431 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
432 /* GL locking is done by the caller */
433 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
434 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
435 unsigned char *stack, UINT version)
437 const local_constant *lconst;
439 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
440 if (This->baseShader.reg_maps.shader_version.major == 1
441 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
442 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
444 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
446 if (!This->baseShader.load_local_constsF)
448 TRACE("No need to load local float constants for this shader\n");
452 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
453 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
455 GLint location = constant_locations[lconst->idx];
456 /* We found this uniform name in the program - go ahead and send the data */
457 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
459 checkGLcall("glUniform4fvARB()");
462 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
463 /* GL locking is done by the caller */
464 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
465 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
470 for (i = 0; constants_set; constants_set >>= 1, ++i)
472 if (!(constants_set & 1)) continue;
474 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
475 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
477 /* We found this uniform name in the program - go ahead and send the data */
478 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
479 checkGLcall("glUniform4ivARB");
482 /* Load immediate constants */
483 ptr = list_head(&This->baseShader.constantsI);
485 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
486 unsigned int idx = lconst->idx;
487 const GLint *values = (const GLint *)lconst->value;
489 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
490 values[0], values[1], values[2], values[3]);
492 /* We found this uniform name in the program - go ahead and send the data */
493 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
494 checkGLcall("glUniform4ivARB");
495 ptr = list_next(&This->baseShader.constantsI, ptr);
499 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
500 /* GL locking is done by the caller */
501 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
502 GLhandleARB programId, const BOOL *constants, WORD constants_set)
510 switch (This->baseShader.reg_maps.shader_version.type)
512 case WINED3D_SHADER_TYPE_VERTEX:
516 case WINED3D_SHADER_TYPE_GEOMETRY:
520 case WINED3D_SHADER_TYPE_PIXEL:
525 FIXME("Unknown shader type %#x.\n",
526 This->baseShader.reg_maps.shader_version.type);
531 /* TODO: Benchmark and see if it would be beneficial to store the
532 * locations of the constants to avoid looking up each time */
533 for (i = 0; constants_set; constants_set >>= 1, ++i)
535 if (!(constants_set & 1)) continue;
537 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
539 /* TODO: Benchmark and see if it would be beneficial to store the
540 * locations of the constants to avoid looking up each time */
541 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
542 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
545 /* We found this uniform name in the program - go ahead and send the data */
546 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
547 checkGLcall("glUniform1ivARB");
551 /* Load immediate constants */
552 ptr = list_head(&This->baseShader.constantsB);
554 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
555 unsigned int idx = lconst->idx;
556 const GLint *values = (const GLint *)lconst->value;
558 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
560 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
561 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
563 /* We found this uniform name in the program - go ahead and send the data */
564 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
565 checkGLcall("glUniform1ivARB");
567 ptr = list_next(&This->baseShader.constantsB, ptr);
571 static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
573 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
577 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
579 /* GL locking is done by the caller (state handler) */
580 static void shader_glsl_load_np2fixup_constants(
581 IWineD3DDevice* device,
583 char useVertexShader) {
585 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
586 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
589 /* No GLSL program set - nothing to do. */
593 if (!usePixelShader) {
594 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
598 if (prog->ps_args.np2_fixup && -1 != prog->np2Fixup_location) {
599 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
600 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
602 UINT fixup = prog->ps_args.np2_fixup;
603 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
605 for (i = 0; fixup; fixup >>= 1, ++i) {
606 const unsigned char idx = prog->np2Fixup_info->idx[i];
607 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
608 GLfloat* tex_dim = &np2fixup_constants[(idx >> 1) * 4];
611 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
616 tex_dim[2] = tex->baseTexture.pow2Matrix[0]; tex_dim[3] = tex->baseTexture.pow2Matrix[5];
618 tex_dim[0] = tex->baseTexture.pow2Matrix[0]; tex_dim[1] = tex->baseTexture.pow2Matrix[5];
622 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, prog->np2Fixup_info->num_consts, np2fixup_constants));
627 * Loads the app-supplied constants into the currently set GLSL program.
629 /* GL locking is done by the caller (state handler) */
630 static void shader_glsl_load_constants(const struct wined3d_context *context,
631 char usePixelShader, char useVertexShader)
633 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
634 const struct wined3d_gl_info *gl_info = context->gl_info;
635 IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
636 struct shader_glsl_priv *priv = device->shader_priv;
638 GLhandleARB programId;
639 struct glsl_shader_prog_link *prog = priv->glsl_program;
640 UINT constant_version;
644 /* No GLSL program set - nothing to do. */
647 programId = prog->programId;
648 constant_version = prog->constant_version;
650 if (useVertexShader) {
651 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
653 /* Load DirectX 9 float constants/uniforms for vertex shader */
654 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
655 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
657 /* Load DirectX 9 integer constants/uniforms for vertex shader */
658 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
659 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
661 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
662 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
663 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
665 /* Upload the position fixup params */
666 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &device->posFixup[0]));
667 checkGLcall("glUniform4fvARB");
670 if (usePixelShader) {
672 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
674 /* Load DirectX 9 float constants/uniforms for pixel shader */
675 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
676 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
678 /* Load DirectX 9 integer constants/uniforms for pixel shader */
679 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
680 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
682 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
683 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
684 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
686 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
687 * It can't be 0 for a valid texbem instruction.
689 for(i = 0; i < MAX_TEXTURES; i++) {
692 if(prog->bumpenvmat_location[i] == -1) continue;
694 data = (const float *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVMAT00];
695 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
696 checkGLcall("glUniformMatrix2fvARB");
698 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
699 * is set too, so we can check that in the needsbumpmat check
701 if(prog->luminancescale_location[i] != -1) {
702 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLSCALE];
703 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLOFFSET];
705 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
706 checkGLcall("glUniform1fvARB");
707 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
708 checkGLcall("glUniform1fvARB");
712 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
713 float correction_params[4];
715 if (context->render_offscreen)
717 correction_params[0] = 0.0f;
718 correction_params[1] = 1.0f;
720 /* position is window relative, not viewport relative */
721 correction_params[0] = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
722 correction_params[1] = -1.0f;
724 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
728 if (priv->next_constant_version == UINT_MAX)
730 TRACE("Max constant version reached, resetting to 0.\n");
731 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
732 priv->next_constant_version = 1;
736 prog->constant_version = priv->next_constant_version++;
740 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
741 unsigned int heap_idx, DWORD new_version)
743 struct constant_entry *entries = heap->entries;
744 unsigned int *positions = heap->positions;
745 unsigned int parent_idx;
749 parent_idx = heap_idx >> 1;
751 if (new_version <= entries[parent_idx].version) break;
753 entries[heap_idx] = entries[parent_idx];
754 positions[entries[parent_idx].idx] = heap_idx;
755 heap_idx = parent_idx;
758 entries[heap_idx].version = new_version;
759 entries[heap_idx].idx = idx;
760 positions[idx] = heap_idx;
763 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
765 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
766 struct shader_glsl_priv *priv = This->shader_priv;
767 struct constant_heap *heap = &priv->vconst_heap;
770 for (i = start; i < count + start; ++i)
772 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
773 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
775 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
779 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
781 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
782 struct shader_glsl_priv *priv = This->shader_priv;
783 struct constant_heap *heap = &priv->pconst_heap;
786 for (i = start; i < count + start; ++i)
788 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
789 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
791 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
795 static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
797 unsigned int ret = gl_info->max_glsl_varyings / 4;
798 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
799 if(shader_major > 3) return ret;
801 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
802 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
806 /** Generate the variable & register declarations for the GLSL output target */
807 static void shader_generate_glsl_declarations(const struct wined3d_context *context,
808 struct wined3d_shader_buffer *buffer, IWineD3DBaseShader *iface,
809 const shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
811 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
812 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
813 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
814 const struct wined3d_gl_info *gl_info = context->gl_info;
815 unsigned int i, extra_constants_needed = 0;
816 const local_constant *lconst;
819 /* There are some minor differences between pixel and vertex shaders */
820 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
821 char prefix = pshader ? 'P' : 'V';
823 /* Prototype the subroutines */
824 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
826 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
829 /* Declare the constants (aka uniforms) */
830 if (This->baseShader.limits.constant_float > 0) {
831 unsigned max_constantsF;
832 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
833 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
834 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
835 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
836 * a dx9 card, as long as it doesn't also use all the other constants.
838 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
839 * declare only the amount that we're assured to have.
841 * Thus we run into problems in these two cases:
842 * 1) The shader really uses more uniforms than supported
843 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
846 /* No indirect addressing here */
847 max_constantsF = gl_info->max_ps_glsl_constantsF;
851 if(This->baseShader.reg_maps.usesrelconstF) {
852 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
853 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
854 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
855 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
857 * Writing gl_ClipPos requires one uniform for each clipplane as well.
859 max_constantsF = gl_info->max_vs_glsl_constantsF - 3 - gl_info->max_clipplanes;
860 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
861 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
862 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
863 * for now take this into account when calculating the number of available constants
865 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
866 /* Set by driver quirks in directx.c */
867 max_constantsF -= gl_info->reserved_glsl_constants;
871 max_constantsF = gl_info->max_vs_glsl_constantsF;
874 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
875 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
878 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
879 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
881 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
882 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
884 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
885 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
888 shader_addline(buffer, "uniform vec4 posFixup;\n");
889 /* Predeclaration; This function is added at link time based on the pixel shader.
890 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
891 * that. We know the input to the reorder function at vertex shader compile time, so
892 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
893 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
894 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
895 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
896 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
899 if (reg_maps->shader_version.major >= 3)
901 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
903 shader_addline(buffer, "void order_ps_input();\n");
906 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
908 if (!(map & 1)) continue;
910 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
912 if (reg_maps->luminanceparams & (1 << i))
914 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
915 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
916 extra_constants_needed++;
919 extra_constants_needed++;
922 if (ps_args->srgb_correction)
924 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
925 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
926 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
929 if (reg_maps->vpos || reg_maps->usesdsy)
931 if (This->baseShader.limits.constant_float + extra_constants_needed + 1 < gl_info->max_ps_glsl_constantsF)
933 shader_addline(buffer, "uniform vec4 ycorrection;\n");
934 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
935 extra_constants_needed++;
937 /* This happens because we do not have proper tracking of the constant registers that are
938 * actually used, only the max limit of the shader version
940 FIXME("Cannot find a free uniform for vpos correction params\n");
941 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
942 context->render_offscreen ? 0.0f : ((IWineD3DSurfaceImpl *)device->render_targets[0])->currentDesc.Height,
943 context->render_offscreen ? 1.0f : -1.0f);
945 shader_addline(buffer, "vec4 vpos;\n");
949 /* Declare texture samplers */
950 for (i = 0; i < This->baseShader.limits.sampler; i++) {
951 if (reg_maps->sampler_type[i])
953 switch (reg_maps->sampler_type[i])
956 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
959 if(device->stateBlock->textures[i] &&
960 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
961 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
963 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
966 case WINED3DSTT_CUBE:
967 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
969 case WINED3DSTT_VOLUME:
970 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
973 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
974 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
980 /* Declare uniforms for NP2 texcoord fixup:
981 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
982 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
983 * Modern cards just skip the code anyway, so put it inside a separate loop. */
984 if (pshader && ps_args->np2_fixup) {
986 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
989 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
990 * while D3D has them in the (normalized) [0,1]x[0,1] range.
991 * samplerNP2Fixup stores texture dimensions and is updated through
992 * shader_glsl_load_np2fixup_constants when the sampler changes. */
994 for (i = 0; i < This->baseShader.limits.sampler; ++i) {
995 if (reg_maps->sampler_type[i]) {
996 if (!(ps_args->np2_fixup & (1 << i))) continue;
998 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
999 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1003 fixup->idx[i] = cur++;
1007 fixup->num_consts = (cur + 1) >> 1;
1008 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1011 /* Declare address variables */
1012 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1014 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1017 /* Declare texture coordinate temporaries and initialize them */
1018 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1020 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1023 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1024 * helper function shader that is linked in at link time
1026 if (pshader && reg_maps->shader_version.major >= 3)
1028 if (use_vs(device->stateBlock))
1030 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1032 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1033 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1034 * pixel shader that reads the fixed function color into the packed input registers.
1036 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1040 /* Declare output register temporaries */
1041 if(This->baseShader.limits.packed_output) {
1042 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
1045 /* Declare temporary variables */
1046 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1048 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1051 /* Declare attributes */
1052 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1054 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1056 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1060 /* Declare loop registers aLx */
1061 for (i = 0; i < reg_maps->loop_depth; i++) {
1062 shader_addline(buffer, "int aL%u;\n", i);
1063 shader_addline(buffer, "int tmpInt%u;\n", i);
1066 /* Temporary variables for matrix operations */
1067 shader_addline(buffer, "vec4 tmp0;\n");
1068 shader_addline(buffer, "vec4 tmp1;\n");
1070 /* Local constants use a different name so they can be loaded once at shader link time
1071 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1072 * float -> string conversion can cause precision loss.
1074 if(!This->baseShader.load_local_constsF) {
1075 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1076 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1080 /* Start the main program */
1081 shader_addline(buffer, "void main() {\n");
1082 if(pshader && reg_maps->vpos) {
1083 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1084 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1085 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1086 * precision troubles when we just substract 0.5.
1088 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1090 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1092 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1093 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1094 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1095 * correctly on drivers that returns integer values.
1097 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1101 /*****************************************************************************
1102 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1104 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1105 ****************************************************************************/
1108 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1109 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1111 /** Used for opcode modifiers - They multiply the result by the specified amount */
1112 static const char * const shift_glsl_tab[] = {
1114 "2.0 * ", /* 1 (x2) */
1115 "4.0 * ", /* 2 (x4) */
1116 "8.0 * ", /* 3 (x8) */
1117 "16.0 * ", /* 4 (x16) */
1118 "32.0 * ", /* 5 (x32) */
1125 "0.0625 * ", /* 12 (d16) */
1126 "0.125 * ", /* 13 (d8) */
1127 "0.25 * ", /* 14 (d4) */
1128 "0.5 * " /* 15 (d2) */
1131 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1132 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1136 switch (src_modifier)
1138 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1139 case WINED3DSPSM_DW:
1140 case WINED3DSPSM_NONE:
1141 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1143 case WINED3DSPSM_NEG:
1144 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1146 case WINED3DSPSM_NOT:
1147 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1149 case WINED3DSPSM_BIAS:
1150 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1152 case WINED3DSPSM_BIASNEG:
1153 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1155 case WINED3DSPSM_SIGN:
1156 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1158 case WINED3DSPSM_SIGNNEG:
1159 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1161 case WINED3DSPSM_COMP:
1162 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1164 case WINED3DSPSM_X2:
1165 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1167 case WINED3DSPSM_X2NEG:
1168 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1170 case WINED3DSPSM_ABS:
1171 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1173 case WINED3DSPSM_ABSNEG:
1174 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1177 FIXME("Unhandled modifier %u\n", src_modifier);
1178 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1182 /** Writes the GLSL variable name that corresponds to the register that the
1183 * DX opcode parameter is trying to access */
1184 static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1185 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1187 /* oPos, oFog and oPts in D3D */
1188 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1190 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1191 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1192 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
1193 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1199 case WINED3DSPR_TEMP:
1200 sprintf(register_name, "R%u", reg->idx);
1203 case WINED3DSPR_INPUT:
1204 /* vertex shaders */
1207 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1208 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1209 sprintf(register_name, "attrib%u", reg->idx);
1213 /* pixel shaders >= 3.0 */
1214 if (This->baseShader.reg_maps.shader_version.major >= 3)
1216 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1217 unsigned int in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1221 glsl_src_param_t rel_param;
1223 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1225 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1226 * operation there */
1229 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1231 sprintf(register_name,
1232 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1233 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1234 rel_param.param_str, idx);
1238 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1243 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1245 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1246 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1247 rel_param.param_str);
1251 sprintf(register_name, "IN[%s]", rel_param.param_str);
1257 if (idx == in_count) sprintf(register_name, "gl_Color");
1258 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1259 else sprintf(register_name, "IN[%u]", idx);
1264 if (reg->idx == 0) strcpy(register_name, "gl_Color");
1265 else strcpy(register_name, "gl_SecondaryColor");
1270 case WINED3DSPR_CONST:
1272 const char prefix = pshader ? 'P' : 'V';
1274 /* Relative addressing */
1277 glsl_src_param_t rel_param;
1278 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1279 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1280 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1284 if (shader_constant_is_local(This, reg->idx))
1285 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1287 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1292 case WINED3DSPR_CONSTINT:
1293 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1294 else sprintf(register_name, "VI[%u]", reg->idx);
1297 case WINED3DSPR_CONSTBOOL:
1298 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1299 else sprintf(register_name, "VB[%u]", reg->idx);
1302 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1303 if (pshader) sprintf(register_name, "T%u", reg->idx);
1304 else sprintf(register_name, "A%u", reg->idx);
1307 case WINED3DSPR_LOOP:
1308 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1311 case WINED3DSPR_SAMPLER:
1312 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1313 else sprintf(register_name, "Vsampler%u", reg->idx);
1316 case WINED3DSPR_COLOROUT:
1317 if (reg->idx >= gl_info->max_buffers)
1318 WARN("Write to render target %u, only %d supported\n", reg->idx, gl_info->max_buffers);
1320 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1323 case WINED3DSPR_RASTOUT:
1324 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1327 case WINED3DSPR_DEPTHOUT:
1328 sprintf(register_name, "gl_FragDepth");
1331 case WINED3DSPR_ATTROUT:
1332 if (reg->idx == 0) sprintf(register_name, "gl_FrontColor");
1333 else sprintf(register_name, "gl_FrontSecondaryColor");
1336 case WINED3DSPR_TEXCRDOUT:
1337 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1338 if (This->baseShader.reg_maps.shader_version.major >= 3) sprintf(register_name, "OUT[%u]", reg->idx);
1339 else sprintf(register_name, "gl_TexCoord[%u]", reg->idx);
1342 case WINED3DSPR_MISCTYPE:
1346 sprintf(register_name, "vpos");
1348 else if (reg->idx == 1)
1350 /* Note that gl_FrontFacing is a bool, while vFace is
1351 * a float for which the sign determines front/back */
1352 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1356 FIXME("Unhandled misctype register %d\n", reg->idx);
1357 sprintf(register_name, "unrecognized_register");
1361 case WINED3DSPR_IMMCONST:
1362 switch (reg->immconst_type)
1364 case WINED3D_IMMCONST_FLOAT:
1365 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1368 case WINED3D_IMMCONST_FLOAT4:
1369 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1370 *(const float *)®->immconst_data[0], *(const float *)®->immconst_data[1],
1371 *(const float *)®->immconst_data[2], *(const float *)®->immconst_data[3]);
1375 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1376 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1381 FIXME("Unhandled register name Type(%d)\n", reg->type);
1382 sprintf(register_name, "unrecognized_register");
1387 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1390 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1391 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1392 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1393 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1397 /* Get the GLSL write mask for the destination register */
1398 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1400 DWORD mask = param->write_mask;
1402 if (shader_is_scalar(¶m->reg))
1404 mask = WINED3DSP_WRITEMASK_0;
1409 shader_glsl_write_mask_to_str(mask, write_mask);
1415 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1416 unsigned int size = 0;
1418 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1419 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1420 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1421 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1426 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1428 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1429 * but addressed as "rgba". To fix this we need to swap the register's x
1430 * and z components. */
1431 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1434 /* swizzle bits fields: wwzzyyxx */
1435 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1436 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1437 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1438 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1442 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1443 BOOL fixup, DWORD mask, char *swizzle_str)
1445 if (shader_is_scalar(¶m->reg))
1446 *swizzle_str = '\0';
1448 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1451 /* From a given parameter token, generate the corresponding GLSL string.
1452 * Also, return the actual register name and swizzle in case the
1453 * caller needs this information as well. */
1454 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1455 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1457 BOOL is_color = FALSE;
1458 char swizzle_str[6];
1460 glsl_src->reg_name[0] = '\0';
1461 glsl_src->param_str[0] = '\0';
1462 swizzle_str[0] = '\0';
1464 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1465 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1466 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1469 /* From a given parameter token, generate the corresponding GLSL string.
1470 * Also, return the actual register name and swizzle in case the
1471 * caller needs this information as well. */
1472 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1473 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1475 BOOL is_color = FALSE;
1477 glsl_dst->mask_str[0] = '\0';
1478 glsl_dst->reg_name[0] = '\0';
1480 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1481 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1484 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1485 static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1486 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1488 glsl_dst_param_t glsl_dst;
1491 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1492 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1497 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1498 static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1500 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1503 /** Process GLSL instruction modifiers */
1504 static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1506 glsl_dst_param_t dst_param;
1509 if (!ins->dst_count) return;
1511 modifiers = ins->dst[0].modifiers;
1512 if (!modifiers) return;
1514 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1516 if (modifiers & WINED3DSPDM_SATURATE)
1518 /* _SAT means to clamp the value of the register to between 0 and 1 */
1519 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1520 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1523 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1525 FIXME("_centroid modifier not handled\n");
1528 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1530 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1534 static inline const char *shader_get_comp_op(DWORD op)
1537 case COMPARISON_GT: return ">";
1538 case COMPARISON_EQ: return "==";
1539 case COMPARISON_GE: return ">=";
1540 case COMPARISON_LT: return "<";
1541 case COMPARISON_NE: return "!=";
1542 case COMPARISON_LE: return "<=";
1544 FIXME("Unrecognized comparison value: %u\n", op);
1549 static void shader_glsl_get_sample_function(DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1551 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1552 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1553 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1554 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1556 /* Note that there's no such thing as a projected cube texture. */
1557 switch(sampler_type) {
1560 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1562 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1564 sample_function->name = projected ? "texture1DProj" : "texture1D";
1566 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1571 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1573 /* What good are texrect grad functions? I don't know, but GL_EXT_gpu_shader4 defines them.
1574 * There is no GL_ARB_shader_texture_lod spec yet, so I don't know if they're defined there
1576 sample_function->name = projected ? "shadow2DRectProjGradARB" : "shadow2DRectGradARB";
1578 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1582 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1584 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1586 sample_function->name = projected ? "texture2DProj" : "texture2D";
1589 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1591 case WINED3DSTT_CUBE:
1593 sample_function->name = "textureCubeLod";
1595 sample_function->name = "textureCubeGradARB";
1597 sample_function->name = "textureCube";
1599 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1601 case WINED3DSTT_VOLUME:
1603 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1605 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1607 sample_function->name = projected ? "texture3DProj" : "texture3D";
1609 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1612 sample_function->name = "";
1613 sample_function->coord_mask = 0;
1614 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1619 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1620 BOOL sign_fixup, enum fixup_channel_source channel_source)
1622 switch(channel_source)
1624 case CHANNEL_SOURCE_ZERO:
1625 strcat(arguments, "0.0");
1628 case CHANNEL_SOURCE_ONE:
1629 strcat(arguments, "1.0");
1632 case CHANNEL_SOURCE_X:
1633 strcat(arguments, reg_name);
1634 strcat(arguments, ".x");
1637 case CHANNEL_SOURCE_Y:
1638 strcat(arguments, reg_name);
1639 strcat(arguments, ".y");
1642 case CHANNEL_SOURCE_Z:
1643 strcat(arguments, reg_name);
1644 strcat(arguments, ".z");
1647 case CHANNEL_SOURCE_W:
1648 strcat(arguments, reg_name);
1649 strcat(arguments, ".w");
1653 FIXME("Unhandled channel source %#x\n", channel_source);
1654 strcat(arguments, "undefined");
1658 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1661 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1663 struct wined3d_shader_dst_param dst;
1664 unsigned int mask_size, remaining;
1665 glsl_dst_param_t dst_param;
1666 char arguments[256];
1670 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1671 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1672 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1673 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1674 mask &= ins->dst[0].write_mask;
1676 if (!mask) return; /* Nothing to do */
1678 if (is_yuv_fixup(fixup))
1680 enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1681 FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1685 mask_size = shader_glsl_get_write_mask_size(mask);
1688 dst.write_mask = mask;
1689 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1691 arguments[0] = '\0';
1692 remaining = mask_size;
1693 if (mask & WINED3DSP_WRITEMASK_0)
1695 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1696 if (--remaining) strcat(arguments, ", ");
1698 if (mask & WINED3DSP_WRITEMASK_1)
1700 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1701 if (--remaining) strcat(arguments, ", ");
1703 if (mask & WINED3DSP_WRITEMASK_2)
1705 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1706 if (--remaining) strcat(arguments, ", ");
1708 if (mask & WINED3DSP_WRITEMASK_3)
1710 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1711 if (--remaining) strcat(arguments, ", ");
1716 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1717 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1721 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1725 static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
1726 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
1727 const char *dx, const char *dy,
1728 const char *bias, const char *coord_reg_fmt, ...)
1730 const char *sampler_base;
1731 char dst_swizzle[6];
1732 struct color_fixup_desc fixup;
1733 BOOL np2_fixup = FALSE;
1736 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
1738 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
1740 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1741 fixup = priv->cur_ps_args->color_fixup[sampler];
1742 sampler_base = "Psampler";
1744 if(priv->cur_ps_args->np2_fixup & (1 << sampler)) {
1746 FIXME("Biased sampling from NP2 textures is unsupported\n");
1752 sampler_base = "Vsampler";
1753 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
1756 shader_glsl_append_dst(ins->ctx->buffer, ins);
1758 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
1760 va_start(args, coord_reg_fmt);
1761 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
1765 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
1768 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1769 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
1771 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
1772 (idx % 2) ? "zw" : "xy", dst_swizzle);
1773 } else if(dx && dy) {
1774 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
1776 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
1780 if(!is_identity_fixup(fixup)) {
1781 shader_glsl_color_correction(ins, fixup);
1785 /*****************************************************************************
1786 * Begin processing individual instruction opcodes
1787 ****************************************************************************/
1789 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1790 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
1792 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1793 glsl_src_param_t src0_param;
1794 glsl_src_param_t src1_param;
1798 /* Determine the GLSL operator to use based on the opcode */
1799 switch (ins->handler_idx)
1801 case WINED3DSIH_MUL: op = '*'; break;
1802 case WINED3DSIH_ADD: op = '+'; break;
1803 case WINED3DSIH_SUB: op = '-'; break;
1806 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1810 write_mask = shader_glsl_append_dst(buffer, ins);
1811 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1812 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1813 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1816 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1817 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
1819 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1820 glsl_src_param_t src0_param;
1823 write_mask = shader_glsl_append_dst(buffer, ins);
1824 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1826 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1827 * shader versions WINED3DSIO_MOVA is used for this. */
1828 if (ins->ctx->reg_maps->shader_version.major == 1
1829 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
1830 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
1832 /* This is a simple floor() */
1833 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1834 if (mask_size > 1) {
1835 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1837 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1840 else if(ins->handler_idx == WINED3DSIH_MOVA)
1842 /* We need to *round* to the nearest int here. */
1843 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1844 if (mask_size > 1) {
1845 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n", mask_size, src0_param.param_str, mask_size, src0_param.param_str);
1847 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1850 shader_addline(buffer, "%s);\n", src0_param.param_str);
1854 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1855 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
1857 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1858 glsl_src_param_t src0_param;
1859 glsl_src_param_t src1_param;
1860 DWORD dst_write_mask, src_write_mask;
1861 unsigned int dst_size = 0;
1863 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1864 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1866 /* dp3 works on vec3, dp4 on vec4 */
1867 if (ins->handler_idx == WINED3DSIH_DP4)
1869 src_write_mask = WINED3DSP_WRITEMASK_ALL;
1871 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1874 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
1875 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
1878 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1880 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1884 /* Note that this instruction has some restrictions. The destination write mask
1885 * can't contain the w component, and the source swizzles have to be .xyzw */
1886 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
1888 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1889 glsl_src_param_t src0_param;
1890 glsl_src_param_t src1_param;
1893 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1894 shader_glsl_append_dst(ins->ctx->buffer, ins);
1895 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
1896 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
1897 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1900 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1901 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1902 * GLSL uses the value as-is. */
1903 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
1905 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1906 glsl_src_param_t src0_param;
1907 glsl_src_param_t src1_param;
1908 DWORD dst_write_mask;
1909 unsigned int dst_size;
1911 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1912 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1914 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1915 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
1918 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1920 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1924 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
1925 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
1926 * GLSL uses the value as-is. */
1927 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
1929 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1930 glsl_src_param_t src0_param;
1931 DWORD dst_write_mask;
1932 unsigned int dst_size;
1934 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1935 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1937 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1940 shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
1942 shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
1946 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1947 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
1949 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
1950 glsl_src_param_t src_param;
1951 const char *instruction;
1955 /* Determine the GLSL function to use based on the opcode */
1956 /* TODO: Possibly make this a table for faster lookups */
1957 switch (ins->handler_idx)
1959 case WINED3DSIH_MIN: instruction = "min"; break;
1960 case WINED3DSIH_MAX: instruction = "max"; break;
1961 case WINED3DSIH_ABS: instruction = "abs"; break;
1962 case WINED3DSIH_FRC: instruction = "fract"; break;
1963 case WINED3DSIH_NRM: instruction = "normalize"; break;
1964 case WINED3DSIH_EXP: instruction = "exp2"; break;
1965 case WINED3DSIH_DSX: instruction = "dFdx"; break;
1966 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
1967 default: instruction = "";
1968 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1972 write_mask = shader_glsl_append_dst(buffer, ins);
1974 shader_addline(buffer, "%s(", instruction);
1978 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
1979 shader_addline(buffer, "%s", src_param.param_str);
1980 for (i = 1; i < ins->src_count; ++i)
1982 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
1983 shader_addline(buffer, ", %s", src_param.param_str);
1987 shader_addline(buffer, "));\n");
1990 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1991 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1992 * dst.x = 2^(floor(src))
1993 * dst.y = src - floor(src)
1994 * dst.z = 2^src (partial precision is allowed, but optional)
1996 * For 2.0 shaders, just do this (honoring writemask and swizzle):
1997 * dst = 2^src; (partial precision is allowed, but optional)
1999 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2001 glsl_src_param_t src_param;
2003 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2005 if (ins->ctx->reg_maps->shader_version.major < 2)
2009 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2010 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2011 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2012 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2014 shader_glsl_append_dst(ins->ctx->buffer, ins);
2015 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2016 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2019 unsigned int mask_size;
2021 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2022 mask_size = shader_glsl_get_write_mask_size(write_mask);
2024 if (mask_size > 1) {
2025 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2027 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2032 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2033 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2035 glsl_src_param_t src_param;
2037 unsigned int mask_size;
2039 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2040 mask_size = shader_glsl_get_write_mask_size(write_mask);
2041 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2043 if (mask_size > 1) {
2044 shader_addline(ins->ctx->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
2046 shader_addline(ins->ctx->buffer, "1.0 / %s);\n", src_param.param_str);
2050 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2052 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2053 glsl_src_param_t src_param;
2055 unsigned int mask_size;
2057 write_mask = shader_glsl_append_dst(buffer, ins);
2058 mask_size = shader_glsl_get_write_mask_size(write_mask);
2060 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2062 if (mask_size > 1) {
2063 shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
2065 shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
2069 /** Process signed comparison opcodes in GLSL. */
2070 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2072 glsl_src_param_t src0_param;
2073 glsl_src_param_t src1_param;
2075 unsigned int mask_size;
2077 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2078 mask_size = shader_glsl_get_write_mask_size(write_mask);
2079 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2080 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2082 if (mask_size > 1) {
2083 const char *compare;
2085 switch(ins->handler_idx)
2087 case WINED3DSIH_SLT: compare = "lessThan"; break;
2088 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2089 default: compare = "";
2090 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2093 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2094 src0_param.param_str, src1_param.param_str);
2096 switch(ins->handler_idx)
2098 case WINED3DSIH_SLT:
2099 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2100 * to return 0.0 but step returns 1.0 because step is not < x
2101 * An alternative is a bvec compare padded with an unused second component.
2102 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2103 * issue. Playing with not() is not possible either because not() does not accept
2106 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2107 src0_param.param_str, src1_param.param_str);
2109 case WINED3DSIH_SGE:
2110 /* Here we can use the step() function and safe a conditional */
2111 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2114 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2120 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2121 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2123 glsl_src_param_t src0_param;
2124 glsl_src_param_t src1_param;
2125 glsl_src_param_t src2_param;
2126 DWORD write_mask, cmp_channel = 0;
2129 BOOL temp_destination = FALSE;
2131 if (shader_is_scalar(&ins->src[0].reg))
2133 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2135 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2136 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2137 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2139 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2140 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2142 DWORD dst_mask = ins->dst[0].write_mask;
2143 struct wined3d_shader_dst_param dst = ins->dst[0];
2145 /* Cycle through all source0 channels */
2146 for (i=0; i<4; i++) {
2148 /* Find the destination channels which use the current source0 channel */
2149 for (j=0; j<4; j++) {
2150 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2152 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2153 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2156 dst.write_mask = dst_mask & write_mask;
2158 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2159 * The first lines may overwrite source parameters of the following lines.
2160 * Deal with that by using a temporary destination register if needed
2162 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2163 && ins->src[0].reg.type == ins->dst[0].reg.type)
2164 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2165 && ins->src[1].reg.type == ins->dst[0].reg.type)
2166 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2167 && ins->src[2].reg.type == ins->dst[0].reg.type))
2169 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2170 if (!write_mask) continue;
2171 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2172 temp_destination = TRUE;
2174 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2175 if (!write_mask) continue;
2178 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2179 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2180 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2182 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2183 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2186 if(temp_destination) {
2187 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2188 shader_glsl_append_dst(ins->ctx->buffer, ins);
2189 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2195 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2196 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2197 * the compare is done per component of src0. */
2198 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2200 struct wined3d_shader_dst_param dst;
2201 glsl_src_param_t src0_param;
2202 glsl_src_param_t src1_param;
2203 glsl_src_param_t src2_param;
2204 DWORD write_mask, cmp_channel = 0;
2207 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2208 ins->ctx->reg_maps->shader_version.minor);
2210 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2212 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2213 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2214 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2215 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2217 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2220 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2222 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2223 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2227 /* Cycle through all source0 channels */
2228 dst_mask = ins->dst[0].write_mask;
2230 for (i=0; i<4; i++) {
2232 /* Find the destination channels which use the current source0 channel */
2233 for (j=0; j<4; j++) {
2234 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2236 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2237 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2241 dst.write_mask = dst_mask & write_mask;
2242 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2243 if (!write_mask) continue;
2245 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2246 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2247 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2249 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2250 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2254 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2255 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2257 glsl_src_param_t src0_param;
2258 glsl_src_param_t src1_param;
2259 glsl_src_param_t src2_param;
2262 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2263 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2264 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2265 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2266 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2267 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2270 /* Handles transforming all WINED3DSIO_M?x? opcodes for
2271 Vertex shaders to GLSL codes */
2272 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2275 int nComponents = 0;
2276 struct wined3d_shader_dst_param tmp_dst = {{0}};
2277 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2278 struct wined3d_shader_instruction tmp_ins;
2280 memset(&tmp_ins, 0, sizeof(tmp_ins));
2282 /* Set constants for the temporary argument */
2283 tmp_ins.ctx = ins->ctx;
2284 tmp_ins.dst_count = 1;
2285 tmp_ins.dst = &tmp_dst;
2286 tmp_ins.src_count = 2;
2287 tmp_ins.src = tmp_src;
2289 switch(ins->handler_idx)
2291 case WINED3DSIH_M4x4:
2293 tmp_ins.handler_idx = WINED3DSIH_DP4;
2295 case WINED3DSIH_M4x3:
2297 tmp_ins.handler_idx = WINED3DSIH_DP4;
2299 case WINED3DSIH_M3x4:
2301 tmp_ins.handler_idx = WINED3DSIH_DP3;
2303 case WINED3DSIH_M3x3:
2305 tmp_ins.handler_idx = WINED3DSIH_DP3;
2307 case WINED3DSIH_M3x2:
2309 tmp_ins.handler_idx = WINED3DSIH_DP3;
2315 tmp_dst = ins->dst[0];
2316 tmp_src[0] = ins->src[0];
2317 tmp_src[1] = ins->src[1];
2318 for (i = 0; i < nComponents; ++i)
2320 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2321 shader_glsl_dot(&tmp_ins);
2322 ++tmp_src[1].reg.idx;
2327 The LRP instruction performs a component-wise linear interpolation
2328 between the second and third operands using the first operand as the
2329 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2330 This is equivalent to mix(src2, src1, src0);
2332 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2334 glsl_src_param_t src0_param;
2335 glsl_src_param_t src1_param;
2336 glsl_src_param_t src2_param;
2339 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2341 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2342 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2343 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2345 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2346 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2349 /** Process the WINED3DSIO_LIT instruction in GLSL:
2350 * dst.x = dst.w = 1.0
2351 * dst.y = (src0.x > 0) ? src0.x
2352 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2353 * where src.w is clamped at +- 128
2355 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2357 glsl_src_param_t src0_param;
2358 glsl_src_param_t src1_param;
2359 glsl_src_param_t src3_param;
2362 shader_glsl_append_dst(ins->ctx->buffer, ins);
2363 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2365 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2366 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2367 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2369 /* The sdk specifies the instruction like this
2371 * if(src.x > 0.0) dst.y = src.x
2373 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2377 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2378 * dst.x = 1.0 ... No further explanation needed
2379 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2380 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2381 * dst.w = 1.0. ... Nothing fancy.
2383 * So we still have one conditional in there. So do this:
2384 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2386 * 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),
2387 * 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.
2388 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2390 shader_addline(ins->ctx->buffer,
2391 "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",
2392 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2395 /** Process the WINED3DSIO_DST instruction in GLSL:
2397 * dst.y = src0.x * src0.y
2401 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2403 glsl_src_param_t src0y_param;
2404 glsl_src_param_t src0z_param;
2405 glsl_src_param_t src1y_param;
2406 glsl_src_param_t src1w_param;
2409 shader_glsl_append_dst(ins->ctx->buffer, ins);
2410 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2412 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2413 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2414 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2415 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2417 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2418 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2421 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2422 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2423 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2425 * dst.x = cos(src0.?)
2426 * dst.y = sin(src0.?)
2430 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2432 glsl_src_param_t src0_param;
2435 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2436 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2438 switch (write_mask) {
2439 case WINED3DSP_WRITEMASK_0:
2440 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2443 case WINED3DSP_WRITEMASK_1:
2444 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2447 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2448 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2452 ERR("Write mask should be .x, .y or .xy\n");
2457 /* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2458 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2459 * generate invalid code
2461 static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2463 glsl_src_param_t src0_param;
2466 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2467 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2469 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2472 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2473 * Start a for() loop where src1.y is the initial value of aL,
2474 * increment aL by src1.z for a total of src1.x iterations.
2475 * Need to use a temporary variable for this operation.
2477 /* FIXME: I don't think nested loops will work correctly this way. */
2478 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2480 glsl_src_param_t src1_param;
2481 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2482 const DWORD *control_values = NULL;
2483 const local_constant *constant;
2485 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2487 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2488 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2489 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2492 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
2494 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2495 if (constant->idx == ins->src[1].reg.idx)
2497 control_values = constant->value;
2505 struct wined3d_shader_loop_control loop_control;
2506 loop_control.count = control_values[0];
2507 loop_control.start = control_values[1];
2508 loop_control.step = (int)control_values[2];
2510 if (loop_control.step > 0)
2512 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
2513 shader->baseShader.cur_loop_depth, loop_control.start,
2514 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2515 shader->baseShader.cur_loop_depth, loop_control.step);
2517 else if (loop_control.step < 0)
2519 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
2520 shader->baseShader.cur_loop_depth, loop_control.start,
2521 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
2522 shader->baseShader.cur_loop_depth, loop_control.step);
2526 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
2527 shader->baseShader.cur_loop_depth, loop_control.start, shader->baseShader.cur_loop_depth,
2528 shader->baseShader.cur_loop_depth, loop_control.count,
2529 shader->baseShader.cur_loop_depth);
2532 shader_addline(ins->ctx->buffer,
2533 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2534 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2535 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2536 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2539 shader->baseShader.cur_loop_depth++;
2540 shader->baseShader.cur_loop_regno++;
2543 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2545 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2547 shader_addline(ins->ctx->buffer, "}\n");
2549 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2551 shader->baseShader.cur_loop_depth--;
2552 shader->baseShader.cur_loop_regno--;
2555 if (ins->handler_idx == WINED3DSIH_ENDREP)
2557 shader->baseShader.cur_loop_depth--;
2561 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2563 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2564 glsl_src_param_t src0_param;
2565 const DWORD *control_values = NULL;
2566 const local_constant *constant;
2568 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2569 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
2571 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
2573 if (constant->idx == ins->src[0].reg.idx)
2575 control_values = constant->value;
2581 if(control_values) {
2582 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2583 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2584 control_values[0], shader->baseShader.cur_loop_depth);
2586 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2587 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2588 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2589 src0_param.param_str, shader->baseShader.cur_loop_depth);
2591 shader->baseShader.cur_loop_depth++;
2594 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2596 glsl_src_param_t src0_param;
2598 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2599 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2602 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2604 glsl_src_param_t src0_param;
2605 glsl_src_param_t src1_param;
2607 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2608 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2610 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2611 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2614 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2616 shader_addline(ins->ctx->buffer, "} else {\n");
2619 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2621 shader_addline(ins->ctx->buffer, "break;\n");
2624 /* FIXME: According to MSDN the compare is done per component. */
2625 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2627 glsl_src_param_t src0_param;
2628 glsl_src_param_t src1_param;
2630 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2631 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2633 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2634 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2637 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2639 shader_addline(ins->ctx->buffer, "}\n");
2640 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
2643 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2645 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
2648 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2650 glsl_src_param_t src1_param;
2652 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2653 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
2656 static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
2658 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
2659 * function only suppresses the unhandled instruction warning
2663 /*********************************************
2664 * Pixel Shader Specific Code begins here
2665 ********************************************/
2666 static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
2668 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2669 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2670 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2671 ins->ctx->reg_maps->shader_version.minor);
2672 glsl_sample_function_t sample_function;
2673 DWORD sample_flags = 0;
2674 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
2676 DWORD mask = 0, swizzle;
2678 /* 1.0-1.4: Use destination register as sampler source.
2679 * 2.0+: Use provided sampler source. */
2680 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
2681 else sampler_idx = ins->src[1].reg.idx;
2682 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2684 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2686 DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2688 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
2689 if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
2690 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2691 switch (flags & ~WINED3DTTFF_PROJECTED) {
2692 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2693 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2694 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2695 case WINED3DTTFF_COUNT4:
2696 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2700 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
2702 DWORD src_mod = ins->src[0].modifiers;
2704 if (src_mod == WINED3DSPSM_DZ) {
2705 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2706 mask = WINED3DSP_WRITEMASK_2;
2707 } else if (src_mod == WINED3DSPSM_DW) {
2708 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2709 mask = WINED3DSP_WRITEMASK_3;
2712 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
2714 /* ps 2.0 texldp instruction always divides by the fourth component. */
2715 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2716 mask = WINED3DSP_WRITEMASK_3;
2720 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2721 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2722 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2725 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2726 mask |= sample_function.coord_mask;
2728 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
2729 else swizzle = ins->src[1].swizzle;
2731 /* 1.0-1.3: Use destination register as coordinate source.
2732 1.4+: Use provided coordinate source register. */
2733 if (shader_version < WINED3D_SHADER_VERSION(1,4))
2736 shader_glsl_write_mask_to_str(mask, coord_mask);
2737 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2738 "T%u%s", sampler_idx, coord_mask);
2740 glsl_src_param_t coord_param;
2741 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
2742 if (ins->flags & WINED3DSI_TEXLD_BIAS)
2744 glsl_src_param_t bias;
2745 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
2746 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
2747 "%s", coord_param.param_str);
2749 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
2750 "%s", coord_param.param_str);
2755 static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
2757 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2758 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2759 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
2760 glsl_sample_function_t sample_function;
2761 glsl_src_param_t coord_param, dx_param, dy_param;
2762 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
2765 DWORD swizzle = ins->src[1].swizzle;
2767 if(!GL_SUPPORT(ARB_SHADER_TEXTURE_LOD)) {
2768 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
2769 return shader_glsl_tex(ins);
2772 sampler_idx = ins->src[1].reg.idx;
2773 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2774 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2775 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2776 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2779 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2780 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2781 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
2782 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
2784 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
2785 "%s", coord_param.param_str);
2788 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
2790 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2791 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2792 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
2793 glsl_sample_function_t sample_function;
2794 glsl_src_param_t coord_param, lod_param;
2795 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
2798 DWORD swizzle = ins->src[1].swizzle;
2800 sampler_idx = ins->src[1].reg.idx;
2801 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2802 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2803 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2804 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2806 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2807 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2809 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
2811 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD]
2812 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2814 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2815 * However, they seem to work just fine in fragment shaders as well. */
2816 WARN("Using %s in fragment shader.\n", sample_function.name);
2818 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
2819 "%s", coord_param.param_str);
2822 static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
2824 /* FIXME: Make this work for more than just 2D textures */
2825 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2826 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2828 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
2832 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2833 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
2834 ins->dst[0].reg.idx, dst_mask);
2836 DWORD reg = ins->src[0].reg.idx;
2837 DWORD src_mod = ins->src[0].modifiers;
2838 char dst_swizzle[6];
2840 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
2842 if (src_mod == WINED3DSPSM_DZ) {
2843 glsl_src_param_t div_param;
2844 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2845 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
2847 if (mask_size > 1) {
2848 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2850 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2852 } else if (src_mod == WINED3DSPSM_DW) {
2853 glsl_src_param_t div_param;
2854 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2855 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
2857 if (mask_size > 1) {
2858 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2860 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2863 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
2868 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2869 * Take a 3-component dot product of the TexCoord[dstreg] and src,
2870 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2871 static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
2873 glsl_src_param_t src0_param;
2874 glsl_sample_function_t sample_function;
2875 DWORD sampler_idx = ins->dst[0].reg.idx;
2876 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2877 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2880 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2882 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2883 * scalar, and projected sampling would require 4.
2885 * It is a dependent read - not valid with conditional NP2 textures
2887 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2888 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
2893 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2894 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
2898 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2899 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
2903 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
2904 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
2908 FIXME("Unexpected mask size %u\n", mask_size);
2913 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2914 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2915 static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
2917 glsl_src_param_t src0_param;
2918 DWORD dstreg = ins->dst[0].reg.idx;
2919 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2921 unsigned int mask_size;
2923 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2924 mask_size = shader_glsl_get_write_mask_size(dst_mask);
2925 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2927 if (mask_size > 1) {
2928 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2930 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2934 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2935 * Calculate the depth as dst.x / dst.y */
2936 static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
2938 glsl_dst_param_t dst_param;
2940 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
2942 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
2943 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2944 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
2945 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2948 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
2949 dst_param.reg_name, dst_param.reg_name);
2952 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2953 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2954 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
2955 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2957 static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
2959 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2960 DWORD dstreg = ins->dst[0].reg.idx;
2961 glsl_src_param_t src0_param;
2963 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2965 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2966 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2969 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2970 * Calculate the 1st of a 2-row matrix multiplication. */
2971 static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
2973 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2974 DWORD reg = ins->dst[0].reg.idx;
2975 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2976 glsl_src_param_t src0_param;
2978 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2979 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2982 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
2983 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
2984 static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
2986 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2987 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2988 DWORD reg = ins->dst[0].reg.idx;
2989 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2990 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2991 glsl_src_param_t src0_param;
2993 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2994 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
2995 current_state->texcoord_w[current_state->current_row++] = reg;
2998 static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3000 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3001 DWORD reg = ins->dst[0].reg.idx;
3002 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3003 glsl_src_param_t src0_param;
3004 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3005 glsl_sample_function_t sample_function;
3007 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3008 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3010 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3012 /* Sample the texture using the calculated coordinates */
3013 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3016 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3017 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3018 static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3020 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3021 glsl_src_param_t src0_param;
3022 DWORD reg = ins->dst[0].reg.idx;
3023 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3024 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
3025 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3026 glsl_sample_function_t sample_function;
3028 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3029 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3031 /* Dependent read, not valid with conditional NP2 */
3032 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3034 /* Sample the texture using the calculated coordinates */
3035 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3037 current_state->current_row = 0;
3040 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3041 * Perform the 3rd row of a 3x3 matrix multiply */
3042 static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3044 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3045 glsl_src_param_t src0_param;
3047 DWORD reg = ins->dst[0].reg.idx;
3048 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3049 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
3051 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3053 shader_glsl_append_dst(ins->ctx->buffer, ins);
3054 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3055 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3057 current_state->current_row = 0;
3060 /* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3061 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3062 static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3064 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3065 DWORD reg = ins->dst[0].reg.idx;
3066 glsl_src_param_t src0_param;
3067 glsl_src_param_t src1_param;
3068 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3069 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3070 WINED3DSAMPLER_TEXTURE_TYPE stype = ins->ctx->reg_maps->sampler_type[reg];
3071 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3072 glsl_sample_function_t sample_function;
3074 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3075 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3077 /* Perform the last matrix multiply operation */
3078 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3079 /* Reflection calculation */
3080 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3082 /* Dependent read, not valid with conditional NP2 */
3083 shader_glsl_get_sample_function(stype, 0, &sample_function);
3085 /* Sample the texture */
3086 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3088 current_state->current_row = 0;
3091 /* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3092 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3093 static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3095 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3096 DWORD reg = ins->dst[0].reg.idx;
3097 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3098 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3099 glsl_src_param_t src0_param;
3100 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3101 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3102 glsl_sample_function_t sample_function;
3104 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3106 /* Perform the last matrix multiply operation */
3107 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3109 /* Construct the eye-ray vector from w coordinates */
3110 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3111 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
3112 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3114 /* Dependent read, not valid with conditional NP2 */
3115 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3117 /* Sample the texture using the calculated coordinates */
3118 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3120 current_state->current_row = 0;
3123 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3124 * Apply a fake bump map transform.
3125 * texbem is pshader <= 1.3 only, this saves a few version checks
3127 static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3129 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
3130 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3131 glsl_sample_function_t sample_function;
3132 glsl_src_param_t coord_param;
3133 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
3139 sampler_idx = ins->dst[0].reg.idx;
3140 flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
3142 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3143 /* Dependent read, not valid with conditional NP2 */
3144 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3145 mask = sample_function.coord_mask;
3147 shader_glsl_write_mask_to_str(mask, coord_mask);
3149 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3150 * so we can't let the GL handle this.
3152 if (flags & WINED3DTTFF_PROJECTED) {
3154 char coord_div_mask[3];
3155 switch (flags & ~WINED3DTTFF_PROJECTED) {
3156 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3157 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3158 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3159 case WINED3DTTFF_COUNT4:
3160 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3162 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3163 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3166 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3168 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3169 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3170 coord_param.param_str, coord_mask);
3172 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3174 glsl_src_param_t luminance_param;
3175 glsl_dst_param_t dst_param;
3177 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3178 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3180 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3181 dst_param.reg_name, dst_param.mask_str,
3182 luminance_param.param_str, sampler_idx, sampler_idx);
3186 static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3188 glsl_src_param_t src0_param, src1_param;
3189 DWORD sampler_idx = ins->dst[0].reg.idx;
3191 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3192 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3194 shader_glsl_append_dst(ins->ctx->buffer, ins);
3195 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3196 src0_param.param_str, sampler_idx, src1_param.param_str);
3199 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3200 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3201 static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3203 glsl_src_param_t src0_param;
3204 DWORD sampler_idx = ins->dst[0].reg.idx;
3205 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3206 glsl_sample_function_t sample_function;
3208 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3210 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3211 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3212 "%s.wx", src0_param.reg_name);
3215 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3216 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3217 static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3219 glsl_src_param_t src0_param;
3220 DWORD sampler_idx = ins->dst[0].reg.idx;
3221 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3222 glsl_sample_function_t sample_function;
3224 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3226 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3227 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3228 "%s.yz", src0_param.reg_name);
3231 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3232 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3233 static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3235 glsl_src_param_t src0_param;
3236 DWORD sampler_idx = ins->dst[0].reg.idx;
3237 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3238 glsl_sample_function_t sample_function;
3240 /* Dependent read, not valid with conditional NP2 */
3241 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
3242 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3244 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3245 "%s", src0_param.param_str);
3248 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3249 * If any of the first 3 components are < 0, discard this pixel */
3250 static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3252 glsl_dst_param_t dst_param;
3254 /* The argument is a destination parameter, and no writemasks are allowed */
3255 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3256 if (ins->ctx->reg_maps->shader_version.major >= 2)
3258 /* 2.0 shaders compare all 4 components in texkill */
3259 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3261 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3262 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3263 * 4 components are defined, only the first 3 are used
3265 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3269 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3270 * dst = dot2(src0, src1) + src2 */
3271 static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3273 glsl_src_param_t src0_param;
3274 glsl_src_param_t src1_param;
3275 glsl_src_param_t src2_param;
3277 unsigned int mask_size;
3279 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3280 mask_size = shader_glsl_get_write_mask_size(write_mask);
3282 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3283 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3284 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3286 if (mask_size > 1) {
3287 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3288 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3290 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3291 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3295 static void shader_glsl_input_pack(IWineD3DPixelShader *iface, struct wined3d_shader_buffer *buffer,
3296 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps,
3297 enum vertexprocessing_mode vertexprocessing)
3300 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3301 WORD map = reg_maps->input_registers;
3303 for (i = 0; map; map >>= 1, ++i)
3305 const char *semantic_name;
3310 if (!(map & 1)) continue;
3312 semantic_name = input_signature[i].semantic_name;
3313 semantic_idx = input_signature[i].semantic_idx;
3314 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3316 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3318 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3319 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3320 This->input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3322 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3323 This->input_reg_map[i], reg_mask, reg_mask);
3325 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3327 if (semantic_idx == 0)
3328 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3329 This->input_reg_map[i], reg_mask, reg_mask);
3330 else if (semantic_idx == 1)
3331 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3332 This->input_reg_map[i], reg_mask, reg_mask);
3334 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3335 This->input_reg_map[i], reg_mask, reg_mask);
3339 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3340 This->input_reg_map[i], reg_mask, reg_mask);
3345 /*********************************************
3346 * Vertex Shader Specific Code begins here
3347 ********************************************/
3349 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3350 glsl_program_key_t key;
3352 key.vshader = entry->vshader;
3353 key.pshader = entry->pshader;
3354 key.vs_args = entry->vs_args;
3355 key.ps_args = entry->ps_args;
3357 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3359 ERR("Failed to insert program entry.\n");
3363 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3364 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3365 struct ps_compile_args *ps_args) {
3366 struct wine_rb_entry *entry;
3367 glsl_program_key_t key;
3369 key.vshader = vshader;
3370 key.pshader = pshader;
3371 key.vs_args = *vs_args;
3372 key.ps_args = *ps_args;
3374 entry = wine_rb_get(&priv->program_lookup, &key);
3375 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3378 /* GL locking is done by the caller */
3379 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3380 struct glsl_shader_prog_link *entry)
3382 glsl_program_key_t key;
3384 key.vshader = entry->vshader;
3385 key.pshader = entry->pshader;
3386 key.vs_args = entry->vs_args;
3387 key.ps_args = entry->ps_args;
3388 wine_rb_remove(&priv->program_lookup, &key);
3390 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3391 if (entry->vshader) list_remove(&entry->vshader_entry);
3392 if (entry->pshader) list_remove(&entry->pshader_entry);
3393 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3394 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3395 HeapFree(GetProcessHeap(), 0, entry);
3398 static void handle_ps3_input(struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info, const DWORD *map,
3399 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3400 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3403 const char *semantic_name_in, *semantic_name_out;
3404 UINT semantic_idx_in, semantic_idx_out;
3407 unsigned int in_count = vec4_varyings(3, gl_info);
3408 char reg_mask[6], reg_mask_out[6];
3409 char destination[50];
3410 WORD input_map, output_map;
3412 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3414 if (!output_signature)
3416 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3417 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3418 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3421 input_map = reg_maps_in->input_registers;
3422 for (i = 0; input_map; input_map >>= 1, ++i)
3424 if (!(input_map & 1)) continue;
3427 if (in_idx >= (in_count + 2)) {
3428 FIXME("More input varyings declared than supported, expect issues\n");
3431 else if (map[i] == ~0U)
3433 /* Declared, but not read register */
3437 if (in_idx == in_count) {
3438 sprintf(destination, "gl_FrontColor");
3439 } else if (in_idx == in_count + 1) {
3440 sprintf(destination, "gl_FrontSecondaryColor");
3442 sprintf(destination, "IN[%u]", in_idx);
3445 semantic_name_in = input_signature[i].semantic_name;
3446 semantic_idx_in = input_signature[i].semantic_idx;
3447 set[map[i]] = input_signature[i].mask;
3448 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3450 if (!output_signature)
3452 if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_COLOR))
3454 if (semantic_idx_in == 0)
3455 shader_addline(buffer, "%s%s = front_color%s;\n",
3456 destination, reg_mask, reg_mask);
3457 else if (semantic_idx_in == 1)
3458 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3459 destination, reg_mask, reg_mask);
3461 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3462 destination, reg_mask, reg_mask);
3464 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_TEXCOORD))
3466 if (semantic_idx_in < 8)
3468 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3469 destination, reg_mask, semantic_idx_in, reg_mask);
3473 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3474 destination, reg_mask, reg_mask);
3477 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_FOG))
3479 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3480 destination, reg_mask, reg_mask);
3484 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3485 destination, reg_mask, reg_mask);
3490 output_map = reg_maps_out->output_registers;
3491 for (j = 0; output_map; output_map >>= 1, ++j)
3493 if (!(output_map & 1)) continue;
3495 semantic_name_out = output_signature[j].semantic_name;
3496 semantic_idx_out = output_signature[j].semantic_idx;
3497 shader_glsl_write_mask_to_str(output_signature[j].mask, reg_mask_out);
3499 if (semantic_idx_in == semantic_idx_out
3500 && !strcmp(semantic_name_in, semantic_name_out))
3502 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3503 destination, reg_mask, j, reg_mask);
3508 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3509 destination, reg_mask, reg_mask);
3514 /* This is solely to make the compiler / linker happy and avoid warning about undefined
3515 * varyings. It shouldn't result in any real code executed on the GPU, since all read
3516 * input varyings are assigned above, if the optimizer works properly.
3518 for(i = 0; i < in_count + 2; i++) {
3519 if (set[i] && set[i] != WINED3DSP_WRITEMASK_ALL)
3521 unsigned int size = 0;
3522 memset(reg_mask, 0, sizeof(reg_mask));
3523 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3524 reg_mask[size] = 'x';
3527 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3528 reg_mask[size] = 'y';
3531 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3532 reg_mask[size] = 'z';
3535 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3536 reg_mask[size] = 'w';
3540 if (i == in_count) {
3541 sprintf(destination, "gl_FrontColor");
3542 } else if (i == in_count + 1) {
3543 sprintf(destination, "gl_FrontSecondaryColor");
3545 sprintf(destination, "IN[%u]", i);
3549 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3551 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3556 HeapFree(GetProcessHeap(), 0, set);
3559 /* GL locking is done by the caller */
3560 static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
3561 IWineD3DVertexShader *vertexshader, IWineD3DPixelShader *pixelshader, const struct wined3d_gl_info *gl_info)
3563 GLhandleARB ret = 0;
3564 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3565 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3566 IWineD3DDeviceImpl *device;
3567 DWORD vs_major = vs->baseShader.reg_maps.shader_version.major;
3568 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
3570 const char *semantic_name;
3573 const struct wined3d_shader_signature_element *output_signature;
3575 shader_buffer_clear(buffer);
3577 shader_addline(buffer, "#version 120\n");
3579 if(vs_major < 3 && ps_major < 3) {
3580 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3581 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3583 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3584 if ((gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W)
3585 && ps_major == 0 && vs_major > 0 && !device->frag_pipe->ffp_proj_control)
3587 shader_addline(buffer, "void order_ps_input() {\n");
3588 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3589 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3590 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3591 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3594 shader_addline(buffer, "}\n");
3596 shader_addline(buffer, "void order_ps_input() { /* do nothing */ }\n");
3598 } else if(ps_major < 3 && vs_major >= 3) {
3599 WORD map = vs->baseShader.reg_maps.output_registers;
3601 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3602 output_signature = vs->output_signature;
3604 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3605 for (i = 0; map; map >>= 1, ++i)
3609 if (!(map & 1)) continue;
3611 semantic_name = output_signature[i].semantic_name;
3612 semantic_idx = output_signature[i].semantic_idx;
3613 write_mask = output_signature[i].mask;
3614 shader_glsl_write_mask_to_str(write_mask, reg_mask);
3616 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3618 if (semantic_idx == 0)
3619 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3620 else if (semantic_idx == 1)
3621 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3623 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3625 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3627 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3629 if (semantic_idx < 8)
3631 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
3632 write_mask |= WINED3DSP_WRITEMASK_3;
3634 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3635 semantic_idx, reg_mask, i, reg_mask);
3636 if (!(write_mask & WINED3DSP_WRITEMASK_3))
3637 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
3640 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3642 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
3644 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3646 shader_addline(buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3649 shader_addline(buffer, "}\n");
3651 } else if(ps_major >= 3 && vs_major >= 3) {
3652 WORD map = vs->baseShader.reg_maps.output_registers;
3654 output_signature = vs->output_signature;
3656 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3657 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3658 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3660 /* First, sort out position and point size. Those are not passed to the pixel shader */
3661 for (i = 0; map; map >>= 1, ++i)
3663 if (!(map & 1)) continue;
3665 semantic_name = output_signature[i].semantic_name;
3666 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
3668 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3670 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3672 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3674 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
3678 /* Then, fix the pixel shader input */
3679 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->input_signature,
3680 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
3682 shader_addline(buffer, "}\n");
3683 } else if(ps_major >= 3 && vs_major < 3) {
3684 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
3685 shader_addline(buffer, "void order_ps_input() {\n");
3686 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3687 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3688 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3690 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->input_signature,
3691 &ps->baseShader.reg_maps, NULL, NULL);
3692 shader_addline(buffer, "}\n");
3694 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3697 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3698 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3699 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer->buffer, NULL));
3700 checkGLcall("glShaderSourceARB(ret, 1, &buffer->buffer, NULL)");
3701 GL_EXTCALL(glCompileShaderARB(ret));
3702 checkGLcall("glCompileShaderARB(ret)");
3707 /* GL locking is done by the caller */
3708 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const struct wined3d_gl_info *gl_info,
3709 GLhandleARB programId, char prefix)
3711 const local_constant *lconst;
3716 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3717 value = (const float *)lconst->value;
3718 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3719 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3720 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3722 checkGLcall("Hardcoding local constants");
3725 /* GL locking is done by the caller */
3726 static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
3727 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *This,
3728 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
3730 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3731 const struct wined3d_gl_info *gl_info = context->gl_info;
3732 CONST DWORD *function = This->baseShader.function;
3733 struct shader_glsl_ctx_priv priv_ctx;
3735 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3736 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3738 memset(&priv_ctx, 0, sizeof(priv_ctx));
3739 priv_ctx.cur_ps_args = args;
3740 priv_ctx.cur_np2fixup_info = np2fixup_info;
3742 shader_addline(buffer, "#version 120\n");
3744 if(GL_SUPPORT(ARB_SHADER_TEXTURE_LOD) && reg_maps->usestexldd) {
3745 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
3747 if (GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
3748 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
3749 * drivers write a warning if we don't do so
3751 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
3754 /* Base Declarations */
3755 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
3757 /* Pack 3.0 inputs */
3758 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
3760 shader_glsl_input_pack((IWineD3DPixelShader *) This, buffer, This->input_signature, reg_maps, args->vp_mode);
3763 /* Base Shader Body */
3764 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3766 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
3767 if (reg_maps->shader_version.major < 2)
3769 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
3770 shader_addline(buffer, "gl_FragData[0] = R0;\n");
3773 if (args->srgb_correction)
3775 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
3776 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
3777 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
3778 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
3779 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
3780 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
3782 /* Pixel shader < 3.0 do not replace the fog stage.
3783 * This implements linear fog computation and blending.
3784 * TODO: non linear fog
3785 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
3786 * -1/(e-s) and e/(e-s) respectively.
3788 if (reg_maps->shader_version.major < 3)
3791 case FOG_OFF: break;
3793 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
3794 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
3795 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
3796 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
3799 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
3800 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
3801 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3802 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
3805 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
3806 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
3807 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
3808 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
3813 shader_addline(buffer, "}\n");
3815 TRACE("Compiling shader object %u\n", shader_obj);
3816 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
3817 GL_EXTCALL(glCompileShaderARB(shader_obj));
3818 print_glsl_info_log(gl_info, shader_obj);
3820 /* Store the shader object */
3824 /* GL locking is done by the caller */
3825 static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
3826 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *This,
3827 const struct vs_compile_args *args)
3829 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3830 const struct wined3d_gl_info *gl_info = context->gl_info;
3831 CONST DWORD *function = This->baseShader.function;
3832 struct shader_glsl_ctx_priv priv_ctx;
3834 /* Create the hw GLSL shader program and assign it as the shader->prgId */
3835 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3837 shader_addline(buffer, "#version 120\n");
3839 memset(&priv_ctx, 0, sizeof(priv_ctx));
3840 priv_ctx.cur_vs_args = args;
3842 /* Base Declarations */
3843 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
3845 /* Base Shader Body */
3846 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
3848 /* Unpack 3.0 outputs */
3849 if (reg_maps->shader_version.major >= 3) shader_addline(buffer, "order_ps_input(OUT);\n");
3850 else shader_addline(buffer, "order_ps_input();\n");
3852 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
3853 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
3854 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
3855 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
3857 if(args->fog_src == VS_FOG_Z) {
3858 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
3859 } else if (!reg_maps->fog) {
3860 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
3863 /* Write the final position.
3865 * OpenGL coordinates specify the center of the pixel while d3d coords specify
3866 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
3867 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
3868 * contains 1.0 to allow a mad.
3870 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
3871 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
3872 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
3874 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
3876 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
3877 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
3878 * which is the same as z = z * 2 - w.
3880 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
3882 shader_addline(buffer, "}\n");
3884 TRACE("Compiling shader object %u\n", shader_obj);
3885 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
3886 GL_EXTCALL(glCompileShaderARB(shader_obj));
3887 print_glsl_info_log(gl_info, shader_obj);
3892 static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
3893 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
3894 const struct ps_compile_args *args, const struct ps_np2fixup_info **np2fixup_info)
3898 struct glsl_ps_compiled_shader *new_array;
3899 struct glsl_pshader_private *shader_data;
3900 struct ps_np2fixup_info *np2fixup = NULL;
3903 if (!shader->baseShader.backend_data)
3905 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3906 if (!shader->baseShader.backend_data)
3908 ERR("Failed to allocate backend data.\n");
3912 shader_data = shader->baseShader.backend_data;
3914 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3915 * so a linear search is more performant than a hashmap or a binary search
3916 * (cache coherency etc)
3918 for(i = 0; i < shader_data->num_gl_shaders; i++) {
3919 if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
3920 if(args->np2_fixup) *np2fixup_info = &shader_data->gl_shaders[i].np2fixup;
3921 return shader_data->gl_shaders[i].prgId;
3925 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
3926 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
3927 if (shader_data->num_gl_shaders)
3929 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
3930 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
3931 new_size * sizeof(*shader_data->gl_shaders));
3933 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
3938 ERR("Out of memory\n");
3941 shader_data->gl_shaders = new_array;
3942 shader_data->shader_array_size = new_size;
3945 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
3947 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
3948 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
3950 pixelshader_update_samplers(&shader->baseShader.reg_maps,
3951 ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
3953 shader_buffer_clear(buffer);
3954 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
3955 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
3956 *np2fixup_info = np2fixup;
3961 static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
3962 const DWORD use_map) {
3963 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
3964 return stored->fog_src == new->fog_src;
3967 static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
3968 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
3969 const struct vs_compile_args *args)
3973 struct glsl_vs_compiled_shader *new_array;
3974 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
3975 struct glsl_vshader_private *shader_data;
3978 if (!shader->baseShader.backend_data)
3980 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3981 if (!shader->baseShader.backend_data)
3983 ERR("Failed to allocate backend data.\n");
3987 shader_data = shader->baseShader.backend_data;
3989 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3990 * so a linear search is more performant than a hashmap or a binary search
3991 * (cache coherency etc)
3993 for(i = 0; i < shader_data->num_gl_shaders; i++) {
3994 if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
3995 return shader_data->gl_shaders[i].prgId;
3999 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4001 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4002 if (shader_data->num_gl_shaders)
4004 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4005 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4006 new_size * sizeof(*shader_data->gl_shaders));
4008 new_array = HeapAlloc(GetProcessHeap(), 0, sizeof(*shader_data->gl_shaders));
4013 ERR("Out of memory\n");
4016 shader_data->gl_shaders = new_array;
4017 shader_data->shader_array_size = new_size;
4020 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4022 shader_buffer_clear(buffer);
4023 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4024 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4029 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
4030 * It sets the programId on the current StateBlock (because it should be called
4031 * inside of the DrawPrimitive() part of the render loop).
4033 * If a program for the given combination does not exist, create one, and store
4034 * the program in the hash table. If it creates a program, it will link the
4035 * given objects, too.
4038 /* GL locking is done by the caller */
4039 static void set_glsl_shader_program(const struct wined3d_context *context,
4040 IWineD3DDeviceImpl *device, BOOL use_ps, BOOL use_vs)
4042 IWineD3DVertexShader *vshader = use_vs ? device->stateBlock->vertexShader : NULL;
4043 IWineD3DPixelShader *pshader = use_ps ? device->stateBlock->pixelShader : NULL;
4044 const struct wined3d_gl_info *gl_info = context->gl_info;
4045 struct shader_glsl_priv *priv = device->shader_priv;
4046 struct glsl_shader_prog_link *entry = NULL;
4047 GLhandleARB programId = 0;
4048 GLhandleARB reorder_shader_id = 0;
4051 struct ps_compile_args ps_compile_args;
4052 struct vs_compile_args vs_compile_args;
4054 if (vshader) find_vs_compile_args((IWineD3DVertexShaderImpl *)vshader, device->stateBlock, &vs_compile_args);
4055 if (pshader) find_ps_compile_args((IWineD3DPixelShaderImpl *)pshader, device->stateBlock, &ps_compile_args);
4057 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
4059 priv->glsl_program = entry;
4063 /* If we get to this point, then no matching program exists, so we create one */
4064 programId = GL_EXTCALL(glCreateProgramObjectARB());
4065 TRACE("Created new GLSL shader program %u\n", programId);
4067 /* Create the entry */
4068 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
4069 entry->programId = programId;
4070 entry->vshader = vshader;
4071 entry->pshader = pshader;
4072 entry->vs_args = vs_compile_args;
4073 entry->ps_args = ps_compile_args;
4074 entry->constant_version = 0;
4075 entry->np2Fixup_info = NULL;
4076 /* Add the hash table entry */
4077 add_glsl_program_entry(priv, entry);
4079 /* Set the current program */
4080 priv->glsl_program = entry;
4082 /* Attach GLSL vshader */
4085 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer,
4086 (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
4087 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4090 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4091 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
4092 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4093 checkGLcall("glAttachObjectARB");
4094 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4097 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4099 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
4100 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4101 checkGLcall("glAttachObjectARB");
4103 /* Bind vertex attributes to a corresponding index number to match
4104 * the same index numbers as ARB_vertex_programs (makes loading
4105 * vertex attributes simpler). With this method, we can use the
4106 * exact same code to load the attributes later for both ARB and
4109 * We have to do this here because we need to know the Program ID
4110 * in order to make the bindings work, and it has to be done prior
4111 * to linking the GLSL program. */
4112 for (i = 0; map; map >>= 1, ++i)
4114 if (!(map & 1)) continue;
4116 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4117 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4119 checkGLcall("glBindAttribLocationARB");
4121 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4124 /* Attach GLSL pshader */
4127 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4128 (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args, &entry->np2Fixup_info);
4129 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
4130 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4131 checkGLcall("glAttachObjectARB");
4133 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4136 /* Link the program */
4137 TRACE("Linking GLSL shader program %u\n", programId);
4138 GL_EXTCALL(glLinkProgramARB(programId));
4139 print_glsl_info_log(gl_info, programId);
4141 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * gl_info->max_vs_glsl_constantsF);
4142 for (i = 0; i < gl_info->max_vs_glsl_constantsF; ++i)
4144 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4145 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4147 for (i = 0; i < MAX_CONST_I; ++i)
4149 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4150 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4152 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * gl_info->max_ps_glsl_constantsF);
4153 for (i = 0; i < gl_info->max_ps_glsl_constantsF; ++i)
4155 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4156 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4158 for (i = 0; i < MAX_CONST_I; ++i)
4160 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4161 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4167 for(i = 0; i < MAX_TEXTURES; i++) {
4168 sprintf(name, "bumpenvmat%u", i);
4169 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4170 sprintf(name, "luminancescale%u", i);
4171 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4172 sprintf(name, "luminanceoffset%u", i);
4173 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4176 if (ps_compile_args.np2_fixup) {
4177 if (entry->np2Fixup_info) {
4178 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4180 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4185 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4186 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4187 checkGLcall("Find glsl program uniform locations");
4190 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4191 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4193 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
4194 entry->vertex_color_clamp = GL_FALSE;
4196 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4199 /* Set the shader to allow uniform loading on it */
4200 GL_EXTCALL(glUseProgramObjectARB(programId));
4201 checkGLcall("glUseProgramObjectARB(programId)");
4203 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4204 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4205 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4206 * vertex shader with fixed function pixel processing is used we make sure that the card
4207 * supports enough samplers to allow the max number of vertex samplers with all possible
4208 * fixed function fragment processing setups. So once the program is linked these samplers
4211 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4212 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4214 /* If the local constants do not have to be loaded with the environment constants,
4215 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4218 if(pshader && !((IWineD3DPixelShaderImpl*)pshader)->baseShader.load_local_constsF) {
4219 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4221 if(vshader && !((IWineD3DVertexShaderImpl*)vshader)->baseShader.load_local_constsF) {
4222 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4226 /* GL locking is done by the caller */
4227 static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type)
4229 GLhandleARB program_id;
4230 GLhandleARB vshader_id, pshader_id;
4231 static const char *blt_vshader[] =
4236 " gl_Position = gl_Vertex;\n"
4237 " gl_FrontColor = vec4(1.0);\n"
4238 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4242 static const char *blt_pshaders[tex_type_count] =
4248 "uniform sampler2D sampler;\n"
4251 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4257 "uniform samplerCube sampler;\n"
4260 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4264 "#extension GL_ARB_texture_rectangle : enable\n"
4265 "uniform sampler2DRect sampler;\n"
4268 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4272 if (!blt_pshaders[tex_type])
4274 FIXME("tex_type %#x not supported\n", tex_type);
4278 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4279 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
4280 GL_EXTCALL(glCompileShaderARB(vshader_id));
4282 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4283 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
4284 GL_EXTCALL(glCompileShaderARB(pshader_id));
4286 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4287 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4288 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4289 GL_EXTCALL(glLinkProgramARB(program_id));
4291 print_glsl_info_log(gl_info, program_id);
4293 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4296 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4297 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4301 /* GL locking is done by the caller */
4302 static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4304 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
4305 const struct wined3d_gl_info *gl_info = context->gl_info;
4306 struct shader_glsl_priv *priv = device->shader_priv;
4307 GLhandleARB program_id = 0;
4308 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4310 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4312 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4313 else priv->glsl_program = NULL;
4315 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4317 if (old_vertex_color_clamp != current_vertex_color_clamp) {
4318 if (GL_SUPPORT(ARB_COLOR_BUFFER_FLOAT)) {
4319 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4320 checkGLcall("glClampColorARB");
4322 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4326 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4327 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4328 GL_EXTCALL(glUseProgramObjectARB(program_id));
4329 checkGLcall("glUseProgramObjectARB");
4331 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
4332 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
4333 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
4334 if (priv->glsl_program && priv->glsl_program->np2Fixup_info)
4336 shader_glsl_load_np2fixup_constants((IWineD3DDevice *)device, usePS, useVS);
4340 /* GL locking is done by the caller */
4341 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
4342 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4343 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4344 struct shader_glsl_priv *priv = This->shader_priv;
4345 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
4347 if (!*blt_program) {
4349 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
4350 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
4351 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4352 GL_EXTCALL(glUniform1iARB(loc, 0));
4354 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
4358 /* GL locking is done by the caller */
4359 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
4360 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4361 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4362 struct shader_glsl_priv *priv = This->shader_priv;
4363 GLhandleARB program_id;
4365 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
4366 if (program_id) TRACE("Using GLSL program %u\n", program_id);
4368 GL_EXTCALL(glUseProgramObjectARB(program_id));
4369 checkGLcall("glUseProgramObjectARB");
4372 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
4373 const struct list *linked_programs;
4374 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
4375 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
4376 struct shader_glsl_priv *priv = device->shader_priv;
4377 const struct wined3d_context *context;
4378 const struct wined3d_gl_info *gl_info;
4379 IWineD3DPixelShaderImpl *ps = NULL;
4380 IWineD3DVertexShaderImpl *vs = NULL;
4382 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
4383 * can be called from IWineD3DBaseShader::Release
4385 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
4388 struct glsl_pshader_private *shader_data;
4389 ps = (IWineD3DPixelShaderImpl *) This;
4390 shader_data = ps->baseShader.backend_data;
4391 if(!shader_data || shader_data->num_gl_shaders == 0)
4393 HeapFree(GetProcessHeap(), 0, shader_data);
4394 ps->baseShader.backend_data = NULL;
4398 context = ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
4399 gl_info = context->gl_info;
4401 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
4404 shader_glsl_select(context, FALSE, FALSE);
4408 struct glsl_vshader_private *shader_data;
4409 vs = (IWineD3DVertexShaderImpl *) This;
4410 shader_data = vs->baseShader.backend_data;
4411 if(!shader_data || shader_data->num_gl_shaders == 0)
4413 HeapFree(GetProcessHeap(), 0, shader_data);
4414 vs->baseShader.backend_data = NULL;
4418 context = ActivateContext(device, NULL, CTXUSAGE_RESOURCELOAD);
4419 gl_info = context->gl_info;
4421 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
4424 shader_glsl_select(context, FALSE, FALSE);
4429 linked_programs = &This->baseShader.linked_programs;
4431 TRACE("Deleting linked programs\n");
4432 if (linked_programs->next) {
4433 struct glsl_shader_prog_link *entry, *entry2;
4437 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
4438 delete_glsl_program_entry(priv, gl_info, entry);
4441 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
4442 delete_glsl_program_entry(priv, gl_info, entry);
4450 struct glsl_pshader_private *shader_data = ps->baseShader.backend_data;
4453 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4454 TRACE("deleting pshader %u\n", shader_data->gl_shaders[i].prgId);
4455 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4456 checkGLcall("glDeleteObjectARB");
4459 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4460 HeapFree(GetProcessHeap(), 0, shader_data);
4461 ps->baseShader.backend_data = NULL;
4464 struct glsl_vshader_private *shader_data = vs->baseShader.backend_data;
4467 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4468 TRACE("deleting vshader %u\n", shader_data->gl_shaders[i].prgId);
4469 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
4470 checkGLcall("glDeleteObjectARB");
4473 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4474 HeapFree(GetProcessHeap(), 0, shader_data);
4475 vs->baseShader.backend_data = NULL;
4479 static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
4481 const glsl_program_key_t *k = key;
4482 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
4483 const struct glsl_shader_prog_link, program_lookup_entry);
4486 if (k->vshader > prog->vshader) return 1;
4487 else if (k->vshader < prog->vshader) return -1;
4489 if (k->pshader > prog->pshader) return 1;
4490 else if (k->pshader < prog->pshader) return -1;
4492 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
4493 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
4498 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
4500 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
4501 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
4505 ERR("Failed to allocate memory\n");
4509 heap->entries = mem;
4510 heap->entries[1].version = 0;
4511 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
4517 static void constant_heap_free(struct constant_heap *heap)
4519 HeapFree(GetProcessHeap(), 0, heap->entries);
4522 static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
4527 glsl_program_key_compare,
4530 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
4531 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4532 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4533 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
4534 SIZE_T stack_size = wined3d_log2i(max(gl_info->max_vs_glsl_constantsF, gl_info->max_ps_glsl_constantsF)) + 1;
4536 if (!shader_buffer_init(&priv->shader_buffer))
4538 ERR("Failed to initialize shader buffer.\n");
4542 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
4545 ERR("Failed to allocate memory.\n");
4549 if (!constant_heap_init(&priv->vconst_heap, gl_info->max_vs_glsl_constantsF))
4551 ERR("Failed to initialize vertex shader constant heap\n");
4555 if (!constant_heap_init(&priv->pconst_heap, gl_info->max_ps_glsl_constantsF))
4557 ERR("Failed to initialize pixel shader constant heap\n");
4561 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
4563 ERR("Failed to initialize rbtree.\n");
4567 priv->next_constant_version = 1;
4569 This->shader_priv = priv;
4573 constant_heap_free(&priv->pconst_heap);
4574 constant_heap_free(&priv->vconst_heap);
4575 HeapFree(GetProcessHeap(), 0, priv->stack);
4576 shader_buffer_free(&priv->shader_buffer);
4577 HeapFree(GetProcessHeap(), 0, priv);
4578 return E_OUTOFMEMORY;
4581 /* Context activation is done by the caller. */
4582 static void shader_glsl_free(IWineD3DDevice *iface) {
4583 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4584 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4585 struct shader_glsl_priv *priv = This->shader_priv;
4589 for (i = 0; i < tex_type_count; ++i)
4591 if (priv->depth_blt_program[i])
4593 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
4598 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
4599 constant_heap_free(&priv->pconst_heap);
4600 constant_heap_free(&priv->vconst_heap);
4601 HeapFree(GetProcessHeap(), 0, priv->stack);
4602 shader_buffer_free(&priv->shader_buffer);
4604 HeapFree(GetProcessHeap(), 0, This->shader_priv);
4605 This->shader_priv = NULL;
4608 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
4609 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
4613 static void shader_glsl_get_caps(WINED3DDEVTYPE devtype,
4614 const struct wined3d_gl_info *gl_info, struct shader_caps *pCaps)
4616 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4617 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support based
4618 * on the version of NV_vertex_program.
4619 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4620 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4621 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4622 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4624 if ((gl_info->supported[NV_VERTEX_PROGRAM2] && !gl_info->supported[NV_VERTEX_PROGRAM3])
4625 || gl_info->max_ps_arb_instructions <= 512)
4626 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4628 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4629 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4630 pCaps->MaxVertexShaderConst = gl_info->max_vs_glsl_constantsF;
4632 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4633 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4634 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4635 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4636 * in max native instructions. Intel and others also offer the info in this extension but they
4637 * don't support GLSL (at least on Windows).
4639 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4640 * of instructions is 512 or less we have to do with ps2.0 hardware.
4641 * 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.
4643 if ((gl_info->supported[NV_FRAGMENT_PROGRAM] && !gl_info->supported[NV_FRAGMENT_PROGRAM2])
4644 || (gl_info->max_ps_arb_instructions <= 512))
4645 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4647 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4649 pCaps->MaxPixelShaderConst = gl_info->max_ps_glsl_constantsF;
4651 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4652 * Direct3D minimum requirement.
4654 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4655 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4657 * The problem is that the refrast clamps temporary results in the shader to
4658 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4659 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4660 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4661 * offer a way to query this.
4663 pCaps->PixelShader1xMaxValue = 8.0;
4664 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4666 pCaps->VSClipping = TRUE;
4669 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4671 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4673 TRACE("Checking support for fixup:\n");
4674 dump_color_fixup_desc(fixup);
4677 /* We support everything except YUV conversions. */
4678 if (!is_yuv_fixup(fixup))
4684 TRACE("[FAILED]\n");
4688 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4690 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4691 /* WINED3DSIH_ADD */ shader_glsl_arith,
4692 /* WINED3DSIH_BEM */ shader_glsl_bem,
4693 /* WINED3DSIH_BREAK */ shader_glsl_break,
4694 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4695 /* WINED3DSIH_BREAKP */ NULL,
4696 /* WINED3DSIH_CALL */ shader_glsl_call,
4697 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4698 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4699 /* WINED3DSIH_CND */ shader_glsl_cnd,
4700 /* WINED3DSIH_CRS */ shader_glsl_cross,
4701 /* WINED3DSIH_DCL */ NULL,
4702 /* WINED3DSIH_DEF */ NULL,
4703 /* WINED3DSIH_DEFB */ NULL,
4704 /* WINED3DSIH_DEFI */ NULL,
4705 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
4706 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4707 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4708 /* WINED3DSIH_DST */ shader_glsl_dst,
4709 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4710 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4711 /* WINED3DSIH_ELSE */ shader_glsl_else,
4712 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4713 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
4714 /* WINED3DSIH_ENDREP */ shader_glsl_end,
4715 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
4716 /* WINED3DSIH_EXPP */ shader_glsl_expp,
4717 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
4718 /* WINED3DSIH_IF */ shader_glsl_if,
4719 /* WINED3DSIH_IFC */ shader_glsl_ifc,
4720 /* WINED3DSIH_LABEL */ shader_glsl_label,
4721 /* WINED3DSIH_LIT */ shader_glsl_lit,
4722 /* WINED3DSIH_LOG */ shader_glsl_log,
4723 /* WINED3DSIH_LOGP */ shader_glsl_log,
4724 /* WINED3DSIH_LOOP */ shader_glsl_loop,
4725 /* WINED3DSIH_LRP */ shader_glsl_lrp,
4726 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
4727 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
4728 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
4729 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
4730 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
4731 /* WINED3DSIH_MAD */ shader_glsl_mad,
4732 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
4733 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
4734 /* WINED3DSIH_MOV */ shader_glsl_mov,
4735 /* WINED3DSIH_MOVA */ shader_glsl_mov,
4736 /* WINED3DSIH_MUL */ shader_glsl_arith,
4737 /* WINED3DSIH_NOP */ NULL,
4738 /* WINED3DSIH_NRM */ shader_glsl_map2gl,
4739 /* WINED3DSIH_PHASE */ NULL,
4740 /* WINED3DSIH_POW */ shader_glsl_pow,
4741 /* WINED3DSIH_RCP */ shader_glsl_rcp,
4742 /* WINED3DSIH_REP */ shader_glsl_rep,
4743 /* WINED3DSIH_RET */ shader_glsl_ret,
4744 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
4745 /* WINED3DSIH_SETP */ NULL,
4746 /* WINED3DSIH_SGE */ shader_glsl_compare,
4747 /* WINED3DSIH_SGN */ shader_glsl_sgn,
4748 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
4749 /* WINED3DSIH_SLT */ shader_glsl_compare,
4750 /* WINED3DSIH_SUB */ shader_glsl_arith,
4751 /* WINED3DSIH_TEX */ shader_glsl_tex,
4752 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
4753 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
4754 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
4755 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
4756 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
4757 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
4758 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
4759 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
4760 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
4761 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
4762 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
4763 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
4764 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
4765 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
4766 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
4767 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
4768 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
4769 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
4770 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
4771 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
4772 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
4775 static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
4776 SHADER_HANDLER hw_fct;
4778 /* Select handler */
4779 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
4781 /* Unhandled opcode */
4784 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
4789 shader_glsl_add_instruction_modifiers(ins);
4792 const shader_backend_t glsl_shader_backend = {
4793 shader_glsl_handle_instruction,
4795 shader_glsl_select_depth_blt,
4796 shader_glsl_deselect_depth_blt,
4797 shader_glsl_update_float_vertex_constants,
4798 shader_glsl_update_float_pixel_constants,
4799 shader_glsl_load_constants,
4800 shader_glsl_load_np2fixup_constants,
4801 shader_glsl_destroy,
4804 shader_glsl_dirty_const,
4805 shader_glsl_get_caps,
4806 shader_glsl_color_fixup_supported,