glsl_shader.c 138 KB
Newer Older
1 2 3 4
/*
 * GLSL pixel and vertex shader implementation
 *
 * Copyright 2006 Jason Green 
5
 * Copyright 2006-2007 Henri Verbeet
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

22 23 24 25 26 27 28 29
/*
 * D3D shader asm has swizzles on source parameters, and write masks for
 * destination parameters. GLSL uses swizzles for both. The result of this is
 * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
 * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
 * mask for the destination parameter into account.
 */

30 31 32 33 34
#include "config.h"
#include <stdio.h>
#include "wined3d_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
35
WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
36 37 38

#define GLINFO_LOCATION      (*gl_info)

39 40 41 42 43
typedef struct {
    char reg_name[50];
    char mask_str[6];
} glsl_dst_param_t;

44 45 46 47 48
typedef struct {
    char reg_name[50];
    char param_str[100];
} glsl_src_param_t;

49 50 51 52 53
typedef struct {
    const char *name;
    DWORD coord_mask;
} glsl_sample_function_t;

54 55 56 57 58 59 60 61 62 63 64 65 66 67
/** Prints the GLSL info log which will contain error messages if they exist */
void print_glsl_info_log(WineD3D_GL_Info *gl_info, GLhandleARB obj) {
    
    int infologLength = 0;
    char *infoLog;

    GL_EXTCALL(glGetObjectParameterivARB(obj,
               GL_OBJECT_INFO_LOG_LENGTH_ARB,
               &infologLength));

    /* A size of 1 is just a null-terminated string, so the log should be bigger than
     * that if there are errors. */
    if (infologLength > 1)
    {
68
        infoLog = HeapAlloc(GetProcessHeap(), 0, infologLength);
69
        GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
70
        FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
71 72 73 74
        HeapFree(GetProcessHeap(), 0, infoLog);
    }
}

75 76 77
/**
 * Loads (pixel shader) samplers
 */
78
static void shader_glsl_load_psamplers(
79
    WineD3D_GL_Info *gl_info,
80 81
    IWineD3DStateBlock* iface,
    GLhandleARB programId) {
82 83 84 85 86 87

    IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
    GLhandleARB name_loc;
    int i;
    char sampler_name[20];

88 89 90 91 92 93
    for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
        snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
        name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
        if (name_loc != -1) {
            int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[i];
            if (mapped_unit != -1 && mapped_unit < GL_LIMITS(fragment_samplers)) {
94 95 96
                TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
                GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
                checkGLcall("glUniform1iARB");
97 98
            } else {
                ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
99
            }
100 101 102 103
        }
    }
}

104
static void shader_glsl_load_vsamplers(WineD3D_GL_Info *gl_info, IWineD3DStateBlock* iface, GLhandleARB programId) {
H. Verbeet's avatar
H. Verbeet committed
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
    GLhandleARB name_loc;
    char sampler_name[20];
    int i;

    for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
        snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
        name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
        if (name_loc != -1) {
            int mapped_unit = stateBlock->wineD3DDevice->texUnitMap[MAX_FRAGMENT_SAMPLERS + i];
            if (mapped_unit != -1 && mapped_unit < GL_LIMITS(combined_samplers)) {
                TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
                GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
                checkGLcall("glUniform1iARB");
            } else {
                ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
            }
        }
    }
}

126 127
/** 
 * Loads floating point constants (aka uniforms) into the currently set GLSL program.
128
 * When constant_list == NULL, it will load all the constants.
129
 */
130
static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl* This, WineD3D_GL_Info *gl_info,
131
        unsigned int max_constants, float* constants, GLhandleARB *constant_locations,
132
        struct list *constant_list) {
133
    constants_entry *constant;
134
    local_constant* lconst;
135
    GLhandleARB tmp_loc;
136
    DWORD i, j, k;
137
    DWORD *idx;
138

139
    if (TRACE_ON(d3d_shader)) {
140 141 142 143 144 145 146 147 148 149 150
        LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
            idx = constant->idx;
            j = constant->count;
            while (j--) {
                i = *idx++;
                tmp_loc = constant_locations[i];
                if (tmp_loc != -1) {
                    TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
                            constants[i * 4 + 0], constants[i * 4 + 1],
                            constants[i * 4 + 2], constants[i * 4 + 3]);
                }
151 152
            }
        }
153
    }
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

    /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
    if(WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) == 1 &&
       shader_is_pshader_version(This->baseShader.hex_version)) {
        float lcl_const[4];

        LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
            idx = constant->idx;
            j = constant->count;
            while (j--) {
                i = *idx++;
                tmp_loc = constant_locations[i];
                if (tmp_loc != -1) {
                    /* We found this uniform name in the program - go ahead and send the data */
                    k = i * 4;
                    if(constants[k + 0] < -1.0) lcl_const[0] = -1.0;
                    else if(constants[k + 0] > 1.0) lcl_const[0] = 1.0;
                    else lcl_const[0] = constants[k + 0];
                    if(constants[k + 1] < -1.0) lcl_const[1] = -1.0;
                    else if(constants[k + 1] > 1.0) lcl_const[1] = 1.0;
                    else lcl_const[1] = constants[k + 1];
                    if(constants[k + 2] < -1.0) lcl_const[2] = -1.0;
                    else if(constants[k + 2] > 1.0) lcl_const[2] = 1.0;
                    else lcl_const[2] = constants[k + 2];
                    if(constants[k + 3] < -1.0) lcl_const[3] = -1.0;
                    else if(constants[k + 3] > 1.0) lcl_const[3] = 1.0;
                    else lcl_const[3] = constants[k + 3];

                    GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, lcl_const));
                }
            }
        }
    } else {
        LIST_FOR_EACH_ENTRY(constant, constant_list, constants_entry, entry) {
            idx = constant->idx;
            j = constant->count;
            while (j--) {
                i = *idx++;
                tmp_loc = constant_locations[i];
                if (tmp_loc != -1) {
                    /* We found this uniform name in the program - go ahead and send the data */
                    GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, constants + (i * 4)));
                }
197
            }
198 199 200
        }
    }
    checkGLcall("glUniform4fvARB()");
201

202 203 204 205 206
    if(!This->baseShader.load_local_constsF) {
        TRACE("No need to load local float constants for this shader\n");
        return;
    }

207
    /* Load immediate constants */
208 209 210 211 212
    if (TRACE_ON(d3d_shader)) {
        LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
            tmp_loc = constant_locations[lconst->idx];
            if (tmp_loc != -1) {
                GLfloat* values = (GLfloat*)lconst->value;
213
                TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
214 215 216 217
                        values[0], values[1], values[2], values[3]);
            }
        }
    }
218
    /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
219 220
    LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
        tmp_loc = constant_locations[lconst->idx];
221 222
        if (tmp_loc != -1) {
            /* We found this uniform name in the program - go ahead and send the data */
223
            GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, (GLfloat*)lconst->value));
224 225
        }
    }
226
    checkGLcall("glUniform4fvARB()");
227 228
}

229 230 231 232
/** 
 * Loads integer constants (aka uniforms) into the currently set GLSL program.
 * When @constants_set == NULL, it will load all the constants.
 */
233
static void shader_glsl_load_constantsI(
234
    IWineD3DBaseShaderImpl* This,
235 236
    WineD3D_GL_Info *gl_info,
    GLhandleARB programId,
237
    GLhandleARB locations[MAX_CONST_I],
238 239
    unsigned max_constants,
    int* constants,
240
    BOOL* constants_set) {
241 242
    
    int i;
243
    struct list* ptr;
244 245 246 247

    for (i=0; i<max_constants; ++i) {
        if (NULL == constants_set || constants_set[i]) {

248
            TRACE_(d3d_constants)("Loading constants %i: %i, %i, %i, %i\n",
249 250
                  i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);

251 252 253
            /* We found this uniform name in the program - go ahead and send the data */
            GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
            checkGLcall("glUniform4ivARB");
254 255
        }
    }
256 257 258 259 260 261 262 263

    /* Load immediate constants */
    ptr = list_head(&This->baseShader.constantsI);
    while (ptr) {
        local_constant* lconst = LIST_ENTRY(ptr, struct local_constant, entry);
        unsigned int idx = lconst->idx;
        GLint* values = (GLint*) lconst->value;

264
        TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
265 266
            values[0], values[1], values[2], values[3]);

267 268 269
        /* We found this uniform name in the program - go ahead and send the data */
        GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
        checkGLcall("glUniform4ivARB");
270 271
        ptr = list_next(&This->baseShader.constantsI, ptr);
    }
272 273 274 275 276 277
}

/** 
 * Loads boolean constants (aka uniforms) into the currently set GLSL program.
 * When @constants_set == NULL, it will load all the constants.
 */
278
static void shader_glsl_load_constantsB(
279
    IWineD3DBaseShaderImpl* This,
280 281 282 283
    WineD3D_GL_Info *gl_info,
    GLhandleARB programId,
    unsigned max_constants,
    BOOL* constants,
284
    BOOL* constants_set) {
285 286 287
    
    GLhandleARB tmp_loc;
    int i;
288
    char tmp_name[8];
289
    char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
290
    const char* prefix = is_pshader? "PB":"VB";
291
    struct list* ptr;
292 293 294 295

    for (i=0; i<max_constants; ++i) {
        if (NULL == constants_set || constants_set[i]) {

296
            TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
297 298 299 300 301 302 303

            /* TODO: Benchmark and see if it would be beneficial to store the 
             * locations of the constants to avoid looking up each time */
            snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
            tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
            if (tmp_loc != -1) {
                /* We found this uniform name in the program - go ahead and send the data */
304
                GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
305 306 307 308
                checkGLcall("glUniform1ivARB");
            }
        }
    }
309 310 311 312 313 314 315 316

    /* Load immediate constants */
    ptr = list_head(&This->baseShader.constantsB);
    while (ptr) {
        local_constant* lconst = LIST_ENTRY(ptr, struct local_constant, entry);
        unsigned int idx = lconst->idx;
        GLint* values = (GLint*) lconst->value;

317
        TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
318 319 320 321 322 323 324 325 326 327

        snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
        tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
        if (tmp_loc != -1) {
            /* We found this uniform name in the program - go ahead and send the data */
            GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
            checkGLcall("glUniform1ivARB");
        }
        ptr = list_next(&This->baseShader.constantsB, ptr);
    }
328 329 330 331
}



332 333 334 335
/**
 * Loads the app-supplied constants into the currently set GLSL program.
 */
void shader_glsl_load_constants(
336
    IWineD3DDevice* device,
337 338
    char usePixelShader,
    char useVertexShader) {
339 340 341
   
    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
    IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
342
    WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
343

344
    GLhandleARB *constant_locations;
345
    struct list *constant_list;
346
    GLhandleARB programId;
347
    struct glsl_shader_prog_link *prog = stateBlock->glsl_program;
348

349
    if (!prog) {
350 351 352
        /* No GLSL program set - nothing to do. */
        return;
    }
353
    programId = prog->programId;
354 355

    if (useVertexShader) {
356 357
        IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;

358
        constant_locations = prog->vuniformF_locations;
359
        constant_list = &stateBlock->set_vconstantsF;
360

361
        /* Load DirectX 9 float constants/uniforms for vertex shader */
362
        shader_glsl_load_constantsF(vshader, gl_info, GL_LIMITS(vshader_constantsF),
363
                stateBlock->vertexShaderConstantF, constant_locations, constant_list);
364

365
        /* Load DirectX 9 integer constants/uniforms for vertex shader */
366 367
        shader_glsl_load_constantsI(vshader, gl_info, programId,
                                    prog->vuniformI_locations, MAX_CONST_I,
368
                                    stateBlock->vertexShaderConstantI,
369
                                    stateBlock->changed.vertexShaderConstantsI);
370 371

        /* Load DirectX 9 boolean constants/uniforms for vertex shader */
372
        shader_glsl_load_constantsB(vshader, gl_info, programId, MAX_CONST_B,
373
                                    stateBlock->vertexShaderConstantB,
374
                                    stateBlock->changed.vertexShaderConstantsB);
375 376

        /* Upload the position fixup params */
377
        GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &deviceImpl->posFixup[0]));
378
        checkGLcall("glUniform4fvARB");
379 380 381 382
    }

    if (usePixelShader) {

383 384
        IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;

385
        constant_locations = prog->puniformF_locations;
386
        constant_list = &stateBlock->set_pconstantsF;
387

388
        /* Load DirectX 9 float constants/uniforms for pixel shader */
389
        shader_glsl_load_constantsF(pshader, gl_info, GL_LIMITS(pshader_constantsF),
390
                stateBlock->pixelShaderConstantF, constant_locations, constant_list);
391

392
        /* Load DirectX 9 integer constants/uniforms for pixel shader */
393 394
        shader_glsl_load_constantsI(pshader, gl_info, programId,
                                    prog->puniformI_locations, MAX_CONST_I,
395
                                    stateBlock->pixelShaderConstantI, 
396
                                    stateBlock->changed.pixelShaderConstantsI);
397

398
        /* Load DirectX 9 boolean constants/uniforms for pixel shader */
399
        shader_glsl_load_constantsB(pshader, gl_info, programId, MAX_CONST_B,
400
                                    stateBlock->pixelShaderConstantB, 
401
                                    stateBlock->changed.pixelShaderConstantsB);
402 403 404 405

        /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
         * It can't be 0 for a valid texbem instruction.
         */
406
        if(((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat != -1) {
407
            float *data = (float *) &stateBlock->textureState[(int) ((IWineD3DPixelShaderImpl *) pshader)->needsbumpmat][WINED3DTSS_BUMPENVMAT00];
408
            GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location, 1, 0, data));
409 410 411 412 413 414 415 416 417 418
            checkGLcall("glUniformMatrix2fvARB");

            /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
             * is set too, so we can check that in the needsbumpmat check
             */
            if(((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams != -1) {
                int stage = ((IWineD3DPixelShaderImpl *) pshader)->baseShader.reg_maps.luminanceparams;
                GLfloat *scale = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLSCALE];
                GLfloat *offset = (GLfloat *) &stateBlock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET];

419
                GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location, 1, scale));
420
                checkGLcall("glUniform1fvARB");
421
                GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location, 1, offset));
422 423
                checkGLcall("glUniform1fvARB");
            }
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        } else if(((IWineD3DPixelShaderImpl *) pshader)->srgb_enabled &&
                  !((IWineD3DPixelShaderImpl *) pshader)->srgb_mode_hardcoded) {
            float comparison[4];
            float mul_low[4];

            if(stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE]) {
                comparison[0] = srgb_cmp; comparison[1] = srgb_cmp;
                comparison[2] = srgb_cmp; comparison[3] = srgb_cmp;

                mul_low[0] = srgb_mul_low; mul_low[1] = srgb_mul_low;
                mul_low[2] = srgb_mul_low; mul_low[3] = srgb_mul_low;
            } else {
                comparison[0] = 1.0 / 0.0; comparison[1] = 1.0 / 0.0;
                comparison[2] = 1.0 / 0.0; comparison[3] = 1.0 / 0.0;

                mul_low[0] = 1.0; mul_low[1] = 1.0;
                mul_low[2] = 1.0; mul_low[3] = 1.0;
            }

