glsl_shader.c 80.2 KB
Newer Older
1 2 3 4
/*
 * GLSL pixel and vertex shader implementation
 *
 * Copyright 2006 Jason Green 
5
 * Copyright 2006 Henri Verbeet
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 *
 * 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
 */

#include "config.h"
#include <stdio.h>
#include "wined3d_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);

#define GLINFO_LOCATION      (*gl_info)

/** 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)
    {
        infoLog = (char *)HeapAlloc(GetProcessHeap(), 0, infologLength);
        GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
46
        FIXME("Error received from GLSL shader #%u: %s\n", obj, debugstr_a(infoLog));
47 48 49 50
        HeapFree(GetProcessHeap(), 0, infoLog);
    }
}

51 52 53 54 55 56 57 58
/**
 * Loads (pixel shader) samplers
 */
void shader_glsl_load_psamplers(
    WineD3D_GL_Info *gl_info,
    IWineD3DStateBlock* iface) {

    IWineD3DStateBlockImpl* stateBlock = (IWineD3DStateBlockImpl*) iface;
59
    GLhandleARB programId = stateBlock->glsl_program->programId;
60 61 62 63
    GLhandleARB name_loc;
    int i;
    char sampler_name[20];

64
    for (i=0; i< GL_LIMITS(samplers); ++i) {
65
        if (stateBlock->textures[i] != NULL) {
66
           snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
67 68
           name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
           if (name_loc != -1) {
69
               TRACE("Loading %s for texture %d\n", sampler_name, i);
70 71 72 73 74 75 76 77 78
               GL_EXTCALL(glUniform1iARB(name_loc, i));
               checkGLcall("glUniform1iARB");
           }
        }
    }
}

/** 
 * Loads floating point constants (aka uniforms) into the currently set GLSL program.
79
 * When constant_list == NULL, it will load all the constants.
80
 */
81
static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl* This, WineD3D_GL_Info *gl_info,
82
        unsigned int max_constants, float* constants, GLhandleARB *constant_locations,
83 84
        struct list *constant_list) {
    local_constant* lconst;
85 86 87
    GLhandleARB tmp_loc;
    int i;

88 89 90 91 92 93 94 95 96 97 98 99
    if (!constant_list) {
        if (TRACE_ON(d3d_shader)) {
            for (i = 0; i < max_constants; ++i) {
                tmp_loc = constant_locations[i];
                if (tmp_loc != -1) {
                    TRACE("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]);
                }
            }
        }
        for (i = 0; i < max_constants; ++i) {
100
            tmp_loc = constant_locations[i];
101 102
            if (tmp_loc != -1) {
                /* We found this uniform name in the program - go ahead and send the data */
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
                GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, constants + (i * 4)));
            }
        }
        checkGLcall("glUniform4fvARB()");
    } else {
        constant_entry *constant;
        if (TRACE_ON(d3d_shader)) {
            LIST_FOR_EACH_ENTRY(constant, constant_list, constant_entry, entry) {
                i = constant->idx;
                tmp_loc = constant_locations[i];
                if (tmp_loc != -1) {
                    TRACE("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]);
                }
118 119
            }
        }
120 121 122 123 124 125 126 127 128
        LIST_FOR_EACH_ENTRY(constant, constant_list, constant_entry, entry) {
            i = constant->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)));
            }
        }
        checkGLcall("glUniform4fvARB()");
129
    }
130 131

    /* Load immediate constants */
132 133 134 135 136 137 138 139 140 141 142 143
    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;
                TRACE("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
                        values[0], values[1], values[2], values[3]);
            }
        }
    }
    LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
        tmp_loc = constant_locations[lconst->idx];
144 145
        if (tmp_loc != -1) {
            /* We found this uniform name in the program - go ahead and send the data */
146
            GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, (GLfloat*)lconst->value));
147 148
        }
    }
149
    checkGLcall("glUniform4fvARB()");
150 151
}

152 153 154 155 156
/** 
 * Loads integer constants (aka uniforms) into the currently set GLSL program.
 * When @constants_set == NULL, it will load all the constants.
 */
void shader_glsl_load_constantsI(
157
    IWineD3DBaseShaderImpl* This,
158 159 160 161
    WineD3D_GL_Info *gl_info,
    GLhandleARB programId,
    unsigned max_constants,
    int* constants,
162
    BOOL* constants_set) {
163 164 165
    
    GLhandleARB tmp_loc;
    int i;
166
    char tmp_name[8];
167
    char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
168
    const char* prefix = is_pshader? "PI":"VI";
169
    struct list* ptr;
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187

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

            TRACE("Loading constants %i: %i, %i, %i, %i\n",
                  i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);

            /* 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 */
                GL_EXTCALL(glUniform4ivARB(tmp_loc, 1, &constants[i*4]));
                checkGLcall("glUniform4ivARB");
            }
        }
    }
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

    /* 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;

        TRACE("Loading local constants %i: %i, %i, %i, %i\n", idx,
            values[0], values[1], values[2], values[3]);

        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(glUniform4ivARB(tmp_loc, 1, values));
            checkGLcall("glUniform4ivARB");
        }
        ptr = list_next(&This->baseShader.constantsI, ptr);
    }
208 209 210 211 212 213 214
}

/** 
 * Loads boolean constants (aka uniforms) into the currently set GLSL program.
 * When @constants_set == NULL, it will load all the constants.
 */
void shader_glsl_load_constantsB(
215
    IWineD3DBaseShaderImpl* This,
216 217 218 219
    WineD3D_GL_Info *gl_info,
    GLhandleARB programId,
    unsigned max_constants,
    BOOL* constants,
220
    BOOL* constants_set) {
221 222 223
    
    GLhandleARB tmp_loc;
    int i;
224
    char tmp_name[8];
225
    char is_pshader = shader_is_pshader_version(This->baseShader.hex_version);
226
    const char* prefix = is_pshader? "PB":"VB";
227
    struct list* ptr;
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

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

            TRACE("Loading constants %i: %i;\n", i, constants[i*4]);

            /* 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 */
                GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i*4]));
                checkGLcall("glUniform1ivARB");
            }
        }
    }
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

    /* 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;

        TRACE("Loading local constants %i: %i\n", idx, values[0]);

        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);
    }
264 265 266 267
}



268 269 270 271
/**
 * Loads the app-supplied constants into the currently set GLSL program.
 */
void shader_glsl_load_constants(
272
    IWineD3DDevice* device,
273 274
    char usePixelShader,
    char useVertexShader) {
275 276 277 278 279
   
    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device;
    IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
    WineD3D_GL_Info *gl_info = &((IWineD3DImpl*) deviceImpl->wineD3D)->gl_info;

280
    GLhandleARB *constant_locations;
281
    struct list *constant_list;
282
    GLhandleARB programId;
283
    
284
    if (!stateBlock->glsl_program) {
285 286 287
        /* No GLSL program set - nothing to do. */
        return;
    }
288
    programId = stateBlock->glsl_program->programId;
289 290

    if (useVertexShader) {
291 292
        IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
        IWineD3DVertexShaderImpl* vshader_impl = (IWineD3DVertexShaderImpl*) vshader;
293
        GLint pos;
294

295
        IWineD3DVertexDeclarationImpl* vertexDeclaration =
296
            (IWineD3DVertexDeclarationImpl*) vshader_impl->vertexDeclaration;
297

298
        constant_locations = stateBlock->glsl_program->vuniformF_locations;
299
        constant_list = &stateBlock->set_vconstantsF;
300

301 302
        if (NULL != vertexDeclaration && NULL != vertexDeclaration->constants) {
            /* Load DirectX 8 float constants/uniforms for vertex shader */
303 304
            shader_glsl_load_constantsF(vshader, gl_info, GL_LIMITS(vshader_constantsF),
                    vertexDeclaration->constants, constant_locations, NULL);
305 306 307
        }

        /* Load DirectX 9 float constants/uniforms for vertex shader */
308
        shader_glsl_load_constantsF(vshader, gl_info, GL_LIMITS(vshader_constantsF),
309
                stateBlock->vertexShaderConstantF, constant_locations, constant_list);
310

311
        /* Load DirectX 9 integer constants/uniforms for vertex shader */
312
        shader_glsl_load_constantsI(vshader, gl_info, programId, MAX_CONST_I,
313
                                    stateBlock->vertexShaderConstantI,
314
                                    stateBlock->set.vertexShaderConstantsI);
315 316

        /* Load DirectX 9 boolean constants/uniforms for vertex shader */
317
        shader_glsl_load_constantsB(vshader, gl_info, programId, MAX_CONST_B,
318
                                    stateBlock->vertexShaderConstantB,
319
                                    stateBlock->set.vertexShaderConstantsB);
320 321 322 323

        /* Upload the position fixup params */
        pos = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
        checkGLcall("glGetUniformLocationARB");
324
        GL_EXTCALL(glUniform4fvARB(pos, 1, &deviceImpl->posFixup[0]));
325
        checkGLcall("glUniform4fvARB");
326 327 328 329
    }

    if (usePixelShader) {

330 331
        IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;

332
        constant_locations = stateBlock->glsl_program->puniformF_locations;
333
        constant_list = &stateBlock->set_pconstantsF;
334

335
        /* Load pixel shader samplers */
336
        shader_glsl_load_psamplers(gl_info, (IWineD3DStateBlock*) stateBlock);
337 338

        /* Load DirectX 9 float constants/uniforms for pixel shader */
339
        shader_glsl_load_constantsF(pshader, gl_info, GL_LIMITS(pshader_constantsF),
340
                stateBlock->pixelShaderConstantF, constant_locations, constant_list);
341

342
        /* Load DirectX 9 integer constants/uniforms for pixel shader */
343
        shader_glsl_load_constantsI(pshader, gl_info, programId, MAX_CONST_I,
344
                                    stateBlock->pixelShaderConstantI, 
345
                                    stateBlock->set.pixelShaderConstantsI);
346 347
        
        /* Load DirectX 9 boolean constants/uniforms for pixel shader */
348
        shader_glsl_load_constantsB(pshader, gl_info, programId, MAX_CONST_B,
349
                                    stateBlock->pixelShaderConstantB, 
350
                                    stateBlock->set.pixelShaderConstantsB);
351 352 353
    }
}

