push 20d539bd3127e997ce79233e3988ba5740356ce5
[wine/hacks.git] / dlls / wined3d / glsl_shader.c
blob3fd950022df20dabaa6437746b894b80ed007e5b
1 /*
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.
32 #include "config.h"
33 #include <limits.h>
34 #include <stdio.h>
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
48 typedef struct {
49 char reg_name[150];
50 char mask_str[6];
51 } glsl_dst_param_t;
53 typedef struct {
54 char reg_name[150];
55 char param_str[100];
56 } glsl_src_param_t;
58 typedef struct {
59 const char *name;
60 DWORD coord_mask;
61 } glsl_sample_function_t;
63 enum heap_node_op
65 HEAP_NODE_TRAVERSE_LEFT,
66 HEAP_NODE_TRAVERSE_RIGHT,
67 HEAP_NODE_POP,
70 struct constant_entry
72 unsigned int idx;
73 unsigned int version;
76 struct constant_heap
78 struct constant_entry *entries;
79 unsigned int *positions;
80 unsigned int size;
83 /* GLSL shader private data */
84 struct shader_glsl_priv {
85 struct hash_table_t *glsl_program_lookup;
86 struct glsl_shader_prog_link *glsl_program;
87 struct constant_heap vconst_heap;
88 struct constant_heap pconst_heap;
89 unsigned char *stack;
90 GLhandleARB depth_blt_program[tex_type_count];
91 UINT next_constant_version;
94 /* Struct to maintain data about a linked GLSL program */
95 struct glsl_shader_prog_link {
96 struct list vshader_entry;
97 struct list pshader_entry;
98 GLhandleARB programId;
99 GLint *vuniformF_locations;
100 GLint *puniformF_locations;
101 GLint vuniformI_locations[MAX_CONST_I];
102 GLint puniformI_locations[MAX_CONST_I];
103 GLint posFixup_location;
104 GLint np2Fixup_location[MAX_FRAGMENT_SAMPLERS];
105 GLint bumpenvmat_location[MAX_TEXTURES];
106 GLint luminancescale_location[MAX_TEXTURES];
107 GLint luminanceoffset_location[MAX_TEXTURES];
108 GLint ycorrection_location;
109 GLenum vertex_color_clamp;
110 IWineD3DVertexShader *vshader;
111 IWineD3DPixelShader *pshader;
112 struct vs_compile_args vs_args;
113 struct ps_compile_args ps_args;
114 UINT constant_version;
117 typedef struct {
118 IWineD3DVertexShader *vshader;
119 IWineD3DPixelShader *pshader;
120 struct ps_compile_args ps_args;
121 struct vs_compile_args vs_args;
122 } glsl_program_key_t;
125 /** Prints the GLSL info log which will contain error messages if they exist */
126 static void print_glsl_info_log(const WineD3D_GL_Info *gl_info, GLhandleARB obj)
128 int infologLength = 0;
129 char *infoLog;
130 unsigned int i;
131 BOOL is_spam;
133 static const char * const spam[] =
135 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
136 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx */
137 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
138 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
139 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
140 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
141 "Fragment shader was successfully compiled to run on hardware.\n"
142 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported",
143 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
144 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
145 "WARNING: 0:2: extension 'GL_ARB_draw_buffers' is not supported\n" /* MacOS ati */
148 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
150 GL_EXTCALL(glGetObjectParameterivARB(obj,
151 GL_OBJECT_INFO_LOG_LENGTH_ARB,
152 &infologLength));
154 /* A size of 1 is just a null-terminated string, so the log should be bigger than
155 * that if there are errors. */
156 if (infologLength > 1)
158 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
159 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
161 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
162 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
163 is_spam = FALSE;
165 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
166 if(strcmp(infoLog, spam[i]) == 0) {
167 is_spam = TRUE;
168 break;
171 if(is_spam) {
172 TRACE("Spam received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
173 } else {
174 FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
176 HeapFree(GetProcessHeap(), 0, infoLog);
181 * Loads (pixel shader) samplers
183 static void shader_glsl_load_psamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
185 GLint name_loc;
186 int i;
187 char sampler_name[20];
189 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
190 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
191 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
192 if (name_loc != -1) {
193 DWORD mapped_unit = tex_unit_map[i];
194 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(fragment_samplers))
196 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
197 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
198 checkGLcall("glUniform1iARB");
199 } else {
200 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
206 static void shader_glsl_load_vsamplers(const WineD3D_GL_Info *gl_info, DWORD *tex_unit_map, GLhandleARB programId)
208 GLint name_loc;
209 char sampler_name[20];
210 int i;
212 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
213 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
214 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
215 if (name_loc != -1) {
216 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
217 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < GL_LIMITS(combined_samplers))
219 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
220 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
221 checkGLcall("glUniform1iARB");
222 } else {
223 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
229 static inline void walk_constant_heap(const WineD3D_GL_Info *gl_info, const float *constants,
230 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
232 int stack_idx = 0;
233 unsigned int heap_idx = 1;
234 unsigned int idx;
236 if (heap->entries[heap_idx].version <= version) return;
238 idx = heap->entries[heap_idx].idx;
239 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
240 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
242 while (stack_idx >= 0)
244 /* Note that we fall through to the next case statement. */
245 switch(stack[stack_idx])
247 case HEAP_NODE_TRAVERSE_LEFT:
249 unsigned int left_idx = heap_idx << 1;
250 if (left_idx < heap->size && heap->entries[left_idx].version > version)
252 heap_idx = left_idx;
253 idx = heap->entries[heap_idx].idx;
254 if (constant_locations[idx] != -1)
255 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
257 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
258 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
259 break;
263 case HEAP_NODE_TRAVERSE_RIGHT:
265 unsigned int right_idx = (heap_idx << 1) + 1;
266 if (right_idx < heap->size && heap->entries[right_idx].version > version)
268 heap_idx = right_idx;
269 idx = heap->entries[heap_idx].idx;
270 if (constant_locations[idx] != -1)
271 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
273 stack[stack_idx++] = HEAP_NODE_POP;
274 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
275 break;
279 case HEAP_NODE_POP:
281 heap_idx >>= 1;
282 --stack_idx;
283 break;
287 checkGLcall("walk_constant_heap()");
290 static inline void apply_clamped_constant(const WineD3D_GL_Info *gl_info, GLint location, const GLfloat *data)
292 GLfloat clamped_constant[4];
294 if (location == -1) return;
296 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0 ? 1.0 : data[0];
297 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0 ? 1.0 : data[1];
298 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0 ? 1.0 : data[2];
299 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0 ? 1.0 : data[3];
301 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
304 static inline void walk_constant_heap_clamped(const WineD3D_GL_Info *gl_info, const float *constants,
305 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
307 int stack_idx = 0;
308 unsigned int heap_idx = 1;
309 unsigned int idx;
311 if (heap->entries[heap_idx].version <= version) return;
313 idx = heap->entries[heap_idx].idx;
314 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
315 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
317 while (stack_idx >= 0)
319 /* Note that we fall through to the next case statement. */
320 switch(stack[stack_idx])
322 case HEAP_NODE_TRAVERSE_LEFT:
324 unsigned int left_idx = heap_idx << 1;
325 if (left_idx < heap->size && heap->entries[left_idx].version > version)
327 heap_idx = left_idx;
328 idx = heap->entries[heap_idx].idx;
329 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
331 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
332 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
333 break;
337 case HEAP_NODE_TRAVERSE_RIGHT:
339 unsigned int right_idx = (heap_idx << 1) + 1;
340 if (right_idx < heap->size && heap->entries[right_idx].version > version)
342 heap_idx = right_idx;
343 idx = heap->entries[heap_idx].idx;
344 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
346 stack[stack_idx++] = HEAP_NODE_POP;
347 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
348 break;
352 case HEAP_NODE_POP:
354 heap_idx >>= 1;
355 --stack_idx;
356 break;
360 checkGLcall("walk_constant_heap_clamped()");
363 /* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
364 static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
365 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
366 unsigned char *stack, UINT version)
368 const local_constant *lconst;
370 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
371 if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.reg_maps.shader_version) == 1
372 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version))
373 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
374 else
375 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
377 if (!This->baseShader.load_local_constsF)
379 TRACE("No need to load local float constants for this shader\n");
380 return;
383 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
384 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
386 GLint location = constant_locations[lconst->idx];
387 /* We found this uniform name in the program - go ahead and send the data */
388 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
390 checkGLcall("glUniform4fvARB()");
393 /* Loads integer constants (aka uniforms) into the currently set GLSL program. */
394 static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
395 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
397 unsigned int i;
398 struct list* ptr;
400 for (i = 0; constants_set; constants_set >>= 1, ++i)
402 if (!(constants_set & 1)) continue;
404 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
405 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
407 /* We found this uniform name in the program - go ahead and send the data */
408 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
409 checkGLcall("glUniform4ivARB");
412 /* Load immediate constants */
413 ptr = list_head(&This->baseShader.constantsI);
414 while (ptr) {
415 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
416 unsigned int idx = lconst->idx;
417 const GLint *values = (const GLint *)lconst->value;
419 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
420 values[0], values[1], values[2], values[3]);
422 /* We found this uniform name in the program - go ahead and send the data */
423 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
424 checkGLcall("glUniform4ivARB");
425 ptr = list_next(&This->baseShader.constantsI, ptr);
429 /* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
430 static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const WineD3D_GL_Info *gl_info,
431 GLhandleARB programId, const BOOL *constants, WORD constants_set)
433 GLint tmp_loc;
434 unsigned int i;
435 char tmp_name[8];
436 char is_pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version);
437 const char* prefix = is_pshader? "PB":"VB";
438 struct list* ptr;
440 /* TODO: Benchmark and see if it would be beneficial to store the
441 * locations of the constants to avoid looking up each time */
442 for (i = 0; constants_set; constants_set >>= 1, ++i)
444 if (!(constants_set & 1)) continue;
446 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
448 /* TODO: Benchmark and see if it would be beneficial to store the
449 * locations of the constants to avoid looking up each time */
450 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
451 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
452 if (tmp_loc != -1)
454 /* We found this uniform name in the program - go ahead and send the data */
455 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
456 checkGLcall("glUniform1ivARB");
460 /* Load immediate constants */
461 ptr = list_head(&This->baseShader.constantsB);
462 while (ptr) {
463 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
464 unsigned int idx = lconst->idx;
465 const GLint *values = (const GLint *)lconst->value;
467 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
469 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
470 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
471 if (tmp_loc != -1) {
472 /* We found this uniform name in the program - go ahead and send the data */
473 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
474 checkGLcall("glUniform1ivARB");
476 ptr = list_next(&This->baseShader.constantsB, ptr);
480 static void reset_program_constant_version(void *value, void *context)
482 struct glsl_shader_prog_link *entry = value;
483 entry->constant_version = 0;
487 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
489 static void shader_glsl_load_np2fixup_constants(
490 IWineD3DDevice* device,
491 char usePixelShader,
492 char useVertexShader) {
494 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
495 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
497 if (!prog) {
498 /* No GLSL program set - nothing to do. */
499 return;
502 if (!usePixelShader) {
503 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
504 return;
507 if (prog->ps_args.np2_fixup) {
508 UINT i;
509 UINT fixup = prog->ps_args.np2_fixup;
510 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
511 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
513 for (i = 0; fixup; fixup >>= 1, ++i) {
514 if (-1 != prog->np2Fixup_location[i]) {
515 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
516 if (!tex) {
517 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
518 continue;
519 } else {
520 const float tex_dim[2] = {tex->baseTexture.pow2Matrix[0], tex->baseTexture.pow2Matrix[5]};
521 GL_EXTCALL(glUniform2fvARB(prog->np2Fixup_location[i], 1, tex_dim));
529 * Loads the app-supplied constants into the currently set GLSL program.
531 static void shader_glsl_load_constants(
532 IWineD3DDevice* device,
533 char usePixelShader,
534 char useVertexShader) {
536 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
537 struct shader_glsl_priv *priv = deviceImpl->shader_priv;
538 IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
539 const WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
541 GLhandleARB programId;
542 struct glsl_shader_prog_link *prog = priv->glsl_program;
543 UINT constant_version;
544 int i;
546 if (!prog) {
547 /* No GLSL program set - nothing to do. */
548 return;
550 programId = prog->programId;
551 constant_version = prog->constant_version;
553 if (useVertexShader) {
554 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
556 /* Load DirectX 9 float constants/uniforms for vertex shader */
557 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
558 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
560 /* Load DirectX 9 integer constants/uniforms for vertex shader */
561 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
562 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
564 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
565 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
566 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
568 /* Upload the position fixup params */
569 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &deviceImpl->posFixup[0]));
570 checkGLcall("glUniform4fvARB");
573 if (usePixelShader) {
575 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
577 /* Load DirectX 9 float constants/uniforms for pixel shader */
578 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
579 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
581 /* Load DirectX 9 integer constants/uniforms for pixel shader */
582 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
583 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
585 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
586 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
587 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
589 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
590 * It can't be 0 for a valid texbem instruction.
592 for(i = 0; i < ((IWineD3DPixelShaderImpl *) pshader)->numbumpenvmatconsts; i++) {
593 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pshader;
594 int stage = ps->luminanceconst[i].texunit;
596 const float *data = (const float *)&stateBlock->textureState[(int)ps->bumpenvmatconst[i].texunit][WINED3DTSS_BUMPENVMAT00];
597 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
598 checkGLcall("glUniformMatrix2fvARB");
600 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
601 * is set too, so we can check that in the needsbumpmat check
603 if(ps->baseShader.reg_maps.luminanceparams[stage]) {
604 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
605 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];
607 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
608 checkGLcall("glUniform1fvARB");
609 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
610 checkGLcall("glUniform1fvARB");
614 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
615 float correction_params[4];
616 if(deviceImpl->render_offscreen) {
617 correction_params[0] = 0.0;
618 correction_params[1] = 1.0;
619 } else {
620 /* position is window relative, not viewport relative */
621 correction_params[0] = ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
622 correction_params[1] = -1.0;
624 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
628 if (priv->next_constant_version == UINT_MAX)
630 TRACE("Max constant version reached, resetting to 0.\n");
631 hash_table_for_each_entry(priv->glsl_program_lookup, reset_program_constant_version, NULL);
632 priv->next_constant_version = 1;
634 else
636 prog->constant_version = priv->next_constant_version++;
640 static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
641 unsigned int heap_idx, DWORD new_version)
643 struct constant_entry *entries = heap->entries;
644 unsigned int *positions = heap->positions;
645 unsigned int parent_idx;
647 while (heap_idx > 1)
649 parent_idx = heap_idx >> 1;
651 if (new_version <= entries[parent_idx].version) break;
653 entries[heap_idx] = entries[parent_idx];
654 positions[entries[parent_idx].idx] = heap_idx;
655 heap_idx = parent_idx;
658 entries[heap_idx].version = new_version;
659 entries[heap_idx].idx = idx;
660 positions[idx] = heap_idx;
663 static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
665 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
666 struct shader_glsl_priv *priv = This->shader_priv;
667 struct constant_heap *heap = &priv->vconst_heap;
668 UINT i;
670 for (i = start; i < count + start; ++i)
672 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
673 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
674 else
675 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
679 static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
681 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
682 struct shader_glsl_priv *priv = This->shader_priv;
683 struct constant_heap *heap = &priv->pconst_heap;
684 UINT i;
686 for (i = start; i < count + start; ++i)
688 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
689 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
690 else
691 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
695 /** Generate the variable & register declarations for the GLSL output target */
696 static void shader_generate_glsl_declarations(IWineD3DBaseShader *iface, const shader_reg_maps *reg_maps,
697 SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info,
698 const struct ps_compile_args *ps_args)
700 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
701 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
702 DWORD shader_version = reg_maps->shader_version;
703 unsigned int i, extra_constants_needed = 0;
704 const local_constant *lconst;
706 /* There are some minor differences between pixel and vertex shaders */
707 char pshader = shader_is_pshader_version(shader_version);
708 char prefix = pshader ? 'P' : 'V';
710 /* Prototype the subroutines */
711 for (i = 0; i < This->baseShader.limits.label; i++) {
712 if (reg_maps->labels[i])
713 shader_addline(buffer, "void subroutine%u();\n", i);
716 /* Declare the constants (aka uniforms) */
717 if (This->baseShader.limits.constant_float > 0) {
718 unsigned max_constantsF;
719 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
720 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
721 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
722 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
723 * a dx9 card, as long as it doesn't also use all the other constants.
725 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
726 * declare only the amount that we're assured to have.
728 * Thus we run into problems in these two cases:
729 * 1) The shader really uses more uniforms than supported
730 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
732 if(pshader) {
733 /* No indirect addressing here */
734 max_constantsF = GL_LIMITS(pshader_constantsF);
735 } else {
736 if(This->baseShader.reg_maps.usesrelconstF) {
737 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
738 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
739 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
740 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float
742 max_constantsF = GL_LIMITS(vshader_constantsF) - 3;
743 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
744 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
745 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
746 * for now take this into account when calculating the number of available constants
748 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
749 /* Set by driver quirks in directx.c */
750 max_constantsF -= GLINFO_LOCATION.reserved_glsl_constants;
751 } else {
752 max_constantsF = GL_LIMITS(vshader_constantsF);
755 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
756 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
759 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
760 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
762 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
763 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
765 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
766 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
768 if(!pshader) {
769 shader_addline(buffer, "uniform vec4 posFixup;\n");
770 /* Predeclaration; This function is added at link time based on the pixel shader.
771 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
772 * that. We know the input to the reorder function at vertex shader compile time, so
773 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
774 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
775 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
776 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
777 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
778 * inout.
780 if (shader_version >= WINED3DVS_VERSION(3, 0))
782 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
783 } else {
784 shader_addline(buffer, "void order_ps_input();\n");
786 } else {
787 IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;
789 ps_impl->numbumpenvmatconsts = 0;
790 for(i = 0; i < (sizeof(reg_maps->bumpmat) / sizeof(reg_maps->bumpmat[0])); i++) {
791 if(!reg_maps->bumpmat[i]) {
792 continue;
795 ps_impl->bumpenvmatconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
796 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
798 if(reg_maps->luminanceparams) {
799 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = i;
800 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
801 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
802 extra_constants_needed++;
803 } else {
804 ps_impl->luminanceconst[(int) ps_impl->numbumpenvmatconsts].texunit = -1;
807 extra_constants_needed++;
808 ps_impl->numbumpenvmatconsts++;
811 if(ps_args->srgb_correction) {
812 shader_addline(buffer, "const vec4 srgb_mul_low = vec4(%f, %f, %f, %f);\n",
813 srgb_mul_low, srgb_mul_low, srgb_mul_low, srgb_mul_low);
814 shader_addline(buffer, "const vec4 srgb_comparison = vec4(%f, %f, %f, %f);\n",
815 srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
817 if(reg_maps->vpos || reg_maps->usesdsy) {
818 if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
819 shader_addline(buffer, "uniform vec4 ycorrection;\n");
820 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
821 extra_constants_needed++;
822 } else {
823 /* This happens because we do not have proper tracking of the constant registers that are
824 * actually used, only the max limit of the shader version
826 FIXME("Cannot find a free uniform for vpos correction params\n");
827 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
828 device->render_offscreen ? 0.0 : ((IWineD3DSurfaceImpl *) device->render_targets[0])->currentDesc.Height,
829 device->render_offscreen ? 1.0 : -1.0);
831 shader_addline(buffer, "vec4 vpos;\n");
835 /* Declare texture samplers */
836 for (i = 0; i < This->baseShader.limits.sampler; i++) {
837 if (reg_maps->sampler_type[i])
839 switch (reg_maps->sampler_type[i])
841 case WINED3DSTT_1D:
842 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
843 break;
844 case WINED3DSTT_2D:
845 if(device->stateBlock->textures[i] &&
846 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
847 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
848 } else {
849 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
852 if (pshader && ps_args->np2_fixup & (1 << i))
854 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
855 * while D3D has them in the (normalized) [0,1]x[0,1] range.
856 * samplerNP2Fixup stores texture dimensions and is updated through
857 * shader_glsl_load_np2fixup_constants when the sampler changes. */
858 shader_addline(buffer, "uniform vec2 %csamplerNP2Fixup%u;\n", prefix, i);
860 break;
861 case WINED3DSTT_CUBE:
862 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
863 break;
864 case WINED3DSTT_VOLUME:
865 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
866 break;
867 default:
868 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
869 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
870 break;
875 /* Declare address variables */
876 for (i = 0; i < This->baseShader.limits.address; i++) {
877 if (reg_maps->address[i])
878 shader_addline(buffer, "ivec4 A%d;\n", i);
881 /* Declare texture coordinate temporaries and initialize them */
882 for (i = 0; i < This->baseShader.limits.texcoord; i++) {
883 if (reg_maps->texcoord[i])
884 shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
887 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
888 * helper function shader that is linked in at link time
890 if (pshader && shader_version >= WINED3DPS_VERSION(3, 0))
892 if (use_vs(device->stateBlock))
894 shader_addline(buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
895 } else {
896 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
897 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
898 * pixel shader that reads the fixed function color into the packed input registers.
900 shader_addline(buffer, "vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
904 /* Declare output register temporaries */
905 if(This->baseShader.limits.packed_output) {
906 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
909 /* Declare temporary variables */
910 for(i = 0; i < This->baseShader.limits.temporary; i++) {
911 if (reg_maps->temporary[i])
912 shader_addline(buffer, "vec4 R%u;\n", i);
915 /* Declare attributes */
916 for (i = 0; i < This->baseShader.limits.attributes; i++) {
917 if (reg_maps->attributes[i])
918 shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
921 /* Declare loop registers aLx */
922 for (i = 0; i < reg_maps->loop_depth; i++) {
923 shader_addline(buffer, "int aL%u;\n", i);
924 shader_addline(buffer, "int tmpInt%u;\n", i);
927 /* Temporary variables for matrix operations */
928 shader_addline(buffer, "vec4 tmp0;\n");
929 shader_addline(buffer, "vec4 tmp1;\n");
931 /* Local constants use a different name so they can be loaded once at shader link time
932 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
933 * float -> string conversion can cause precision loss.
935 if(!This->baseShader.load_local_constsF) {
936 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
937 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
941 /* Start the main program */
942 shader_addline(buffer, "void main() {\n");
943 if(pshader && reg_maps->vpos) {
944 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
945 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
946 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
947 * precision troubles when we just substract 0.5.
949 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
951 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
953 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
954 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
955 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
956 * correctly on drivers that returns integer values.
958 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
962 /*****************************************************************************
963 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
965 * For more information, see http://wiki.winehq.org/DirectX-Shaders
966 ****************************************************************************/
968 /* Prototypes */
969 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
970 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
972 /** Used for opcode modifiers - They multiply the result by the specified amount */
973 static const char * const shift_glsl_tab[] = {
974 "", /* 0 (none) */
975 "2.0 * ", /* 1 (x2) */
976 "4.0 * ", /* 2 (x4) */
977 "8.0 * ", /* 3 (x8) */
978 "16.0 * ", /* 4 (x16) */
979 "32.0 * ", /* 5 (x32) */
980 "", /* 6 (x64) */
981 "", /* 7 (x128) */
982 "", /* 8 (d256) */
983 "", /* 9 (d128) */
984 "", /* 10 (d64) */
985 "", /* 11 (d32) */
986 "0.0625 * ", /* 12 (d16) */
987 "0.125 * ", /* 13 (d8) */
988 "0.25 * ", /* 14 (d4) */
989 "0.5 * " /* 15 (d2) */
992 /* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
993 static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
995 out_str[0] = 0;
997 switch (src_modifier)
999 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1000 case WINED3DSPSM_DW:
1001 case WINED3DSPSM_NONE:
1002 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1003 break;
1004 case WINED3DSPSM_NEG:
1005 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1006 break;
1007 case WINED3DSPSM_NOT:
1008 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1009 break;
1010 case WINED3DSPSM_BIAS:
1011 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1012 break;
1013 case WINED3DSPSM_BIASNEG:
1014 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1015 break;
1016 case WINED3DSPSM_SIGN:
1017 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1018 break;
1019 case WINED3DSPSM_SIGNNEG:
1020 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1021 break;
1022 case WINED3DSPSM_COMP:
1023 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1024 break;
1025 case WINED3DSPSM_X2:
1026 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1027 break;
1028 case WINED3DSPSM_X2NEG:
1029 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1030 break;
1031 case WINED3DSPSM_ABS:
1032 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1033 break;
1034 case WINED3DSPSM_ABSNEG:
1035 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1036 break;
1037 default:
1038 FIXME("Unhandled modifier %u\n", src_modifier);
1039 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1043 /** Writes the GLSL variable name that corresponds to the register that the
1044 * DX opcode parameter is trying to access */
1045 static void shader_glsl_get_register_name(WINED3DSHADER_PARAM_REGISTER_TYPE register_type, UINT register_idx,
1046 const struct wined3d_shader_src_param *rel_addr, char *register_name, BOOL *is_color,
1047 const struct wined3d_shader_instruction *ins)
1049 /* oPos, oFog and oPts in D3D */
1050 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1052 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1053 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1054 const WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
1055 DWORD shader_version = This->baseShader.reg_maps.shader_version;
1056 char pshader = shader_is_pshader_version(shader_version);
1058 *is_color = FALSE;
1060 switch (register_type)
1062 case WINED3DSPR_TEMP:
1063 sprintf(register_name, "R%u", register_idx);
1064 break;
1065 case WINED3DSPR_INPUT:
1066 if (pshader) {
1067 /* Pixel shaders >= 3.0 */
1068 if (WINED3DSHADER_VERSION_MAJOR(shader_version) >= 3)
1070 DWORD in_count = GL_LIMITS(glsl_varyings) / 4;
1072 if (rel_addr)
1074 glsl_src_param_t rel_param;
1075 shader_glsl_add_src_param(ins, rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1077 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1078 * operation there
1080 if (((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx])
1082 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count) {
1083 sprintf(register_name, "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1084 rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx], in_count - 1,
1085 rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx], in_count,
1086 rel_param.param_str, ((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx]);
1087 } else {
1088 sprintf(register_name, "IN[%s + %u]", rel_param.param_str,
1089 ((IWineD3DPixelShaderImpl *)This)->input_reg_map[register_idx]);
1091 } else {
1092 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count) {
1093 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1094 rel_param.param_str, in_count - 1,
1095 rel_param.param_str, in_count,
1096 rel_param.param_str);
1097 } else {
1098 sprintf(register_name, "IN[%s]", rel_param.param_str);
1101 } else {
1102 DWORD idx = ((IWineD3DPixelShaderImpl *) This)->input_reg_map[register_idx];
1103 if (idx == in_count) {
1104 sprintf(register_name, "gl_Color");
1105 } else if (idx == in_count + 1) {
1106 sprintf(register_name, "gl_SecondaryColor");
1107 } else {
1108 sprintf(register_name, "IN[%u]", idx);
1111 } else {
1112 if (register_idx == 0)
1113 strcpy(register_name, "gl_Color");
1114 else
1115 strcpy(register_name, "gl_SecondaryColor");
1117 } else {
1118 if (((IWineD3DVertexShaderImpl *)This)->cur_args->swizzle_map & (1 << register_idx)) *is_color = TRUE;
1119 sprintf(register_name, "attrib%u", register_idx);
1121 break;
1122 case WINED3DSPR_CONST:
1124 const char prefix = pshader? 'P':'V';
1126 /* Relative addressing */
1127 if (rel_addr)
1129 glsl_src_param_t rel_param;
1130 shader_glsl_add_src_param(ins, rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1131 if (register_idx)
1132 sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, register_idx);
1133 else
1134 sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1135 } else {
1136 if (shader_constant_is_local(This, register_idx))
1138 sprintf(register_name, "%cLC%u", prefix, register_idx);
1139 } else {
1140 sprintf(register_name, "%cC[%u]", prefix, register_idx);
1144 break;
1146 case WINED3DSPR_CONSTINT:
1147 if (pshader)
1148 sprintf(register_name, "PI[%u]", register_idx);
1149 else
1150 sprintf(register_name, "VI[%u]", register_idx);
1151 break;
1152 case WINED3DSPR_CONSTBOOL:
1153 if (pshader)
1154 sprintf(register_name, "PB[%u]", register_idx);
1155 else
1156 sprintf(register_name, "VB[%u]", register_idx);
1157 break;
1158 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1159 if (pshader) {
1160 sprintf(register_name, "T%u", register_idx);
1161 } else {
1162 sprintf(register_name, "A%u", register_idx);
1164 break;
1165 case WINED3DSPR_LOOP:
1166 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1167 break;
1168 case WINED3DSPR_SAMPLER:
1169 if (pshader)
1170 sprintf(register_name, "Psampler%u", register_idx);
1171 else
1172 sprintf(register_name, "Vsampler%u", register_idx);
1173 break;
1174 case WINED3DSPR_COLOROUT:
1175 if (register_idx >= GL_LIMITS(buffers))
1176 WARN("Write to render target %u, only %d supported\n", register_idx, 4);
1178 if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
1179 sprintf(register_name, "gl_FragData[%u]", register_idx);
1180 } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
1181 sprintf(register_name, "gl_FragColor");
1183 break;
1184 case WINED3DSPR_RASTOUT:
1185 sprintf(register_name, "%s", hwrastout_reg_names[register_idx]);
1186 break;
1187 case WINED3DSPR_DEPTHOUT:
1188 sprintf(register_name, "gl_FragDepth");
1189 break;
1190 case WINED3DSPR_ATTROUT:
1191 if (register_idx == 0)
1193 sprintf(register_name, "gl_FrontColor");
1194 } else {
1195 sprintf(register_name, "gl_FrontSecondaryColor");
1197 break;
1198 case WINED3DSPR_TEXCRDOUT:
1199 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1200 if (WINED3DSHADER_VERSION_MAJOR(shader_version) >= 3) sprintf(register_name, "OUT[%u]", register_idx);
1201 else sprintf(register_name, "gl_TexCoord[%u]", register_idx);
1202 break;
1203 case WINED3DSPR_MISCTYPE:
1204 if (register_idx == 0)
1206 /* vPos */
1207 sprintf(register_name, "vpos");
1209 else if (register_idx == 1)
1211 /* Note that gl_FrontFacing is a bool, while vFace is
1212 * a float for which the sign determines front/back
1214 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1215 } else {
1216 FIXME("Unhandled misctype register %d\n", register_idx);
1217 sprintf(register_name, "unrecognized_register");
1219 break;
1220 default:
1221 FIXME("Unhandled register name Type(%d)\n", register_type);
1222 sprintf(register_name, "unrecognized_register");
1223 break;
1227 static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1229 *str++ = '.';
1230 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1231 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1232 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1233 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1234 *str = '\0';
1237 /* Get the GLSL write mask for the destination register */
1238 static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1240 DWORD mask = param->write_mask;
1242 if (shader_is_scalar(param->register_type, param->register_idx))
1244 mask = WINED3DSP_WRITEMASK_0;
1245 *write_mask = '\0';
1247 else
1249 shader_glsl_write_mask_to_str(mask, write_mask);
1252 return mask;
1255 static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1256 unsigned int size = 0;
1258 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1259 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1260 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1261 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1263 return size;
1266 static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1268 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1269 * but addressed as "rgba". To fix this we need to swap the register's x
1270 * and z components. */
1271 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1273 *str++ = '.';
1274 /* swizzle bits fields: wwzzyyxx */
1275 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1276 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1277 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1278 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1279 *str = '\0';
1282 static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1283 BOOL fixup, DWORD mask, char *swizzle_str)
1285 if (shader_is_scalar(param->register_type, param->register_idx))
1286 *swizzle_str = '\0';
1287 else
1288 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1291 /* From a given parameter token, generate the corresponding GLSL string.
1292 * Also, return the actual register name and swizzle in case the
1293 * caller needs this information as well. */
1294 static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1295 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1297 BOOL is_color = FALSE;
1298 char swizzle_str[6];
1300 glsl_src->reg_name[0] = '\0';
1301 glsl_src->param_str[0] = '\0';
1302 swizzle_str[0] = '\0';
1304 shader_glsl_get_register_name(wined3d_src->register_type, wined3d_src->register_idx,
1305 wined3d_src->rel_addr, glsl_src->reg_name, &is_color, ins);
1307 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1308 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1311 /* From a given parameter token, generate the corresponding GLSL string.
1312 * Also, return the actual register name and swizzle in case the
1313 * caller needs this information as well. */
1314 static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1315 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1317 BOOL is_color = FALSE;
1319 glsl_dst->mask_str[0] = '\0';
1320 glsl_dst->reg_name[0] = '\0';
1322 shader_glsl_get_register_name(wined3d_dst->register_type, wined3d_dst->register_idx,
1323 wined3d_dst->rel_addr, glsl_dst->reg_name, &is_color, ins);
1324 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1327 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1328 static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer,
1329 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1331 glsl_dst_param_t glsl_dst;
1332 DWORD mask;
1334 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1335 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1337 return mask;
1340 /* Append the destination part of the instruction to the buffer, return the effective write mask */
1341 static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, const struct wined3d_shader_instruction *ins)
1343 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1346 /** Process GLSL instruction modifiers */
1347 void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1349 glsl_dst_param_t dst_param;
1350 DWORD modifiers;
1352 if (!ins->dst_count) return;
1354 modifiers = ins->dst[0].modifiers;
1355 if (!modifiers) return;
1357 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1359 if (modifiers & WINED3DSPDM_SATURATE)
1361 /* _SAT means to clamp the value of the register to between 0 and 1 */
1362 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1363 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1366 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1368 FIXME("_centroid modifier not handled\n");
1371 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1373 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1377 static inline const char *shader_get_comp_op(DWORD op)
1379 switch (op) {
1380 case COMPARISON_GT: return ">";
1381 case COMPARISON_EQ: return "==";
1382 case COMPARISON_GE: return ">=";
1383 case COMPARISON_LT: return "<";
1384 case COMPARISON_NE: return "!=";
1385 case COMPARISON_LE: return "<=";
1386 default:
1387 FIXME("Unrecognized comparison value: %u\n", op);
1388 return "(\?\?)";
1392 static void shader_glsl_get_sample_function(DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1394 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1395 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1396 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1398 /* Note that there's no such thing as a projected cube texture. */
1399 switch(sampler_type) {
1400 case WINED3DSTT_1D:
1401 if(lod) {
1402 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1403 } else {
1404 sample_function->name = projected ? "texture1DProj" : "texture1D";
1406 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1407 break;
1408 case WINED3DSTT_2D:
1409 if(texrect) {
1410 if(lod) {
1411 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1412 } else {
1413 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1415 } else {
1416 if(lod) {
1417 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1418 } else {
1419 sample_function->name = projected ? "texture2DProj" : "texture2D";
1422 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1423 break;
1424 case WINED3DSTT_CUBE:
1425 if(lod) {
1426 sample_function->name = "textureCubeLod";
1427 } else {
1428 sample_function->name = "textureCube";
1430 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1431 break;
1432 case WINED3DSTT_VOLUME:
1433 if(lod) {
1434 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1435 } else {
1436 sample_function->name = projected ? "texture3DProj" : "texture3D";
1438 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1439 break;
1440 default:
1441 sample_function->name = "";
1442 sample_function->coord_mask = 0;
1443 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1444 break;
1448 static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1449 BOOL sign_fixup, enum fixup_channel_source channel_source)
1451 switch(channel_source)
1453 case CHANNEL_SOURCE_ZERO:
1454 strcat(arguments, "0.0");
1455 break;
1457 case CHANNEL_SOURCE_ONE:
1458 strcat(arguments, "1.0");
1459 break;
1461 case CHANNEL_SOURCE_X:
1462 strcat(arguments, reg_name);
1463 strcat(arguments, ".x");
1464 break;
1466 case CHANNEL_SOURCE_Y:
1467 strcat(arguments, reg_name);
1468 strcat(arguments, ".y");
1469 break;
1471 case CHANNEL_SOURCE_Z:
1472 strcat(arguments, reg_name);
1473 strcat(arguments, ".z");
1474 break;
1476 case CHANNEL_SOURCE_W:
1477 strcat(arguments, reg_name);
1478 strcat(arguments, ".w");
1479 break;
1481 default:
1482 FIXME("Unhandled channel source %#x\n", channel_source);
1483 strcat(arguments, "undefined");
1484 break;
1487 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
1490 static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
1492 struct wined3d_shader_dst_param dst;
1493 unsigned int mask_size, remaining;
1494 glsl_dst_param_t dst_param;
1495 char arguments[256];
1496 DWORD mask;
1498 mask = 0;
1499 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
1500 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
1501 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
1502 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
1503 mask &= ins->dst[0].write_mask;
1505 if (!mask) return; /* Nothing to do */
1507 if (is_yuv_fixup(fixup))
1509 enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
1510 FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
1511 return;
1514 mask_size = shader_glsl_get_write_mask_size(mask);
1516 dst = ins->dst[0];
1517 dst.write_mask = mask;
1518 shader_glsl_add_dst_param(ins, &dst, &dst_param);
1520 arguments[0] = '\0';
1521 remaining = mask_size;
1522 if (mask & WINED3DSP_WRITEMASK_0)
1524 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
1525 if (--remaining) strcat(arguments, ", ");
1527 if (mask & WINED3DSP_WRITEMASK_1)
1529 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
1530 if (--remaining) strcat(arguments, ", ");
1532 if (mask & WINED3DSP_WRITEMASK_2)
1534 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
1535 if (--remaining) strcat(arguments, ", ");
1537 if (mask & WINED3DSP_WRITEMASK_3)
1539 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
1540 if (--remaining) strcat(arguments, ", ");
1543 if (mask_size > 1)
1545 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
1546 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
1548 else
1550 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
1554 static void PRINTF_ATTR(6, 7) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
1555 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
1556 const char *bias, const char *coord_reg_fmt, ...)
1558 const char *sampler_base;
1559 char dst_swizzle[6];
1560 struct color_fixup_desc fixup;
1561 BOOL np2_fixup = FALSE;
1562 va_list args;
1564 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
1566 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version))
1568 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1569 fixup = This->cur_args->color_fixup[sampler];
1570 sampler_base = "Psampler";
1572 if(This->cur_args->np2_fixup & (1 << sampler)) {
1573 if(bias) {
1574 FIXME("Biased sampling from NP2 textures is unsupported\n");
1575 } else {
1576 np2_fixup = TRUE;
1579 } else {
1580 sampler_base = "Vsampler";
1581 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
1584 shader_glsl_append_dst(ins->ctx->buffer, ins);
1586 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
1588 va_start(args, coord_reg_fmt);
1589 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
1590 va_end(args);
1592 if(bias) {
1593 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
1594 } else {
1595 if (np2_fixup) {
1596 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup%u)%s);\n", sampler, dst_swizzle);
1597 } else {
1598 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
1602 if(!is_identity_fixup(fixup)) {
1603 shader_glsl_color_correction(ins, fixup);
1607 /*****************************************************************************
1609 * Begin processing individual instruction opcodes
1611 ****************************************************************************/
1613 /* Generate GLSL arithmetic functions (dst = src1 + src2) */
1614 static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
1616 SHADER_BUFFER *buffer = ins->ctx->buffer;
1617 glsl_src_param_t src0_param;
1618 glsl_src_param_t src1_param;
1619 DWORD write_mask;
1620 char op;
1622 /* Determine the GLSL operator to use based on the opcode */
1623 switch (ins->handler_idx)
1625 case WINED3DSIH_MUL: op = '*'; break;
1626 case WINED3DSIH_ADD: op = '+'; break;
1627 case WINED3DSIH_SUB: op = '-'; break;
1628 default:
1629 op = ' ';
1630 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1631 break;
1634 write_mask = shader_glsl_append_dst(buffer, ins);
1635 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1636 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1637 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1640 /* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1641 static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
1643 SHADER_BUFFER *buffer = ins->ctx->buffer;
1644 glsl_src_param_t src0_param;
1645 DWORD write_mask;
1647 write_mask = shader_glsl_append_dst(buffer, ins);
1648 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1650 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1651 * shader versions WINED3DSIO_MOVA is used for this. */
1652 if ((WINED3DSHADER_VERSION_MAJOR(ins->ctx->reg_maps->shader_version) == 1
1653 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version)
1654 && ins->dst[0].register_type == WINED3DSPR_ADDR))
1656 /* This is a simple floor() */
1657 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1658 if (mask_size > 1) {
1659 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
1660 } else {
1661 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
1664 else if(ins->handler_idx == WINED3DSIH_MOVA)
1666 /* We need to *round* to the nearest int here. */
1667 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
1668 if (mask_size > 1) {
1669 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);
1670 } else {
1671 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1673 } else {
1674 shader_addline(buffer, "%s);\n", src0_param.param_str);
1678 /* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
1679 static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
1681 SHADER_BUFFER *buffer = ins->ctx->buffer;
1682 glsl_src_param_t src0_param;
1683 glsl_src_param_t src1_param;
1684 DWORD dst_write_mask, src_write_mask;
1685 unsigned int dst_size = 0;
1687 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1688 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1690 /* dp3 works on vec3, dp4 on vec4 */
1691 if (ins->handler_idx == WINED3DSIH_DP4)
1693 src_write_mask = WINED3DSP_WRITEMASK_ALL;
1694 } else {
1695 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1698 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
1699 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
1701 if (dst_size > 1) {
1702 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1703 } else {
1704 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1708 /* Note that this instruction has some restrictions. The destination write mask
1709 * can't contain the w component, and the source swizzles have to be .xyzw */
1710 static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
1712 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1713 glsl_src_param_t src0_param;
1714 glsl_src_param_t src1_param;
1715 char dst_mask[6];
1717 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1718 shader_glsl_append_dst(ins->ctx->buffer, ins);
1719 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
1720 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
1721 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1724 /* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
1725 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
1726 * GLSL uses the value as-is. */
1727 static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
1729 SHADER_BUFFER *buffer = ins->ctx->buffer;
1730 glsl_src_param_t src0_param;
1731 glsl_src_param_t src1_param;
1732 DWORD dst_write_mask;
1733 unsigned int dst_size;
1735 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1736 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1738 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1739 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
1741 if (dst_size > 1) {
1742 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1743 } else {
1744 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
1748 /* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
1749 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
1750 * GLSL uses the value as-is. */
1751 static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
1753 SHADER_BUFFER *buffer = ins->ctx->buffer;
1754 glsl_src_param_t src0_param;
1755 DWORD dst_write_mask;
1756 unsigned int dst_size;
1758 dst_write_mask = shader_glsl_append_dst(buffer, ins);
1759 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1761 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
1763 if (dst_size > 1) {
1764 shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
1765 } else {
1766 shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
1770 /* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
1771 static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
1773 SHADER_BUFFER *buffer = ins->ctx->buffer;
1774 glsl_src_param_t src_param;
1775 const char *instruction;
1776 DWORD write_mask;
1777 unsigned i;
1779 /* Determine the GLSL function to use based on the opcode */
1780 /* TODO: Possibly make this a table for faster lookups */
1781 switch (ins->handler_idx)
1783 case WINED3DSIH_MIN: instruction = "min"; break;
1784 case WINED3DSIH_MAX: instruction = "max"; break;
1785 case WINED3DSIH_ABS: instruction = "abs"; break;
1786 case WINED3DSIH_FRC: instruction = "fract"; break;
1787 case WINED3DSIH_NRM: instruction = "normalize"; break;
1788 case WINED3DSIH_EXP: instruction = "exp2"; break;
1789 case WINED3DSIH_SGN: instruction = "sign"; break;
1790 case WINED3DSIH_DSX: instruction = "dFdx"; break;
1791 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
1792 default: instruction = "";
1793 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
1794 break;
1797 write_mask = shader_glsl_append_dst(buffer, ins);
1799 shader_addline(buffer, "%s(", instruction);
1801 if (ins->src_count)
1803 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
1804 shader_addline(buffer, "%s", src_param.param_str);
1805 for (i = 1; i < ins->src_count; ++i)
1807 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
1808 shader_addline(buffer, ", %s", src_param.param_str);
1812 shader_addline(buffer, "));\n");
1815 /** Process the WINED3DSIO_EXPP instruction in GLSL:
1816 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
1817 * dst.x = 2^(floor(src))
1818 * dst.y = src - floor(src)
1819 * dst.z = 2^src (partial precision is allowed, but optional)
1820 * dst.w = 1.0;
1821 * For 2.0 shaders, just do this (honoring writemask and swizzle):
1822 * dst = 2^src; (partial precision is allowed, but optional)
1824 static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
1826 glsl_src_param_t src_param;
1828 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
1830 if (ins->ctx->reg_maps->shader_version < WINED3DPS_VERSION(2,0))
1832 char dst_mask[6];
1834 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
1835 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
1836 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1837 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
1839 shader_glsl_append_dst(ins->ctx->buffer, ins);
1840 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
1841 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
1842 } else {
1843 DWORD write_mask;
1844 unsigned int mask_size;
1846 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1847 mask_size = shader_glsl_get_write_mask_size(write_mask);
1849 if (mask_size > 1) {
1850 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1851 } else {
1852 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
1857 /** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
1858 static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
1860 glsl_src_param_t src_param;
1861 DWORD write_mask;
1862 unsigned int mask_size;
1864 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1865 mask_size = shader_glsl_get_write_mask_size(write_mask);
1866 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
1868 if (mask_size > 1) {
1869 shader_addline(ins->ctx->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1870 } else {
1871 shader_addline(ins->ctx->buffer, "1.0 / %s);\n", src_param.param_str);
1875 static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
1877 SHADER_BUFFER *buffer = ins->ctx->buffer;
1878 glsl_src_param_t src_param;
1879 DWORD write_mask;
1880 unsigned int mask_size;
1882 write_mask = shader_glsl_append_dst(buffer, ins);
1883 mask_size = shader_glsl_get_write_mask_size(write_mask);
1885 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
1887 if (mask_size > 1) {
1888 shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
1889 } else {
1890 shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
1894 /** Process signed comparison opcodes in GLSL. */
1895 static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
1897 glsl_src_param_t src0_param;
1898 glsl_src_param_t src1_param;
1899 DWORD write_mask;
1900 unsigned int mask_size;
1902 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1903 mask_size = shader_glsl_get_write_mask_size(write_mask);
1904 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
1905 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1907 if (mask_size > 1) {
1908 const char *compare;
1910 switch(ins->handler_idx)
1912 case WINED3DSIH_SLT: compare = "lessThan"; break;
1913 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
1914 default: compare = "";
1915 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
1918 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
1919 src0_param.param_str, src1_param.param_str);
1920 } else {
1921 switch(ins->handler_idx)
1923 case WINED3DSIH_SLT:
1924 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
1925 * to return 0.0 but step returns 1.0 because step is not < x
1926 * An alternative is a bvec compare padded with an unused second component.
1927 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
1928 * issue. Playing with not() is not possible either because not() does not accept
1929 * a scalar.
1931 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
1932 src0_param.param_str, src1_param.param_str);
1933 break;
1934 case WINED3DSIH_SGE:
1935 /* Here we can use the step() function and safe a conditional */
1936 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
1937 break;
1938 default:
1939 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
1945 /** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
1946 static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
1948 glsl_src_param_t src0_param;
1949 glsl_src_param_t src1_param;
1950 glsl_src_param_t src2_param;
1951 DWORD write_mask, cmp_channel = 0;
1952 unsigned int i, j;
1953 char mask_char[6];
1954 BOOL temp_destination = FALSE;
1956 if (shader_is_scalar(ins->src[0].register_type, ins->src[0].register_idx))
1958 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
1960 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
1961 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
1962 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
1964 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
1965 src0_param.param_str, src1_param.param_str, src2_param.param_str);
1966 } else {
1967 DWORD dst_mask = ins->dst[0].write_mask;
1968 struct wined3d_shader_dst_param dst = ins->dst[0];
1970 /* Cycle through all source0 channels */
1971 for (i=0; i<4; i++) {
1972 write_mask = 0;
1973 /* Find the destination channels which use the current source0 channel */
1974 for (j=0; j<4; j++) {
1975 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
1977 write_mask |= WINED3DSP_WRITEMASK_0 << j;
1978 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
1981 dst.write_mask = dst_mask & write_mask;
1983 /* Splitting the cmp instruction up in multiple lines imposes a problem:
1984 * The first lines may overwrite source parameters of the following lines.
1985 * Deal with that by using a temporary destination register if needed
1987 if ((ins->src[0].register_idx == ins->dst[0].register_idx
1988 && ins->src[0].register_type == ins->dst[0].register_type)
1989 || (ins->src[1].register_idx == ins->dst[0].register_idx
1990 && ins->src[1].register_type == ins->dst[0].register_type)
1991 || (ins->src[2].register_idx == ins->dst[0].register_idx
1992 && ins->src[2].register_type == ins->dst[0].register_type))
1994 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
1995 if (!write_mask) continue;
1996 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
1997 temp_destination = TRUE;
1998 } else {
1999 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2000 if (!write_mask) continue;
2003 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2004 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2005 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2007 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2008 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2011 if(temp_destination) {
2012 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2013 shader_glsl_append_dst(ins->ctx->buffer, ins);
2014 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2020 /** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2021 /* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2022 * the compare is done per component of src0. */
2023 static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2025 struct wined3d_shader_dst_param dst;
2026 glsl_src_param_t src0_param;
2027 glsl_src_param_t src1_param;
2028 glsl_src_param_t src2_param;
2029 DWORD write_mask, cmp_channel = 0;
2030 unsigned int i, j;
2031 DWORD dst_mask;
2033 if (ins->ctx->reg_maps->shader_version < WINED3DPS_VERSION(1, 4))
2035 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2036 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2037 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2038 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2040 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2041 if (ins->coissue)
2043 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2044 } else {
2045 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2046 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2048 return;
2050 /* Cycle through all source0 channels */
2051 dst_mask = ins->dst[0].write_mask;
2052 dst = ins->dst[0];
2053 for (i=0; i<4; i++) {
2054 write_mask = 0;
2055 /* Find the destination channels which use the current source0 channel */
2056 for (j=0; j<4; j++) {
2057 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2059 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2060 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2064 dst.write_mask = dst_mask & write_mask;
2065 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2066 if (!write_mask) continue;
2068 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2069 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2070 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2072 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2073 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2077 /** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2078 static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2080 glsl_src_param_t src0_param;
2081 glsl_src_param_t src1_param;
2082 glsl_src_param_t src2_param;
2083 DWORD write_mask;
2085 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2086 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2087 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2088 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2089 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2090 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2093 /** Handles transforming all WINED3DSIO_M?x? opcodes for
2094 Vertex shaders to GLSL codes */
2095 static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2097 int i;
2098 int nComponents = 0;
2099 struct wined3d_shader_dst_param tmp_dst = {0};
2100 struct wined3d_shader_src_param tmp_src[2] = {{0}};
2101 struct wined3d_shader_instruction tmp_ins;
2103 memset(&tmp_ins, 0, sizeof(tmp_ins));
2105 /* Set constants for the temporary argument */
2106 tmp_ins.ctx = ins->ctx;
2107 tmp_ins.dst_count = 1;
2108 tmp_ins.dst = &tmp_dst;
2109 tmp_ins.src_count = 2;
2110 tmp_ins.src = tmp_src;
2112 switch(ins->handler_idx)
2114 case WINED3DSIH_M4x4:
2115 nComponents = 4;
2116 tmp_ins.handler_idx = WINED3DSIH_DP4;
2117 break;
2118 case WINED3DSIH_M4x3:
2119 nComponents = 3;
2120 tmp_ins.handler_idx = WINED3DSIH_DP4;
2121 break;
2122 case WINED3DSIH_M3x4:
2123 nComponents = 4;
2124 tmp_ins.handler_idx = WINED3DSIH_DP3;
2125 break;
2126 case WINED3DSIH_M3x3:
2127 nComponents = 3;
2128 tmp_ins.handler_idx = WINED3DSIH_DP3;
2129 break;
2130 case WINED3DSIH_M3x2:
2131 nComponents = 2;
2132 tmp_ins.handler_idx = WINED3DSIH_DP3;
2133 break;
2134 default:
2135 break;
2138 tmp_dst = ins->dst[0];
2139 tmp_src[0] = ins->src[0];
2140 tmp_src[1] = ins->src[1];
2141 for (i = 0; i < nComponents; ++i)
2143 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2144 shader_glsl_dot(&tmp_ins);
2145 ++tmp_src[1].register_idx;
2150 The LRP instruction performs a component-wise linear interpolation
2151 between the second and third operands using the first operand as the
2152 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2153 This is equivalent to mix(src2, src1, src0);
2155 static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2157 glsl_src_param_t src0_param;
2158 glsl_src_param_t src1_param;
2159 glsl_src_param_t src2_param;
2160 DWORD write_mask;
2162 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2164 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2165 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2166 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2168 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2169 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2172 /** Process the WINED3DSIO_LIT instruction in GLSL:
2173 * dst.x = dst.w = 1.0
2174 * dst.y = (src0.x > 0) ? src0.x
2175 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2176 * where src.w is clamped at +- 128
2178 static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2180 glsl_src_param_t src0_param;
2181 glsl_src_param_t src1_param;
2182 glsl_src_param_t src3_param;
2183 char dst_mask[6];
2185 shader_glsl_append_dst(ins->ctx->buffer, ins);
2186 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2188 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2189 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2190 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2192 /* The sdk specifies the instruction like this
2193 * dst.x = 1.0;
2194 * if(src.x > 0.0) dst.y = src.x
2195 * else dst.y = 0.0.
2196 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2197 * else dst.z = 0.0;
2198 * dst.w = 1.0;
2200 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2201 * dst.x = 1.0 ... No further explanation needed
2202 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2203 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2204 * dst.w = 1.0. ... Nothing fancy.
2206 * So we still have one conditional in there. So do this:
2207 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2209 * 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),
2210 * 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.
2211 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2213 shader_addline(ins->ctx->buffer,
2214 "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",
2215 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2218 /** Process the WINED3DSIO_DST instruction in GLSL:
2219 * dst.x = 1.0
2220 * dst.y = src0.x * src0.y
2221 * dst.z = src0.z
2222 * dst.w = src1.w
2224 static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2226 glsl_src_param_t src0y_param;
2227 glsl_src_param_t src0z_param;
2228 glsl_src_param_t src1y_param;
2229 glsl_src_param_t src1w_param;
2230 char dst_mask[6];
2232 shader_glsl_append_dst(ins->ctx->buffer, ins);
2233 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2235 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2236 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2237 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2238 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2240 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2241 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2244 /** Process the WINED3DSIO_SINCOS instruction in GLSL:
2245 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2246 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2248 * dst.x = cos(src0.?)
2249 * dst.y = sin(src0.?)
2250 * dst.z = dst.z
2251 * dst.w = dst.w
2253 static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2255 glsl_src_param_t src0_param;
2256 DWORD write_mask;
2258 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2259 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2261 switch (write_mask) {
2262 case WINED3DSP_WRITEMASK_0:
2263 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2264 break;
2266 case WINED3DSP_WRITEMASK_1:
2267 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2268 break;
2270 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2271 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2272 break;
2274 default:
2275 ERR("Write mask should be .x, .y or .xy\n");
2276 break;
2280 /** Process the WINED3DSIO_LOOP instruction in GLSL:
2281 * Start a for() loop where src1.y is the initial value of aL,
2282 * increment aL by src1.z for a total of src1.x iterations.
2283 * Need to use a temporary variable for this operation.
2285 /* FIXME: I don't think nested loops will work correctly this way. */
2286 static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
2288 glsl_src_param_t src1_param;
2289 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2290 const DWORD *control_values = NULL;
2291 const local_constant *constant;
2293 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
2295 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
2296 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
2297 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
2298 * addressing.
2300 if (ins->src[1].register_type == WINED3DSPR_CONSTINT)
2302 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2303 if (constant->idx == ins->src[1].register_idx)
2305 control_values = constant->value;
2306 break;
2311 if(control_values) {
2312 if(control_values[2] > 0) {
2313 shader_addline(ins->ctx->buffer, "for (aL%u = %d; aL%u < (%d * %d + %d); aL%u += %d) {\n",
2314 shader->baseShader.cur_loop_depth, control_values[1],
2315 shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2316 shader->baseShader.cur_loop_depth, control_values[2]);
2317 } else if(control_values[2] == 0) {
2318 shader_addline(ins->ctx->buffer, "for (aL%u = %d, tmpInt%u = 0; tmpInt%u < %d; tmpInt%u++) {\n",
2319 shader->baseShader.cur_loop_depth, control_values[1], shader->baseShader.cur_loop_depth,
2320 shader->baseShader.cur_loop_depth, control_values[0],
2321 shader->baseShader.cur_loop_depth);
2322 } else {
2323 shader_addline(ins->ctx->buffer, "for (aL%u = %d; aL%u > (%d * %d + %d); aL%u += %d) {\n",
2324 shader->baseShader.cur_loop_depth, control_values[1],
2325 shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
2326 shader->baseShader.cur_loop_depth, control_values[2]);
2328 } else {
2329 shader_addline(ins->ctx->buffer,
2330 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
2331 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
2332 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
2333 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
2336 shader->baseShader.cur_loop_depth++;
2337 shader->baseShader.cur_loop_regno++;
2340 static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
2342 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2344 shader_addline(ins->ctx->buffer, "}\n");
2346 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
2348 shader->baseShader.cur_loop_depth--;
2349 shader->baseShader.cur_loop_regno--;
2352 if (ins->handler_idx == WINED3DSIH_ENDREP)
2354 shader->baseShader.cur_loop_depth--;
2358 static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
2360 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2361 glsl_src_param_t src0_param;
2362 const DWORD *control_values = NULL;
2363 const local_constant *constant;
2365 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
2366 if(ins->src[0].register_type == WINED3DSPR_CONSTINT) {
2367 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
2368 if(constant->idx == ins->src[0].register_idx) {
2369 control_values = constant->value;
2370 break;
2375 if(control_values) {
2376 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
2377 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2378 control_values[0], shader->baseShader.cur_loop_depth);
2379 } else {
2380 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2381 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
2382 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
2383 src0_param.param_str, shader->baseShader.cur_loop_depth);
2385 shader->baseShader.cur_loop_depth++;
2388 static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
2390 glsl_src_param_t src0_param;
2392 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2393 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
2396 static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
2398 glsl_src_param_t src0_param;
2399 glsl_src_param_t src1_param;
2401 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2402 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2404 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
2405 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2408 static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
2410 shader_addline(ins->ctx->buffer, "} else {\n");
2413 static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
2415 shader_addline(ins->ctx->buffer, "break;\n");
2418 /* FIXME: According to MSDN the compare is done per component. */
2419 static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
2421 glsl_src_param_t src0_param;
2422 glsl_src_param_t src1_param;
2424 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2425 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2427 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
2428 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
2431 static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
2433 shader_addline(ins->ctx->buffer, "}\n");
2434 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].register_idx);
2437 static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
2439 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].register_idx);
2442 static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
2444 glsl_src_param_t src1_param;
2446 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2447 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].register_idx);
2450 /*********************************************
2451 * Pixel Shader Specific Code begins here
2452 ********************************************/
2453 static void pshader_glsl_tex(const struct wined3d_shader_instruction *ins)
2455 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2456 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2457 DWORD shader_version = ins->ctx->reg_maps->shader_version;
2458 glsl_sample_function_t sample_function;
2459 DWORD sample_flags = 0;
2460 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
2461 DWORD sampler_idx;
2462 DWORD mask = 0, swizzle;
2464 /* 1.0-1.4: Use destination register as sampler source.
2465 * 2.0+: Use provided sampler source. */
2466 if (shader_version < WINED3DPS_VERSION(2,0)) sampler_idx = ins->dst[0].register_idx;
2467 else sampler_idx = ins->src[1].register_idx;
2468 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2470 if (shader_version < WINED3DPS_VERSION(1,4))
2472 DWORD flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2474 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
2475 if (flags & WINED3DTTFF_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
2476 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2477 switch (flags & ~WINED3DTTFF_PROJECTED) {
2478 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2479 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
2480 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
2481 case WINED3DTTFF_COUNT4:
2482 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
2486 else if (shader_version < WINED3DPS_VERSION(2,0))
2488 DWORD src_mod = ins->src[0].modifiers;
2490 if (src_mod == WINED3DSPSM_DZ) {
2491 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2492 mask = WINED3DSP_WRITEMASK_2;
2493 } else if (src_mod == WINED3DSPSM_DW) {
2494 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2495 mask = WINED3DSP_WRITEMASK_3;
2497 } else {
2498 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
2500 /* ps 2.0 texldp instruction always divides by the fourth component. */
2501 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
2502 mask = WINED3DSP_WRITEMASK_3;
2506 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2507 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2508 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2511 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2512 mask |= sample_function.coord_mask;
2514 if (shader_version < WINED3DPS_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
2515 else swizzle = ins->src[1].swizzle;
2517 /* 1.0-1.3: Use destination register as coordinate source.
2518 1.4+: Use provided coordinate source register. */
2519 if (shader_version < WINED3DPS_VERSION(1,4))
2521 char coord_mask[6];
2522 shader_glsl_write_mask_to_str(mask, coord_mask);
2523 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL,
2524 "T%u%s", sampler_idx, coord_mask);
2525 } else {
2526 glsl_src_param_t coord_param;
2527 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
2528 if (ins->flags & WINED3DSI_TEXLD_BIAS)
2530 glsl_src_param_t bias;
2531 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
2532 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, bias.param_str,
2533 "%s", coord_param.param_str);
2534 } else {
2535 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL,
2536 "%s", coord_param.param_str);
2541 static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
2543 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
2544 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2545 glsl_sample_function_t sample_function;
2546 glsl_src_param_t coord_param, lod_param;
2547 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
2548 DWORD sampler_type;
2549 DWORD sampler_idx;
2550 DWORD swizzle = ins->src[1].swizzle;
2552 sampler_idx = ins->src[1].register_idx;
2553 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2554 if(deviceImpl->stateBlock->textures[sampler_idx] &&
2555 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
2556 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
2558 shader_glsl_get_sample_function(sampler_type, sample_flags, &sample_function);
2559 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
2561 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
2563 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version))
2565 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
2566 * However, they seem to work just fine in fragment shaders as well. */
2567 WARN("Using %s in fragment shader.\n", sample_function.name);
2569 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, lod_param.param_str,
2570 "%s", coord_param.param_str);
2573 static void pshader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
2575 /* FIXME: Make this work for more than just 2D textures */
2576 SHADER_BUFFER *buffer = ins->ctx->buffer;
2577 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2579 if (ins->ctx->reg_maps->shader_version != WINED3DPS_VERSION(1,4))
2581 char dst_mask[6];
2583 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2584 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
2585 ins->dst[0].register_idx, dst_mask);
2586 } else {
2587 DWORD reg = ins->src[0].register_idx;
2588 DWORD src_mod = ins->src[0].modifiers;
2589 char dst_swizzle[6];
2591 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
2593 if (src_mod == WINED3DSPSM_DZ) {
2594 glsl_src_param_t div_param;
2595 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2596 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
2598 if (mask_size > 1) {
2599 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2600 } else {
2601 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2603 } else if (src_mod == WINED3DSPSM_DW) {
2604 glsl_src_param_t div_param;
2605 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2606 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
2608 if (mask_size > 1) {
2609 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2610 } else {
2611 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2613 } else {
2614 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
2619 /** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2620 * Take a 3-component dot product of the TexCoord[dstreg] and src,
2621 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
2622 static void pshader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
2624 glsl_src_param_t src0_param;
2625 glsl_sample_function_t sample_function;
2626 DWORD sampler_idx = ins->dst[0].register_idx;
2627 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2628 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2629 UINT mask_size;
2631 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2633 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2634 * scalar, and projected sampling would require 4.
2636 * It is a dependent read - not valid with conditional NP2 textures
2638 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2639 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
2641 switch(mask_size)
2643 case 1:
2644 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL,
2645 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
2646 break;
2648 case 2:
2649 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL,
2650 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
2651 break;
2653 case 3:
2654 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL,
2655 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
2656 break;
2658 default:
2659 FIXME("Unexpected mask size %u\n", mask_size);
2660 break;
2664 /** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2665 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
2666 static void pshader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
2668 glsl_src_param_t src0_param;
2669 DWORD dstreg = ins->dst[0].register_idx;
2670 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2671 DWORD dst_mask;
2672 unsigned int mask_size;
2674 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2675 mask_size = shader_glsl_get_write_mask_size(dst_mask);
2676 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2678 if (mask_size > 1) {
2679 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2680 } else {
2681 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2685 /** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2686 * Calculate the depth as dst.x / dst.y */
2687 static void pshader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
2689 glsl_dst_param_t dst_param;
2691 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
2693 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
2694 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2695 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
2696 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2697 * >= 1.0 or < 0.0
2699 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
2700 dst_param.reg_name, dst_param.reg_name);
2703 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2704 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
2705 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
2706 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
2708 static void pshader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
2710 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2711 DWORD dstreg = ins->dst[0].register_idx;
2712 glsl_src_param_t src0_param;
2714 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2716 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2717 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2720 /** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2721 * Calculate the 1st of a 2-row matrix multiplication. */
2722 static void pshader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
2724 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2725 DWORD reg = ins->dst[0].register_idx;
2726 SHADER_BUFFER *buffer = ins->ctx->buffer;
2727 glsl_src_param_t src0_param;
2729 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2730 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2733 /** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
2734 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
2735 static void pshader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
2737 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2738 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2739 DWORD reg = ins->dst[0].register_idx;
2740 SHADER_BUFFER *buffer = ins->ctx->buffer;
2741 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2742 glsl_src_param_t src0_param;
2744 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2745 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
2746 current_state->texcoord_w[current_state->current_row++] = reg;
2749 static void pshader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
2751 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2752 DWORD reg = ins->dst[0].register_idx;
2753 SHADER_BUFFER *buffer = ins->ctx->buffer;
2754 glsl_src_param_t src0_param;
2755 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
2756 glsl_sample_function_t sample_function;
2758 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2759 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2761 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2763 /* Sample the texture using the calculated coordinates */
2764 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, "tmp0.xy");
2767 /** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
2768 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
2769 static void pshader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
2771 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2772 glsl_src_param_t src0_param;
2773 DWORD reg = ins->dst[0].register_idx;
2774 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2775 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2776 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
2777 glsl_sample_function_t sample_function;
2779 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2780 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2782 /* Dependent read, not valid with conditional NP2 */
2783 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2785 /* Sample the texture using the calculated coordinates */
2786 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, "tmp0.xyz");
2788 current_state->current_row = 0;
2791 /** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
2792 * Perform the 3rd row of a 3x3 matrix multiply */
2793 static void pshader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
2795 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2796 glsl_src_param_t src0_param;
2797 char dst_mask[6];
2798 DWORD reg = ins->dst[0].register_idx;
2799 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2800 SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2802 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2804 shader_glsl_append_dst(ins->ctx->buffer, ins);
2805 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2806 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
2808 current_state->current_row = 0;
2811 /** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
2812 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2813 static void pshader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
2815 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2816 DWORD reg = ins->dst[0].register_idx;
2817 glsl_src_param_t src0_param;
2818 glsl_src_param_t src1_param;
2819 SHADER_BUFFER *buffer = ins->ctx->buffer;
2820 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2821 WINED3DSAMPLER_TEXTURE_TYPE stype = ins->ctx->reg_maps->sampler_type[reg];
2822 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2823 glsl_sample_function_t sample_function;
2825 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2826 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2828 /* Perform the last matrix multiply operation */
2829 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2830 /* Reflection calculation */
2831 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
2833 /* Dependent read, not valid with conditional NP2 */
2834 shader_glsl_get_sample_function(stype, 0, &sample_function);
2836 /* Sample the texture */
2837 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, "tmp0.xyz");
2839 current_state->current_row = 0;
2842 /** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
2843 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
2844 static void pshader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
2846 IWineD3DPixelShaderImpl *shader = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2847 DWORD reg = ins->dst[0].register_idx;
2848 SHADER_BUFFER *buffer = ins->ctx->buffer;
2849 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2850 glsl_src_param_t src0_param;
2851 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2852 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
2853 glsl_sample_function_t sample_function;
2855 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2857 /* Perform the last matrix multiply operation */
2858 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
2860 /* Construct the eye-ray vector from w coordinates */
2861 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
2862 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
2863 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
2865 /* Dependent read, not valid with conditional NP2 */
2866 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2868 /* Sample the texture using the calculated coordinates */
2869 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, "tmp0.xyz");
2871 current_state->current_row = 0;
2874 /** Process the WINED3DSIO_TEXBEM instruction in GLSL.
2875 * Apply a fake bump map transform.
2876 * texbem is pshader <= 1.3 only, this saves a few version checks
2878 static void pshader_glsl_texbem(const struct wined3d_shader_instruction *ins)
2880 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
2881 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2882 glsl_sample_function_t sample_function;
2883 glsl_src_param_t coord_param;
2884 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
2885 DWORD sampler_idx;
2886 DWORD mask;
2887 DWORD flags;
2888 char coord_mask[6];
2890 sampler_idx = ins->dst[0].register_idx;
2891 flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];
2893 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2894 /* Dependent read, not valid with conditional NP2 */
2895 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2896 mask = sample_function.coord_mask;
2898 shader_glsl_write_mask_to_str(mask, coord_mask);
2900 /* with projective textures, texbem only divides the static texture coord, not the displacement,
2901 * so we can't let the GL handle this.
2903 if (flags & WINED3DTTFF_PROJECTED) {
2904 DWORD div_mask=0;
2905 char coord_div_mask[3];
2906 switch (flags & ~WINED3DTTFF_PROJECTED) {
2907 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2908 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
2909 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
2910 case WINED3DTTFF_COUNT4:
2911 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
2913 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
2914 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
2917 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
2919 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL,
2920 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
2921 coord_param.param_str, coord_mask);
2923 if (ins->handler_idx == WINED3DSIH_TEXBEML)
2925 glsl_src_param_t luminance_param;
2926 glsl_dst_param_t dst_param;
2928 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
2929 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
2931 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
2932 dst_param.reg_name, dst_param.mask_str,
2933 luminance_param.param_str, sampler_idx, sampler_idx);
2937 static void pshader_glsl_bem(const struct wined3d_shader_instruction *ins)
2939 glsl_src_param_t src0_param, src1_param;
2940 DWORD sampler_idx = ins->dst[0].register_idx;
2942 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
2943 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
2945 shader_glsl_append_dst(ins->ctx->buffer, ins);
2946 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
2947 src0_param.param_str, sampler_idx, src1_param.param_str);
2950 /** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
2951 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
2952 static void pshader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
2954 glsl_src_param_t src0_param;
2955 DWORD sampler_idx = ins->dst[0].register_idx;
2956 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2957 glsl_sample_function_t sample_function;
2959 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2961 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2962 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL,
2963 "%s.wx", src0_param.reg_name);
2966 /** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
2967 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
2968 static void pshader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
2970 glsl_src_param_t src0_param;
2971 DWORD sampler_idx = ins->dst[0].register_idx;
2972 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2973 glsl_sample_function_t sample_function;
2975 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2977 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2978 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL,
2979 "%s.yz", src0_param.reg_name);
2982 /** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
2983 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
2984 static void pshader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
2986 glsl_src_param_t src0_param;
2987 DWORD sampler_idx = ins->dst[0].register_idx;
2988 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
2989 glsl_sample_function_t sample_function;
2991 /* Dependent read, not valid with conditional NP2 */
2992 shader_glsl_get_sample_function(sampler_type, 0, &sample_function);
2993 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
2995 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL,
2996 "%s", src0_param.param_str);
2999 /** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3000 * If any of the first 3 components are < 0, discard this pixel */
3001 static void pshader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3003 glsl_dst_param_t dst_param;
3005 /* The argument is a destination parameter, and no writemasks are allowed */
3006 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3007 if ((ins->ctx->reg_maps->shader_version >= WINED3DPS_VERSION(2,0)))
3009 /* 2.0 shaders compare all 4 components in texkill */
3010 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3011 } else {
3012 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3013 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3014 * 4 components are defined, only the first 3 are used
3016 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3020 /** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3021 * dst = dot2(src0, src1) + src2 */
3022 static void pshader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3024 glsl_src_param_t src0_param;
3025 glsl_src_param_t src1_param;
3026 glsl_src_param_t src2_param;
3027 DWORD write_mask;
3028 unsigned int mask_size;
3030 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3031 mask_size = shader_glsl_get_write_mask_size(write_mask);
3033 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3034 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3035 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3037 if (mask_size > 1) {
3038 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3039 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3040 } else {
3041 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3042 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3046 static void pshader_glsl_input_pack(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer,
3047 const struct wined3d_shader_semantic *semantics_in, const struct shader_reg_maps *reg_maps,
3048 enum vertexprocessing_mode vertexprocessing)
3050 unsigned int i;
3051 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3053 for (i = 0; i < MAX_REG_INPUT; ++i)
3055 DWORD usage, usage_idx;
3056 char reg_mask[6];
3058 /* Unused */
3059 if (!reg_maps->packed_input[i]) continue;
3061 usage = semantics_in[i].usage;
3062 usage_idx = semantics_in[i].usage_idx;
3063 shader_glsl_get_write_mask(&semantics_in[i].reg, reg_mask);
3065 switch (usage)
3067 case WINED3DDECLUSAGE_TEXCOORD:
3068 if (usage_idx < 8 && vertexprocessing == pretransformed)
3069 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3070 This->input_reg_map[i], reg_mask, usage_idx, reg_mask);
3071 else
3072 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3073 This->input_reg_map[i], reg_mask, reg_mask);
3074 break;
3076 case WINED3DDECLUSAGE_COLOR:
3077 if (usage_idx == 0)
3078 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3079 This->input_reg_map[i], reg_mask, reg_mask);
3080 else if (usage_idx == 1)
3081 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3082 This->input_reg_map[i], reg_mask, reg_mask);
3083 else
3084 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3085 This->input_reg_map[i], reg_mask, reg_mask);
3086 break;
3088 default:
3089 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3090 This->input_reg_map[i], reg_mask, reg_mask);
3091 break;
3096 /*********************************************
3097 * Vertex Shader Specific Code begins here
3098 ********************************************/
3100 static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3101 glsl_program_key_t *key;
3103 key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
3104 key->vshader = entry->vshader;
3105 key->pshader = entry->pshader;
3106 key->vs_args = entry->vs_args;
3107 key->ps_args = entry->ps_args;
3109 hash_table_put(priv->glsl_program_lookup, key, entry);
3112 static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3113 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3114 struct ps_compile_args *ps_args) {
3115 glsl_program_key_t key;
3117 key.vshader = vshader;
3118 key.pshader = pshader;
3119 key.vs_args = *vs_args;
3120 key.ps_args = *ps_args;
3122 return hash_table_get(priv->glsl_program_lookup, &key);
3125 static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const WineD3D_GL_Info *gl_info,
3126 struct glsl_shader_prog_link *entry)
3128 glsl_program_key_t *key;
3130 key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
3131 key->vshader = entry->vshader;
3132 key->pshader = entry->pshader;
3133 key->vs_args = entry->vs_args;
3134 key->ps_args = entry->ps_args;
3135 hash_table_remove(priv->glsl_program_lookup, key);
3137 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3138 if (entry->vshader) list_remove(&entry->vshader_entry);
3139 if (entry->pshader) list_remove(&entry->pshader_entry);
3140 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3141 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3142 HeapFree(GetProcessHeap(), 0, entry);
3145 static void handle_ps3_input(SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info, const DWORD *map,
3146 const struct wined3d_shader_semantic *semantics_in, const struct shader_reg_maps *reg_maps_in,
3147 const struct wined3d_shader_semantic *semantics_out, const struct shader_reg_maps *reg_maps_out)
3149 unsigned int i, j;
3150 DWORD usage, usage_idx, usage_out, usage_idx_out;
3151 DWORD *set;
3152 DWORD in_idx;
3153 DWORD in_count = GL_LIMITS(glsl_varyings) / 4;
3154 char reg_mask[6], reg_mask_out[6];
3155 char destination[50];
3157 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3159 if (!semantics_out) {
3160 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3161 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3162 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3165 for(i = 0; i < MAX_REG_INPUT; i++) {
3166 if (!reg_maps_in->packed_input[i]) continue;
3168 in_idx = map[i];
3169 if (in_idx >= (in_count + 2)) {
3170 FIXME("More input varyings declared than supported, expect issues\n");
3171 continue;
3173 else if (map[i] == ~0U)
3175 /* Declared, but not read register */
3176 continue;
3179 if (in_idx == in_count) {
3180 sprintf(destination, "gl_FrontColor");
3181 } else if (in_idx == in_count + 1) {
3182 sprintf(destination, "gl_FrontSecondaryColor");
3183 } else {
3184 sprintf(destination, "IN[%u]", in_idx);
3187 usage = semantics_in[i].usage;
3188 usage_idx = semantics_in[i].usage_idx;
3189 set[map[i]] = shader_glsl_get_write_mask(&semantics_in[i].reg, reg_mask);
3191 if(!semantics_out) {
3192 switch(usage) {
3193 case WINED3DDECLUSAGE_COLOR:
3194 if (usage_idx == 0)
3195 shader_addline(buffer, "%s%s = front_color%s;\n",
3196 destination, reg_mask, reg_mask);
3197 else if (usage_idx == 1)
3198 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
3199 destination, reg_mask, reg_mask);
3200 else
3201 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3202 destination, reg_mask, reg_mask);
3203 break;
3205 case WINED3DDECLUSAGE_TEXCOORD:
3206 if (usage_idx < 8) {
3207 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
3208 destination, reg_mask, usage_idx, reg_mask);
3209 } else {
3210 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3211 destination, reg_mask, reg_mask);
3213 break;
3215 case WINED3DDECLUSAGE_FOG:
3216 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
3217 destination, reg_mask, reg_mask);
3218 break;
3220 default:
3221 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3222 destination, reg_mask, reg_mask);
3224 } else {
3225 BOOL found = FALSE;
3226 for(j = 0; j < MAX_REG_OUTPUT; j++) {
3227 if (!reg_maps_out->packed_output[j]) continue;
3229 usage_out = semantics_out[j].usage;
3230 usage_idx_out = semantics_out[j].usage_idx;
3231 shader_glsl_get_write_mask(&semantics_out[j].reg, reg_mask_out);
3233 if(usage == usage_out &&
3234 usage_idx == usage_idx_out) {
3235 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
3236 destination, reg_mask, j, reg_mask);
3237 found = TRUE;
3240 if(!found) {
3241 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3242 destination, reg_mask, reg_mask);
3247 /* This is solely to make the compiler / linker happy and avoid warning about undefined
3248 * varyings. It shouldn't result in any real code executed on the GPU, since all read
3249 * input varyings are assigned above, if the optimizer works properly.
3251 for(i = 0; i < in_count + 2; i++) {
3252 if(set[i] != WINED3DSP_WRITEMASK_ALL) {
3253 unsigned int size = 0;
3254 memset(reg_mask, 0, sizeof(reg_mask));
3255 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
3256 reg_mask[size] = 'x';
3257 size++;
3259 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
3260 reg_mask[size] = 'y';
3261 size++;
3263 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
3264 reg_mask[size] = 'z';
3265 size++;
3267 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
3268 reg_mask[size] = 'w';
3269 size++;
3272 if (i == in_count) {
3273 sprintf(destination, "gl_FrontColor");
3274 } else if (i == in_count + 1) {
3275 sprintf(destination, "gl_FrontSecondaryColor");
3276 } else {
3277 sprintf(destination, "IN[%u]", i);
3280 if (size == 1) {
3281 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
3282 } else {
3283 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
3288 HeapFree(GetProcessHeap(), 0, set);
3291 static GLhandleARB generate_param_reorder_function(IWineD3DVertexShader *vertexshader,
3292 IWineD3DPixelShader *pixelshader, const WineD3D_GL_Info *gl_info)
3294 GLhandleARB ret = 0;
3295 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
3296 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
3297 IWineD3DDeviceImpl *device;
3298 DWORD vs_major = WINED3DSHADER_VERSION_MAJOR(vs->baseShader.reg_maps.shader_version);
3299 DWORD ps_major = ps ? WINED3DSHADER_VERSION_MAJOR(ps->baseShader.reg_maps.shader_version) : 0;
3300 unsigned int i;
3301 SHADER_BUFFER buffer;
3302 DWORD usage, usage_idx, writemask;
3303 char reg_mask[6];
3304 const struct wined3d_shader_semantic *semantics_out;
3306 shader_buffer_init(&buffer);
3308 shader_addline(&buffer, "#version 120\n");
3310 if(vs_major < 3 && ps_major < 3) {
3311 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
3312 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
3314 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
3315 if((GLINFO_LOCATION).set_texcoord_w && ps_major == 0 && vs_major > 0 &&
3316 !device->frag_pipe->ffp_proj_control) {
3317 shader_addline(&buffer, "void order_ps_input() {\n");
3318 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
3319 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
3320 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
3321 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
3324 shader_addline(&buffer, "}\n");
3325 } else {
3326 shader_addline(&buffer, "void order_ps_input() { /* do nothing */ }\n");
3328 } else if(ps_major < 3 && vs_major >= 3) {
3329 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
3330 semantics_out = vs->semantics_out;
3332 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3333 for(i = 0; i < MAX_REG_OUTPUT; i++) {
3334 if (!vs->baseShader.reg_maps.packed_output[i]) continue;
3336 usage = semantics_out[i].usage;
3337 usage_idx = semantics_out[i].usage_idx;
3338 writemask = shader_glsl_get_write_mask(&semantics_out[i].reg, reg_mask);
3340 switch(usage) {
3341 case WINED3DDECLUSAGE_COLOR:
3342 if (usage_idx == 0)
3343 shader_addline(&buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3344 else if (usage_idx == 1)
3345 shader_addline(&buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3346 break;
3348 case WINED3DDECLUSAGE_POSITION:
3349 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3350 break;
3352 case WINED3DDECLUSAGE_TEXCOORD:
3353 if (usage_idx < 8) {
3354 if(!(GLINFO_LOCATION).set_texcoord_w || ps_major > 0) writemask |= WINED3DSP_WRITEMASK_3;
3356 shader_addline(&buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
3357 usage_idx, reg_mask, i, reg_mask);
3358 if(!(writemask & WINED3DSP_WRITEMASK_3)) {
3359 shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", usage_idx);
3362 break;
3364 case WINED3DDECLUSAGE_PSIZE:
3365 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3366 break;
3368 case WINED3DDECLUSAGE_FOG:
3369 shader_addline(&buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
3370 break;
3372 default:
3373 break;
3376 shader_addline(&buffer, "}\n");
3378 } else if(ps_major >= 3 && vs_major >= 3) {
3379 semantics_out = vs->semantics_out;
3381 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
3382 shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
3383 shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
3385 /* First, sort out position and point size. Those are not passed to the pixel shader */
3386 for(i = 0; i < MAX_REG_OUTPUT; i++) {
3387 if (!vs->baseShader.reg_maps.packed_output[i]) continue;
3389 usage = semantics_out[i].usage;
3390 usage_idx = semantics_out[i].usage_idx;
3391 shader_glsl_get_write_mask(&semantics_out[i].reg, reg_mask);
3393 switch(usage) {
3394 case WINED3DDECLUSAGE_POSITION:
3395 shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
3396 break;
3398 case WINED3DDECLUSAGE_PSIZE:
3399 shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
3400 break;
3402 default:
3403 break;
3407 /* Then, fix the pixel shader input */
3408 handle_ps3_input(&buffer, gl_info, ps->input_reg_map,
3409 ps->semantics_in, &ps->baseShader.reg_maps, semantics_out, &vs->baseShader.reg_maps);
3411 shader_addline(&buffer, "}\n");
3412 } else if(ps_major >= 3 && vs_major < 3) {
3413 shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
3414 shader_addline(&buffer, "void order_ps_input() {\n");
3415 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
3416 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
3417 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
3419 handle_ps3_input(&buffer, gl_info, ps->input_reg_map, ps->semantics_in, &ps->baseShader.reg_maps, NULL, NULL);
3420 shader_addline(&buffer, "}\n");
3421 } else {
3422 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
3425 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3426 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
3427 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL));
3428 checkGLcall("glShaderSourceARB(ret, 1, &buffer.buffer, NULL)");
3429 GL_EXTCALL(glCompileShaderARB(ret));
3430 checkGLcall("glCompileShaderARB(ret)");
3432 shader_buffer_free(&buffer);
3433 return ret;
3436 static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const WineD3D_GL_Info *gl_info,
3437 GLhandleARB programId, char prefix)
3439 const local_constant *lconst;
3440 GLint tmp_loc;
3441 const float *value;
3442 char glsl_name[8];
3444 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
3445 value = (const float *)lconst->value;
3446 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
3447 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3448 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
3450 checkGLcall("Hardcoding local constants\n");
3453 /** Sets the GLSL program ID for the given pixel and vertex shader combination.
3454 * It sets the programId on the current StateBlock (because it should be called
3455 * inside of the DrawPrimitive() part of the render loop).
3457 * If a program for the given combination does not exist, create one, and store
3458 * the program in the hash table. If it creates a program, it will link the
3459 * given objects, too.
3461 static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
3462 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3463 struct shader_glsl_priv *priv = This->shader_priv;
3464 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3465 IWineD3DPixelShader *pshader = This->stateBlock->pixelShader;
3466 IWineD3DVertexShader *vshader = This->stateBlock->vertexShader;
3467 struct glsl_shader_prog_link *entry = NULL;
3468 GLhandleARB programId = 0;
3469 GLhandleARB reorder_shader_id = 0;
3470 unsigned int i;
3471 char glsl_name[8];
3472 GLhandleARB vshader_id, pshader_id;
3473 struct ps_compile_args ps_compile_args;
3474 struct vs_compile_args vs_compile_args;
3476 if(use_vs) {
3477 find_vs_compile_args((IWineD3DVertexShaderImpl*)This->stateBlock->vertexShader, This->stateBlock, &vs_compile_args);
3478 } else {
3479 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3480 memset(&vs_compile_args, 0, sizeof(vs_compile_args));
3482 if(use_ps) {
3483 find_ps_compile_args((IWineD3DPixelShaderImpl*)This->stateBlock->pixelShader, This->stateBlock, &ps_compile_args);
3484 } else {
3485 /* FIXME: Do we really have to spend CPU cycles to generate a few zeroed bytes? */
3486 memset(&ps_compile_args, 0, sizeof(ps_compile_args));
3488 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args);
3489 if (entry) {
3490 priv->glsl_program = entry;
3491 return;
3494 /* If we get to this point, then no matching program exists, so we create one */
3495 programId = GL_EXTCALL(glCreateProgramObjectARB());
3496 TRACE("Created new GLSL shader program %u\n", programId);
3498 /* Create the entry */
3499 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
3500 entry->programId = programId;
3501 entry->vshader = vshader;
3502 entry->pshader = pshader;
3503 entry->vs_args = vs_compile_args;
3504 entry->ps_args = ps_compile_args;
3505 entry->constant_version = 0;
3506 /* Add the hash table entry */
3507 add_glsl_program_entry(priv, entry);
3509 /* Set the current program */
3510 priv->glsl_program = entry;
3512 if(use_vs) {
3513 vshader_id = find_gl_vshader((IWineD3DVertexShaderImpl *) vshader, &vs_compile_args);
3514 } else {
3515 vshader_id = 0;
3518 /* Attach GLSL vshader */
3519 if (vshader_id) {
3520 const unsigned int max_attribs = 16; /* TODO: Will this always be the case? It is at the moment... */
3521 char tmp_name[10];
3523 reorder_shader_id = generate_param_reorder_function(vshader, pshader, gl_info);
3524 TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
3525 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
3526 checkGLcall("glAttachObjectARB");
3527 /* Flag the reorder function for deletion, then it will be freed automatically when the program
3528 * is destroyed
3530 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
3532 TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
3533 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
3534 checkGLcall("glAttachObjectARB");
3536 /* Bind vertex attributes to a corresponding index number to match
3537 * the same index numbers as ARB_vertex_programs (makes loading
3538 * vertex attributes simpler). With this method, we can use the
3539 * exact same code to load the attributes later for both ARB and
3540 * GLSL shaders.
3542 * We have to do this here because we need to know the Program ID
3543 * in order to make the bindings work, and it has to be done prior
3544 * to linking the GLSL program. */
3545 for (i = 0; i < max_attribs; ++i) {
3546 if (((IWineD3DBaseShaderImpl*)vshader)->baseShader.reg_maps.attributes[i]) {
3547 snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
3548 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
3551 checkGLcall("glBindAttribLocationARB");
3553 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
3556 if(use_ps) {
3557 pshader_id = find_gl_pshader((IWineD3DPixelShaderImpl *) pshader, &ps_compile_args);
3558 } else {
3559 pshader_id = 0;
3562 /* Attach GLSL pshader */
3563 if (pshader_id) {
3564 TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
3565 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
3566 checkGLcall("glAttachObjectARB");
3568 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
3571 /* Link the program */
3572 TRACE("Linking GLSL shader program %u\n", programId);
3573 GL_EXTCALL(glLinkProgramARB(programId));
3574 print_glsl_info_log(&GLINFO_LOCATION, programId);
3576 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
3577 for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
3578 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
3579 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3581 for (i = 0; i < MAX_CONST_I; ++i) {
3582 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
3583 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3585 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
3586 for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
3587 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
3588 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3590 for (i = 0; i < MAX_CONST_I; ++i) {
3591 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
3592 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3595 if(pshader) {
3596 for(i = 0; i < ((IWineD3DPixelShaderImpl*)pshader)->numbumpenvmatconsts; i++) {
3597 char name[32];
3598 sprintf(name, "bumpenvmat%d", ((IWineD3DPixelShaderImpl*)pshader)->bumpenvmatconst[i].texunit);
3599 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3600 sprintf(name, "luminancescale%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
3601 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3602 sprintf(name, "luminanceoffset%d", ((IWineD3DPixelShaderImpl*)pshader)->luminanceconst[i].texunit);
3603 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3607 if (use_ps && ps_compile_args.np2_fixup) {
3608 char name[32];
3609 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
3610 if (ps_compile_args.np2_fixup & (1 << i)) {
3611 sprintf(name, "PsamplerNP2Fixup%u", i);
3612 entry->np2Fixup_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
3613 } else {
3614 entry->np2Fixup_location[i] = -1;
3619 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
3620 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
3621 checkGLcall("Find glsl program uniform locations");
3623 if (pshader
3624 && WINED3DSHADER_VERSION_MAJOR(((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version) >= 3
3625 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > GL_LIMITS(glsl_varyings) / 4)
3627 TRACE("Shader %d needs vertex color clamping disabled\n", programId);
3628 entry->vertex_color_clamp = GL_FALSE;
3629 } else {
3630 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
3633 /* Set the shader to allow uniform loading on it */
3634 GL_EXTCALL(glUseProgramObjectARB(programId));
3635 checkGLcall("glUseProgramObjectARB(programId)");
3637 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
3638 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
3639 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
3640 * vertex shader with fixed function pixel processing is used we make sure that the card
3641 * supports enough samplers to allow the max number of vertex samplers with all possible
3642 * fixed function fragment processing setups. So once the program is linked these samplers
3643 * won't change.
3645 if(vshader_id) {
3646 /* Load vertex shader samplers */
3647 shader_glsl_load_vsamplers(gl_info, This->texUnitMap, programId);
3649 if(pshader_id) {
3650 /* Load pixel shader samplers */
3651 shader_glsl_load_psamplers(gl_info, This->texUnitMap, programId);
3654 /* If the local constants do not have to be loaded with the environment constants,
3655 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
3656 * later
3658 if(pshader && !((IWineD3DPixelShaderImpl*)pshader)->baseShader.load_local_constsF) {
3659 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
3661 if(vshader && !((IWineD3DVertexShaderImpl*)vshader)->baseShader.load_local_constsF) {
3662 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
3666 static GLhandleARB create_glsl_blt_shader(const WineD3D_GL_Info *gl_info, enum tex_types tex_type)
3668 GLhandleARB program_id;
3669 GLhandleARB vshader_id, pshader_id;
3670 static const char *blt_vshader[] =
3672 "#version 120\n"
3673 "void main(void)\n"
3674 "{\n"
3675 " gl_Position = gl_Vertex;\n"
3676 " gl_FrontColor = vec4(1.0);\n"
3677 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
3678 "}\n"
3681 static const char *blt_pshaders[tex_type_count] =
3683 /* tex_1d */
3684 NULL,
3685 /* tex_2d */
3686 "#version 120\n"
3687 "uniform sampler2D sampler;\n"
3688 "void main(void)\n"
3689 "{\n"
3690 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
3691 "}\n",
3692 /* tex_3d */
3693 NULL,
3694 /* tex_cube */
3695 "#version 120\n"
3696 "uniform samplerCube sampler;\n"
3697 "void main(void)\n"
3698 "{\n"
3699 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
3700 "}\n",
3701 /* tex_rect */
3702 "#version 120\n"
3703 "#extension GL_ARB_texture_rectangle : enable\n"
3704 "uniform sampler2DRect sampler;\n"
3705 "void main(void)\n"
3706 "{\n"
3707 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
3708 "}\n",
3711 if (!blt_pshaders[tex_type])
3713 FIXME("tex_type %#x not supported\n", tex_type);
3714 tex_type = tex_2d;
3717 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
3718 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
3719 GL_EXTCALL(glCompileShaderARB(vshader_id));
3721 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3722 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
3723 GL_EXTCALL(glCompileShaderARB(pshader_id));
3725 program_id = GL_EXTCALL(glCreateProgramObjectARB());
3726 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
3727 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
3728 GL_EXTCALL(glLinkProgramARB(program_id));
3730 print_glsl_info_log(&GLINFO_LOCATION, program_id);
3732 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
3733 * is destroyed
3735 GL_EXTCALL(glDeleteObjectARB(vshader_id));
3736 GL_EXTCALL(glDeleteObjectARB(pshader_id));
3737 return program_id;
3740 static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
3741 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3742 struct shader_glsl_priv *priv = This->shader_priv;
3743 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3744 GLhandleARB program_id = 0;
3745 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
3747 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
3749 if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
3750 else priv->glsl_program = NULL;
3752 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
3754 if (old_vertex_color_clamp != current_vertex_color_clamp) {
3755 if (GL_SUPPORT(ARB_COLOR_BUFFER_FLOAT)) {
3756 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
3757 checkGLcall("glClampColorARB");
3758 } else {
3759 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
3763 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
3764 if (program_id) TRACE("Using GLSL program %u\n", program_id);
3765 GL_EXTCALL(glUseProgramObjectARB(program_id));
3766 checkGLcall("glUseProgramObjectARB");
3769 static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
3770 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3771 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3772 struct shader_glsl_priv *priv = This->shader_priv;
3773 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
3775 if (!*blt_program) {
3776 GLint loc;
3777 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
3778 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
3779 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
3780 GL_EXTCALL(glUniform1iARB(loc, 0));
3781 } else {
3782 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
3786 static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
3787 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3788 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3789 struct shader_glsl_priv *priv = This->shader_priv;
3790 GLhandleARB program_id;
3792 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
3793 if (program_id) TRACE("Using GLSL program %u\n", program_id);
3795 GL_EXTCALL(glUseProgramObjectARB(program_id));
3796 checkGLcall("glUseProgramObjectARB");
3799 static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
3800 const struct list *linked_programs;
3801 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
3802 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
3803 struct shader_glsl_priv *priv = device->shader_priv;
3804 const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
3805 IWineD3DPixelShaderImpl *ps = NULL;
3806 IWineD3DVertexShaderImpl *vs = NULL;
3808 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
3809 * can be called from IWineD3DBaseShader::Release
3811 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version);
3813 if(pshader) {
3814 ps = (IWineD3DPixelShaderImpl *) This;
3815 if(ps->num_gl_shaders == 0) return;
3816 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
3817 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
3818 } else {
3819 vs = (IWineD3DVertexShaderImpl *) This;
3820 if(vs->num_gl_shaders == 0) return;
3821 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
3822 shader_glsl_select(This->baseShader.device, FALSE, FALSE);
3825 linked_programs = &This->baseShader.linked_programs;
3827 TRACE("Deleting linked programs\n");
3828 if (linked_programs->next) {
3829 struct glsl_shader_prog_link *entry, *entry2;
3831 if(pshader) {
3832 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
3833 delete_glsl_program_entry(priv, gl_info, entry);
3835 } else {
3836 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
3837 delete_glsl_program_entry(priv, gl_info, entry);
3842 if(pshader) {
3843 UINT i;
3845 ENTER_GL();
3846 for(i = 0; i < ps->num_gl_shaders; i++) {
3847 TRACE("deleting pshader %u\n", ps->gl_shaders[i].prgId);
3848 GL_EXTCALL(glDeleteObjectARB(ps->gl_shaders[i].prgId));
3849 checkGLcall("glDeleteObjectARB");
3851 LEAVE_GL();
3852 HeapFree(GetProcessHeap(), 0, ps->gl_shaders);
3853 ps->gl_shaders = NULL;
3854 ps->num_gl_shaders = 0;
3855 ps->shader_array_size = 0;
3856 } else {
3857 UINT i;
3859 ENTER_GL();
3860 for(i = 0; i < vs->num_gl_shaders; i++) {
3861 TRACE("deleting vshader %u\n", vs->gl_shaders[i].prgId);
3862 GL_EXTCALL(glDeleteObjectARB(vs->gl_shaders[i].prgId));
3863 checkGLcall("glDeleteObjectARB");
3865 LEAVE_GL();
3866 HeapFree(GetProcessHeap(), 0, vs->gl_shaders);
3867 vs->gl_shaders = NULL;
3868 vs->num_gl_shaders = 0;
3869 vs->shader_array_size = 0;
3873 static unsigned int glsl_program_key_hash(const void *key)
3875 const glsl_program_key_t *k = key;
3877 unsigned int hash = ((DWORD_PTR) k->vshader) | ((DWORD_PTR) k->pshader) << 16;
3878 hash += ~(hash << 15);
3879 hash ^= (hash >> 10);
3880 hash += (hash << 3);
3881 hash ^= (hash >> 6);
3882 hash += ~(hash << 11);
3883 hash ^= (hash >> 16);
3885 return hash;
3888 static BOOL glsl_program_key_compare(const void *keya, const void *keyb)
3890 const glsl_program_key_t *ka = keya;
3891 const glsl_program_key_t *kb = keyb;
3893 return ka->vshader == kb->vshader && ka->pshader == kb->pshader &&
3894 (memcmp(&ka->ps_args, &kb->ps_args, sizeof(kb->ps_args)) == 0) &&
3895 (memcmp(&ka->vs_args, &kb->vs_args, sizeof(kb->vs_args)) == 0);
3898 static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
3900 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
3901 void *mem = HeapAlloc(GetProcessHeap(), 0, size);
3903 if (!mem)
3905 ERR("Failed to allocate memory\n");
3906 return FALSE;
3909 heap->entries = mem;
3910 heap->entries[1].version = 0;
3911 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
3912 heap->size = 1;
3914 return TRUE;
3917 static void constant_heap_free(struct constant_heap *heap)
3919 HeapFree(GetProcessHeap(), 0, heap->entries);
3922 static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
3923 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3924 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3925 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
3926 SIZE_T stack_size = wined3d_log2i(max(GL_LIMITS(vshader_constantsF), GL_LIMITS(pshader_constantsF))) + 1;
3928 priv->stack = HeapAlloc(GetProcessHeap(), 0, stack_size * sizeof(*priv->stack));
3929 if (!priv->stack)
3931 ERR("Failed to allocate memory.\n");
3932 HeapFree(GetProcessHeap(), 0, priv);
3933 return E_OUTOFMEMORY;
3936 if (!constant_heap_init(&priv->vconst_heap, GL_LIMITS(vshader_constantsF)))
3938 ERR("Failed to initialize vertex shader constant heap\n");
3939 HeapFree(GetProcessHeap(), 0, priv->stack);
3940 HeapFree(GetProcessHeap(), 0, priv);
3941 return E_OUTOFMEMORY;
3944 if (!constant_heap_init(&priv->pconst_heap, GL_LIMITS(pshader_constantsF)))
3946 ERR("Failed to initialize pixel shader constant heap\n");
3947 constant_heap_free(&priv->vconst_heap);
3948 HeapFree(GetProcessHeap(), 0, priv->stack);
3949 HeapFree(GetProcessHeap(), 0, priv);
3950 return E_OUTOFMEMORY;
3953 priv->glsl_program_lookup = hash_table_create(glsl_program_key_hash, glsl_program_key_compare);
3954 priv->next_constant_version = 1;
3956 This->shader_priv = priv;
3957 return WINED3D_OK;
3960 static void shader_glsl_free(IWineD3DDevice *iface) {
3961 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3962 const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3963 struct shader_glsl_priv *priv = This->shader_priv;
3964 int i;
3966 for (i = 0; i < tex_type_count; ++i)
3968 if (priv->depth_blt_program[i])
3970 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
3974 hash_table_destroy(priv->glsl_program_lookup, NULL, NULL);
3975 constant_heap_free(&priv->pconst_heap);
3976 constant_heap_free(&priv->vconst_heap);
3978 HeapFree(GetProcessHeap(), 0, This->shader_priv);
3979 This->shader_priv = NULL;
3982 static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
3983 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
3984 return FALSE;
3987 static GLuint shader_glsl_generate_pshader(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer, const struct ps_compile_args *args) {
3988 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3989 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3990 CONST DWORD *function = This->baseShader.function;
3991 const char *fragcolor;
3992 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3994 /* Create the hw GLSL shader object and assign it as the shader->prgId */
3995 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
3997 shader_addline(buffer, "#version 120\n");
3999 if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
4000 shader_addline(buffer, "#extension GL_ARB_draw_buffers : enable\n");
4002 if (GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
4003 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
4004 * drivers write a warning if we don't do so
4006 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4009 /* Base Declarations */
4010 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, args);
4012 /* Pack 3.0 inputs */
4013 if (reg_maps->shader_version >= WINED3DPS_VERSION(3,0) && args->vp_mode != vertexshader) {
4014 pshader_glsl_input_pack(iface, buffer, This->semantics_in, reg_maps, args->vp_mode);
4017 /* Base Shader Body */
4018 shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
4020 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4021 if (reg_maps->shader_version < WINED3DPS_VERSION(2,0))
4023 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4024 if(GL_SUPPORT(ARB_DRAW_BUFFERS))
4025 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4026 else
4027 shader_addline(buffer, "gl_FragColor = R0;\n");
4030 if(GL_SUPPORT(ARB_DRAW_BUFFERS)) {
4031 fragcolor = "gl_FragData[0]";
4032 } else {
4033 fragcolor = "gl_FragColor";
4035 if(args->srgb_correction) {
4036 shader_addline(buffer, "tmp0.xyz = pow(%s.xyz, vec3(%f, %f, %f)) * vec3(%f, %f, %f) - vec3(%f, %f, %f);\n",
4037 fragcolor, srgb_pow, srgb_pow, srgb_pow, srgb_mul_high, srgb_mul_high, srgb_mul_high,
4038 srgb_sub_high, srgb_sub_high, srgb_sub_high);
4039 shader_addline(buffer, "tmp1.xyz = %s.xyz * srgb_mul_low.xyz;\n", fragcolor);
4040 shader_addline(buffer, "%s.x = %s.x < srgb_comparison.x ? tmp1.x : tmp0.x;\n", fragcolor, fragcolor);
4041 shader_addline(buffer, "%s.y = %s.y < srgb_comparison.y ? tmp1.y : tmp0.y;\n", fragcolor, fragcolor);
4042 shader_addline(buffer, "%s.z = %s.z < srgb_comparison.z ? tmp1.z : tmp0.z;\n", fragcolor, fragcolor);
4043 shader_addline(buffer, "%s = clamp(%s, 0.0, 1.0);\n", fragcolor, fragcolor);
4045 /* Pixel shader < 3.0 do not replace the fog stage.
4046 * This implements linear fog computation and blending.
4047 * TODO: non linear fog
4048 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4049 * -1/(e-s) and e/(e-s) respectively.
4051 if(reg_maps->shader_version < WINED3DPS_VERSION(3,0)) {
4052 switch(args->fog) {
4053 case FOG_OFF: break;
4054 case FOG_LINEAR:
4055 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4056 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4057 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4058 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
4059 break;
4060 case FOG_EXP:
4061 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4062 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4063 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4064 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
4065 break;
4066 case FOG_EXP2:
4067 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4068 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4069 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4070 shader_addline(buffer, "%s.xyz = mix(gl_Fog.color.xyz, %s.xyz, Fog);\n", fragcolor, fragcolor);
4071 break;
4075 shader_addline(buffer, "}\n");
4077 TRACE("Compiling shader object %u\n", shader_obj);
4078 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4079 GL_EXTCALL(glCompileShaderARB(shader_obj));
4080 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
4082 /* Store the shader object */
4083 return shader_obj;
4086 static GLuint shader_glsl_generate_vshader(IWineD3DVertexShader *iface, SHADER_BUFFER *buffer, const struct vs_compile_args *args) {
4087 IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *)iface;
4088 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4089 CONST DWORD *function = This->baseShader.function;
4090 const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
4092 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4093 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4095 shader_addline(buffer, "#version 120\n");
4097 /* Base Declarations */
4098 shader_generate_glsl_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, NULL);
4100 /* Base Shader Body */
4101 shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
4103 /* Unpack 3.0 outputs */
4104 if (reg_maps->shader_version >= WINED3DVS_VERSION(3,0)) shader_addline(buffer, "order_ps_input(OUT);\n");
4105 else shader_addline(buffer, "order_ps_input();\n");
4107 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4108 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4109 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4110 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4112 if(args->fog_src == VS_FOG_Z) {
4113 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4114 } else if (!reg_maps->fog) {
4115 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4118 /* Write the final position.
4120 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4121 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4122 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4123 * contains 1.0 to allow a mad.
4125 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4126 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4128 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4130 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4131 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4132 * which is the same as z = z * 2 - w.
4134 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4136 shader_addline(buffer, "}\n");
4138 TRACE("Compiling shader object %u\n", shader_obj);
4139 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4140 GL_EXTCALL(glCompileShaderARB(shader_obj));
4141 print_glsl_info_log(&GLINFO_LOCATION, shader_obj);
4143 return shader_obj;
4146 static void shader_glsl_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct shader_caps *pCaps)
4148 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
4149 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support using
4150 * vs_nv_version which is based on NV_vertex_program.
4151 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
4152 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
4153 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
4154 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
4156 if((GLINFO_LOCATION.vs_nv_version == VS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4157 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4158 else
4159 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4160 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
4161 pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF);
4163 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
4164 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
4165 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
4166 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
4167 * in max native instructions. Intel and others also offer the info in this extension but they
4168 * don't support GLSL (at least on Windows).
4170 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
4171 * of instructions is 512 or less we have to do with ps2.0 hardware.
4172 * 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.
4174 if((GLINFO_LOCATION.ps_nv_version == PS_VERSION_20) || (GLINFO_LOCATION.ps_arb_max_instructions <= 512))
4175 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
4176 else
4177 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
4179 pCaps->MaxPixelShaderConst = GL_LIMITS(pshader_constantsF);
4181 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
4182 * Direct3D minimum requirement.
4184 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
4185 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
4187 * The problem is that the refrast clamps temporary results in the shader to
4188 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
4189 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
4190 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
4191 * offer a way to query this.
4193 pCaps->PixelShader1xMaxValue = 8.0;
4194 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
4197 static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
4199 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4201 TRACE("Checking support for fixup:\n");
4202 dump_color_fixup_desc(fixup);
4205 /* We support everything except YUV conversions. */
4206 if (!is_yuv_fixup(fixup))
4208 TRACE("[OK]\n");
4209 return TRUE;
4212 TRACE("[FAILED]\n");
4213 return FALSE;
4216 static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4218 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
4219 /* WINED3DSIH_ADD */ shader_glsl_arith,
4220 /* WINED3DSIH_BEM */ pshader_glsl_bem,
4221 /* WINED3DSIH_BREAK */ shader_glsl_break,
4222 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
4223 /* WINED3DSIH_BREAKP */ NULL,
4224 /* WINED3DSIH_CALL */ shader_glsl_call,
4225 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
4226 /* WINED3DSIH_CMP */ shader_glsl_cmp,
4227 /* WINED3DSIH_CND */ shader_glsl_cnd,
4228 /* WINED3DSIH_CRS */ shader_glsl_cross,
4229 /* WINED3DSIH_DCL */ NULL,
4230 /* WINED3DSIH_DEF */ NULL,
4231 /* WINED3DSIH_DEFB */ NULL,
4232 /* WINED3DSIH_DEFI */ NULL,
4233 /* WINED3DSIH_DP2ADD */ pshader_glsl_dp2add,
4234 /* WINED3DSIH_DP3 */ shader_glsl_dot,
4235 /* WINED3DSIH_DP4 */ shader_glsl_dot,
4236 /* WINED3DSIH_DST */ shader_glsl_dst,
4237 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
4238 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
4239 /* WINED3DSIH_ELSE */ shader_glsl_else,
4240 /* WINED3DSIH_ENDIF */ shader_glsl_end,
4241 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
4242 /* WINED3DSIH_ENDREP */ shader_glsl_end,
4243 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
4244 /* WINED3DSIH_EXPP */ shader_glsl_expp,
4245 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
4246 /* WINED3DSIH_IF */ shader_glsl_if,
4247 /* WINED3DSIH_IFC */ shader_glsl_ifc,
4248 /* WINED3DSIH_LABEL */ shader_glsl_label,
4249 /* WINED3DSIH_LIT */ shader_glsl_lit,
4250 /* WINED3DSIH_LOG */ shader_glsl_log,
4251 /* WINED3DSIH_LOGP */ shader_glsl_log,
4252 /* WINED3DSIH_LOOP */ shader_glsl_loop,
4253 /* WINED3DSIH_LRP */ shader_glsl_lrp,
4254 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
4255 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
4256 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
4257 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
4258 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
4259 /* WINED3DSIH_MAD */ shader_glsl_mad,
4260 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
4261 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
4262 /* WINED3DSIH_MOV */ shader_glsl_mov,
4263 /* WINED3DSIH_MOVA */ shader_glsl_mov,
4264 /* WINED3DSIH_MUL */ shader_glsl_arith,
4265 /* WINED3DSIH_NOP */ NULL,
4266 /* WINED3DSIH_NRM */ shader_glsl_map2gl,
4267 /* WINED3DSIH_PHASE */ NULL,
4268 /* WINED3DSIH_POW */ shader_glsl_pow,
4269 /* WINED3DSIH_RCP */ shader_glsl_rcp,
4270 /* WINED3DSIH_REP */ shader_glsl_rep,
4271 /* WINED3DSIH_RET */ NULL,
4272 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
4273 /* WINED3DSIH_SETP */ NULL,
4274 /* WINED3DSIH_SGE */ shader_glsl_compare,
4275 /* WINED3DSIH_SGN */ shader_glsl_map2gl,
4276 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
4277 /* WINED3DSIH_SLT */ shader_glsl_compare,
4278 /* WINED3DSIH_SUB */ shader_glsl_arith,
4279 /* WINED3DSIH_TEX */ pshader_glsl_tex,
4280 /* WINED3DSIH_TEXBEM */ pshader_glsl_texbem,
4281 /* WINED3DSIH_TEXBEML */ pshader_glsl_texbem,
4282 /* WINED3DSIH_TEXCOORD */ pshader_glsl_texcoord,
4283 /* WINED3DSIH_TEXDEPTH */ pshader_glsl_texdepth,
4284 /* WINED3DSIH_TEXDP3 */ pshader_glsl_texdp3,
4285 /* WINED3DSIH_TEXDP3TEX */ pshader_glsl_texdp3tex,
4286 /* WINED3DSIH_TEXKILL */ pshader_glsl_texkill,
4287 /* WINED3DSIH_TEXLDD */ NULL,
4288 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
4289 /* WINED3DSIH_TEXM3x2DEPTH */ pshader_glsl_texm3x2depth,
4290 /* WINED3DSIH_TEXM3x2PAD */ pshader_glsl_texm3x2pad,
4291 /* WINED3DSIH_TEXM3x2TEX */ pshader_glsl_texm3x2tex,
4292 /* WINED3DSIH_TEXM3x3 */ pshader_glsl_texm3x3,
4293 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
4294 /* WINED3DSIH_TEXM3x3PAD */ pshader_glsl_texm3x3pad,
4295 /* WINED3DSIH_TEXM3x3SPEC */ pshader_glsl_texm3x3spec,
4296 /* WINED3DSIH_TEXM3x3TEX */ pshader_glsl_texm3x3tex,
4297 /* WINED3DSIH_TEXM3x3VSPEC */ pshader_glsl_texm3x3vspec,
4298 /* WINED3DSIH_TEXREG2AR */ pshader_glsl_texreg2ar,
4299 /* WINED3DSIH_TEXREG2GB */ pshader_glsl_texreg2gb,
4300 /* WINED3DSIH_TEXREG2RGB */ pshader_glsl_texreg2rgb,
4303 const shader_backend_t glsl_shader_backend = {
4304 shader_glsl_instruction_handler_table,
4305 shader_glsl_select,
4306 shader_glsl_select_depth_blt,
4307 shader_glsl_deselect_depth_blt,
4308 shader_glsl_update_float_vertex_constants,
4309 shader_glsl_update_float_pixel_constants,
4310 shader_glsl_load_constants,
4311 shader_glsl_load_np2fixup_constants,
4312 shader_glsl_destroy,
4313 shader_glsl_alloc,
4314 shader_glsl_free,
4315 shader_glsl_dirty_const,
4316 shader_glsl_generate_pshader,
4317 shader_glsl_generate_vshader,
4318 shader_glsl_get_caps,
4319 shader_glsl_color_fixup_supported,