443 444
            GL_EXTCALL(glUniform4fvARB(prog->srgb_comparison_location, 1, comparison));
            GL_EXTCALL(glUniform4fvARB(prog->srgb_mul_low_location, 1, mul_low));
445
        }
446 447 448 449 450 451 452 453 454 455
        if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
            float correction_params[4];
            if(deviceImpl->render_offscreen) {
                correction_params[0] = 0.0;
                correction_params[1] = 1.0;
            } else {
                /* position is window relative, not viewport relative */
                correction_params[0] = ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
                correction_params[1] = -1.0;
            }
456
            GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
457
        }
458 459 460
    }
}

461 462 463 464
/** Generate the variable & register declarations for the GLSL output target */
void shader_generate_glsl_declarations(
    IWineD3DBaseShader *iface,
    shader_reg_maps* reg_maps,
465 466
    SHADER_BUFFER* buffer,
    WineD3D_GL_Info* gl_info) {
467 468

    IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
469
    IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
470
    int i;
471
    unsigned int extra_constants_needed = 0;
472
    local_constant* lconst;
473 474 475 476 477

    /* There are some minor differences between pixel and vertex shaders */
    char pshader = shader_is_pshader_version(This->baseShader.hex_version);
    char prefix = pshader ? 'P' : 'V';

478 479 480
    /* Prototype the subroutines */
    for (i = 0; i < This->baseShader.limits.label; i++) {
        if (reg_maps->labels[i])
481
            shader_addline(buffer, "void subroutine%u();\n", i);
482 483
    }

484
    /* Declare the constants (aka uniforms) */
485 486 487 488 489
    if (This->baseShader.limits.constant_float > 0) {
        unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
                (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
        shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
    }
490 491 492 493 494 495 496

    if (This->baseShader.limits.constant_int > 0)
        shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);

    if (This->baseShader.limits.constant_bool > 0)
        shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);

497
    if(!pshader) {
498
        shader_addline(buffer, "uniform vec4 posFixup;\n");
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
        /* Predeclaration; This function is added at link time based on the pixel shader.
         * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
         * that. We know the input to the reorder function at vertex shader compile time, so
         * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
         * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
         * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
         * it will write to the varying array. Here we depend on the shader optimizer on sorting that
         * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
         * inout.
         */
        if(This->baseShader.hex_version >= WINED3DVS_VERSION(3, 0)) {
            shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
        } else {
            shader_addline(buffer, "void order_ps_input();\n");
        }
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    } else {
        IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;

        if(reg_maps->bumpmat != -1) {
            shader_addline(buffer, "uniform mat2 bumpenvmat;\n");
            if(reg_maps->luminanceparams) {
                shader_addline(buffer, "uniform float luminancescale;\n");
                shader_addline(buffer, "uniform float luminanceoffset;\n");
                extra_constants_needed++;
            }
            extra_constants_needed++;
        }

        if(device->stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE]) {
            ps_impl->srgb_enabled = 1;
            if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
                shader_addline(buffer, "uniform vec4 srgb_mul_low;\n");
                shader_addline(buffer, "uniform vec4 srgb_comparison;\n");
                ps_impl->srgb_mode_hardcoded = 0;
533
                extra_constants_needed++;
534 535
            } else {
                ps_impl->srgb_mode_hardcoded = 1;
536
                shader_addline(buffer, "const vec4 srgb_mul_low = vec4(%f, %f, %f, %f);\n",
537
                               srgb_mul_low, srgb_mul_low, srgb_mul_low, srgb_mul_low);
538
                shader_addline(buffer, "const vec4 srgb_comparison = vec4(%f, %f, %f, %f);\n",
539 540 541 542 543 544 545 546 547 548
                               srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
            }
        } else {
            IWineD3DPixelShaderImpl *ps_impl = (IWineD3DPixelShaderImpl *) This;

            /* Do not write any srgb fixup into the shader to save shader size and processing time.
             * As a consequence, we can't toggle srgb write on without recompilation
             */
            ps_impl->srgb_enabled = 0;
            ps_impl->srgb_mode_hardcoded = 1;
549
        }
550
        if(reg_maps->vpos || reg_maps->usesdsy) {
551 552 553 554 555 556 557 558 559
            if(This->baseShader.limits.constant_float + extra_constants_needed + 1 < GL_LIMITS(pshader_constantsF)) {
                shader_addline(buffer, "uniform vec4 ycorrection;\n");
                ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
                extra_constants_needed++;
            } else {
                /* This happens because we do not have proper tracking of the constant registers that are
                 * actually used, only the max limit of the shader version
                 */
                FIXME("Cannot find a free uniform for vpos correction params\n");
560
                shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
561 562 563 564 565
                               device->render_offscreen ? 0.0 : ((IWineD3DSurfaceImpl *) device->render_targets[0])->currentDesc.Height,
                               device->render_offscreen ? 1.0 : -1.0);
            }
            shader_addline(buffer, "vec4 vpos;\n");
        }
566
    }
567

568 569 570 571
    /* Declare texture samplers */ 
    for (i = 0; i < This->baseShader.limits.sampler; i++) {
        if (reg_maps->samplers[i]) {

572
            DWORD stype = reg_maps->samplers[i] & WINED3DSP_TEXTURETYPE_MASK;
573 574
            switch (stype) {

575
                case WINED3DSTT_1D:
576
                    shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
577 578
                    break;
                case WINED3DSTT_2D:
579 580 581 582 583 584
                    if(device->stateBlock->textures[i] &&
                       IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
                        shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
                    } else {
                        shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
                    }
585
                    break;
586
                case WINED3DSTT_CUBE:
587
                    shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
588
                    break;
589
                case WINED3DSTT_VOLUME:
590
                    shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
591 592
                    break;
                default:
593
                    shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
594
                    FIXME("Unrecognized sampler type: %#x\n", stype);
595 596 597 598 599 600 601 602
                    break;
            }
        }
    }
    
    /* Declare address variables */
    for (i = 0; i < This->baseShader.limits.address; i++) {
        if (reg_maps->address[i])
603
            shader_addline(buffer, "ivec4 A%d;\n", i);
604 605 606 607 608
    }

    /* Declare texture coordinate temporaries and initialize them */
    for (i = 0; i < This->baseShader.limits.texcoord; i++) {
        if (reg_maps->texcoord[i]) 
609
            shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
610 611
    }

612 613 614 615 616
    /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
     * helper function shader that is linked in at link time
     */
    if(pshader && This->baseShader.hex_version >= WINED3DVS_VERSION(3, 0)) {
        if(use_vs(device)) {
617
            shader_addline(buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
618 619 620 621 622
        } else {
            /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
             * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
             * pixel shader that reads the fixed function color into the packed input registers.
             */
623
            shader_addline(buffer, "vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
624
        }
625 626 627
    }

    /* Declare output register temporaries */
628
    if(This->baseShader.limits.packed_output) {
629
        shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
630 631 632 633 634
    }

    /* Declare temporary variables */
    for(i = 0; i < This->baseShader.limits.temporary; i++) {
        if (reg_maps->temporary[i])
635
            shader_addline(buffer, "vec4 R%u;\n", i);
636 637 638 639 640 641 642 643
    }

    /* Declare attributes */
    for (i = 0; i < This->baseShader.limits.attributes; i++) {
        if (reg_maps->attributes[i])
            shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
    }

644 645 646 647
    /* Declare loop registers aLx */
    for (i = 0; i < reg_maps->loop_depth; i++) {
        shader_addline(buffer, "int aL%u;\n", i);
        shader_addline(buffer, "int tmpInt%u;\n", i);
648
    }
649

650 651 652 653
    /* Temporary variables for matrix operations */
    shader_addline(buffer, "vec4 tmp0;\n");
    shader_addline(buffer, "vec4 tmp1;\n");

654
    /* Hardcodable local constants */
655 656 657 658 659 660 661 662
    if(!This->baseShader.load_local_constsF) {
        LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
            float *value = (float *) lconst->value;
            shader_addline(buffer, "const vec4 LC%u = vec4(%f, %f, %f, %f);\n", lconst->idx,
                           value[0], value[1], value[2], value[3]);
        }
    }

663 664
    /* Start the main program */
    shader_addline(buffer, "void main() {\n");
665 666 667
    if(pshader && reg_maps->vpos) {
        shader_addline(buffer, "vpos = vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1) - 0.5;\n");
    }
668 669
}

670 671 672 673 674 675 676
/*****************************************************************************
 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
 *
 * For more information, see http://wiki.winehq.org/DirectX-Shaders
 ****************************************************************************/

/* Prototypes */
677
static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
678
        const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param);
679

680
/** Used for opcode modifiers - They multiply the result by the specified amount */
681
static const char * const shift_glsl_tab[] = {
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
    "",           /*  0 (none) */ 
    "2.0 * ",     /*  1 (x2)   */ 
    "4.0 * ",     /*  2 (x4)   */ 
    "8.0 * ",     /*  3 (x8)   */ 
    "16.0 * ",    /*  4 (x16)  */ 
    "32.0 * ",    /*  5 (x32)  */ 
    "",           /*  6 (x64)  */ 
    "",           /*  7 (x128) */ 
    "",           /*  8 (d256) */ 
    "",           /*  9 (d128) */ 
    "",           /* 10 (d64)  */ 
    "",           /* 11 (d32)  */ 
    "0.0625 * ",  /* 12 (d16)  */ 
    "0.125 * ",   /* 13 (d8)   */ 
    "0.25 * ",    /* 14 (d4)   */ 
    "0.5 * "      /* 15 (d2)   */ 
};

/* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
701
static void shader_glsl_gen_modifier (
702 703 704 705 706 707 708
    const DWORD instr,
    const char *in_reg,
    const char *in_regswizzle,
    char *out_str) {

    out_str[0] = 0;
    
709
    if (instr == WINED3DSIO_TEXKILL)
710 711
        return;

712
    switch (instr & WINED3DSP_SRCMOD_MASK) {
713 714
    case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
    case WINED3DSPSM_DW:
715
    case WINED3DSPSM_NONE:
716 717
        sprintf(out_str, "%s%s", in_reg, in_regswizzle);
        break;
718
    case WINED3DSPSM_NEG:
719 720
        sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
        break;
721
    case WINED3DSPSM_NOT:
722 723
        sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
        break;
724
    case WINED3DSPSM_BIAS:
725 726
        sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
        break;
727
    case WINED3DSPSM_BIASNEG:
728 729
        sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
        break;
730
    case WINED3DSPSM_SIGN:
731 732
        sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
        break;
733
    case WINED3DSPSM_SIGNNEG:
734 735
        sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
        break;
736
    case WINED3DSPSM_COMP:
737 738
        sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
        break;
739
    case WINED3DSPSM_X2:
740 741
        sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
        break;
742
    case WINED3DSPSM_X2NEG:
743 744
        sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
        break;
745
    case WINED3DSPSM_ABS:
746 747
        sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
        break;
748
    case WINED3DSPSM_ABSNEG:
749 750 751
        sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
        break;
    default:
752
        FIXME("Unhandled modifier %u\n", (instr & WINED3DSP_SRCMOD_MASK));
753 754 755 756
        sprintf(out_str, "%s%s", in_reg, in_regswizzle);
    }
}

757 758 759 760 761 762 763 764 765 766 767
static BOOL constant_is_local(IWineD3DBaseShaderImpl* This, DWORD reg) {
    local_constant* lconst;

    if(This->baseShader.load_local_constsF) return FALSE;
    LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
        if(lconst->idx == reg) return TRUE;
    }
    return FALSE;

}

768 769
/** Writes the GLSL variable name that corresponds to the register that the
 * DX opcode parameter is trying to access */
770
static void shader_glsl_get_register_name(
771 772 773 774 775 776 777
    const DWORD param,
    const DWORD addr_token,
    char* regstr,
    BOOL* is_color,
    SHADER_OPCODE_ARG* arg) {

    /* oPos, oFog and oPts in D3D */
778
    static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
779

780
    DWORD reg = param & WINED3DSP_REGNUM_MASK;
781 782
    DWORD regtype = shader_get_regtype(param);
    IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) arg->shader;
783
    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
784
    WineD3D_GL_Info* gl_info = &deviceImpl->adapter->gl_info;
785

786
    char pshader = shader_is_pshader_version(This->baseShader.hex_version);
787
    char tmpStr[50];
788 789 790

    *is_color = FALSE;   
 
791
    switch (regtype) {
792
    case WINED3DSPR_TEMP:
793
        sprintf(tmpStr, "R%u", reg);
794
    break;
795
    case WINED3DSPR_INPUT:
796
        if (pshader) {
797
            /* Pixel shaders >= 3.0 */
798 799 800 801 802
            if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3) {
                if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
                    glsl_src_param_t rel_param;
                    shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);

803 804 805 806 807 808 809 810 811
                    /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
                     * operation there
                     */
                    if(((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg]) {
                        sprintf(tmpStr, "IN[%s + %u]", rel_param.param_str,
                                ((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg]);
                    } else {
                        sprintf(tmpStr, "IN[%s]", rel_param.param_str);
                    }
812
                } else {
813 814
                    sprintf(tmpStr, "IN[%u]",
                            ((IWineD3DPixelShaderImpl *) This)->input_reg_map[reg]);
815 816
                }
            } else {
817 818 819 820
                if (reg==0)
                    strcpy(tmpStr, "gl_Color");
                else
                    strcpy(tmpStr, "gl_SecondaryColor");
821 822
            }
        } else {
823 824
            if (vshader_input_is_color((IWineD3DVertexShader*) This, reg))
               *is_color = TRUE;
825
            sprintf(tmpStr, "attrib%u", reg);
826 827
        } 
        break;
828
    case WINED3DSPR_CONST:
829 830 831
    {
        const char* prefix = pshader? "PC":"VC";

832
        /* Relative addressing */
833
        if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
834 835 836

           /* Relative addressing on shaders 2.0+ have a relative address token, 
            * prior to that, it was hard-coded as "A0.x" because there's only 1 register */
837
           if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 2)  {
838 839
               glsl_src_param_t rel_param;
               shader_glsl_add_src_param(arg, addr_token, 0, WINED3DSP_WRITEMASK_0, &rel_param);
840 841 842 843 844 845 846 847 848 849 850 851
               if(reg) {
                   sprintf(tmpStr, "%s[%s + %u]", prefix, rel_param.param_str, reg);
               } else {
                   sprintf(tmpStr, "%s[%s]", prefix, rel_param.param_str);
               }
           } else {
               if(reg) {
                   sprintf(tmpStr, "%s[A0.x + %u]", prefix, reg);
               } else {
                   sprintf(tmpStr, "%s[A0.x]", prefix);
               }
           }