354 355 356 357
/** Generate the variable & register declarations for the GLSL output target */
void shader_generate_glsl_declarations(
    IWineD3DBaseShader *iface,
    shader_reg_maps* reg_maps,
358 359
    SHADER_BUFFER* buffer,
    WineD3D_GL_Info* gl_info) {
360 361 362 363 364 365 366 367

    IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
    int i;

    /* 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';

368 369 370 371 372 373
    /* Prototype the subroutines */
    for (i = 0; i < This->baseShader.limits.label; i++) {
        if (reg_maps->labels[i])
            shader_addline(buffer, "void subroutine%lu();\n", i);
    }

374
    /* Declare the constants (aka uniforms) */
375 376 377 378 379
    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);
    }
380 381 382 383 384 385 386

    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);

387 388 389
    if(!pshader)
        shader_addline(buffer, "uniform vec4 posFixup;\n");

390 391 392 393
    /* Declare texture samplers */ 
    for (i = 0; i < This->baseShader.limits.sampler; i++) {
        if (reg_maps->samplers[i]) {

394
            DWORD stype = reg_maps->samplers[i] & WINED3DSP_TEXTURETYPE_MASK;
395 396
            switch (stype) {

397 398 399 400
                case WINED3DSTT_1D:
                    shader_addline(buffer, "uniform sampler1D %csampler%lu;\n", prefix, i);
                    break;
                case WINED3DSTT_2D:
401 402
                    shader_addline(buffer, "uniform sampler2D %csampler%lu;\n", prefix, i);
                    break;
403
                case WINED3DSTT_CUBE:
404 405
                    shader_addline(buffer, "uniform samplerCube %csampler%lu;\n", prefix, i);
                    break;
406
                case WINED3DSTT_VOLUME:
407 408 409 410
                    shader_addline(buffer, "uniform sampler3D %csampler%lu;\n", prefix, i);
                    break;
                default:
                    shader_addline(buffer, "uniform unsupported_sampler %csampler%lu;\n", prefix, i);
411
                    FIXME("Unrecognized sampler type: %#x\n", stype);
412 413 414 415 416 417 418 419
                    break;
            }
        }
    }
    
    /* Declare address variables */
    for (i = 0; i < This->baseShader.limits.address; i++) {
        if (reg_maps->address[i])
420
            shader_addline(buffer, "ivec4 A%d;\n", i);
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    }

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

    /* Declare input register temporaries */
    for (i=0; i < This->baseShader.limits.packed_input; i++) {
        if (reg_maps->packed_input[i])
            shader_addline(buffer, "vec4 IN%lu;\n", i);
    }

    /* Declare output register temporaries */
    for (i = 0; i < This->baseShader.limits.packed_output; i++) {
        if (reg_maps->packed_output[i])
            shader_addline(buffer, "vec4 OUT%lu;\n", i);
    }

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

    /* 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);
    }

    /* Declare loop register aL */
454
    if (reg_maps->loop) {
455
        shader_addline(buffer, "int aL;\n");
456 457
        shader_addline(buffer, "int tmpInt;\n");
    }
458 459 460 461 462 463 464 465 466
    
    /* Temporary variables for matrix operations */
    shader_addline(buffer, "vec4 tmp0;\n");
    shader_addline(buffer, "vec4 tmp1;\n");

    /* Start the main program */
    shader_addline(buffer, "void main() {\n");
}

467 468 469 470 471 472 473
/*****************************************************************************
 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
 *
 * For more information, see http://wiki.winehq.org/DirectX-Shaders
 ****************************************************************************/

/* Prototypes */
474
static void shader_glsl_add_param(
475 476 477 478 479 480 481 482 483
    SHADER_OPCODE_ARG* arg,
    const DWORD param,
    const DWORD addr_token,
    BOOL is_input,
    char *reg_name,
    char *reg_mask,
    char *out_str);

/** Used for opcode modifiers - They multiply the result by the specified amount */
484
static const char * const shift_glsl_tab[] = {
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    "",           /*  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)   */ 
};

503 504 505
/** Print the beginning of the generated GLSL string. example: "reg_name.xyzw = vec4("
 * Will also change the reg_mask if necessary (not all register types are equal in DX vs GL)  */
static void shader_glsl_add_dst(DWORD param, const char* reg_name, char* reg_mask, char* outStr) {
506

507
    int shift = (param & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
508 509
    char cast[6];
    
510
    if ((shader_get_regtype(param) == WINED3DSPR_RASTOUT)
511
         && ((param & WINED3DSP_REGNUM_MASK) != 0)) {
512 513 514 515 516 517 518 519 520 521 522 523 524 525
        /* gl_FogFragCoord or glPointSize - both floats */
        strcpy(cast, "float");
        strcpy(reg_mask, "");

    } else if (reg_name[0] == 'A') {
        /* Address register for vertex shaders (ivec4) */
        strcpy(cast, "ivec4");
        
    } else {
        /* Everything else should be a 4 component float vector */
        strcpy(cast, "vec4");
    }
    
    sprintf(outStr, "%s%s = %s%s(", reg_name, reg_mask, shift_glsl_tab[shift], cast); 
526 527 528
}

/* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
529
static void shader_glsl_gen_modifier (
530 531 532 533 534 535 536
    const DWORD instr,
    const char *in_reg,
    const char *in_regswizzle,
    char *out_str) {

    out_str[0] = 0;
    
537
    if (instr == WINED3DSIO_TEXKILL)
538 539
        return;

540 541
    switch (instr & WINED3DSP_SRCMOD_MASK) {
    case WINED3DSPSM_NONE:
542 543
        sprintf(out_str, "%s%s", in_reg, in_regswizzle);
        break;
544
    case WINED3DSPSM_NEG:
545 546
        sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
        break;
547
    case WINED3DSPSM_NOT:
548 549
        sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
        break;
550
    case WINED3DSPSM_BIAS:
551 552
        sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
        break;
553
    case WINED3DSPSM_BIASNEG:
554 555
        sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
        break;
556
    case WINED3DSPSM_SIGN:
557 558
        sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
        break;
559
    case WINED3DSPSM_SIGNNEG:
560 561
        sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
        break;
562
    case WINED3DSPSM_COMP:
563 564
        sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
        break;
565
    case WINED3DSPSM_X2:
566 567
        sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
        break;
568
    case WINED3DSPSM_X2NEG:
569 570
        sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
        break;
571
    case WINED3DSPSM_DZ:    /* reg1_db = { reg1.r/b, reg1.g/b, ...}  The g & a components are undefined, so we'll leave them alone */
572 573
        sprintf(out_str, "vec4(%s.r / %s.b, %s.g / %s.b, %s.b, %s.a)", in_reg, in_reg, in_reg, in_reg, in_reg, in_reg);
        break;
574
    case WINED3DSPSM_DW:
575 576
        sprintf(out_str, "vec4(%s.r / %s.a, %s.g / %s.a, %s.b, %s.a)", in_reg, in_reg, in_reg, in_reg, in_reg, in_reg);
        break;
577
    case WINED3DSPSM_ABS:
578 579
        sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
        break;
580
    case WINED3DSPSM_ABSNEG:
581 582 583
        sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
        break;
    default:
584
        FIXME("Unhandled modifier %u\n", (instr & WINED3DSP_SRCMOD_MASK));
585 586 587 588 589 590
        sprintf(out_str, "%s%s", in_reg, in_regswizzle);
    }
}