852

853 854 855 856 857 858 859
        } else {
            if(constant_is_local(This, reg)) {
                sprintf(tmpStr, "LC%u", reg);
            } else {
                sprintf(tmpStr, "%s[%u]", prefix, reg);
            }
        }
860

861 862
        break;
    }
863
    case WINED3DSPR_CONSTINT:
864
        if (pshader)
865
            sprintf(tmpStr, "PI[%u]", reg);
866
        else
867
            sprintf(tmpStr, "VI[%u]", reg);
868
        break;
869
    case WINED3DSPR_CONSTBOOL:
870
        if (pshader)
871
            sprintf(tmpStr, "PB[%u]", reg);
872
        else
873
            sprintf(tmpStr, "VB[%u]", reg);
874
        break;
875
    case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
876
        if (pshader) {
877
            sprintf(tmpStr, "T%u", reg);
878
        } else {
879
            sprintf(tmpStr, "A%u", reg);
880 881
        }
    break;
882
    case WINED3DSPR_LOOP:
883
        sprintf(tmpStr, "aL%u", This->baseShader.cur_loop_regno - 1);
884
    break;
885
    case WINED3DSPR_SAMPLER:
886
        if (pshader)
887
            sprintf(tmpStr, "Psampler%u", reg);
888
        else
889
            sprintf(tmpStr, "Vsampler%u", reg);
890
    break;
891
    case WINED3DSPR_COLOROUT:
892 893 894
        if (reg >= GL_LIMITS(buffers)) {
            WARN("Write to render target %u, only %d supported\n", reg, 4);
        }
895
        if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
896
            sprintf(tmpStr, "gl_FragData[%u]", reg);
897
        } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
898
            sprintf(tmpStr, "gl_FragColor");
899 900
        }
    break;
901
    case WINED3DSPR_RASTOUT:
902 903
        sprintf(tmpStr, "%s", hwrastout_reg_names[reg]);
    break;
904
    case WINED3DSPR_DEPTHOUT:
905 906
        sprintf(tmpStr, "gl_FragDepth");
    break;
907
    case WINED3DSPR_ATTROUT:
908 909 910 911 912 913
        if (reg == 0) {
            sprintf(tmpStr, "gl_FrontColor");
        } else {
            sprintf(tmpStr, "gl_FrontSecondaryColor");
        }
    break;
914 915
    case WINED3DSPR_TEXCRDOUT:
        /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
916
        if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
917
            sprintf(tmpStr, "OUT[%u]", reg);
918
        else
919
            sprintf(tmpStr, "gl_TexCoord[%u]", reg);
920
    break;
921 922 923
    case WINED3DSPR_MISCTYPE:
        if (reg == 0) {
            /* vPos */
924
            sprintf(tmpStr, "vpos");
925 926 927 928 929
        } else if (reg == 1){
            /* Note that gl_FrontFacing is a bool, while vFace is
             * a float for which the sign determines front/back
             */
            sprintf(tmpStr, "(gl_FrontFacing ? 1.0 : -1.0)");
930 931 932 933 934
        } else {
            FIXME("Unhandled misctype register %d\n", reg);
            sprintf(tmpStr, "unrecognized_register");
        }
        break;
935
    default:
936
        FIXME("Unhandled register name Type(%d)\n", regtype);
937 938 939 940 941 942 943
        sprintf(tmpStr, "unrecognized_register");
    break;
    }

    strcat(regstr, tmpStr);
}

944
/* Get the GLSL write mask for the destination register */
945
static DWORD shader_glsl_get_write_mask(const DWORD param, char *write_mask) {
946
    char *ptr = write_mask;
947
    DWORD mask = param & WINED3DSP_WRITEMASK_ALL;
948

949
    if (shader_is_scalar(param)) {
950 951
        mask = WINED3DSP_WRITEMASK_0;
    } else {
952 953 954 955 956
        *ptr++ = '.';
        if (param & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
        if (param & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
        if (param & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
        if (param & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
957 958
    }

959
    *ptr = '\0';
960 961

    return mask;
962 963
}

964 965 966 967 968 969 970 971 972 973 974
static size_t shader_glsl_get_write_mask_size(DWORD write_mask) {
    size_t size = 0;

    if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
    if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
    if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
    if (write_mask & WINED3DSP_WRITEMASK_3) ++size;

    return size;
}

975
static void shader_glsl_get_swizzle(const DWORD param, BOOL fixup, DWORD mask, char *swizzle_str) {
976 977 978
    /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
     * but addressed as "rgba". To fix this we need to swap the register's x
     * and z components. */
979
    DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
980 981 982
    const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
    char *ptr = swizzle_str;

983 984 985 986 987 988 989 990
    if (!shader_is_scalar(param)) {
        *ptr++ = '.';
        /* swizzle bits fields: wwzzyyxx */
        if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = swizzle_chars[swizzle & 0x03];
        if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = swizzle_chars[(swizzle >> 2) & 0x03];
        if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = swizzle_chars[(swizzle >> 4) & 0x03];
        if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = swizzle_chars[(swizzle >> 6) & 0x03];
    }
991

992
    *ptr = '\0';
993 994
}

995 996
/* From a given parameter token, generate the corresponding GLSL string.
 * Also, return the actual register name and swizzle in case the
997
 * caller needs this information as well. */
998
static void shader_glsl_add_src_param(SHADER_OPCODE_ARG* arg, const DWORD param,
999
        const DWORD addr_token, DWORD mask, glsl_src_param_t *src_param) {
1000
    BOOL is_color = FALSE;
1001 1002 1003 1004 1005
    char swizzle_str[6];

    src_param->reg_name[0] = '\0';
    src_param->param_str[0] = '\0';
    swizzle_str[0] = '\0';
1006

1007
    shader_glsl_get_register_name(param, addr_token, src_param->reg_name, &is_color, arg);
1008

1009 1010
    shader_glsl_get_swizzle(param, is_color, mask, swizzle_str);
    shader_glsl_gen_modifier(param, src_param->reg_name, swizzle_str, src_param->param_str);
1011 1012 1013 1014 1015
}

/* From a given parameter token, generate the corresponding GLSL string.
 * Also, return the actual register name and swizzle in case the
 * caller needs this information as well. */
1016
static DWORD shader_glsl_add_dst_param(SHADER_OPCODE_ARG* arg, const DWORD param,
1017
        const DWORD addr_token, glsl_dst_param_t *dst_param) {
1018 1019
    BOOL is_color = FALSE;

1020 1021
    dst_param->mask_str[0] = '\0';
    dst_param->reg_name[0] = '\0';
1022

1023 1024
    shader_glsl_get_register_name(param, addr_token, dst_param->reg_name, &is_color, arg);
    return shader_glsl_get_write_mask(param, dst_param->mask_str);
1025 1026
}

1027
/* Append the destination part of the instruction to the buffer, return the effective write mask */
1028
static DWORD shader_glsl_append_dst_ext(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg, const DWORD param) {
1029
    glsl_dst_param_t dst_param;
1030 1031 1032
    DWORD mask;
    int shift;

1033 1034 1035 1036 1037 1038
    mask = shader_glsl_add_dst_param(arg, param, arg->dst_addr, &dst_param);

    if(mask) {
        shift = (param & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
        shader_addline(buffer, "%s%s = %s(", dst_param.reg_name, dst_param.mask_str, shift_glsl_tab[shift]);
    }
1039 1040 1041 1042

    return mask;
}

1043 1044 1045 1046 1047
/* Append the destination part of the instruction to the buffer, return the effective write mask */
static DWORD shader_glsl_append_dst(SHADER_BUFFER *buffer, SHADER_OPCODE_ARG *arg) {
    return shader_glsl_append_dst_ext(buffer, arg, arg->dst);
}

1048 1049
/** Process GLSL instruction modifiers */
void shader_glsl_add_instruction_modifiers(SHADER_OPCODE_ARG* arg) {
1050
    
1051
    DWORD mask = arg->dst & WINED3DSP_DSTMOD_MASK;
1052 1053
 
    if (arg->opcode->dst_token && mask != 0) {
1054 1055 1056
        glsl_dst_param_t dst_param;

        shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
1057

1058
        if (mask & WINED3DSPDM_SATURATE) {
1059
            /* _SAT means to clamp the value of the register to between 0 and 1 */
1060 1061
            shader_addline(arg->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
                    dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1062
        }
1063
        if (mask & WINED3DSPDM_MSAMPCENTROID) {
1064 1065
            FIXME("_centroid modifier not handled\n");
        }
1066
        if (mask & WINED3DSPDM_PARTIALPRECISION) {
1067 1068 1069 1070 1071
            /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
        }
    }
}

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
static inline const char* shader_get_comp_op(
    const DWORD opcode) {

    DWORD op = (opcode & INST_CONTROLS_MASK) >> INST_CONTROLS_SHIFT;
    switch (op) {
        case COMPARISON_GT: return ">";
        case COMPARISON_EQ: return "==";
        case COMPARISON_GE: return ">=";
        case COMPARISON_LT: return "<";
        case COMPARISON_NE: return "!=";
        case COMPARISON_LE: return "<=";
        default:
1084
            FIXME("Unrecognized comparison value: %u\n", op);
1085 1086 1087 1088
            return "(\?\?)";
    }
}

1089
static void shader_glsl_get_sample_function(DWORD sampler_type, BOOL projected, BOOL texrect, glsl_sample_function_t *sample_function) {
1090 1091 1092 1093 1094 1095 1096
    /* Note that there's no such thing as a projected cube texture. */
    switch(sampler_type) {
        case WINED3DSTT_1D:
            sample_function->name = projected ? "texture1DProj" : "texture1D";
            sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
            break;
        case WINED3DSTT_2D:
1097 1098 1099 1100 1101
            if(texrect) {
                sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
            } else {
                sample_function->name = projected ? "texture2DProj" : "texture2D";
            }
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
            sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
            break;
        case WINED3DSTT_CUBE:
            sample_function->name = "textureCube";
            sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
            break;
        case WINED3DSTT_VOLUME:
            sample_function->name = projected ? "texture3DProj" : "texture3D";
            sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
            break;
        default:
            sample_function->name = "";
            FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
            break;
    }
}

1119
static void shader_glsl_color_correction(SHADER_OPCODE_ARG* arg) {
1120 1121 1122 1123 1124 1125
    IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) shader->baseShader.device;
    WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
    glsl_dst_param_t dst_param;
    glsl_dst_param_t dst_param2;
    WINED3DFORMAT fmt;
1126
    WINED3DFORMAT conversion_group;
1127 1128
    IWineD3DBaseTextureImpl *texture;
    DWORD mask, mask_size;
1129 1130
    UINT i;
    BOOL recorded = FALSE;
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    DWORD sampler_idx;
    DWORD hex_version = shader->baseShader.hex_version;

    switch(arg->opcode->opcode) {
        case WINED3DSIO_TEX:
            if (hex_version < WINED3DPS_VERSION(2,0)) {
                sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
            } else {
                sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
            }
            break;

        case WINED3DSIO_TEXLDL:
            FIXME("Add color fixup for vertex texture WINED3DSIO_TEXLDL\n");
            return;

        case WINED3DSIO_TEXDP3TEX:
        case WINED3DSIO_TEXM3x3TEX:
        case WINED3DSIO_TEXM3x3SPEC:
        case WINED3DSIO_TEXM3x3VSPEC:
        case WINED3DSIO_TEXBEM:
        case WINED3DSIO_TEXREG2AR:
        case WINED3DSIO_TEXREG2GB:
        case WINED3DSIO_TEXREG2RGB:
            sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
            break;

        default:
            /* Not a texture sampling instruction, nothing to do */
            return;
    };
1162 1163 1164 1165

    texture = (IWineD3DBaseTextureImpl *) deviceImpl->stateBlock->textures[sampler_idx];
    if(texture) {
        fmt = texture->resource.format;
1166
        conversion_group = texture->baseTexture.shader_conversion_group;
1167 1168
    } else {
        fmt = WINED3DFMT_UNKNOWN;
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
        conversion_group = WINED3DFMT_UNKNOWN;
    }

    /* before doing anything, record the sampler with the format in the format conversion list,
     * but check if it's not there already
     */
    for(i = 0; i < shader->baseShader.num_sampled_samplers; i++) {
        if(shader->baseShader.sampled_samplers[i] == sampler_idx) {
            recorded = TRUE;
            break;
        }
    }
    if(!recorded) {
        shader->baseShader.sampled_samplers[shader->baseShader.num_sampled_samplers] = sampler_idx;
        shader->baseShader.num_sampled_samplers++;
        shader->baseShader.sampled_format[sampler_idx] = conversion_group;
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    }

    switch(fmt) {
        case WINED3DFMT_V8U8:
        case WINED3DFMT_V16U16:
            if(GL_SUPPORT(NV_TEXTURE_SHADER) ||
              (GL_SUPPORT(ATI_ENVMAP_BUMPMAP) && fmt == WINED3DFMT_V8U8)) {
                /* The 3rd channel returns 1.0 in d3d, but 0.0 in gl. Fix this while we're at it :-) */
                mask = shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_2, &dst_param);
                mask_size = shader_glsl_get_write_mask_size(mask);
                if(mask_size >= 3) {
                    shader_addline(arg->buffer, "%s.%c = 1.0;\n", dst_param.reg_name, dst_param.mask_str[3]);
                }
            } else {
                /* Correct the sign, but leave the blue as it is - it was loaded correctly already */
                mask = shader_glsl_add_dst_param(arg, arg->dst,
                                          WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1,
                                          &dst_param);
                mask_size = shader_glsl_get_write_mask_size(mask);
                if(mask_size >= 2) {
                    shader_addline(arg->buffer, "%s.%c%c = %s.%c%c * 2.0 - 1.0;\n",
                    dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2],
                    dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2]);
                } else if(mask_size == 1) {
                    shader_addline(arg->buffer, "%s.%c = %s.%c * 2.0 - 1.0;\n", dst_param.reg_name, dst_param.mask_str[1],
                    dst_param.reg_name, dst_param.mask_str[1]);
                }
            }
            break;

        case WINED3DFMT_X8L8V8U8:
            if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
                /* Red and blue are the signed channels, fix them up; Blue(=L) is correct already,
                 * and a(X) is always 1.0
                 */
                mask = shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &dst_param);
                mask_size = shader_glsl_get_write_mask_size(mask);
                if(mask_size >= 2) {
                    shader_addline(arg->buffer, "%s.%c%c = %s.%c%c * 2.0 - 1.0;\n",
                                   dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2],
                                   dst_param.reg_name, dst_param.mask_str[1], dst_param.mask_str[2]);
                } else if(mask_size == 1) {
                    shader_addline(arg->buffer, "%s.%c = %s.%c * 2.0 - 1.0;\n",
                                   dst_param.reg_name, dst_param.mask_str[1],
                                   dst_param.reg_name, dst_param.mask_str[1]);
                }
            }
            break;

        case WINED3DFMT_L6V5U5:
            if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
                mask = shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &dst_param);
                mask_size = shader_glsl_get_write_mask_size(mask);
                shader_glsl_add_dst_param(arg, arg->dst, WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_2, &dst_param2);
                if(mask_size >= 3) {
                    /* Swap y and z (U and L), and do a sign conversion on x and the new y(V and U) */
                    shader_addline(arg->buffer, "tmp0.g = %s.%c;\n",
                                   dst_param.reg_name, dst_param.mask_str[2]);
                    shader_addline(arg->buffer, "%s.%c%c = %s.%c%c * 2.0 - 1.0;\n",
                                   dst_param.reg_name, dst_param.mask_str[2], dst_param.mask_str[1],
                                   dst_param2.reg_name, dst_param.mask_str[1], dst_param.mask_str[3]);
                    shader_addline(arg->buffer, "%s.%c = tmp0.g;\n", dst_param.reg_name,
                                   dst_param.mask_str[3]);
                } else if(mask_size == 2) {
                    /* This is bad: We have VL, but we need VU */
                    FIXME("2 components sampled from a converted L6V5U5 texture\n");
                } else {
                    shader_addline(arg->buffer, "%s.%c = %s.%c * 2.0 - 1.0;\n",
                                   dst_param.reg_name, dst_param.mask_str[1],
                                   dst_param2.reg_name, dst_param.mask_str[1]);
                }
            }
            break;

        case WINED3DFMT_Q8W8V8U8:
            if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
                /* Correct the sign in all channels. The writemask just applies as-is, no
                 * need for checking the mask size
                 */
                shader_glsl_add_dst_param(arg, arg->dst,
                                          WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 |
                                          WINED3DSP_WRITEMASK_2 | WINED3DSP_WRITEMASK_3,
                                          &dst_param);
                shader_addline(arg->buffer, "%s%s = %s%s * 2.0 - 1.0;\n", dst_param.reg_name, dst_param.mask_str,
                               dst_param.reg_name, dst_param.mask_str);
            }
            break;

            /* stupid compiler */
        default:
            break;
    }
}
1278

1279 1280 1281 1282 1283 1284
/*****************************************************************************
 * 
 * Begin processing individual instruction opcodes
 * 
 ****************************************************************************/

1285
/* Generate GLSL arithmetic functions (dst = src1 + src2) */
1286 1287 1288
void shader_glsl_arith(SHADER_OPCODE_ARG* arg) {
    CONST SHADER_OPCODE* curOpcode = arg->opcode;
    SHADER_BUFFER* buffer = arg->buffer;
1289 1290
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
1291 1292
    DWORD write_mask;
    char op;
1293 1294 1295

    /* Determine the GLSL operator to use based on the opcode */
    switch (curOpcode->opcode) {
1296 1297 1298
        case WINED3DSIO_MUL: op = '*'; break;
        case WINED3DSIO_ADD: op = '+'; break;
        case WINED3DSIO_SUB: op = '-'; break;
1299
        default:
1300
            op = ' ';
1301 1302 1303
            FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
            break;
    }
1304 1305

    write_mask = shader_glsl_append_dst(buffer, arg);
1306 1307 1308
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
    shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
1309 1310
}

1311
/* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
1312
void shader_glsl_mov(SHADER_OPCODE_ARG* arg) {
1313
    IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1314
    SHADER_BUFFER* buffer = arg->buffer;
1315
    glsl_src_param_t src0_param;
1316 1317 1318
    DWORD write_mask;

    write_mask = shader_glsl_append_dst(buffer, arg);
1319
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
1320

1321
    /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
1322 1323 1324
     * shader versions WINED3DSIO_MOVA is used for this. */
    if ((WINED3DSHADER_VERSION_MAJOR(shader->baseShader.hex_version) == 1 &&
            !shader_is_pshader_version(shader->baseShader.hex_version) &&
1325 1326 1327 1328 1329 1330 1331 1332 1333
            shader_get_regtype(arg->dst) == WINED3DSPR_ADDR)) {
        /* This is a simple floor() */
        size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
        if (mask_size > 1) {
            shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
        } else {
            shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
        }
    } else if(arg->opcode->opcode == WINED3DSIO_MOVA) {
1334 1335 1336
        /* We need to *round* to the nearest int here. */
        size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
        if (mask_size > 1) {
1337
            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);
1338
        } else {
1339
            shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n", src0_param.param_str, src0_param.param_str);
1340 1341
        }
    } else {
1342
        shader_addline(buffer, "%s);\n", src0_param.param_str);
1343
    }
1344 1345 1346 1347 1348 1349
}

/* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
void shader_glsl_dot(SHADER_OPCODE_ARG* arg) {
    CONST SHADER_OPCODE* curOpcode = arg->opcode;
    SHADER_BUFFER* buffer = arg->buffer;
1350 1351
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
1352 1353
    DWORD dst_write_mask, src_write_mask;
    size_t dst_size = 0;
1354

1355 1356
    dst_write_mask = shader_glsl_append_dst(buffer, arg);
    dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
1357

1358 1359 1360 1361 1362 1363 1364
    /* dp3 works on vec3, dp4 on vec4 */
    if (curOpcode->opcode == WINED3DSIO_DP4) {
        src_write_mask = WINED3DSP_WRITEMASK_ALL;
    } else {
        src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
    }

1365 1366
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_write_mask, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_write_mask, &src1_param);
1367 1368

    if (dst_size > 1) {
1369
        shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
1370
    } else {
1371
        shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
1372
    }
1373 1374
}

1375 1376 1377 1378
/* Note that this instruction has some restrictions. The destination write mask
 * can't contain the w component, and the source swizzles have to be .xyzw */
void shader_glsl_cross(SHADER_OPCODE_ARG *arg) {
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1379 1380
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
1381 1382 1383 1384
    char dst_mask[6];

    shader_glsl_get_write_mask(arg->dst, dst_mask);
    shader_glsl_append_dst(arg->buffer, arg);
1385 1386
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
1387
    shader_addline(arg->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
1388 1389
}

1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
/* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
 * GLSL uses the value as-is. */
void shader_glsl_pow(SHADER_OPCODE_ARG *arg) {
    SHADER_BUFFER *buffer = arg->buffer;
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
    DWORD dst_write_mask;
    size_t dst_size;

    dst_write_mask = shader_glsl_append_dst(buffer, arg);
    dst_size = shader_glsl_get_write_mask_size(dst_write_mask);

    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);

    if (dst_size > 1) {
        shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
    } else {
        shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
    }
}

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
/* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
 * GLSL uses the value as-is. */
void shader_glsl_log(SHADER_OPCODE_ARG *arg) {
    SHADER_BUFFER *buffer = arg->buffer;
    glsl_src_param_t src0_param;
    DWORD dst_write_mask;
    size_t dst_size;

    dst_write_mask = shader_glsl_append_dst(buffer, arg);
    dst_size = shader_glsl_get_write_mask_size(dst_write_mask);

    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);

    if (dst_size > 1) {
        shader_addline(buffer, "vec%d(log2(abs(%s))));\n", dst_size, src0_param.param_str);
    } else {
        shader_addline(buffer, "log2(abs(%s)));\n", src0_param.param_str);
    }
}

1434 1435 1436 1437
/* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
void shader_glsl_map2gl(SHADER_OPCODE_ARG* arg) {
    CONST SHADER_OPCODE* curOpcode = arg->opcode;
    SHADER_BUFFER* buffer = arg->buffer;
1438
    glsl_src_param_t src_param;
1439 1440 1441
    const char *instruction;
    char arguments[256];
    DWORD write_mask;
1442 1443 1444 1445 1446
    unsigned i;

    /* Determine the GLSL function to use based on the opcode */
    /* TODO: Possibly make this a table for faster lookups */
    switch (curOpcode->opcode) {
1447 1448 1449 1450 1451 1452 1453 1454 1455
        case WINED3DSIO_MIN: instruction = "min"; break;
        case WINED3DSIO_MAX: instruction = "max"; break;
        case WINED3DSIO_ABS: instruction = "abs"; break;
        case WINED3DSIO_FRC: instruction = "fract"; break;
        case WINED3DSIO_NRM: instruction = "normalize"; break;
        case WINED3DSIO_LOGP:
        case WINED3DSIO_LOG: instruction = "log2"; break;
        case WINED3DSIO_EXP: instruction = "exp2"; break;
        case WINED3DSIO_SGN: instruction = "sign"; break;
1456
        case WINED3DSIO_DSX: instruction = "dFdx"; break;
1457
        case WINED3DSIO_DSY: instruction = "ycorrection.y * dFdy"; break;
1458
        default: instruction = "";
1459 1460 1461 1462
            FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
            break;
    }

1463
    write_mask = shader_glsl_append_dst(buffer, arg);
1464

1465
    arguments[0] = '\0';
1466
    if (curOpcode->num_params > 0) {
1467 1468
        shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src_param);
        strcat(arguments, src_param.param_str);
1469
        for (i = 2; i < curOpcode->num_params; ++i) {
1470
            strcat(arguments, ", ");
1471 1472
            shader_glsl_add_src_param(arg, arg->src[i-1], arg->src_addr[i-1], write_mask, &src_param);
            strcat(arguments, src_param.param_str);
1473 1474 1475
        }
    }

1476
    shader_addline(buffer, "%s(%s));\n", instruction, arguments);
1477 1478
}

1479
/** Process the WINED3DSIO_EXPP instruction in GLSL:
1480 1481 1482 1483 1484 1485 1486 1487 1488
 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
 *   dst.x = 2^(floor(src))
 *   dst.y = src - floor(src)
 *   dst.z = 2^src   (partial precision is allowed, but optional)
 *   dst.w = 1.0;
 * For 2.0 shaders, just do this (honoring writemask and swizzle):
 *   dst = 2^src;    (partial precision is allowed, but optional)
 */
void shader_glsl_expp(SHADER_OPCODE_ARG* arg) {
1489
    IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)arg->shader;
1490
    glsl_src_param_t src_param;
1491

1492
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src_param);
1493

1494 1495 1496
    if (shader->baseShader.hex_version < WINED3DPS_VERSION(2,0)) {
        char dst_mask[6];

1497 1498 1499
        shader_addline(arg->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
        shader_addline(arg->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
        shader_addline(arg->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
1500
        shader_addline(arg->buffer, "tmp0.w = 1.0;\n");
1501 1502 1503 1504

        shader_glsl_append_dst(arg->buffer, arg);
        shader_glsl_get_write_mask(arg->dst, dst_mask);
        shader_addline(arg->buffer, "tmp0%s);\n", dst_mask);
1505
    } else {
1506 1507 1508 1509 1510 1511 1512
        DWORD write_mask;
        size_t mask_size;

        write_mask = shader_glsl_append_dst(arg->buffer, arg);
        mask_size = shader_glsl_get_write_mask_size(write_mask);

        if (mask_size > 1) {
1513
            shader_addline(arg->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
1514
        } else {
1515
            shader_addline(arg->buffer, "exp2(%s));\n", src_param.param_str);
1516
        }
1517 1518 1519
    }
}

1520 1521
/** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
void shader_glsl_rcp(SHADER_OPCODE_ARG* arg) {
1522
    glsl_src_param_t src_param;
1523 1524
    DWORD write_mask;
    size_t mask_size;
1525

1526 1527
    write_mask = shader_glsl_append_dst(arg->buffer, arg);
    mask_size = shader_glsl_get_write_mask_size(write_mask);
1528
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);
1529 1530

    if (mask_size > 1) {
1531
        shader_addline(arg->buffer, "vec%d(1.0 / %s));\n", mask_size, src_param.param_str);
1532
    } else {
1533
        shader_addline(arg->buffer, "1.0 / %s);\n", src_param.param_str);
1534
    }
1535 1536
}

1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
void shader_glsl_rsq(SHADER_OPCODE_ARG* arg) {
    SHADER_BUFFER* buffer = arg->buffer;
    glsl_src_param_t src_param;
    DWORD write_mask;
    size_t mask_size;

    write_mask = shader_glsl_append_dst(buffer, arg);
    mask_size = shader_glsl_get_write_mask_size(write_mask);

    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src_param);

    if (mask_size > 1) {
        shader_addline(buffer, "vec%d(inversesqrt(%s)));\n", mask_size, src_param.param_str);
    } else {
        shader_addline(buffer, "inversesqrt(%s));\n", src_param.param_str);
    }
}

1555 1556
/** Process signed comparison opcodes in GLSL. */
void shader_glsl_compare(SHADER_OPCODE_ARG* arg) {
1557 1558
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
1559 1560
    DWORD write_mask;
    size_t mask_size;
1561

1562 1563
    write_mask = shader_glsl_append_dst(arg->buffer, arg);
    mask_size = shader_glsl_get_write_mask_size(write_mask);
1564 1565
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
1566

1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    if (mask_size > 1) {
        const char *compare;

        switch(arg->opcode->opcode) {
            case WINED3DSIO_SLT: compare = "lessThan"; break;
            case WINED3DSIO_SGE: compare = "greaterThanEqual"; break;
            default: compare = "";
                FIXME("Can't handle opcode %s\n", arg->opcode->name);
        }

1577 1578
        shader_addline(arg->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
                src0_param.param_str, src1_param.param_str);
1579
    } else {
1580
        switch(arg->opcode->opcode) {
1581
            case WINED3DSIO_SLT:
1582 1583
                /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
                 * to return 0.0 but step returns 1.0 because step is not < x
1584
                 * An alternative is a bvec compare padded with an unused second component.
1585 1586 1587 1588 1589
                 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
                 * issue. Playing with not() is not possible either because not() does not accept
                 * a scalar.
                 */
                shader_addline(arg->buffer, "(%s < %s) ? 1.0 : 0.0);\n", src0_param.param_str, src1_param.param_str);
1590 1591
                break;
            case WINED3DSIO_SGE:
1592
                /* Here we can use the step() function and safe a conditional */
1593 1594 1595
                shader_addline(arg->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
                break;
            default:
1596 1597
                FIXME("Can't handle opcode %s\n", arg->opcode->name);
        }
1598

1599 1600 1601
    }
}

1602
/** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
1603
void shader_glsl_cmp(SHADER_OPCODE_ARG* arg) {
1604 1605 1606
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
    glsl_src_param_t src2_param;
1607 1608
    DWORD write_mask, cmp_channel = 0;
    unsigned int i, j;
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
    char mask_char[6];
    BOOL temp_destination = FALSE;

    DWORD src0reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
    DWORD src1reg = arg->src[1] & WINED3DSP_REGNUM_MASK;
    DWORD src2reg = arg->src[2] & WINED3DSP_REGNUM_MASK;
    DWORD src0regtype = shader_get_regtype(arg->src[0]);
    DWORD src1regtype = shader_get_regtype(arg->src[1]);
    DWORD src2regtype = shader_get_regtype(arg->src[2]);
    DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
    DWORD dstregtype = shader_get_regtype(arg->dst);
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630

    /* Cycle through all source0 channels */
    for (i=0; i<4; i++) {
        write_mask = 0;
        /* Find the destination channels which use the current source0 channel */
        for (j=0; j<4; j++) {
            if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
                write_mask |= WINED3DSP_WRITEMASK_0 << j;
                cmp_channel = WINED3DSP_WRITEMASK_0 << j;
            }
        }
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647

        /* Splitting the cmp instruction up in multiple lines imposes a problem:
         * The first lines may overwrite source parameters of the following lines.
         * Deal with that by using a temporary destination register if needed
         */
        if((src0reg == dstreg && src0regtype == dstregtype) ||
           (src1reg == dstreg && src1regtype == dstregtype) ||
           (src2reg == dstreg && src2regtype == dstregtype)) {

            write_mask = shader_glsl_get_write_mask(arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask), mask_char);
            if (!write_mask) continue;
            shader_addline(arg->buffer, "tmp0%s = (", mask_char);
            temp_destination = TRUE;
        } else {
            write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
            if (!write_mask) continue;
        }
1648

1649 1650 1651
        shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
        shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
        shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1652

1653 1654
            shader_addline(arg->buffer, "%s >= 0.0 ? %s : %s);\n",
                           src0_param.param_str, src1_param.param_str, src2_param.param_str);
1655
    }
1656 1657 1658 1659 1660 1661 1662

    if(temp_destination) {
        shader_glsl_get_write_mask(arg->dst, mask_char);
        shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst);
        shader_addline(arg->buffer, "tmp0%s);\n", mask_char);
    }

1663 1664
}