/** Writes the GLSL variable name that corresponds to the register that the
 * DX opcode parameter is trying to access */
591
static void shader_glsl_get_register_name(
592 593 594 595 596 597 598
    const DWORD param,
    const DWORD addr_token,
    char* regstr,
    BOOL* is_color,
    SHADER_OPCODE_ARG* arg) {

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

601
    DWORD reg = param & WINED3DSP_REGNUM_MASK;
602 603
    DWORD regtype = shader_get_regtype(param);
    IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) arg->shader;
604 605 606
    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
    WineD3D_GL_Info* gl_info = &((IWineD3DImpl*)deviceImpl->wineD3D)->gl_info;

607
    char pshader = shader_is_pshader_version(This->baseShader.hex_version);
608
    char tmpStr[50];
609 610 611

    *is_color = FALSE;   
 
612
    switch (regtype) {
613
    case WINED3DSPR_TEMP:
614
        sprintf(tmpStr, "R%u", reg);
615
    break;
616
    case WINED3DSPR_INPUT:
617
        if (pshader) {
618
            /* Pixel shaders >= 3.0 */
619
            if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
620
                sprintf(tmpStr, "IN%u", reg);
621 622 623 624 625
             else {
                if (reg==0)
                    strcpy(tmpStr, "gl_Color");
                else
                    strcpy(tmpStr, "gl_SecondaryColor");
626 627
            }
        } else {
628 629
            if (vshader_input_is_color((IWineD3DVertexShader*) This, reg))
               *is_color = TRUE;
630
            sprintf(tmpStr, "attrib%u", reg);
631 632
        } 
        break;
633
    case WINED3DSPR_CONST:
634 635 636
    {
        const char* prefix = pshader? "PC":"VC";

637
        /* Relative addressing */
638
        if (param & WINED3DSHADER_ADDRMODE_RELATIVE) {
639 640 641

           /* 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 */
642
           if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 2)  {
643 644
               char relStr[100], relReg[50], relMask[6];
               shader_glsl_add_param(arg, addr_token, 0, TRUE, relReg, relMask, relStr);
645
               sprintf(tmpStr, "%s[%s + %u]", prefix, relStr, reg);
646
           } else
647
               sprintf(tmpStr, "%s[A0.x + %u]", prefix, reg);
648 649

        } else
650
             sprintf(tmpStr, "%s[%u]", prefix, reg);
651

652 653
        break;
    }
654
    case WINED3DSPR_CONSTINT:
655
        if (pshader)
656
            sprintf(tmpStr, "PI[%u]", reg);
657
        else
658
            sprintf(tmpStr, "VI[%u]", reg);
659
        break;
660
    case WINED3DSPR_CONSTBOOL:
661
        if (pshader)
662
            sprintf(tmpStr, "PB[%u]", reg);
663
        else
664
            sprintf(tmpStr, "VB[%u]", reg);
665
        break;
666
    case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
667
        if (pshader) {
668
            sprintf(tmpStr, "T%u", reg);
669
        } else {
670
            sprintf(tmpStr, "A%u", reg);
671 672
        }
    break;
673
    case WINED3DSPR_LOOP:
674 675
        sprintf(tmpStr, "aL");
    break;
676
    case WINED3DSPR_SAMPLER:
677
        if (pshader)
678
            sprintf(tmpStr, "Psampler%u", reg);
679
        else
680
            sprintf(tmpStr, "Vsampler%u", reg);
681
    break;
682
    case WINED3DSPR_COLOROUT:
683 684 685
        if (reg >= GL_LIMITS(buffers)) {
            WARN("Write to render target %u, only %d supported\n", reg, 4);
        }
686
        if (GL_SUPPORT(ARB_DRAW_BUFFERS)) {
687
            sprintf(tmpStr, "gl_FragData[%u]", reg);
688
        } else { /* On older cards with GLSL support like the GeforceFX there's only one buffer. */
689
            sprintf(tmpStr, "gl_FragColor");
690 691
        }
    break;
692
    case WINED3DSPR_RASTOUT:
693 694
        sprintf(tmpStr, "%s", hwrastout_reg_names[reg]);
    break;
695
    case WINED3DSPR_DEPTHOUT:
696 697
        sprintf(tmpStr, "gl_FragDepth");
    break;
698
    case WINED3DSPR_ATTROUT:
699 700 701 702 703 704
        if (reg == 0) {
            sprintf(tmpStr, "gl_FrontColor");
        } else {
            sprintf(tmpStr, "gl_FrontSecondaryColor");
        }
    break;
705 706
    case WINED3DSPR_TEXCRDOUT:
        /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
707
        if (WINED3DSHADER_VERSION_MAJOR(This->baseShader.hex_version) >= 3)
708
            sprintf(tmpStr, "OUT%u", reg);
709
        else
710
            sprintf(tmpStr, "gl_TexCoord[%u]", reg);
711 712
    break;
    default:
713
        FIXME("Unhandled register name Type(%d)\n", regtype);
714 715 716 717 718 719 720
        sprintf(tmpStr, "unrecognized_register");
    break;
    }

    strcat(regstr, tmpStr);
}

721 722 723 724
/* Get the GLSL write mask for the destination register */
static void shader_glsl_get_write_mask(const DWORD param, char *write_mask) {
    char *ptr = write_mask;

725 726 727 728 729 730 731 732
    if ((param & WINED3DSP_WRITEMASK_ALL) != WINED3DSP_WRITEMASK_ALL) {
        *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';
    }

733
    *ptr = '\0';
734 735
}

736 737 738 739 740 741 742 743
static void shader_glsl_get_swizzle(const DWORD param, BOOL fixup, char *swizzle_str) {
    /* 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. */
    const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
    char *ptr = swizzle_str;

    /* swizzle bits fields: wwzzyyxx */
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
    DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
    DWORD swizzle_x = swizzle & 0x03;
    DWORD swizzle_y = (swizzle >> 2) & 0x03;
    DWORD swizzle_z = (swizzle >> 4) & 0x03;
    DWORD swizzle_w = (swizzle >> 6) & 0x03;

    /* If the swizzle is the default swizzle (ie, "xyzw"), we don't need to
     * generate a swizzle string. Unless we need to our own swizzling. */
    if ((WINED3DSP_NOSWIZZLE >> WINED3DSP_SWIZZLE_SHIFT) != swizzle || fixup) {
        *ptr++ = '.';
        if (swizzle_x == swizzle_y && swizzle_x == swizzle_z && swizzle_x == swizzle_w) {
            *ptr++ = swizzle_chars[swizzle_x];
        } else {
            *ptr++ = swizzle_chars[swizzle_x];
            *ptr++ = swizzle_chars[swizzle_y];
            *ptr++ = swizzle_chars[swizzle_z];
            *ptr++ = swizzle_chars[swizzle_w];
        }
762
    }
763

764
    *ptr = '\0';
765 766 767 768 769
}

/** 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. */
770
static void shader_glsl_add_param(
771 772 773 774 775 776 777 778 779 780 781 782 783 784
    SHADER_OPCODE_ARG* arg,
    const DWORD param,
    const DWORD addr_token,
    BOOL is_input,
    char *reg_name,
    char *reg_mask,
    char *out_str) {

    BOOL is_color = FALSE;
    reg_mask[0] = reg_name[0] = out_str[0] = 0;

    shader_glsl_get_register_name(param, addr_token, reg_name, &is_color, arg);
    
    if (is_input) {
785
        shader_glsl_get_swizzle(param, is_color, reg_mask);
786 787
        shader_glsl_gen_modifier(param, reg_name, reg_mask, out_str);
    } else {
788
        shader_glsl_get_write_mask(param, reg_mask);
789 790 791 792 793 794
        sprintf(out_str, "%s%s", reg_name, reg_mask);
    }
}

/** Process GLSL instruction modifiers */
void shader_glsl_add_instruction_modifiers(SHADER_OPCODE_ARG* arg) {
795
    
796
    DWORD mask = arg->dst & WINED3DSP_DSTMOD_MASK;
797 798
 
    if (arg->opcode->dst_token && mask != 0) {
799 800 801 802 803 804
        char dst_reg[50];
        char dst_mask[6];
        char dst_str[100];
       
        shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);

805
        if (mask & WINED3DSPDM_SATURATE) {
806 807 808
            /* _SAT means to clamp the value of the register to between 0 and 1 */
            shader_addline(arg->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_reg, dst_mask, dst_reg, dst_mask);
        }
809
        if (mask & WINED3DSPDM_MSAMPCENTROID) {
810 811
            FIXME("_centroid modifier not handled\n");
        }
812
        if (mask & WINED3DSPDM_PARTIALPRECISION) {
813 814 815 816 817
            /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
        }
    }
}

818 819 820 821 822 823 824 825 826 827 828 829
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:
830
            FIXME("Unrecognized comparison value: %u\n", op);