1665
/** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
1666 1667
/* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
 * the compare is done per component of src0. */
1668
void shader_glsl_cnd(SHADER_OPCODE_ARG* arg) {
1669
    IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1670 1671 1672
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
    glsl_src_param_t src2_param;
1673 1674
    DWORD write_mask, cmp_channel = 0;
    unsigned int i, j;
1675 1676

    if (shader->baseShader.hex_version < WINED3DPS_VERSION(1, 4)) {
1677
        write_mask = shader_glsl_append_dst(arg->buffer, arg);
1678
        shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1679 1680
        shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
        shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1681 1682 1683 1684 1685 1686 1687 1688

        /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
        if(arg->opcode_token & WINED3DSI_COISSUE) {
            shader_addline(arg->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
        } else {
            shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
                    src0_param.param_str, src1_param.param_str, src2_param.param_str);
        }
1689
        return;
1690
    }
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
    /* Cycle through all source0 channels */
    for (i=0; i<4; i++) {
        write_mask = 0;
        /* Find the destination channels which use the current source0 channel */
        for (j=0; j<4; j++) {
            if ( ((arg->src[0] >> (WINED3DSP_SWIZZLE_SHIFT + 2*j)) & 0x3) == i ) {
                write_mask |= WINED3DSP_WRITEMASK_0 << j;
                cmp_channel = WINED3DSP_WRITEMASK_0 << j;
            }
        }
        write_mask = shader_glsl_append_dst_ext(arg->buffer, arg, arg->dst & (~WINED3DSP_SWIZZLE_MASK | write_mask));
        if (!write_mask) continue;
1703

1704 1705 1706
        shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], cmp_channel, &src0_param);
        shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
        shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1707

1708
        shader_addline(arg->buffer, "%s > 0.5 ? %s : %s);\n",
1709
                src0_param.param_str, src1_param.param_str, src2_param.param_str);
1710
    }
1711 1712
}

1713
/** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
1714
void shader_glsl_mad(SHADER_OPCODE_ARG* arg) {
1715 1716 1717
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
    glsl_src_param_t src2_param;
1718
    DWORD write_mask;
1719

1720
    write_mask = shader_glsl_append_dst(arg->buffer, arg);
1721 1722 1723 1724 1725
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
    shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
    shader_addline(arg->buffer, "(%s * %s) + %s);\n",
            src0_param.param_str, src1_param.param_str, src2_param.param_str);
1726 1727
}

1728
/** Handles transforming all WINED3DSIO_M?x? opcodes for 
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
    Vertex shaders to GLSL codes */
void shader_glsl_mnxn(SHADER_OPCODE_ARG* arg) {
    int i;
    int nComponents = 0;
    SHADER_OPCODE_ARG tmpArg;
   
    memset(&tmpArg, 0, sizeof(SHADER_OPCODE_ARG));

    /* Set constants for the temporary argument */
    tmpArg.shader      = arg->shader;
    tmpArg.buffer      = arg->buffer;
    tmpArg.src[0]      = arg->src[0];
    tmpArg.src_addr[0] = arg->src_addr[0];
1742
    tmpArg.src_addr[1] = arg->src_addr[1];
1743 1744 1745
    tmpArg.reg_maps = arg->reg_maps; 
    
    switch(arg->opcode->opcode) {
1746
        case WINED3DSIO_M4x4:
1747
            nComponents = 4;
1748
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1749
            break;
1750
        case WINED3DSIO_M4x3:
1751
            nComponents = 3;
1752
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1753
            break;
1754
        case WINED3DSIO_M3x4:
1755
            nComponents = 4;
1756
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1757
            break;
1758
        case WINED3DSIO_M3x3:
1759
            nComponents = 3;
1760
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1761
            break;
1762
        case WINED3DSIO_M3x2:
1763
            nComponents = 2;
1764
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1765 1766 1767 1768 1769 1770
            break;
        default:
            break;
    }

    for (i = 0; i < nComponents; i++) {
1771
        tmpArg.dst = ((arg->dst) & ~WINED3DSP_WRITEMASK_ALL)|(WINED3DSP_WRITEMASK_0<<i);
1772 1773 1774 1775 1776 1777 1778 1779
        tmpArg.src[1]      = arg->src[1]+i;
        shader_glsl_dot(&tmpArg);
    }
}

/**
    The LRP instruction performs a component-wise linear interpolation 
    between the second and third operands using the first operand as the
1780 1781
    blend factor.  Equation:  (dst = src2 + src0 * (src1 - src2))
    This is equivalent to mix(src2, src1, src0);
1782 1783
*/
void shader_glsl_lrp(SHADER_OPCODE_ARG* arg) {
1784 1785 1786
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
    glsl_src_param_t src2_param;
1787
    DWORD write_mask;
1788

1789
    write_mask = shader_glsl_append_dst(arg->buffer, arg);
1790

1791 1792 1793
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], write_mask, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], write_mask, &src1_param);
    shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], write_mask, &src2_param);
1794

1795 1796
    shader_addline(arg->buffer, "mix(%s, %s, %s));\n",
            src2_param.param_str, src1_param.param_str, src0_param.param_str);
1797 1798
}

1799
/** Process the WINED3DSIO_LIT instruction in GLSL:
1800 1801 1802 1803 1804 1805
 * dst.x = dst.w = 1.0
 * dst.y = (src0.x > 0) ? src0.x
 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
 *                                        where src.w is clamped at +- 128
 */
void shader_glsl_lit(SHADER_OPCODE_ARG* arg) {
1806 1807 1808
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
    glsl_src_param_t src3_param;
1809
    char dst_mask[6];
1810

1811 1812 1813
    shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);

1814 1815 1816
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src1_param);
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &src3_param);
1817

1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
    /* The sdk specifies the instruction like this
     * dst.x = 1.0;
     * if(src.x > 0.0) dst.y = src.x
     * else dst.y = 0.0.
     * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
     * else dst.z = 0.0;
     * dst.w = 1.0;
     *
     * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
     * dst.x = 1.0                                  ... No further explanation needed
     * dst.y = max(src.y, 0.0);                     ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
     * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0;   ... 0 ^ power is 0, and otherwise we use y anyway
     * dst.w = 1.0.                                 ... Nothing fancy.
     *
     * So we still have one conditional in there. So do this:
     * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
     *
     * 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),
     * 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.
     * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
     */
    shader_addline(arg->buffer, "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",
                   src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
1841 1842
}

1843
/** Process the WINED3DSIO_DST instruction in GLSL:
1844 1845 1846 1847 1848 1849
 * dst.x = 1.0
 * dst.y = src0.x * src0.y
 * dst.z = src0.z
 * dst.w = src1.w
 */
void shader_glsl_dst(SHADER_OPCODE_ARG* arg) {
1850 1851 1852 1853 1854
    glsl_src_param_t src0y_param;
    glsl_src_param_t src0z_param;
    glsl_src_param_t src1y_param;
    glsl_src_param_t src1w_param;
    char dst_mask[6];
1855

1856 1857 1858
    shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);

1859 1860 1861 1862
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_1, &src0y_param);
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &src0z_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_1, &src1y_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_3, &src1w_param);
1863

1864
    shader_addline(arg->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
1865
            src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
1866 1867
}

1868
/** Process the WINED3DSIO_SINCOS instruction in GLSL:
1869 1870 1871 1872 1873 1874 1875 1876 1877
 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
 * can handle it.  But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
 * 
 * dst.x = cos(src0.?)
 * dst.y = sin(src0.?)
 * dst.z = dst.z
 * dst.w = dst.w
 */
void shader_glsl_sincos(SHADER_OPCODE_ARG* arg) {
1878
    glsl_src_param_t src0_param;
1879
    DWORD write_mask;
1880

1881
    write_mask = shader_glsl_append_dst(arg->buffer, arg);
1882
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1883 1884 1885

    switch (write_mask) {
        case WINED3DSP_WRITEMASK_0:
1886
            shader_addline(arg->buffer, "cos(%s));\n", src0_param.param_str);
1887 1888 1889
            break;

        case WINED3DSP_WRITEMASK_1:
1890
            shader_addline(arg->buffer, "sin(%s));\n", src0_param.param_str);
1891 1892 1893
            break;

        case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
1894
            shader_addline(arg->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
1895 1896 1897 1898 1899 1900
            break;

        default:
            ERR("Write mask should be .x, .y or .xy\n");
            break;
    }
1901 1902
}

1903
/** Process the WINED3DSIO_LOOP instruction in GLSL:
1904 1905
 * Start a for() loop where src1.y is the initial value of aL,
 *  increment aL by src1.z for a total of src1.x iterations.
1906
 *  Need to use a temporary variable for this operation.
1907
 */
1908
/* FIXME: I don't think nested loops will work correctly this way. */
1909
void shader_glsl_loop(SHADER_OPCODE_ARG* arg) {
1910
    glsl_src_param_t src1_param;
1911
    IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1912 1913 1914 1915
    DWORD regtype = shader_get_regtype(arg->src[1]);
    DWORD reg = arg->src[1] & WINED3DSP_REGNUM_MASK;
    const DWORD *control_values = NULL;
    local_constant *constant;
1916 1917

    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
1918

1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
    /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
     * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
     * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
     * addressing.
     */
    if(regtype == WINED3DSPR_CONSTINT) {
        LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
            if(constant->idx == reg) {
                control_values = constant->value;
                break;
            }
        }
    }

    if(control_values) {
        if(control_values[2] > 0) {
            shader_addline(arg->buffer, "for (aL%u = %d; aL%u < (%d * %d + %d); aL%u += %d) {\n",
                           shader->baseShader.cur_loop_depth, control_values[1],
                           shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
                           shader->baseShader.cur_loop_depth, control_values[2]);
        } else if(control_values[2] == 0) {
            shader_addline(arg->buffer, "for (aL%u = %d, tmpInt%u = 0; tmpInt%u < %d; tmpInt%u++) {\n",
                           shader->baseShader.cur_loop_depth, control_values[1], shader->baseShader.cur_loop_depth,
                           shader->baseShader.cur_loop_depth, control_values[0],
                           shader->baseShader.cur_loop_depth);
        } else {
            shader_addline(arg->buffer, "for (aL%u = %d; aL%u > (%d * %d + %d); aL%u += %d) {\n",
                           shader->baseShader.cur_loop_depth, control_values[1],
                           shader->baseShader.cur_loop_depth, control_values[0], control_values[2], control_values[1],
                           shader->baseShader.cur_loop_depth, control_values[2]);
        }
    } else {
        shader_addline(arg->buffer, "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
                       shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
                       src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
                       shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
    }
1956 1957 1958

    shader->baseShader.cur_loop_depth++;
    shader->baseShader.cur_loop_regno++;
1959 1960 1961
}

void shader_glsl_end(SHADER_OPCODE_ARG* arg) {
1962 1963
    IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;

1964
    shader_addline(arg->buffer, "}\n");
1965 1966 1967 1968 1969 1970 1971 1972

    if(arg->opcode->opcode == WINED3DSIO_ENDLOOP) {
        shader->baseShader.cur_loop_depth--;
        shader->baseShader.cur_loop_regno--;
    }
    if(arg->opcode->opcode == WINED3DSIO_ENDREP) {
        shader->baseShader.cur_loop_depth--;
    }
1973 1974 1975
}

void shader_glsl_rep(SHADER_OPCODE_ARG* arg) {
1976
    IWineD3DBaseShaderImpl* shader = (IWineD3DBaseShaderImpl*) arg->shader;
1977
    glsl_src_param_t src0_param;
1978

1979
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
1980 1981 1982 1983
    shader_addline(arg->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
                   shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
                   src0_param.param_str, shader->baseShader.cur_loop_depth);
    shader->baseShader.cur_loop_depth++;
1984 1985
}

1986
void shader_glsl_if(SHADER_OPCODE_ARG* arg) {
1987
    glsl_src_param_t src0_param;
1988

1989 1990
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
    shader_addline(arg->buffer, "if (%s) {\n", src0_param.param_str);
1991 1992 1993
}

void shader_glsl_ifc(SHADER_OPCODE_ARG* arg) {
1994 1995
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
1996

1997 1998
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
1999 2000

    shader_addline(arg->buffer, "if (%s %s %s) {\n",
2001
            src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
2002 2003 2004 2005
}

void shader_glsl_else(SHADER_OPCODE_ARG* arg) {
    shader_addline(arg->buffer, "} else {\n");
2006 2007
}

2008 2009 2010 2011
void shader_glsl_break(SHADER_OPCODE_ARG* arg) {
    shader_addline(arg->buffer, "break;\n");
}

2012
/* FIXME: According to MSDN the compare is done per component. */
2013
void shader_glsl_breakc(SHADER_OPCODE_ARG* arg) {
2014 2015
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
2016

2017 2018
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
2019 2020

    shader_addline(arg->buffer, "if (%s %s %s) break;\n",
2021
            src0_param.param_str, shader_get_comp_op(arg->opcode_token), src1_param.param_str);
2022
}
2023

2024 2025
void shader_glsl_label(SHADER_OPCODE_ARG* arg) {

2026
    DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
2027
    shader_addline(arg->buffer, "}\n");
2028
    shader_addline(arg->buffer, "void subroutine%u () {\n",  snum);
2029 2030 2031
}

void shader_glsl_call(SHADER_OPCODE_ARG* arg) {
2032
    DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
2033
    shader_addline(arg->buffer, "subroutine%u();\n", snum);
2034 2035 2036
}

void shader_glsl_callnz(SHADER_OPCODE_ARG* arg) {
2037
    glsl_src_param_t src1_param;
2038

2039
    DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
2040
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0, &src1_param);
2041
    shader_addline(arg->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, snum);
2042 2043
}

2044 2045 2046 2047 2048
/*********************************************
 * Pixel Shader Specific Code begins here
 ********************************************/
void pshader_glsl_tex(SHADER_OPCODE_ARG* arg) {
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
2049
    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
2050
    DWORD hex_version = This->baseShader.hex_version;
2051 2052 2053 2054
    char dst_swizzle[6];
    glsl_sample_function_t sample_function;
    DWORD sampler_type;
    DWORD sampler_idx;
2055
    BOOL projected, texrect = FALSE;
2056
    DWORD mask = 0;
2057 2058

    /* All versions have a destination register */
2059
    shader_glsl_append_dst(arg->buffer, arg);
2060

2061 2062
    /* 1.0-1.4: Use destination register as sampler source.
     * 2.0+: Use provided sampler source. */
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
    if (hex_version < WINED3DPS_VERSION(1,4)) {
        DWORD flags;

        sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
        flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];

        if (flags & WINED3DTTFF_PROJECTED) {
            projected = TRUE;
            switch (flags & ~WINED3DTTFF_PROJECTED) {
                case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
                case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
                case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
                case WINED3DTTFF_COUNT4:
                case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
            }
        } else {
            projected = FALSE;
        }
    } else if (hex_version < WINED3DPS_VERSION(2,0)) {
        DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
        sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;

        if (src_mod == WINED3DSPSM_DZ) {
            projected = TRUE;
            mask = WINED3DSP_WRITEMASK_2;
        } else if (src_mod == WINED3DSPSM_DW) {
            projected = TRUE;
            mask = WINED3DSP_WRITEMASK_3;
        } else {
            projected = FALSE;
        }
    } else {
        sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
2096 2097 2098 2099 2100 2101 2102
        if(arg->opcode_token & WINED3DSI_TEXLD_PROJECT) {
                /* ps 2.0 texldp instruction always divides by the fourth component. */
                projected = TRUE;
                mask = WINED3DSP_WRITEMASK_3;
        } else {
            projected = FALSE;
        }
2103 2104
    }

2105 2106 2107 2108 2109
    if(deviceImpl->stateBlock->textures[sampler_idx] &&
       IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
        texrect = TRUE;
    }

2110
    sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2111
    shader_glsl_get_sample_function(sampler_type, projected, texrect, &sample_function);
2112 2113
    mask |= sample_function.coord_mask;

2114
    if (hex_version < WINED3DPS_VERSION(2,0)) {
2115
        shader_glsl_get_write_mask(arg->dst, dst_swizzle);
2116
    } else {
2117
        shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);
2118
    }
2119

2120 2121 2122
    /* 1.0-1.3: Use destination register as coordinate source.
       1.4+: Use provided coordinate source register. */
    if (hex_version < WINED3DPS_VERSION(1,4)) {
2123
        char coord_mask[6];
2124 2125 2126 2127
        shader_glsl_get_write_mask(mask, coord_mask);
        shader_addline(arg->buffer, "%s(Psampler%u, T%u%s)%s);\n",
                sample_function.name, sampler_idx, sampler_idx, coord_mask, dst_swizzle);
    } else {
2128 2129
        glsl_src_param_t coord_param;
        shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], mask, &coord_param);
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
        if(arg->opcode_token & WINED3DSI_TEXLD_BIAS) {
            glsl_src_param_t bias;
            shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &bias);

            shader_addline(arg->buffer, "%s(Psampler%u, %s, %s)%s);\n",
                    sample_function.name, sampler_idx, coord_param.param_str,
                    bias.param_str, dst_swizzle);
        } else {
            shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n",
                    sample_function.name, sampler_idx, coord_param.param_str, dst_swizzle);
        }
2141
    }
2142 2143
}

H. Verbeet's avatar
H. Verbeet committed
2144 2145
void shader_glsl_texldl(SHADER_OPCODE_ARG* arg) {
    IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*)arg->shader;
2146
    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
H. Verbeet's avatar
H. Verbeet committed
2147 2148 2149 2150 2151
    glsl_sample_function_t sample_function;
    glsl_src_param_t coord_param, lod_param;
    char dst_swizzle[6];
    DWORD sampler_type;
    DWORD sampler_idx;
2152
    BOOL texrect = FALSE;
H. Verbeet's avatar
H. Verbeet committed
2153 2154 2155 2156 2157 2158

    shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_swizzle(arg->src[1], FALSE, arg->dst, dst_swizzle);

    sampler_idx = arg->src[1] & WINED3DSP_REGNUM_MASK;
    sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2159 2160 2161 2162 2163
    if(deviceImpl->stateBlock->textures[sampler_idx] &&
       IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
        texrect = TRUE;
    }
    shader_glsl_get_sample_function(sampler_type, FALSE, texrect, &sample_function);    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &coord_param);
H. Verbeet's avatar
H. Verbeet committed
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178

    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &lod_param);

    if (shader_is_pshader_version(This->baseShader.hex_version)) {
        /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
         * However, they seem to work just fine in fragment shaders as well. */
        WARN("Using %sLod in fragment shader.\n", sample_function.name);
        shader_addline(arg->buffer, "%sLod(Psampler%u, %s, %s)%s);\n",
                sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
    } else {
        shader_addline(arg->buffer, "%sLod(Vsampler%u, %s, %s)%s);\n",
                sample_function.name, sampler_idx, coord_param.param_str, lod_param.param_str, dst_swizzle);
    }
}

2179 2180 2181 2182 2183 2184
void pshader_glsl_texcoord(SHADER_OPCODE_ARG* arg) {

    /* FIXME: Make this work for more than just 2D textures */
    
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
    SHADER_BUFFER* buffer = arg->buffer;
2185
    DWORD hex_version = This->baseShader.hex_version;
2186 2187
    DWORD write_mask;
    char dst_mask[6];
2188

2189 2190
    write_mask = shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_write_mask(write_mask, dst_mask);
2191

2192
    if (hex_version != WINED3DPS_VERSION(1,4)) {
2193
        DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2194
        shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n", reg, dst_mask);
2195
    } else {
2196 2197 2198 2199 2200 2201 2202
        DWORD reg = arg->src[0] & WINED3DSP_REGNUM_MASK;
        DWORD src_mod = arg->src[0] & WINED3DSP_SRCMOD_MASK;
        char dst_swizzle[6];

        shader_glsl_get_swizzle(arg->src[0], FALSE, write_mask, dst_swizzle);

        if (src_mod == WINED3DSPSM_DZ) {
2203
            glsl_src_param_t div_param;
2204
            size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
2205
            shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &div_param);
2206 2207

            if (mask_size > 1) {
2208
                shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2209
            } else {
2210
                shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2211 2212
            }
        } else if (src_mod == WINED3DSPSM_DW) {
2213
            glsl_src_param_t div_param;
2214
            size_t mask_size = shader_glsl_get_write_mask_size(write_mask);
2215
            shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_3, &div_param);
2216 2217

            if (mask_size > 1) {
2218
                shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
2219
            } else {
2220
                shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
2221 2222 2223 2224 2225
            }
        } else {
            shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
        }
    }
2226 2227
}

2228
/** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
2229 2230 2231
 * Take a 3-component dot product of the TexCoord[dstreg] and src,
 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
void pshader_glsl_texdp3tex(SHADER_OPCODE_ARG* arg) {
2232
    glsl_src_param_t src0_param;
2233
    char dst_mask[6];
2234
    glsl_sample_function_t sample_function;
2235 2236
    DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2237
    DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2238

2239
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2240

2241 2242
    shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);
2243 2244

    /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
2245 2246 2247
     * scalar, and projected sampling would require 4.
     *
     * It is a dependent read - not valid with conditional NP2 textures
2248
     */
2249
    shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268

    switch(count_bits(sample_function.coord_mask)) {
        case 1:
            shader_addline(arg->buffer, "%s(Psampler%u, dot(gl_TexCoord[%u].xyz, %s))%s);\n",
                           sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
            break;

        case 2:
            shader_addline(arg->buffer, "%s(Psampler%u, vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0))%s);\n",
                          sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
            break;

        case 3:
            shader_addline(arg->buffer, "%s(Psampler%u, vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0))%s);\n",
                           sample_function.name, sampler_idx, sampler_idx, src0_param.param_str, dst_mask);
            break;
        default:
            FIXME("Unexpected mask bitcount %d\n", count_bits(sample_function.coord_mask));
    }
2269 2270
}

2271
/** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
2272 2273
 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
void pshader_glsl_texdp3(SHADER_OPCODE_ARG* arg) {
2274
    glsl_src_param_t src0_param;
2275
    DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
2276 2277 2278
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
    DWORD dst_mask;
    size_t mask_size;
2279

2280 2281
    dst_mask = shader_glsl_append_dst(arg->buffer, arg);
    mask_size = shader_glsl_get_write_mask_size(dst_mask);
2282
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2283

2284
    if (mask_size > 1) {
2285
        shader_addline(arg->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
2286
    } else {
2287
        shader_addline(arg->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
2288
    }
2289 2290
}

2291
/** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
2292 2293
 * Calculate the depth as dst.x / dst.y   */
void pshader_glsl_texdepth(SHADER_OPCODE_ARG* arg) {
2294 2295 2296
    glsl_dst_param_t dst_param;

    shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2297

2298 2299
    /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
     * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
2300 2301
     * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
     * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
2302 2303
     * >= 1.0 or < 0.0
     */
2304
    shader_addline(arg->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n", dst_param.reg_name, dst_param.reg_name);
2305 2306
}

2307
/** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
2308 2309 2310 2311 2312
 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
 */
void pshader_glsl_texm3x2depth(SHADER_OPCODE_ARG* arg) {
2313
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2314
    DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
2315
    glsl_src_param_t src0_param;
2316

2317
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2318

2319
    shader_addline(arg->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
2320
    shader_addline(arg->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
2321 2322
}

2323
/** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
2324
 * Calculate the 1st of a 2-row matrix multiplication. */
2325
void pshader_glsl_texm3x2pad(SHADER_OPCODE_ARG* arg) {
2326
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2327
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2328
    SHADER_BUFFER* buffer = arg->buffer;
2329
    glsl_src_param_t src0_param;
2330

2331 2332
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
    shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2333
}
2334

2335
/** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
2336 2337 2338 2339
 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
void pshader_glsl_texm3x3pad(SHADER_OPCODE_ARG* arg) {

    IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2340
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2341
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2342
    SHADER_BUFFER* buffer = arg->buffer;
2343
    SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2344
    glsl_src_param_t src0_param;
2345

2346 2347
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
    shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
2348
    current_state->texcoord_w[current_state->current_row++] = reg;
2349 2350 2351
}

void pshader_glsl_texm3x2tex(SHADER_OPCODE_ARG* arg) {
2352
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2353
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2354
    SHADER_BUFFER* buffer = arg->buffer;
2355
    glsl_src_param_t src0_param;
2356
    char dst_mask[6];
2357

2358 2359
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
    shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2360 2361 2362

    shader_glsl_append_dst(buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);
2363 2364

    /* Sample the texture using the calculated coordinates */
2365
    shader_addline(buffer, "texture2D(Psampler%u, tmp0.xy)%s);\n", reg, dst_mask);
2366
}
2367

2368
/** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
2369
 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
2370
void pshader_glsl_texm3x3tex(SHADER_OPCODE_ARG* arg) {
2371
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2372
    glsl_src_param_t src0_param;
2373
    char dst_mask[6];
2374
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2375 2376
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
    SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2377 2378
    DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
    glsl_sample_function_t sample_function;
2379

2380 2381
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
    shader_addline(arg->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2382 2383 2384

    shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);
2385 2386
    /* Dependent read, not valid with conditional NP2 */
    shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2387 2388

    /* Sample the texture using the calculated coordinates */
2389 2390
    shader_addline(arg->buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);

2391 2392 2393
    current_state->current_row = 0;
}

2394
/** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
2395 2396
 * Perform the 3rd row of a 3x3 matrix multiply */
void pshader_glsl_texm3x3(SHADER_OPCODE_ARG* arg) {
2397
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2398
    glsl_src_param_t src0_param;
2399
    char dst_mask[6];
2400
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2401 2402
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
    SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
2403

2404
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2405 2406 2407

    shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);
2408
    shader_addline(arg->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
2409

2410 2411 2412
    current_state->current_row = 0;
}

2413
/** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL 
2414 2415 2416 2417
 * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
void pshader_glsl_texm3x3spec(SHADER_OPCODE_ARG* arg) {

    IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2418
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2419 2420
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
2421
    char dst_mask[6];
2422 2423
    SHADER_BUFFER* buffer = arg->buffer;
    SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2424
    DWORD stype = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
2425 2426
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
    glsl_sample_function_t sample_function;
2427

2428 2429
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], src_mask, &src1_param);
2430 2431

    /* Perform the last matrix multiply operation */
2432
    shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
2433 2434
    /* Reflection calculation */
    shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
2435

2436 2437
    shader_glsl_append_dst(buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);
2438 2439
    /* Dependent read, not valid with conditional NP2 */
    shader_glsl_get_sample_function(stype, FALSE, FALSE, &sample_function);
2440 2441

    /* Sample the texture */
2442 2443
    shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);

2444 2445 2446
    current_state->current_row = 0;
}

2447
/** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL 
2448 2449 2450 2451
 * Peform the final texture lookup based on the previous 2 3x3 matrix multiplies */
void pshader_glsl_texm3x3vspec(SHADER_OPCODE_ARG* arg) {

    IWineD3DPixelShaderImpl* shader = (IWineD3DPixelShaderImpl*) arg->shader;
2452
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
2453 2454
    SHADER_BUFFER* buffer = arg->buffer;
    SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
2455 2456
    glsl_src_param_t src0_param;
    char dst_mask[6];
2457 2458 2459
    DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
    DWORD sampler_type = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
    glsl_sample_function_t sample_function;
2460

2461
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], src_mask, &src0_param);
2462 2463

    /* Perform the last matrix multiply operation */
2464
    shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
2465 2466

    /* Construct the eye-ray vector from w coordinates */
2467 2468
    shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
            current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
2469
    shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
2470 2471 2472

    shader_glsl_append_dst(buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);
2473 2474
    /* Dependent read, not valid with conditional NP2 */
    shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2475

2476
    /* Sample the texture using the calculated coordinates */
2477 2478
    shader_addline(buffer, "%s(Psampler%u, tmp0.xyz)%s);\n", sample_function.name, reg, dst_mask);

2479 2480 2481
    current_state->current_row = 0;
}