831 832 833 834
            return "(\?\?)";
    }
}

835 836 837 838 839 840 841 842 843 844 845
static void shader_glsl_sample(SHADER_OPCODE_ARG* arg, DWORD sampler_idx, const char *dst_str, const char *coord_reg) {
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
    IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
    DWORD sampler_type = arg->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
    const char sampler_prefix = shader_is_pshader_version(This->baseShader.hex_version) ? 'P' : 'V';
    SHADER_BUFFER* buffer = arg->buffer;

    if(deviceImpl->stateBlock->textureState[sampler_idx][WINED3DTSS_TEXTURETRANSFORMFLAGS] & WINED3DTTFF_PROJECTED) {
        /* Note that there's no such thing as a projected cube texture. */
        switch(sampler_type) {
            case WINED3DSTT_2D:
846
                shader_addline(buffer, "%s = texture2DProj(%csampler%u, %s);\n", dst_str, sampler_prefix, sampler_idx, coord_reg);
847 848
                break;
            case WINED3DSTT_VOLUME:
849
                shader_addline(buffer, "%s = texture3DProj(%csampler%u, %s);\n", dst_str, sampler_prefix, sampler_idx, coord_reg);
850 851
                break;
            default:
852
                shader_addline(buffer, "%s = unrecognized_stype(%csampler%u, %s);\n", dst_str, sampler_prefix, sampler_idx, coord_reg);
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
                FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
                break;
        }
    } else {
        switch(sampler_type) {
            case WINED3DSTT_2D:
                shader_addline(buffer, "%s = texture2D(%csampler%u, %s.xy);\n", dst_str, sampler_prefix, sampler_idx, coord_reg);
                break;
            case WINED3DSTT_CUBE:
                shader_addline(buffer, "%s = textureCube(%csampler%u, %s.xyz);\n", dst_str, sampler_prefix, sampler_idx, coord_reg);
                break;
            case WINED3DSTT_VOLUME:
                shader_addline(buffer, "%s = texture3D(%csampler%u, %s.xyz);\n", dst_str, sampler_prefix, sampler_idx, coord_reg);
                break;
            default:
                shader_addline(buffer, "%s = unrecognized_stype(%csampler%u, %s);\n", dst_str, sampler_prefix, sampler_idx, coord_reg);
                FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
                break;
        }
    }
}


876 877 878 879 880 881
/*****************************************************************************
 * 
 * Begin processing individual instruction opcodes
 * 
 ****************************************************************************/

882
/* Generate GLSL arithmetic functions (dst = src1 + src2) */
883 884 885 886 887 888 889 890 891 892 893 894 895
void shader_glsl_arith(SHADER_OPCODE_ARG* arg) {

    CONST SHADER_OPCODE* curOpcode = arg->opcode;
    SHADER_BUFFER* buffer = arg->buffer;
    char tmpLine[256];
    char dst_reg[50], src0_reg[50], src1_reg[50];
    char dst_mask[6], src0_mask[6], src1_mask[6];
    char dst_str[100], src0_str[100], src1_str[100];

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
896
    strcat(tmpLine, "vec4(");
897
    strcat(tmpLine, src0_str);
898
    strcat(tmpLine, ")");
899 900 901

    /* Determine the GLSL operator to use based on the opcode */
    switch (curOpcode->opcode) {
902 903 904
        case WINED3DSIO_MUL:    strcat(tmpLine, " * "); break;
        case WINED3DSIO_ADD:    strcat(tmpLine, " + "); break;
        case WINED3DSIO_SUB:    strcat(tmpLine, " - "); break;
905 906 907 908
        default:
            FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
            break;
    }
909
    shader_addline(buffer, "%svec4(%s))%s;\n", tmpLine, src1_str, dst_mask);
910 911
}

912
/* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
void shader_glsl_mov(SHADER_OPCODE_ARG* arg) {

    SHADER_BUFFER* buffer = arg->buffer;
    char tmpLine[256];
    char dst_str[100], src0_str[100];
    char dst_reg[50], src0_reg[50];
    char dst_mask[6], src0_mask[6];

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
    shader_addline(buffer, "%s%s)%s;\n", tmpLine, src0_str, dst_mask);
}

/* 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;
    char tmpDest[100];
    char dst_str[100], src0_str[100], src1_str[100];
    char dst_reg[50], src0_reg[50], src1_reg[50];
    char dst_mask[6], src0_mask[6], src1_mask[6];
    char cast[6];

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);

    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpDest);
 
    /* Need to cast the src vectors to vec3 for dp3, and vec4 for dp4 */
945
    if (curOpcode->opcode == WINED3DSIO_DP4)
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
        strcpy(cast, "vec4(");
    else
        strcpy(cast, "vec3(");
    
    shader_addline(buffer, "%sdot(%s%s), %s%s)))%s;\n",
                   tmpDest, cast, src0_str, cast, src1_str, dst_mask);
}

/* 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;
    char tmpLine[256];
    char dst_str[100], src_str[100];
    char dst_reg[50], src_reg[50];
    char dst_mask[6], src_mask[6];
    unsigned i;
    
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);

    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
 
    /* Determine the GLSL function to use based on the opcode */
    /* TODO: Possibly make this a table for faster lookups */
    switch (curOpcode->opcode) {
972 973 974 975 976 977 978 979 980 981 982 983 984 985
            case WINED3DSIO_MIN:    strcat(tmpLine, "min"); break;
            case WINED3DSIO_MAX:    strcat(tmpLine, "max"); break;
            case WINED3DSIO_RSQ:    strcat(tmpLine, "inversesqrt"); break;
            case WINED3DSIO_ABS:    strcat(tmpLine, "abs"); break;
            case WINED3DSIO_FRC:    strcat(tmpLine, "fract"); break;
            case WINED3DSIO_POW:    strcat(tmpLine, "pow"); break;
            case WINED3DSIO_CRS:    strcat(tmpLine, "cross"); break;
            case WINED3DSIO_NRM:    strcat(tmpLine, "normalize"); break;
            case WINED3DSIO_LOGP:
            case WINED3DSIO_LOG:    strcat(tmpLine, "log2"); break;
            case WINED3DSIO_EXP:    strcat(tmpLine, "exp2"); break;
            case WINED3DSIO_SGE:    strcat(tmpLine, "greaterThanEqual"); break;
            case WINED3DSIO_SLT:    strcat(tmpLine, "lessThan"); break;
            case WINED3DSIO_SGN:    strcat(tmpLine, "sign"); break;
986 987 988 989 990 991 992 993
        default:
            FIXME("Opcode %s not yet handled in GLSL\n", curOpcode->name);
            break;
    }

    strcat(tmpLine, "(");

    if (curOpcode->num_params > 0) {
994
        strcat(tmpLine, "vec4(");
995 996
        shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src_reg, src_mask, src_str);
        strcat(tmpLine, src_str);
997
        strcat(tmpLine, ")");
998
        for (i = 2; i < curOpcode->num_params; ++i) {
999
            strcat(tmpLine, ", vec4(");
1000 1001
            shader_glsl_add_param(arg, arg->src[i-1], arg->src_addr[i-1], TRUE, src_reg, src_mask, src_str);
            strcat(tmpLine, src_str);
1002
            strcat(tmpLine, ")");
1003 1004 1005 1006 1007 1008
        }
    }
    shader_addline(buffer, "%s))%s;\n", tmpLine, dst_mask);

}

1009
/** Process the WINED3DSIO_EXPP instruction in GLSL:
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
 * 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) {

    char tmpLine[256];
    char dst_str[100], src_str[100];
    char dst_reg[50], src_reg[50];
    char dst_mask[6], src_mask[6];
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
    DWORD hex_version = This->baseShader.hex_version;
    
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src_reg, src_mask, src_str);
    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);

1031
    if (hex_version < WINED3DPS_VERSION(2,0)) {
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
        shader_addline(arg->buffer, "tmp0.x = vec4(exp2(floor(%s))).x;\n", src_str);
        shader_addline(arg->buffer, "tmp0.y = vec4(%s - floor(%s)).y;\n", src_str, src_str);
        shader_addline(arg->buffer, "tmp0.z = vec4(exp2(%s)).x;\n", src_str);
        shader_addline(arg->buffer, "tmp0.w = 1.0;\n");
        shader_addline(arg->buffer, "%svec4(tmp0))%s;\n", tmpLine, dst_mask);
    } else {
        shader_addline(arg->buffer, "%svec4(exp2(%s)))%s;\n", tmpLine, src_str, dst_mask);
    }
}

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
/** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
void shader_glsl_rcp(SHADER_OPCODE_ARG* arg) {

    char tmpLine[256];
    char dst_str[100], src_str[100];
    char dst_reg[50], src_reg[50];
    char dst_mask[6], src_mask[6];
    
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src_reg, src_mask, src_str);
    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
    strcat(tmpLine, "1.0 / ");
    shader_addline(arg->buffer, "%s%s)%s;\n", tmpLine, src_str, dst_mask);
}

/** Process signed comparison opcodes in GLSL. */
void shader_glsl_compare(SHADER_OPCODE_ARG* arg) {

    char tmpLine[256];
    char dst_str[100], src0_str[100], src1_str[100];
    char dst_reg[50], src0_reg[50], src1_reg[50];
    char dst_mask[6], src0_mask[6], src1_mask[6];
    
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);

    /* If we are comparing vectors and not scalars, we should process this through map2gl using the GLSL functions. */
    if (strlen(src0_mask) != 2) {
        shader_glsl_map2gl(arg);
    } else {
        char compareStr[3];
        compareStr[0] = 0;
        shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);

        switch (arg->opcode->opcode) {
1078 1079
            case WINED3DSIO_SLT:    strcpy(compareStr, "<"); break;
            case WINED3DSIO_SGE:    strcpy(compareStr, ">="); break;
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
            default:
                FIXME("Can't handle opcode %s\n", arg->opcode->name);
        }
        shader_addline(arg->buffer, "%s(float(%s) %s float(%s)) ? 1.0 : 0.0)%s;\n",
                       tmpLine, src0_str, compareStr, src1_str, dst_mask);
    }
}