2482
/** Process the WINED3DSIO_TEXBEM instruction in GLSL.
2483
 * Apply a fake bump map transform.
2484 2485
 * texbem is pshader <= 1.3 only, this saves a few version checks
 */
2486
void pshader_glsl_texbem(SHADER_OPCODE_ARG* arg) {
2487 2488 2489 2490
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
    char dst_swizzle[6];
    glsl_sample_function_t sample_function;
2491
    glsl_src_param_t coord_param;
2492 2493
    DWORD sampler_type;
    DWORD sampler_idx;
2494
    DWORD mask;
2495 2496 2497 2498 2499 2500
    DWORD flags;
    char coord_mask[6];

    sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
    flags = deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS];

2501
    sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
2502 2503
    /* Dependent read, not valid with conditional NP2 */
    shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2504 2505 2506 2507 2508 2509 2510 2511 2512
    mask = sample_function.coord_mask;

    shader_glsl_get_write_mask(arg->dst, dst_swizzle);

    shader_glsl_get_write_mask(mask, coord_mask);

    /* with projective textures, texbem only divides the static texture coord, not the displacement,
         * so we can't let the GL handle this.
         */
2513
    if (flags & WINED3DTTFF_PROJECTED) {
2514 2515
        DWORD div_mask=0;
        char coord_div_mask[3];
2516 2517
        switch (flags & ~WINED3DTTFF_PROJECTED) {
            case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
2518 2519
            case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
            case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
2520
            case WINED3DTTFF_COUNT4:
2521
            case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
2522
        }
2523 2524
        shader_glsl_get_write_mask(div_mask, coord_div_mask);
        shader_addline(arg->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
2525 2526
    }

2527
    shader_glsl_append_dst(arg->buffer, arg);
2528
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &coord_param);
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
    if(arg->opcode->opcode == WINED3DSIO_TEXBEML) {
        glsl_src_param_t luminance_param;
        shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_2, &luminance_param);
        shader_addline(arg->buffer, "(%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )*(%s * luminancescale + luminanceoffset))%s);\n",
                       sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask,
                       luminance_param.param_str, dst_swizzle);
    } else {
        shader_addline(arg->buffer, "%s(Psampler%u, T%u%s + vec4(bumpenvmat * %s, 0.0, 0.0)%s )%s);\n",
                       sample_function.name, sampler_idx, sampler_idx, coord_mask, coord_param.param_str, coord_mask, dst_swizzle);
    }
2539 2540
}

2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551
void pshader_glsl_bem(SHADER_OPCODE_ARG* arg) {
    glsl_src_param_t src0_param, src1_param;

    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0|WINED3DSP_WRITEMASK_1, &src1_param);

    shader_glsl_append_dst(arg->buffer, arg);
    shader_addline(arg->buffer, "%s + bumpenvmat * %s);\n",
                   src0_param.param_str, src1_param.param_str);
}

2552
/** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
2553 2554
 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
void pshader_glsl_texreg2ar(SHADER_OPCODE_ARG* arg) {
2555

2556
    glsl_src_param_t src0_param;
2557 2558
    DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
    char dst_mask[6];
2559

2560 2561
    shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);
2562
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2563

2564
    shader_addline(arg->buffer, "texture2D(Psampler%u, %s.wx)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2565 2566
}

2567
/** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
2568 2569
 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
void pshader_glsl_texreg2gb(SHADER_OPCODE_ARG* arg) {
2570
    glsl_src_param_t src0_param;
2571 2572
    DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
    char dst_mask[6];
2573

2574 2575
    shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);
2576
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2577

2578
    shader_addline(arg->buffer, "texture2D(Psampler%u, %s.yz)%s);\n", sampler_idx, src0_param.reg_name, dst_mask);
2579 2580
}

2581
/** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
2582 2583
 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
void pshader_glsl_texreg2rgb(SHADER_OPCODE_ARG* arg) {
2584
    glsl_src_param_t src0_param;
2585 2586 2587 2588
    char dst_mask[6];
    DWORD sampler_idx = arg->dst & WINED3DSP_REGNUM_MASK;
    DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
    glsl_sample_function_t sample_function;
2589

2590 2591
    shader_glsl_append_dst(arg->buffer, arg);
    shader_glsl_get_write_mask(arg->dst, dst_mask);
2592 2593
    /* Dependent read, not valid with conditional NP2 */
    shader_glsl_get_sample_function(sampler_type, FALSE, FALSE, &sample_function);
2594
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], sample_function.coord_mask, &src0_param);
2595

2596
    shader_addline(arg->buffer, "%s(Psampler%u, %s)%s);\n", sample_function.name, sampler_idx, src0_param.param_str, dst_mask);
2597 2598
}

2599
/** Process the WINED3DSIO_TEXKILL instruction in GLSL.
2600 2601
 * If any of the first 3 components are < 0, discard this pixel */
void pshader_glsl_texkill(SHADER_OPCODE_ARG* arg) {
2602 2603
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
    DWORD hex_version = This->baseShader.hex_version;
2604
    glsl_dst_param_t dst_param;
2605

2606
    /* The argument is a destination parameter, and no writemasks are allowed */
2607
    shader_glsl_add_dst_param(arg, arg->dst, 0, &dst_param);
2608 2609 2610 2611
    if((hex_version >= WINED3DPS_VERSION(2,0))) {
        /* 2.0 shaders compare all 4 components in texkill */
        shader_addline(arg->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
    } else {
2612
        /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
2613 2614 2615 2616 2617
         * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
         * 4 components are defined, only the first 3 are used
         */
        shader_addline(arg->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
    }
2618 2619
}

2620
/** Process the WINED3DSIO_DP2ADD instruction in GLSL.
2621 2622
 * dst = dot2(src0, src1) + src2 */
void pshader_glsl_dp2add(SHADER_OPCODE_ARG* arg) {
2623 2624 2625
    glsl_src_param_t src0_param;
    glsl_src_param_t src1_param;
    glsl_src_param_t src2_param;
2626 2627
    DWORD write_mask;
    size_t mask_size;
2628

2629 2630 2631
    write_mask = shader_glsl_append_dst(arg->buffer, arg);
    mask_size = shader_glsl_get_write_mask_size(write_mask);

2632 2633 2634
    shader_glsl_add_src_param(arg, arg->src[0], arg->src_addr[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
    shader_glsl_add_src_param(arg, arg->src[1], arg->src_addr[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
    shader_glsl_add_src_param(arg, arg->src[2], arg->src_addr[2], WINED3DSP_WRITEMASK_0, &src2_param);
2635

2636
    shader_addline(arg->buffer, "dot(%s, %s) + %s);\n", src0_param.param_str, src1_param.param_str, src2_param.param_str);
2637 2638
}

2639 2640
void pshader_glsl_input_pack(
   SHADER_BUFFER* buffer,
2641 2642
   semantic* semantics_in,
   IWineD3DPixelShader *iface) {
2643 2644

   unsigned int i;
2645
   IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *) iface;
2646

2647
   for (i = 0; i < MAX_REG_INPUT; i++) {
2648

2649 2650 2651
       DWORD usage_token = semantics_in[i].usage;
       DWORD register_token = semantics_in[i].reg;
       DWORD usage, usage_idx;
2652 2653 2654
       char reg_mask[6];

       /* Uninitialized */
2655
       if (!usage_token) continue;
2656 2657
       usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
       usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2658
       shader_glsl_get_write_mask(register_token, reg_mask);
2659 2660 2661

       switch(usage) {

2662 2663 2664
           case WINED3DDECLUSAGE_TEXCOORD:
               if(usage_idx < 8 && This->vertexprocessing == pretransformed) {
                   shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
2665
                                  This->input_reg_map[i], reg_mask, usage_idx, reg_mask);
2666 2667
               } else {
                   shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2668
                                  This->input_reg_map[i], reg_mask, reg_mask);
2669 2670 2671
               }
               break;

2672
           case WINED3DDECLUSAGE_COLOR:
2673
               if (usage_idx == 0)
2674
                   shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
2675
                       This->input_reg_map[i], reg_mask, reg_mask);
2676
               else if (usage_idx == 1)
2677
                   shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
2678
                       This->input_reg_map[i], reg_mask, reg_mask);
2679
               else
2680
                   shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2681
                       This->input_reg_map[i], reg_mask, reg_mask);
2682 2683 2684
               break;

           default:
2685
               shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
2686
                   This->input_reg_map[i], reg_mask, reg_mask);
2687 2688 2689 2690 2691 2692 2693 2694
        }
    }
}

/*********************************************
 * Vertex Shader Specific Code begins here
 ********************************************/

2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
static void add_glsl_program_entry(IWineD3DDeviceImpl *device, struct glsl_shader_prog_link *entry) {
    glsl_program_key_t *key;

    key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
    key->vshader = entry->vshader;
    key->pshader = entry->pshader;

    hash_table_put(device->glsl_program_lookup, key, entry);
}

static struct glsl_shader_prog_link *get_glsl_program_entry(IWineD3DDeviceImpl *device,
        GLhandleARB vshader, GLhandleARB pshader) {
    glsl_program_key_t key;

    key.vshader = vshader;
    key.pshader = pshader;

    return (struct glsl_shader_prog_link *)hash_table_get(device->glsl_program_lookup, &key);
}

void delete_glsl_program_entry(IWineD3DDevice *iface, struct glsl_shader_prog_link *entry) {
2716
    IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
2717
    WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
    glsl_program_key_t *key;

    key = HeapAlloc(GetProcessHeap(), 0, sizeof(glsl_program_key_t));
    key->vshader = entry->vshader;
    key->pshader = entry->pshader;
    hash_table_remove(This->glsl_program_lookup, key);

    GL_EXTCALL(glDeleteObjectARB(entry->programId));
    if (entry->vshader) list_remove(&entry->vshader_entry);
    if (entry->pshader) list_remove(&entry->pshader_entry);
    HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
    HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
    HeapFree(GetProcessHeap(), 0, entry);
2731 2732
}

2733
static void handle_ps3_input(SHADER_BUFFER *buffer, semantic *semantics_in, semantic *semantics_out, WineD3D_GL_Info *gl_info, DWORD *map) {
2734 2735 2736 2737 2738 2739 2740 2741 2742
    unsigned int i, j;
    DWORD usage_token, usage_token_out;
    DWORD register_token, register_token_out;
    DWORD usage, usage_idx, usage_out, usage_idx_out;
    DWORD *set;
    char reg_mask[6], reg_mask_out[6];

    set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (GL_LIMITS(glsl_varyings) / 4));

2743
    for(i = 0; i < MAX_REG_INPUT; i++) {
2744 2745
        usage_token = semantics_in[i].usage;
        if (!usage_token) continue;
2746 2747 2748
        if(map[i] >= (GL_LIMITS(glsl_varyings) / 4)) {
            FIXME("More input varyings declared than supported, expect issues\n");
            continue;
2749 2750 2751
        } else if(map[i] == -1) {
            /* Declared, but not read register */
            continue;
2752
        }
2753 2754 2755 2756
        register_token = semantics_in[i].reg;

        usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
        usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2757
        set[map[i]] = shader_glsl_get_write_mask(register_token, reg_mask);
2758 2759 2760 2761 2762

        if(!semantics_out) {
            switch(usage) {
                case WINED3DDECLUSAGE_COLOR:
                    if (usage_idx == 0)
2763 2764
                        shader_addline(buffer, "IN[%u]%s = gl_FrontColor%s;\n",
                                       map[i], reg_mask, reg_mask);
2765
                    else if (usage_idx == 1)
2766 2767
                        shader_addline(buffer, "IN[%u]%s = gl_FrontSecondaryColor%s;\n",
                                       map[i], reg_mask, reg_mask);
2768
                    else
2769 2770
                        shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
                                       map[i], reg_mask, reg_mask);
2771 2772 2773 2774 2775
                    break;

                case WINED3DDECLUSAGE_TEXCOORD:
                    if (usage_idx < 8) {
                        shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
2776
                                       map[i], reg_mask, usage_idx, reg_mask);
2777
                    } else {
2778 2779
                        shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
                                       map[i], reg_mask, reg_mask);
2780 2781 2782 2783
                    }
                    break;

                case WINED3DDECLUSAGE_FOG:
2784 2785
                    shader_addline(buffer, "IN[%u]%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
                                   map[i], reg_mask, reg_mask);
2786 2787 2788
                    break;

                default:
2789 2790
                    shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
                                   map[i], reg_mask, reg_mask);
2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
            }
        } else {
            BOOL found = FALSE;
            for(j = 0; j < MAX_REG_OUTPUT; j++) {
                usage_token_out = semantics_out[j].usage;
                if (!usage_token_out) continue;
                register_token_out = semantics_out[j].reg;

                usage_out = (usage_token_out & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
                usage_idx_out = (usage_token_out & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
                shader_glsl_get_write_mask(register_token_out, reg_mask_out);

                if(usage == usage_out &&
                   usage_idx == usage_idx_out) {
2805 2806
                    shader_addline(buffer, "IN[%u]%s = OUT[%u]%s;\n",
                                   map[i], reg_mask, j, reg_mask);
2807 2808 2809 2810
                    found = TRUE;
                }
            }
            if(!found) {
2811 2812
                shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
                               map[i], reg_mask, reg_mask);
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872
            }
        }
    }

    /* This is solely to make the compiler / linker happy and avoid warning about undefined
     * varyings. It shouldn't result in any real code executed on the GPU, since all read
     * input varyings are assigned above, if the optimizer works properly.
     */
    for(i = 0; i < GL_LIMITS(glsl_varyings) / 4; i++) {
        if(set[i] != WINED3DSP_WRITEMASK_ALL) {
            unsigned int size = 0;
            memset(reg_mask, 0, sizeof(reg_mask));
            if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
                reg_mask[size] = 'x';
                size++;
            }
            if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
                reg_mask[size] = 'y';
                size++;
            }
            if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
                reg_mask[size] = 'z';
                size++;
            }
            if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
                reg_mask[size] = 'w';
                size++;
            }
            switch(size) {
                case 1:
                    shader_addline(buffer, "IN[%u].%s = 0.0;\n", i, reg_mask);
                    break;
                case 2:
                    shader_addline(buffer, "IN[%u].%s = vec2(0.0, 0.0);\n", i, reg_mask);
                    break;
                case 3:
                    shader_addline(buffer, "IN[%u].%s = vec3(0.0, 0.0, 0.0);\n", i, reg_mask);
                    break;
                case 4:
                    shader_addline(buffer, "IN[%u].%s = vec4(0.0, 0.0, 0.0, 0.0);\n", i, reg_mask);
                    break;
            }
        }
    }

    HeapFree(GetProcessHeap(), 0, set);
}

static GLhandleARB generate_param_reorder_function(IWineD3DVertexShader *vertexshader,
        IWineD3DPixelShader *pixelshader,
        WineD3D_GL_Info *gl_info) {
    GLhandleARB ret = 0;
    IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) vertexshader;
    IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
    DWORD vs_major = vs ? WINED3DSHADER_VERSION_MAJOR(vs->baseShader.hex_version) : 0;
    DWORD ps_major = ps ? WINED3DSHADER_VERSION_MAJOR(ps->baseShader.hex_version) : 0;
    unsigned int i;
    SHADER_BUFFER buffer;
    DWORD usage_token;
    DWORD register_token;
2873
    DWORD usage, usage_idx, writemask;
2874 2875 2876 2877 2878 2879 2880 2881 2882
    char reg_mask[6];
    semantic *semantics_out, *semantics_in;

    buffer.buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, SHADER_PGMSIZE);
    buffer.bsize = 0;
    buffer.lineNo = 0;
    buffer.newline = TRUE;

    if(vs_major < 3 && ps_major < 3) {
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897
        /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
         * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
         */
        if((GLINFO_LOCATION).set_texcoord_w && ps_major == 0 && vs_major > 0) {
            shader_addline(&buffer, "void order_ps_input() {\n");
            for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
                if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
                   vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
                    shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
                }
            }
            shader_addline(&buffer, "}\n");
        } else {
            shader_addline(&buffer, "void order_ps_input() { /* do nothing */ }\n");
        }
2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
    } else if(ps_major < 3 && vs_major >= 3) {
        /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
        semantics_out = vs->semantics_out;

        shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
        for(i = 0; i < MAX_REG_OUTPUT; i++) {
            usage_token = semantics_out[i].usage;
            if (!usage_token) continue;
            register_token = semantics_out[i].reg;

            usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
            usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
2910
            writemask = shader_glsl_get_write_mask(register_token, reg_mask);
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925

            switch(usage) {
                case WINED3DDECLUSAGE_COLOR:
                    if (usage_idx == 0)
                        shader_addline(&buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
                    else if (usage_idx == 1)
                        shader_addline(&buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
                    break;

                case WINED3DDECLUSAGE_POSITION:
                    shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
                    break;

                case WINED3DDECLUSAGE_TEXCOORD:
                    if (usage_idx < 8) {
2926 2927
                        if(!(GLINFO_LOCATION).set_texcoord_w || ps_major > 0) writemask |= WINED3DSP_WRITEMASK_3;

2928
                        shader_addline(&buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
2929 2930 2931 2932
                                        usage_idx, reg_mask, i, reg_mask);
                        if(!(writemask & WINED3DSP_WRITEMASK_3)) {
                            shader_addline(&buffer, "gl_TexCoord[%u].w = 1.0;\n", usage_idx);
                        }
2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954
                    }
                    break;

                case WINED3DDECLUSAGE_PSIZE:
                    shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
                    break;

                case WINED3DDECLUSAGE_FOG:
                    shader_addline(&buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
                    break;

                default:
                    break;
            }
        }
        shader_addline(&buffer, "}\n");

    } else if(ps_major >= 3 && vs_major >= 3) {
        semantics_out = vs->semantics_out;
        semantics_in = ps->semantics_in;

        /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
2955
        shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982
        shader_addline(&buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);

        /* First, sort out position and point size. Those are not passed to the pixel shader */
        for(i = 0; i < MAX_REG_OUTPUT; i++) {
            usage_token = semantics_out[i].usage;
            if (!usage_token) continue;
            register_token = semantics_out[i].reg;

            usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
            usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
            shader_glsl_get_write_mask(register_token, reg_mask);

            switch(usage) {
                case WINED3DDECLUSAGE_POSITION:
                    shader_addline(&buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
                    break;

                case WINED3DDECLUSAGE_PSIZE:
                    shader_addline(&buffer, "gl_PointSize = OUT[%u].x;\n", i);
                    break;

                default:
                    break;
            }
        }

        /* Then, fix the pixel shader input */
2983
        handle_ps3_input(&buffer, semantics_in, semantics_out, gl_info, ps->input_reg_map);
2984 2985 2986 2987 2988

        shader_addline(&buffer, "}\n");
    } else if(ps_major >= 3 && vs_major < 3) {
        semantics_in = ps->semantics_in;

2989
        shader_addline(&buffer, "varying vec4 IN[%u];\n", GL_LIMITS(glsl_varyings) / 4);
2990 2991 2992 2993 2994
        shader_addline(&buffer, "void order_ps_input() {\n");
        /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
         * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
         * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
         */
2995
        handle_ps3_input(&buffer, semantics_in, NULL, gl_info, ps->input_reg_map);
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
        shader_addline(&buffer, "}\n");
    } else {
        ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
    }

    ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
    checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
    GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL));
    checkGLcall("glShaderSourceARB(ret, 1, (const char**)&buffer.buffer, NULL)");
    GL_EXTCALL(glCompileShaderARB(ret));
    checkGLcall("glCompileShaderARB(ret)");

    HeapFree(GetProcessHeap(), 0, buffer.buffer);
    return ret;
}

3012 3013 3014 3015 3016
/** Sets the GLSL program ID for the given pixel and vertex shader combination.
 * It sets the programId on the current StateBlock (because it should be called
 * inside of the DrawPrimitive() part of the render loop).
 *
 * If a program for the given combination does not exist, create one, and store
3017 3018
 * the program in the hash table.  If it creates a program, it will link the
 * given objects, too.
3019
 */
3020
static void set_glsl_shader_program(IWineD3DDevice *iface, BOOL use_ps, BOOL use_vs) {
3021
    IWineD3DDeviceImpl *This               = (IWineD3DDeviceImpl *)iface;
3022
    WineD3D_GL_Info *gl_info               = &This->adapter->gl_info;
3023 3024
    IWineD3DPixelShader  *pshader          = This->stateBlock->pixelShader;
    IWineD3DVertexShader *vshader          = This->stateBlock->vertexShader;
3025
    struct glsl_shader_prog_link *entry    = NULL;
3026
    GLhandleARB programId                  = 0;
3027
    GLhandleARB reorder_shader_id          = 0;
3028 3029 3030
    int i;
    char glsl_name[8];

3031 3032
    GLhandleARB vshader_id = use_vs ? ((IWineD3DBaseShaderImpl*)vshader)->baseShader.prgId : 0;
    GLhandleARB pshader_id = use_ps ? ((IWineD3DBaseShaderImpl*)pshader)->baseShader.prgId : 0;
3033 3034 3035 3036
    entry = get_glsl_program_entry(This, vshader_id, pshader_id);
    if (entry) {
        This->stateBlock->glsl_program = entry;
        return;
3037 3038 3039 3040 3041 3042
    }

    /* If we get to this point, then no matching program exists, so we create one */
    programId = GL_EXTCALL(glCreateProgramObjectARB());
    TRACE("Created new GLSL shader program %u\n", programId);

3043 3044 3045 3046 3047 3048 3049 3050 3051 3052
    /* Create the entry */
    entry = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
    entry->programId = programId;
    entry->vshader = vshader_id;
    entry->pshader = pshader_id;
    /* Add the hash table entry */
    add_glsl_program_entry(This, entry);

    /* Set the current program */
    This->stateBlock->glsl_program = entry;
3053 3054

    /* Attach GLSL vshader */
3055
    if (vshader_id) {
3056 3057 3058
        int max_attribs = 16;   /* TODO: Will this always be the case? It is at the moment... */
        char tmp_name[10];

3059 3060 3061 3062 3063 3064 3065 3066 3067
        reorder_shader_id = generate_param_reorder_function(vshader, pshader, gl_info);
        TRACE("Attaching GLSL shader object %u to program %u\n", reorder_shader_id, programId);
        GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
        checkGLcall("glAttachObjectARB");
        /* Flag the reorder function for deletion, then it will be freed automatically when the program
         * is destroyed
         */
        GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));

3068 3069 3070
        TRACE("Attaching GLSL shader object %u to program %u\n", vshader_id, programId);
        GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
        checkGLcall("glAttachObjectARB");
3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081

        /* Bind vertex attributes to a corresponding index number to match
         * the same index numbers as ARB_vertex_programs (makes loading
         * vertex attributes simpler).  With this method, we can use the
         * exact same code to load the attributes later for both ARB and
         * GLSL shaders.
         *
         * We have to do this here because we need to know the Program ID
         * in order to make the bindings work, and it has to be done prior
         * to linking the GLSL program. */
        for (i = 0; i < max_attribs; ++i) {
3082 3083 3084 3085
            if (((IWineD3DBaseShaderImpl*)vshader)->baseShader.reg_maps.attributes[i]) {
                snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
                GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
            }
3086 3087
        }
        checkGLcall("glBindAttribLocationARB");
3088 3089

        list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
3090 3091 3092
    }

    /* Attach GLSL pshader */
3093 3094 3095 3096 3097 3098
    if (pshader_id) {
        TRACE("Attaching GLSL shader object %u to program %u\n", pshader_id, programId);
        GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
        checkGLcall("glAttachObjectARB");

        list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
3099 3100 3101 3102 3103 3104 3105
    }

    /* Link the program */
    TRACE("Linking GLSL shader program %u\n", programId);
    GL_EXTCALL(glLinkProgramARB(programId));
    print_glsl_info_log(&GLINFO_LOCATION, programId);

3106
    entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
3107 3108
    for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
        snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
3109
        entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3110
    }
3111 3112 3113 3114
    for (i = 0; i < MAX_CONST_I; ++i) {
        snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
        entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
    }
3115
    entry->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
3116 3117
    for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
        snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
3118
        entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
3119
    }
3120 3121 3122 3123
    for (i = 0; i < MAX_CONST_I; ++i) {
        snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
        entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
    }
3124 3125 3126 3127 3128 3129 3130 3131

    entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
    entry->bumpenvmat_location = GL_EXTCALL(glGetUniformLocationARB(programId, "bumpenvmat"));
    entry->luminancescale_location = GL_EXTCALL(glGetUniformLocationARB(programId, "luminancescale"));
    entry->luminanceoffset_location = GL_EXTCALL(glGetUniformLocationARB(programId, "luminanceoffset"));
    entry->srgb_comparison_location = GL_EXTCALL(glGetUniformLocationARB(programId, "srgb_comparison"));
    entry->srgb_mul_low_location = GL_EXTCALL(glGetUniformLocationARB(programId, "srgb_mul_low"));
    entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
3132
    checkGLcall("Find glsl program uniform locations");
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153

    /* Set the shader to allow uniform loading on it */
    GL_EXTCALL(glUseProgramObjectARB(programId));
    checkGLcall("glUseProgramObjectARB(programId)");

    /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
     * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
     * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
     * vertex shader with fixed function pixel processing is used we make sure that the card
     * supports enough samplers to allow the max number of vertex samplers with all possible
     * fixed function fragment processing setups. So once the program is linked these samplers
     * won't change.
     */
    if(vshader_id) {
        /* Load vertex shader samplers */
        shader_glsl_load_vsamplers(gl_info, (IWineD3DStateBlock*)This->stateBlock, programId);
    }
    if(pshader_id) {
        /* Load pixel shader samplers */
        shader_glsl_load_psamplers(gl_info, (IWineD3DStateBlock*)This->stateBlock, programId);
    }
3154 3155
}

3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196
static GLhandleARB create_glsl_blt_shader(WineD3D_GL_Info *gl_info) {
    GLhandleARB program_id;
    GLhandleARB vshader_id, pshader_id;
    const char *blt_vshader[] = {
        "void main(void)\n"
        "{\n"
        "    gl_Position = gl_Vertex;\n"
        "    gl_FrontColor = vec4(1.0);\n"
        "    gl_TexCoord[0].x = (gl_Vertex.x * 0.5) + 0.5;\n"
        "    gl_TexCoord[0].y = (-gl_Vertex.y * 0.5) + 0.5;\n"
        "}\n"
    };

    const char *blt_pshader[] = {
        "uniform sampler2D sampler;\n"
        "void main(void)\n"
        "{\n"
        "    gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
        "}\n"
    };

    vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
    GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
    GL_EXTCALL(glCompileShaderARB(vshader_id));

    pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
    GL_EXTCALL(glShaderSourceARB(pshader_id, 1, blt_pshader, NULL));
    GL_EXTCALL(glCompileShaderARB(pshader_id));

    program_id = GL_EXTCALL(glCreateProgramObjectARB());
    GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
    GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
    GL_EXTCALL(glLinkProgramARB(program_id));

    print_glsl_info_log(&GLINFO_LOCATION, program_id);

    return program_id;
}

static void shader_glsl_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
    IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3197
    WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3198 3199
    GLhandleARB program_id = 0;

3200
    if (useVS || usePS) set_glsl_shader_program(iface, usePS, useVS);
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
    else This->stateBlock->glsl_program = NULL;

    program_id = This->stateBlock->glsl_program ? This->stateBlock->glsl_program->programId : 0;
    if (program_id) TRACE("Using GLSL program %u\n", program_id);
    GL_EXTCALL(glUseProgramObjectARB(program_id));
    checkGLcall("glUseProgramObjectARB");
}

static void shader_glsl_select_depth_blt(IWineD3DDevice *iface) {
    IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3211
    WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223
    static GLhandleARB program_id = 0;
    static GLhandleARB loc = -1;

    if (!program_id) {
        program_id = create_glsl_blt_shader(gl_info);
        loc = GL_EXTCALL(glGetUniformLocationARB(program_id, "sampler"));
    }

    GL_EXTCALL(glUseProgramObjectARB(program_id));
    GL_EXTCALL(glUniform1iARB(loc, 0));
}

3224 3225
static void shader_glsl_cleanup(IWineD3DDevice *iface) {
    IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3226
    WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3227
    GL_EXTCALL(glUseProgramObjectARB(0));
3228 3229
}

3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
    struct list *linked_programs;
    IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
    WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *) This->baseShader.device)->adapter->gl_info;

    /* Note: Do not use QueryInterface here to find out which shader type this is because this code
     * can be called from IWineD3DBaseShader::Release
     */
    char pshader = shader_is_pshader_version(This->baseShader.hex_version);

    if(This->baseShader.prgId == 0) return;
    linked_programs = &This->baseShader.linked_programs;

    TRACE("Deleting linked programs\n");
    if (linked_programs->next) {
        struct glsl_shader_prog_link *entry, *entry2;

        if(pshader) {
            LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
                delete_glsl_program_entry(This->baseShader.device, entry);
            }
        } else {
            LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
                delete_glsl_program_entry(This->baseShader.device, entry);
            }
        }
    }

    TRACE("Deleting shader object %u\n", This->baseShader.prgId);
    GL_EXTCALL(glDeleteObjectARB(This->baseShader.prgId));
    checkGLcall("glDeleteObjectARB");
}

3263 3264 3265 3266
const shader_backend_t glsl_shader_backend = {
    &shader_glsl_select,
    &shader_glsl_select_depth_blt,
    &shader_glsl_load_constants,
3267
    &shader_glsl_cleanup,
3268 3269
    &shader_glsl_color_correction,
    &shader_glsl_destroy
3270
};