/** Process CMP instruction in GLSL (dst = src0.x > 0.0 ? src1.x : src2.x), per channel */
void shader_glsl_cmp(SHADER_OPCODE_ARG* arg) {

1091
    char tmpLine[256];
1092 1093 1094
    char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
    char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
    char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
1095
   
1096 1097 1098 1099 1100
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
    shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);

1101 1102 1103
    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
    shader_addline(arg->buffer, "%smix(vec4(%s), vec4(%s), vec4(lessThan(vec4(%s), vec4(0.0)))))%s;\n",
        tmpLine, src1_str, src2_str, src0_str, dst_mask);
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
}

/** Process the CND opcode in GLSL (dst = (src0 < 0.5) ? src1 : src2) */
void shader_glsl_cnd(SHADER_OPCODE_ARG* arg) {

    char tmpLine[256];
    char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
    char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
    char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
 
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
    shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);   
    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
    shader_addline(arg->buffer, "%s(%s < 0.5) ? %s : %s)%s;\n", 
                   tmpLine, src0_str, src1_str, src2_str, dst_mask);
}

1123
/** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
void shader_glsl_mad(SHADER_OPCODE_ARG* arg) {

    char tmpLine[256];
    char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
    char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
    char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
    
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
    shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);     
    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);

1137
    shader_addline(arg->buffer, "%s(vec4(%s) * vec4(%s)) + vec4(%s))%s;\n",
1138 1139 1140
                   tmpLine, src0_str, src1_str, src2_str, dst_mask);
}

1141
/** Handles transforming all WINED3DSIO_M?x? opcodes for 
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    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];
1155
    tmpArg.src_addr[1] = arg->src_addr[1];
1156 1157 1158
    tmpArg.reg_maps = arg->reg_maps; 
    
    switch(arg->opcode->opcode) {
1159
        case WINED3DSIO_M4x4:
1160
            nComponents = 4;
1161
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1162
            break;
1163
        case WINED3DSIO_M4x3:
1164
            nComponents = 3;
1165
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP4);
1166
            break;
1167
        case WINED3DSIO_M3x4:
1168
            nComponents = 4;
1169
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1170
            break;
1171
        case WINED3DSIO_M3x3:
1172
            nComponents = 3;
1173
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1174
            break;
1175
        case WINED3DSIO_M3x2:
1176
            nComponents = 2;
1177
            tmpArg.opcode = shader_get_opcode(arg->shader, WINED3DSIO_DP3);
1178 1179 1180 1181 1182 1183
            break;
        default:
            break;
    }

    for (i = 0; i < nComponents; i++) {
1184
        tmpArg.dst = ((arg->dst) & ~WINED3DSP_WRITEMASK_ALL)|(WINED3DSP_WRITEMASK_0<<i);
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
        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
    blend factor.  Equation:  (dst = src2 * (src1 - src0) + src0)
*/
void shader_glsl_lrp(SHADER_OPCODE_ARG* arg) {

    char tmpLine[256];
    char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
    char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
    char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
   
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
    shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);     

    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
    
1209 1210
    shader_addline(arg->buffer, "%s%s + %s * (%s - %s))%s;\n",
                   tmpLine, src2_str, src0_str, src1_str, src2_str, dst_mask);
1211 1212
}

1213
/** Process the WINED3DSIO_LIT instruction in GLSL:
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
 * 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) {

    char dst_str[100], src0_str[100];
    char dst_reg[50], src0_reg[50];
    char dst_mask[6], src0_mask[6];
   
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);

    shader_addline(arg->buffer,
        "%s = vec4(1.0, (%s.x > 0.0 ? %s.x : 0.0), (%s.x > 0.0 ? ((%s.y > 0.0) ? pow(%s.y, clamp(%s.w, -128.0, 128.0)) : 0.0) : 0.0), 1.0)%s;\n",
        dst_str, src0_reg, src0_reg, src0_reg, src0_reg, src0_reg, src0_reg, dst_mask);
}

1233
/** Process the WINED3DSIO_DST instruction in GLSL:
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
 * 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) {

    char dst_str[100], src0_str[100], src1_str[100];
    char dst_reg[50], src0_reg[50], src1_reg[50];
    char dst_mask[6], src0_mask[6], src1_mask[6];
   
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);

    shader_addline(arg->buffer, "%s = vec4(1.0, %s.x * %s.y, %s.z, %s.w)%s;\n",
                   dst_str, src0_reg, src1_reg, src0_reg, src1_reg, dst_mask);
}

1253
/** Process the WINED3DSIO_SINCOS instruction in GLSL:
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
 * 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) {
    
    char dst_str[100], src0_str[100];
    char dst_reg[50], src0_reg[50];
    char dst_mask[6], src0_mask[6];
   
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);

    shader_addline(arg->buffer, "%s = vec4(cos(%s), sin(%s), %s.z, %s.w)%s;\n",
                   dst_str, src0_str, src0_str, dst_reg, dst_reg, dst_mask);
}

1275
/** Process the WINED3DSIO_LOOP instruction in GLSL:
1276
 * Start a for() loop where src0.y is the initial value of aL,
1277 1278
 *  increment aL by src0.z for a total of src0.x iterations.
 *  Need to use a temporary variable for this operation.
1279 1280 1281
 */
void shader_glsl_loop(SHADER_OPCODE_ARG* arg) {
    
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    char src1_str[100];
    char src1_reg[50];
    char src1_mask[6];
    
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
  
    shader_addline(arg->buffer, "for (tmpInt = 0, aL = %s.y; tmpInt < %s.x; tmpInt++, aL += %s.z) {\n",
                   src1_reg, src1_reg, src1_reg);
}

void shader_glsl_end(SHADER_OPCODE_ARG* arg) {
    shader_addline(arg->buffer, "}\n");
}

void shader_glsl_rep(SHADER_OPCODE_ARG* arg) {

1298 1299 1300
    char src0_str[100];
    char src0_reg[50];
    char src0_mask[6];
1301

1302
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
1303
    shader_addline(arg->buffer, "for (tmpInt = 0; tmpInt < %s.x; tmpInt++) {\n", src0_reg);
1304 1305
}

1306
void shader_glsl_if(SHADER_OPCODE_ARG* arg) {
1307

1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
    char src0_str[100];
    char src0_reg[50];
    char src0_mask[6];

    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_addline(arg->buffer, "if (%s) {\n", src0_str); 
}

void shader_glsl_ifc(SHADER_OPCODE_ARG* arg) {

    char src0_str[100], src1_str[100];
    char src0_reg[50], src1_reg[50];
    char src0_mask[6], src1_mask[6];

    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);

    shader_addline(arg->buffer, "if (%s %s %s) {\n",
        src0_str, shader_get_comp_op(arg->opcode_token), src1_str);
}

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

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
void shader_glsl_break(SHADER_OPCODE_ARG* arg) {
    shader_addline(arg->buffer, "break;\n");
}

void shader_glsl_breakc(SHADER_OPCODE_ARG* arg) {

    char src0_str[100], src1_str[100];
    char src0_reg[50], src1_reg[50];
    char src0_mask[6], src1_mask[6];

    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);

    shader_addline(arg->buffer, "if (%s %s %s) break;\n",
        src0_str, shader_get_comp_op(arg->opcode_token), src1_str);
}
1349

1350 1351
void shader_glsl_label(SHADER_OPCODE_ARG* arg) {

1352
    DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1353 1354 1355 1356 1357
    shader_addline(arg->buffer, "}\n");
    shader_addline(arg->buffer, "void subroutine%lu () {\n",  snum);
}

void shader_glsl_call(SHADER_OPCODE_ARG* arg) {
1358
    DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1359 1360 1361 1362 1363 1364 1365 1366 1367
    shader_addline(arg->buffer, "subroutine%lu();\n", snum);
}

void shader_glsl_callnz(SHADER_OPCODE_ARG* arg) {

    char src1_str[100];
    char src1_reg[50];
    char src1_mask[6];
   
1368
    DWORD snum = (arg->src[0]) & WINED3DSP_REGNUM_MASK;
1369 1370 1371 1372
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
    shader_addline(arg->buffer, "if (%s) subroutine%lu();\n", src1_str, snum);
}

1373 1374 1375 1376 1377
/*********************************************
 * Pixel Shader Specific Code begins here
 ********************************************/
void pshader_glsl_tex(SHADER_OPCODE_ARG* arg) {
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
1378

1379
    DWORD hex_version = This->baseShader.hex_version;
1380 1381

    char dst_str[100],   dst_reg[50],  dst_mask[6];
1382
    char coord_str[100], coord_reg[50], coord_mask[6];
1383 1384 1385

    /* All versions have a destination register */
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
1386

1387
    /* 1.0-1.3: Use destination register as coordinate source.
1388
       1.4+: Use provided coordinate source register. */
1389
    if (hex_version < WINED3DPS_VERSION(1,4))
1390 1391 1392 1393
       strcpy(coord_reg, dst_reg);
    else
       shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, coord_reg, coord_mask, coord_str);

1394 1395
    /* 1.0-1.4: Use destination register as sampler source.
     * 2.0+: Use provided sampler source. */
1396
    if (hex_version < WINED3DPS_VERSION(2,0)) {
1397
        shader_glsl_sample(arg, arg->dst & WINED3DSP_REGNUM_MASK, dst_str, coord_reg);
1398
    } else {
1399
        shader_glsl_sample(arg, arg->src[1] & WINED3DSP_REGNUM_MASK, dst_str, coord_reg);
1400
    }
1401

1402 1403 1404 1405 1406 1407 1408 1409
}

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;
1410
    DWORD hex_version = This->baseShader.hex_version;
1411 1412 1413 1414 1415 1416 1417 1418

    char tmpStr[100];
    char tmpReg[50];
    char tmpMask[6];
    tmpReg[0] = 0;

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, tmpReg, tmpMask, tmpStr);

1419
    if (hex_version != WINED3DPS_VERSION(1,4)) {
1420
        DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1421
        shader_addline(buffer, "%s = clamp(gl_TexCoord[%u], 0.0, 1.0);\n", tmpReg, reg);
1422
    } else {
1423
        DWORD reg2 = arg->src[0] & WINED3DSP_REGNUM_MASK;
1424
        shader_addline(buffer, "%s = gl_TexCoord[%u]%s;\n", tmpStr, reg2, tmpMask);
1425 1426 1427
   }
}

1428
/** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
1429 1430 1431 1432
 * 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) {

1433
    DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1434 1435 1436 1437 1438 1439 1440
    char src0_str[100], dst_str[100];
    char src0_name[50], dst_name[50];
    char src0_mask[6],  dst_mask[6];

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_name, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);

1441 1442
    shader_addline(arg->buffer, "tmp0.x = dot(vec3(gl_TexCoord[%u]), vec3(%s));\n", dstreg, src0_str);
    shader_addline(arg->buffer, "%s = vec4(texture1D(Psampler%u, tmp0.x))%s;\n", dst_str, dstreg, dst_mask);
1443 1444
}

1445
/** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
1446 1447 1448
 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
void pshader_glsl_texdp3(SHADER_OPCODE_ARG* arg) {

1449
    DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1450 1451 1452 1453 1454 1455 1456
    char src0_str[100], dst_str[100];
    char src0_name[50], dst_name[50];
    char src0_mask[6],  dst_mask[6];

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_name, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);

1457
    shader_addline(arg->buffer, "%s = vec4(dot(vec3(T%u), vec3(%s)))%s;\n",
1458 1459 1460
            dst_str, dstreg, src0_str, dst_mask);
}

1461
/** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
 * Calculate the depth as dst.x / dst.y   */
void pshader_glsl_texdepth(SHADER_OPCODE_ARG* arg) {
    
    char dst_str[100];
    char dst_reg[50];
    char dst_mask[6];
   
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);

    shader_addline(arg->buffer, "gl_FragDepth = %s.x / %s.y;\n", dst_reg, dst_reg);
}

1474
/** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
1475 1476 1477 1478 1479 1480
 * 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) {
    
1481
    DWORD dstreg = arg->dst & WINED3DSP_REGNUM_MASK;
1482 1483 1484 1485 1486 1487 1488
    char src0_str[100], dst_str[100];
    char src0_name[50], dst_name[50];
    char src0_mask[6],  dst_mask[6];

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_name, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);

1489
    shader_addline(arg->buffer, "tmp0.y = dot(vec3(T%u), vec3(%s));\n", dstreg, src0_str);
1490 1491 1492
    shader_addline(arg->buffer, "gl_FragDepth = vec4((tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y)%s;\n", dst_str, dst_name);
}

1493
/** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
1494
 * Calculate the 1st of a 2-row matrix multiplication. */
1495 1496
void pshader_glsl_texm3x2pad(SHADER_OPCODE_ARG* arg) {

1497
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1498 1499 1500 1501 1502 1503
    SHADER_BUFFER* buffer = arg->buffer;
    char src0_str[100];
    char src0_name[50];
    char src0_mask[6];

    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1504
    shader_addline(buffer, "tmp0.x = dot(vec3(T%u), vec3(%s));\n", reg, src0_str);
1505
}
1506

1507
/** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
1508 1509 1510 1511
 * 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;
1512
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1513
    SHADER_BUFFER* buffer = arg->buffer;
1514
    SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1515 1516 1517 1518 1519
    char src0_str[100];
    char src0_name[50];
    char src0_mask[6];

    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1520
    shader_addline(buffer, "tmp0.%c = dot(vec3(T%u), vec3(%s));\n", 'x' + current_state->current_row, reg, src0_str);
1521
    current_state->texcoord_w[current_state->current_row++] = reg;
1522 1523 1524
}

void pshader_glsl_texm3x2tex(SHADER_OPCODE_ARG* arg) {
1525
    char dst_str[8];
1526
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1527 1528 1529 1530 1531 1532
    SHADER_BUFFER* buffer = arg->buffer;
    char src0_str[100];
    char src0_name[50];
    char src0_mask[6];

    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1533
    shader_addline(buffer, "tmp0.y = dot(vec3(T%u), vec3(%s));\n", reg, src0_str);
1534 1535 1536 1537

    /* Sample the texture using the calculated coordinates */
    sprintf(dst_str, "T%u", reg);
    shader_glsl_sample(arg, reg, dst_str, "tmp0");
1538
}
1539

1540
/** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
1541
 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
1542
void pshader_glsl_texm3x3tex(SHADER_OPCODE_ARG* arg) {
1543
    char dst_str[8];
1544 1545 1546
    char src0_str[100];
    char src0_name[50];
    char src0_mask[6];
1547
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1548 1549 1550 1551
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
    SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;

    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
1552
    shader_addline(arg->buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_str);
1553 1554 1555 1556

    /* Sample the texture using the calculated coordinates */
    sprintf(dst_str, "T%u", reg);
    shader_glsl_sample(arg, reg, dst_str, "tmp0");
1557 1558 1559
    current_state->current_row = 0;
}

1560
/** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
1561 1562 1563 1564 1565 1566
 * Perform the 3rd row of a 3x3 matrix multiply */
void pshader_glsl_texm3x3(SHADER_OPCODE_ARG* arg) {

    char src0_str[100];
    char src0_name[50];
    char src0_mask[6];
1567
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1568 1569 1570 1571 1572
    IWineD3DPixelShaderImpl* This = (IWineD3DPixelShaderImpl*) arg->shader;
    SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
    
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
    
1573 1574
    shader_addline(arg->buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_str);
    shader_addline(arg->buffer, "T%u = vec4(tmp0.x, tmp0.y, tmp0.z, 1.0);\n", reg);
1575 1576 1577
    current_state->current_row = 0;
}

1578
/** Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL 
1579 1580 1581 1582
 * 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;
1583
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1584
    char dimensions[5];
1585
    char dst_str[8];
1586 1587 1588 1589
    char src0_str[100], src0_name[50], src0_mask[6];
    char src1_str[100], src1_name[50], src1_mask[6];
    SHADER_BUFFER* buffer = arg->buffer;
    SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1590
    DWORD stype = arg->reg_maps->samplers[reg] & WINED3DSP_TEXTURETYPE_MASK;
1591 1592

    switch (stype) {
1593 1594 1595
        case WINED3DSTT_2D:     strcpy(dimensions, "2D");   break;
        case WINED3DSTT_CUBE:   strcpy(dimensions, "Cube"); break;
        case WINED3DSTT_VOLUME: strcpy(dimensions, "3D");   break;
1596
        default:
1597
            strcpy(dimensions, "");
1598
            FIXME("Unrecognized sampler type: %#x\n", stype);
1599 1600 1601 1602 1603 1604 1605
            break;
    }

    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_name, src1_mask, src1_str);

    /* Perform the last matrix multiply operation */
1606
    shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_str);
1607 1608 1609 1610 1611

    /* Calculate reflection vector */
    shader_addline(buffer, "tmp0.xyz = reflect(-vec3(%s), vec3(tmp0));\n", src1_str);

    /* Sample the texture */
1612 1613
    sprintf(dst_str, "T%u", reg);
    shader_glsl_sample(arg, reg, dst_str, "tmp0");
1614 1615 1616
    current_state->current_row = 0;
}

1617
/** Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL 
1618 1619 1620 1621
 * 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;
1622
    DWORD reg = arg->dst & WINED3DSP_REGNUM_MASK;
1623 1624
    SHADER_BUFFER* buffer = arg->buffer;
    SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
1625
    char dst_str[8];
1626 1627 1628 1629 1630
    char src0_str[100], src0_name[50], src0_mask[6];

    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_name, src0_mask, src0_str);

    /* Perform the last matrix multiply operation */
1631
    shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_str);
1632 1633

    /* Construct the eye-ray vector from w coordinates */
1634 1635 1636
    shader_addline(buffer, "tmp1.x = gl_TexCoord[%u].w;\n", current_state->texcoord_w[0]);
    shader_addline(buffer, "tmp1.y = gl_TexCoord[%u].w;\n", current_state->texcoord_w[1]);
    shader_addline(buffer, "tmp1.z = gl_TexCoord[%u].w;\n", reg);
1637 1638 1639 1640 1641 1642

    /* Calculate reflection vector (Assume normal is normalized): RF = 2*(N.E)*N -E */
    shader_addline(buffer, "tmp0.x = dot(vec3(tmp0), vec3(tmp1));\n");
    shader_addline(buffer, "tmp0 = tmp0.w * tmp0;\n");
    shader_addline(buffer, "tmp0 = (2.0 * tmp0) - tmp1;\n");

1643 1644 1645
    /* Sample the texture using the calculated coordinates */
    sprintf(dst_str, "T%u", reg);
    shader_glsl_sample(arg, reg, dst_str, "tmp0");
1646 1647 1648
    current_state->current_row = 0;
}

1649
/** Process the WINED3DSIO_TEXBEM instruction in GLSL.
1650 1651 1652 1653
 * Apply a fake bump map transform.
 * FIXME: Should apply the BUMPMAPENV matrix.  For now, just sample the texture */
void pshader_glsl_texbem(SHADER_OPCODE_ARG* arg) {

1654 1655
    DWORD reg1 = arg->dst & WINED3DSP_REGNUM_MASK;
    DWORD reg2 = arg->src[0] & WINED3DSP_REGNUM_MASK;
1656 1657

    FIXME("Not applying the BUMPMAPENV matrix for pixel shader instruction texbem.\n");
1658
    shader_addline(arg->buffer, "T%u = texture2D(Psampler%u, gl_TexCoord[%u].xy + T%u.xy);\n",
1659 1660 1661
            reg1, reg1, reg1, reg2);
}

1662
/** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
1663 1664 1665 1666 1667 1668 1669
 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
void pshader_glsl_texreg2ar(SHADER_OPCODE_ARG* arg) {
    
    char tmpLine[255];
    char dst_str[100], src0_str[100];
    char dst_reg[50], src0_reg[50];
    char dst_mask[6], src0_mask[6];
1670
    DWORD src0_regnum = arg->src[0] & WINED3DSP_REGNUM_MASK;
1671 1672 1673 1674 1675

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);

    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1676
    shader_addline(arg->buffer, "%stexture2D(Psampler%u, %s.yz))%s;\n",
1677 1678 1679
            tmpLine, src0_regnum, dst_reg, dst_mask);
}

1680
/** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
1681 1682 1683 1684 1685 1686 1687
 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
void pshader_glsl_texreg2gb(SHADER_OPCODE_ARG* arg) {

    char tmpLine[255];
    char dst_str[100], src0_str[100];
    char dst_reg[50], src0_reg[50];
    char dst_mask[6], src0_mask[6];
1688
    DWORD src0_regnum = arg->src[0] & WINED3DSP_REGNUM_MASK;
1689 1690 1691 1692 1693

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);

    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1694
    shader_addline(arg->buffer, "%stexture2D(Psampler%u, %s.yz))%s;\n",
1695 1696 1697
            tmpLine, src0_regnum, dst_reg, dst_mask);
}

1698
/** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
1699 1700 1701 1702 1703 1704 1705 1706
 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
void pshader_glsl_texreg2rgb(SHADER_OPCODE_ARG* arg) {

    char tmpLine[255];
    char dst_str[100], src0_str[100];
    char dst_reg[50], src0_reg[50];
    char dst_mask[6], src0_mask[6];
    char dimensions[5];
1707
    DWORD src0_regnum = arg->src[0] & WINED3DSP_REGNUM_MASK;
1708
    DWORD stype = arg->reg_maps->samplers[src0_regnum] & WINED3DSP_TEXTURETYPE_MASK;
1709
    switch (stype) {
1710 1711 1712
        case WINED3DSTT_2D:     strcpy(dimensions, "2D");   break;
        case WINED3DSTT_CUBE:   strcpy(dimensions, "Cube"); break;
        case WINED3DSTT_VOLUME: strcpy(dimensions, "3D");   break;
1713
        default:
1714
            strcpy(dimensions, "");
1715
            FIXME("Unrecognized sampler type: %#x\n", stype);
1716 1717 1718 1719 1720 1721 1722
            break;
    }

    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);

    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
1723
    shader_addline(arg->buffer, "%stexture%s(Psampler%u, %s.%s))%s;\n",
1724
            tmpLine, dimensions, src0_regnum, dst_reg, (stype == WINED3DSTT_2D) ? "xy" : "xyz", dst_mask);
1725 1726
}

1727
/** Process the WINED3DSIO_TEXKILL instruction in GLSL.
1728 1729 1730
 * If any of the first 3 components are < 0, discard this pixel */
void pshader_glsl_texkill(SHADER_OPCODE_ARG* arg) {

1731
    char dst_str[100], dst_name[50], dst_mask[6];
1732

1733 1734
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_name, dst_mask, dst_str);
    shader_addline(arg->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_name);
1735 1736
}

1737
/** Process the WINED3DSIO_DP2ADD instruction in GLSL.
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
 * dst = dot2(src0, src1) + src2 */
void pshader_glsl_dp2add(SHADER_OPCODE_ARG* arg) {

    char tmpLine[256];
    char dst_str[100], src0_str[100], src1_str[100], src2_str[100];
    char dst_reg[50], src0_reg[50], src1_reg[50], src2_reg[50];
    char dst_mask[6], src0_mask[6], src1_mask[6], src2_mask[6];
 
    shader_glsl_add_param(arg, arg->dst, 0, FALSE, dst_reg, dst_mask, dst_str);
    shader_glsl_add_param(arg, arg->src[0], arg->src_addr[0], TRUE, src0_reg, src0_mask, src0_str);
    shader_glsl_add_param(arg, arg->src[1], arg->src_addr[1], TRUE, src1_reg, src1_mask, src1_str);
    shader_glsl_add_param(arg, arg->src[2], arg->src_addr[2], TRUE, src2_reg, src2_mask, src2_str);   
    shader_glsl_add_dst(arg->dst, dst_reg, dst_mask, tmpLine);
    shader_addline(arg->buffer, "%sdot(vec2(%s), vec2(%s)) + %s)%s;\n",
                   tmpLine, src0_str, src1_str, src2_str, dst_mask);
}

1755 1756
void pshader_glsl_input_pack(
   SHADER_BUFFER* buffer,
1757
   semantic* semantics_in) {
1758 1759 1760

   unsigned int i;

1761
   for (i = 0; i < MAX_REG_INPUT; i++) {
1762

1763 1764 1765
       DWORD usage_token = semantics_in[i].usage;
       DWORD register_token = semantics_in[i].reg;
       DWORD usage, usage_idx;
1766 1767 1768
       char reg_mask[6];

       /* Uninitialized */
1769
       if (!usage_token) continue;
1770 1771
       usage = (usage_token & WINED3DSP_DCL_USAGE_MASK) >> WINED3DSP_DCL_USAGE_SHIFT;
       usage_idx = (usage_token & WINED3DSP_DCL_USAGEINDEX_MASK) >> WINED3DSP_DCL_USAGEINDEX_SHIFT;
1772
       shader_glsl_get_write_mask(register_token, reg_mask);
1773 1774 1775 1776 1777

       switch(usage) {

           case D3DDECLUSAGE_COLOR:
               if (usage_idx == 0)
1778
                   shader_addline(buffer, "IN%u%s = vec4(gl_Color)%s;\n",
1779
                       i, reg_mask, reg_mask);
1780
               else if (usage_idx == 1)
1781
                   shader_addline(buffer, "IN%u%s = vec4(gl_SecondaryColor)%s;\n",
1782 1783
                       i, reg_mask, reg_mask);
               else
1784
                   shader_addline(buffer, "IN%u%s = vec4(unsupported_color_input)%s;\n",
1785
                       i, reg_mask, reg_mask);
1786 1787
               break;

1788
           case D3DDECLUSAGE_TEXCOORD:
1789
               shader_addline(buffer, "IN%u%s = vec4(gl_TexCoord[%u])%s;\n",
1790
                   i, reg_mask, usage_idx, reg_mask );
1791 1792
               break;

1793
           case D3DDECLUSAGE_FOG:
1794
               shader_addline(buffer, "IN%u%s = vec4(gl_FogFragCoord)%s;\n",
1795
                   i, reg_mask, reg_mask);
1796 1797 1798
               break;

           default:
1799
               shader_addline(buffer, "IN%u%s = vec4(unsupported_input)%s;\n",
1800
                   i, reg_mask, reg_mask);
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
        }
    }
}

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

void vshader_glsl_output_unpack(
   SHADER_BUFFER* buffer,
1811
   semantic* semantics_out) {
1812 1813 1814

   unsigned int i;

1815
   for (i = 0; i < MAX_REG_OUTPUT; i++) {
1816

1817 1818 1819
       DWORD usage_token = semantics_out[i].usage;
       DWORD register_token = semantics_out[i].reg;
       DWORD usage, usage_idx;
1820 1821 1822
       char reg_mask[6];

       /* Uninitialized */
1823
       if (!usage_token) continue;
1824

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

1829
       switch(usage) {
1830

1831 1832
           case D3DDECLUSAGE_COLOR:
               if (usage_idx == 0)
1833
                   shader_addline(buffer, "gl_FrontColor%s = OUT%u%s;\n", reg_mask, i, reg_mask);
1834
               else if (usage_idx == 1)
1835
                   shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT%u%s;\n", reg_mask, i, reg_mask);
1836
               else
1837
                   shader_addline(buffer, "unsupported_color_output%s = OUT%u%s;\n", reg_mask, i, reg_mask);
1838 1839
               break;

1840
           case D3DDECLUSAGE_POSITION:
1841
               shader_addline(buffer, "gl_Position%s = OUT%u%s;\n", reg_mask, i, reg_mask);
1842
               break;
1843 1844
 
           case D3DDECLUSAGE_TEXCOORD:
1845
               shader_addline(buffer, "gl_TexCoord[%u]%s = OUT%u%s;\n",
1846
                   usage_idx, reg_mask, i, reg_mask);
1847 1848 1849
               break;

           case WINED3DSHADERDECLUSAGE_PSIZE:
1850
               shader_addline(buffer, "gl_PointSize = OUT%u.x;\n", i);
1851 1852 1853
               break;

           case WINED3DSHADERDECLUSAGE_FOG:
1854
               shader_addline(buffer, "gl_FogFragCoord%s = OUT%u%s;\n", reg_mask, i, reg_mask);
1855 1856 1857
               break;

           default:
1858
               shader_addline(buffer, "unsupported_output%s = OUT%u%s;\n", reg_mask, i, reg_mask);
1859 1860
       }
    }
1861
}
1862

1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 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 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
/** Attach a GLSL pixel or vertex shader object to the shader program */
static void attach_glsl_shader(IWineD3DDevice *iface, IWineD3DBaseShader* shader) {
    IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
    WineD3D_GL_Info *gl_info = &((IWineD3DImpl *)(This->wineD3D))->gl_info;
    GLhandleARB shaderObj = ((IWineD3DBaseShaderImpl*)shader)->baseShader.prgId;
    if (This->stateBlock->glsl_program && shaderObj != 0) {
        TRACE("Attaching GLSL shader object %u to program %u\n", shaderObj, This->stateBlock->glsl_program->programId);
        GL_EXTCALL(glAttachObjectARB(This->stateBlock->glsl_program->programId, shaderObj));
        checkGLcall("glAttachObjectARB");
    }
}

/** 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
 * the program in the list.  If it creates a program, it will link the given
 * objects, too.
 *
 * We keep the shader programs around on a list because linking
 * shader objects together is an expensive operation.  It's much
 * faster to loop through a list of pre-compiled & linked programs
 * each time that the application sets a new pixel or vertex shader
 * than it is to re-link them together at that time.
 *
 * The list will be deleted in IWineD3DDevice::Release().
 */
static void set_glsl_shader_program(IWineD3DDevice *iface) {
    IWineD3DDeviceImpl *This               = (IWineD3DDeviceImpl *)iface;
    WineD3D_GL_Info *gl_info               = &((IWineD3DImpl *)(This->wineD3D))->gl_info;
    IWineD3DPixelShader  *pshader          = This->stateBlock->pixelShader;
    IWineD3DVertexShader *vshader          = This->stateBlock->vertexShader;
    struct glsl_shader_prog_link *curLink  = NULL;
    struct glsl_shader_prog_link *newLink  = NULL;
    struct list *ptr                       = NULL;
    GLhandleARB programId                  = 0;
    int i;
    char glsl_name[8];

    ptr = list_head( &This->glsl_shader_progs );
    while (ptr) {
        /* At least one program exists - see if it matches our ps/vs combination */
        curLink = LIST_ENTRY( ptr, struct glsl_shader_prog_link, entry );
        if (vshader == curLink->vertexShader && pshader == curLink->pixelShader) {
            /* Existing Program found, use it */
            TRACE("Found existing program (%u) for this vertex/pixel shader combination\n",
                   curLink->programId);
            This->stateBlock->glsl_program = curLink;
            return;
        }
        /* This isn't the entry we need - try the next one */
        ptr = list_next( &This->glsl_shader_progs, ptr );
    }

    /* 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);

    /* Allocate a new link for the list of programs */
    newLink = HeapAlloc(GetProcessHeap(), 0, sizeof(struct glsl_shader_prog_link));
    newLink->programId    = programId;
    This->stateBlock->glsl_program = newLink;

    /* Attach GLSL vshader */
    if (NULL != vshader && This->vs_selected_mode == SHADER_GLSL) {
        int i;
        int max_attribs = 16;   /* TODO: Will this always be the case? It is at the moment... */
        char tmp_name[10];

        TRACE("Attaching vertex shader to GLSL program\n");
        attach_glsl_shader(iface, (IWineD3DBaseShader*)vshader);

        /* 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) {
             snprintf(tmp_name, sizeof(tmp_name), "attrib%i", i);
             GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
        }
        checkGLcall("glBindAttribLocationARB");
        newLink->vertexShader = vshader;
    }

    /* Attach GLSL pshader */
    if (NULL != pshader && This->ps_selected_mode == SHADER_GLSL) {
        TRACE("Attaching pixel shader to GLSL program\n");
        attach_glsl_shader(iface, (IWineD3DBaseShader*)pshader);
        newLink->pixelShader = pshader;
    }

    /* Link the program */
    TRACE("Linking GLSL shader program %u\n", programId);
    GL_EXTCALL(glLinkProgramARB(programId));
    print_glsl_info_log(&GLINFO_LOCATION, programId);
    list_add_head( &This->glsl_shader_progs, &newLink->entry);

    newLink->vuniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(vshader_constantsF));
    for (i = 0; i < GL_LIMITS(vshader_constantsF); ++i) {
        snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
        newLink->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
    }
    newLink->puniformF_locations = HeapAlloc(GetProcessHeap(), 0, sizeof(GLhandleARB) * GL_LIMITS(pshader_constantsF));
    for (i = 0; i < GL_LIMITS(pshader_constantsF); ++i) {
        snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
        newLink->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
    }

    return;
}

1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
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;
    WineD3D_GL_Info *gl_info = &((IWineD3DImpl *)(This->wineD3D))->gl_info;
    GLhandleARB program_id = 0;

    if (useVS || usePS) set_glsl_shader_program(iface);
    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;
    WineD3D_GL_Info *gl_info = &((IWineD3DImpl *)(This->wineD3D))->gl_info;
    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));
}

static void shader_glsl_cleanup(BOOL usePS, BOOL useVS) {
    /* Nothing to do */
}

const shader_backend_t glsl_shader_backend = {
    &shader_glsl_select,
    &shader_glsl_select_depth_blt,
    &shader_glsl_load_constants,
    &shader_glsl_cleanup
};