wined3d: Use register_idx in the ARB shader backend.
[wine] / dlls / wined3d / arb_program_shader.c
1 /*
2  * Pixel and vertex shaders implementation using ARB_vertex_program
3  * and ARB_fragment_program GL extensions.
4  *
5  * Copyright 2002-2003 Jason Edmeades
6  * Copyright 2002-2003 Raphael Junqueira
7  * Copyright 2004 Christian Costa
8  * Copyright 2005 Oliver Stieber
9  * Copyright 2006 Ivan Gyurdiev
10  * Copyright 2006 Jason Green
11  * Copyright 2006 Henri Verbeet
12  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27  */
28
29 #include "config.h"
30
31 #include <math.h>
32 #include <stdio.h>
33
34 #include "wined3d_private.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
37 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d);
40
41 #define GLINFO_LOCATION      (*gl_info)
42
43 /* Internally used shader constants. Applications can use constants 0 to GL_LIMITS(vshader_constantsF) - 1,
44  * so upload them above that
45  */
46 #define ARB_SHADER_PRIVCONST_BASE GL_LIMITS(vshader_constantsF)
47 #define ARB_SHADER_PRIVCONST_POS ARB_SHADER_PRIVCONST_BASE + 0
48
49 /* ARB_program_shader private data */
50 struct shader_arb_priv {
51     GLuint                  current_vprogram_id;
52     GLuint                  current_fprogram_id;
53     GLuint                  depth_blt_vprogram_id;
54     GLuint                  depth_blt_fprogram_id[tex_type_count];
55     BOOL                    use_arbfp_fixed_func;
56     struct hash_table_t     *fragment_shaders;
57 };
58
59 /********************************************************
60  * ARB_[vertex/fragment]_program helper functions follow
61  ********************************************************/
62
63 /** 
64  * Loads floating point constants into the currently set ARB_vertex/fragment_program.
65  * When constant_list == NULL, it will load all the constants.
66  *  
67  * @target_type should be either GL_VERTEX_PROGRAM_ARB (for vertex shaders)
68  *  or GL_FRAGMENT_PROGRAM_ARB (for pixel shaders)
69  */
70 static unsigned int shader_arb_load_constantsF(IWineD3DBaseShaderImpl* This, const WineD3D_GL_Info *gl_info,
71         GLuint target_type, unsigned int max_constants, const float *constants, char *dirty_consts)
72 {
73     DWORD shader_version = This->baseShader.reg_maps.shader_version;
74     local_constant* lconst;
75     DWORD i, j;
76     unsigned int ret;
77
78     if (TRACE_ON(d3d_shader)) {
79         for(i = 0; i < max_constants; i++) {
80             if(!dirty_consts[i]) continue;
81             TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
82                         constants[i * 4 + 0], constants[i * 4 + 1],
83                         constants[i * 4 + 2], constants[i * 4 + 3]);
84         }
85     }
86     /* In 1.X pixel shaders constants are implicitly clamped in the range [-1;1] */
87     if (target_type == GL_FRAGMENT_PROGRAM_ARB && WINED3DSHADER_VERSION_MAJOR(shader_version) == 1)
88     {
89         float lcl_const[4];
90         for(i = 0; i < max_constants; i++) {
91             if(!dirty_consts[i]) continue;
92             dirty_consts[i] = 0;
93
94             j = 4 * i;
95             if(constants[j + 0] > 1.0) lcl_const[0] = 1.0;
96             else if(constants[j + 0] < -1.0) lcl_const[0] = -1.0;
97             else lcl_const[0] = constants[j + 0];
98
99             if(constants[j + 1] > 1.0) lcl_const[1] = 1.0;
100             else if(constants[j + 1] < -1.0) lcl_const[1] = -1.0;
101             else lcl_const[1] = constants[j + 1];
102
103             if(constants[j + 2] > 1.0) lcl_const[2] = 1.0;
104             else if(constants[j + 2] < -1.0) lcl_const[2] = -1.0;
105             else lcl_const[2] = constants[j + 2];
106
107             if(constants[j + 3] > 1.0) lcl_const[3] = 1.0;
108             else if(constants[j + 3] < -1.0) lcl_const[3] = -1.0;
109             else lcl_const[3] = constants[j + 3];
110
111             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, lcl_const));
112         }
113     } else {
114         if(GL_SUPPORT(EXT_GPU_PROGRAM_PARAMETERS)) {
115             /* TODO: Benchmark if we're better of with finding the dirty constants ourselves,
116              * or just reloading *all* constants at once
117              *
118             GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, 0, max_constants, constants));
119              */
120             for(i = 0; i < max_constants; i++) {
121                 if(!dirty_consts[i]) continue;
122
123                 /* Find the next block of dirty constants */
124                 dirty_consts[i] = 0;
125                 j = i;
126                 for(i++; (i < max_constants) && dirty_consts[i]; i++) {
127                     dirty_consts[i] = 0;
128                 }
129
130                 GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, j, i - j, constants + (j * 4)));
131             }
132         } else {
133             for(i = 0; i < max_constants; i++) {
134                 if(dirty_consts[i]) {
135                     dirty_consts[i] = 0;
136                     GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, constants + (i * 4)));
137                 }
138             }
139         }
140     }
141     checkGLcall("glProgramEnvParameter4fvARB()");
142
143     /* Load immediate constants */
144     if(This->baseShader.load_local_constsF) {
145         if (TRACE_ON(d3d_shader)) {
146             LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
147                 GLfloat* values = (GLfloat*)lconst->value;
148                 TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
149                         values[0], values[1], values[2], values[3]);
150             }
151         }
152         /* Immediate constants are clamped for 1.X shaders at loading times */
153         ret = 0;
154         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
155             dirty_consts[lconst->idx] = 1; /* Dirtify so the non-immediate constant overwrites it next time */
156             ret = max(ret, lconst->idx + 1);
157             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, lconst->idx, (GLfloat*)lconst->value));
158         }
159         checkGLcall("glProgramEnvParameter4fvARB()");
160         return ret; /* The loaded immediate constants need reloading for the next shader */
161     } else {
162         return 0; /* No constants are dirty now */
163     }
164 }
165
166 /**
167  * Loads the app-supplied constants into the currently set ARB_[vertex/fragment]_programs.
168  * 
169  * We only support float constants in ARB at the moment, so don't 
170  * worry about the Integers or Booleans
171  */
172 static void shader_arb_load_constants(
173     IWineD3DDevice* device,
174     char usePixelShader,
175     char useVertexShader) {
176    
177     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device; 
178     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
179     const WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
180     unsigned char i;
181
182     if (useVertexShader) {
183         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
184
185         /* Load DirectX 9 float constants for vertex shader */
186         deviceImpl->highest_dirty_vs_const = shader_arb_load_constantsF(
187                 vshader, gl_info, GL_VERTEX_PROGRAM_ARB,
188                 deviceImpl->highest_dirty_vs_const,
189                 stateBlock->vertexShaderConstantF,
190                 deviceImpl->activeContext->vshader_const_dirty);
191
192         /* Upload the position fixup */
193         GL_EXTCALL(glProgramEnvParameter4fvARB(GL_VERTEX_PROGRAM_ARB, ARB_SHADER_PRIVCONST_POS, deviceImpl->posFixup));
194     }
195
196     if (usePixelShader) {
197
198         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
199         IWineD3DPixelShaderImpl *psi = (IWineD3DPixelShaderImpl *) pshader;
200
201         /* Load DirectX 9 float constants for pixel shader */
202         deviceImpl->highest_dirty_ps_const = shader_arb_load_constantsF(
203                 pshader, gl_info, GL_FRAGMENT_PROGRAM_ARB,
204                 deviceImpl->highest_dirty_ps_const,
205                 stateBlock->pixelShaderConstantF,
206                 deviceImpl->activeContext->pshader_const_dirty);
207
208         for(i = 0; i < psi->numbumpenvmatconsts; i++) {
209             /* The state manager takes care that this function is always called if the bump env matrix changes
210              */
211             const float *data = (const float *)&stateBlock->textureState[(int) psi->bumpenvmatconst[i].texunit][WINED3DTSS_BUMPENVMAT00];
212             GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->bumpenvmatconst[i].const_num, data));
213             deviceImpl->activeContext->pshader_const_dirty[psi->bumpenvmatconst[i].const_num] = 1;
214
215             if (psi->luminanceconst[i].const_num != WINED3D_CONST_NUM_UNUSED)
216             {
217                 /* WINED3DTSS_BUMPENVLSCALE and WINED3DTSS_BUMPENVLOFFSET are next to each other.
218                  * point gl to the scale, and load 4 floats. x = scale, y = offset, z and w are junk, we
219                  * don't care about them. The pointers are valid for sure because the stateblock is bigger.
220                  * (they're WINED3DTSS_TEXTURETRANSFORMFLAGS and WINED3DTSS_ADDRESSW, so most likely 0 or NaN
221                  */
222                 const float *scale = (const float *)&stateBlock->textureState[(int) psi->luminanceconst[i].texunit][WINED3DTSS_BUMPENVLSCALE];
223                 GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, psi->luminanceconst[i].const_num, scale));
224                 deviceImpl->activeContext->pshader_const_dirty[psi->luminanceconst[i].const_num] = 1;
225             }
226         }
227     }
228 }
229
230 static void shader_arb_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
231 {
232     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
233
234     /* We don't want shader constant dirtification to be an O(contexts), so just dirtify the active
235      * context. On a context switch the old context will be fully dirtified */
236     memset(This->activeContext->vshader_const_dirty + start, 1,
237             sizeof(*This->activeContext->vshader_const_dirty) * count);
238     This->highest_dirty_vs_const = max(This->highest_dirty_vs_const, start + count + 1);
239 }
240
241 static void shader_arb_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
242 {
243     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
244
245     /* We don't want shader constant dirtification to be an O(contexts), so just dirtify the active
246      * context. On a context switch the old context will be fully dirtified */
247     memset(This->activeContext->pshader_const_dirty + start, 1,
248             sizeof(*This->activeContext->pshader_const_dirty) * count);
249     This->highest_dirty_ps_const = max(This->highest_dirty_ps_const, start + count + 1);
250 }
251
252 /* Generate the variable & register declarations for the ARB_vertex_program output target */
253 static void shader_generate_arb_declarations(IWineD3DBaseShader *iface, const shader_reg_maps *reg_maps,
254         SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info)
255 {
256     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
257     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
258     DWORD i, cur;
259     char pshader = shader_is_pshader_version(reg_maps->shader_version);
260     unsigned max_constantsF = min(This->baseShader.limits.constant_float, 
261             (pshader ? GL_LIMITS(pshader_constantsF) : GL_LIMITS(vshader_constantsF)));
262     UINT extra_constants_needed = 0;
263     const local_constant *lconst;
264
265     /* Temporary Output register */
266     shader_addline(buffer, "TEMP TMP_OUT;\n");
267
268     for(i = 0; i < This->baseShader.limits.temporary; i++) {
269         if (reg_maps->temporary[i])
270             shader_addline(buffer, "TEMP R%u;\n", i);
271     }
272
273     for (i = 0; i < This->baseShader.limits.address; i++) {
274         if (reg_maps->address[i])
275             shader_addline(buffer, "ADDRESS A%d;\n", i);
276     }
277
278     for(i = 0; i < This->baseShader.limits.texcoord; i++) {
279         if (reg_maps->texcoord[i])
280             shader_addline(buffer,"TEMP T%u;\n", i);
281     }
282
283     /* Texture coordinate registers must be pre-loaded */
284     for (i = 0; i < This->baseShader.limits.texcoord; i++) {
285         if (reg_maps->texcoord[i])
286             shader_addline(buffer, "MOV T%u, fragment.texcoord[%u];\n", i, i);
287     }
288
289     for(i = 0; i < (sizeof(reg_maps->bumpmat) / sizeof(reg_maps->bumpmat[0])); i++) {
290         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) This;
291         if(!reg_maps->bumpmat[i]) continue;
292
293         cur = ps->numbumpenvmatconsts;
294         ps->bumpenvmatconst[cur].const_num = -1;
295         ps->bumpenvmatconst[cur].texunit = i;
296         ps->luminanceconst[cur].const_num = -1;
297         ps->luminanceconst[cur].texunit = i;
298
299         /* If the shader does not use all available constants, use the next free constant to load the bump mapping environment matrix from
300          * the stateblock into the shader. If no constant is available don't load, texbem will then just sample the texture without applying
301          * bump mapping.
302          */
303         if(max_constantsF + extra_constants_needed < GL_LIMITS(pshader_constantsF)) {
304             ps->bumpenvmatconst[cur].const_num = max_constantsF + extra_constants_needed;
305             shader_addline(buffer, "PARAM bumpenvmat%d = program.env[%d];\n",
306                            i, ps->bumpenvmatconst[cur].const_num);
307             extra_constants_needed++;
308
309             if(reg_maps->luminanceparams && max_constantsF + extra_constants_needed < GL_LIMITS(pshader_constantsF)) {
310                 ((IWineD3DPixelShaderImpl *)This)->luminanceconst[cur].const_num = max_constantsF + extra_constants_needed;
311                 shader_addline(buffer, "PARAM luminance%d = program.env[%d];\n",
312                                i, ps->luminanceconst[cur].const_num);
313                 extra_constants_needed++;
314             } else if(reg_maps->luminanceparams) {
315                 FIXME("No free constant to load the luminance parameters\n");
316             }
317         } else {
318             FIXME("No free constant found to load environment bump mapping matrix into the shader. texbem instruction will not apply bump mapping\n");
319         }
320
321         ps->numbumpenvmatconsts = cur + 1;
322     }
323
324     if(device->stateBlock->renderState[WINED3DRS_SRGBWRITEENABLE] && pshader) {
325         shader_addline(buffer, "PARAM srgb_mul_low = {%f, %f, %f, 1.0};\n",
326                         srgb_mul_low, srgb_mul_low, srgb_mul_low);
327         shader_addline(buffer, "PARAM srgb_comparison =  {%f, %f, %f, %f};\n",
328                         srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
329         shader_addline(buffer, "PARAM srgb_pow =  {%f, %f, %f, 1.0};\n",
330                        srgb_pow, srgb_pow, srgb_pow);
331         shader_addline(buffer, "PARAM srgb_mul_hi =  {%f, %f, %f, 1.0};\n",
332                        srgb_mul_high, srgb_mul_high, srgb_mul_high);
333         shader_addline(buffer, "PARAM srgb_sub_hi =  {%f, %f, %f, 0.0};\n",
334                        srgb_sub_high, srgb_sub_high, srgb_sub_high);
335     }
336
337     /* Load local constants using the program-local space,
338      * this avoids reloading them each time the shader is used
339      */
340     if(!This->baseShader.load_local_constsF) {
341         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
342             shader_addline(buffer, "PARAM C%u = program.local[%u];\n", lconst->idx,
343                            lconst->idx);
344         }
345     }
346
347     /* we use the array-based constants array if the local constants are marked for loading,
348      * because then we use indirect addressing, or when the local constant list is empty,
349      * because then we don't know if we're using indirect addressing or not. If we're hardcoding
350      * local constants do not declare the loaded constants as an array because ARB compilers usually
351      * do not optimize unused constants away
352      */
353     if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) {
354         /* Need to PARAM the environment parameters (constants) so we can use relative addressing */
355         shader_addline(buffer, "PARAM C[%d] = { program.env[0..%d] };\n",
356                     max_constantsF, max_constantsF - 1);
357     } else {
358         for(i = 0; i < max_constantsF; i++) {
359             if(!shader_constant_is_local(This, i)) {
360                 shader_addline(buffer, "PARAM C%d = program.env[%d];\n",i, i);
361             }
362         }
363     }
364 }
365
366 static const char * const shift_tab[] = {
367     "dummy",     /*  0 (none) */
368     "coefmul.x", /*  1 (x2)   */
369     "coefmul.y", /*  2 (x4)   */
370     "coefmul.z", /*  3 (x8)   */
371     "coefmul.w", /*  4 (x16)  */
372     "dummy",     /*  5 (x32)  */
373     "dummy",     /*  6 (x64)  */
374     "dummy",     /*  7 (x128) */
375     "dummy",     /*  8 (d256) */
376     "dummy",     /*  9 (d128) */
377     "dummy",     /* 10 (d64)  */
378     "dummy",     /* 11 (d32)  */
379     "coefdiv.w", /* 12 (d16)  */
380     "coefdiv.z", /* 13 (d8)   */
381     "coefdiv.y", /* 14 (d4)   */
382     "coefdiv.x"  /* 15 (d2)   */
383 };
384
385 static void shader_arb_get_write_mask(const struct wined3d_shader_instruction *ins,
386         const DWORD param, char *write_mask)
387 {
388     char *ptr = write_mask;
389     char vshader = shader_is_vshader_version(ins->reg_maps->shader_version);
390
391     if(vshader && shader_get_regtype(param) == WINED3DSPR_ADDR) {
392         *ptr++ = '.';
393         *ptr++ = 'x';
394     } else if ((param & WINED3DSP_WRITEMASK_ALL) != WINED3DSP_WRITEMASK_ALL) {
395         *ptr++ = '.';
396         if (param & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
397         if (param & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
398         if (param & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
399         if (param & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
400     }
401
402     *ptr = '\0';
403 }
404
405 static void shader_arb_get_swizzle(const DWORD param, BOOL fixup, char *swizzle_str) {
406     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
407      * but addressed as "rgba". To fix this we need to swap the register's x
408      * and z components. */
409     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
410     char *ptr = swizzle_str;
411
412     /* swizzle bits fields: wwzzyyxx */
413     DWORD swizzle = (param & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
414     DWORD swizzle_x = swizzle & 0x03;
415     DWORD swizzle_y = (swizzle >> 2) & 0x03;
416     DWORD swizzle_z = (swizzle >> 4) & 0x03;
417     DWORD swizzle_w = (swizzle >> 6) & 0x03;
418
419     /* If the swizzle is the default swizzle (ie, "xyzw"), we don't need to
420      * generate a swizzle string. Unless we need to our own swizzling. */
421     if ((WINED3DSP_NOSWIZZLE >> WINED3DSP_SWIZZLE_SHIFT) != swizzle || fixup) {
422         *ptr++ = '.';
423         if (swizzle_x == swizzle_y && swizzle_x == swizzle_z && swizzle_x == swizzle_w) {
424             *ptr++ = swizzle_chars[swizzle_x];
425         } else {
426             *ptr++ = swizzle_chars[swizzle_x];
427             *ptr++ = swizzle_chars[swizzle_y];
428             *ptr++ = swizzle_chars[swizzle_z];
429             *ptr++ = swizzle_chars[swizzle_w];
430         }
431     }
432
433     *ptr = '\0';
434 }
435
436 static void pshader_get_register_name(IWineD3DBaseShader* iface,
437     const DWORD param, char* regstr) {
438
439     DWORD reg = param & WINED3DSP_REGNUM_MASK;
440     DWORD regtype = shader_get_regtype(param);
441     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
442
443     switch (regtype) {
444     case WINED3DSPR_TEMP:
445         sprintf(regstr, "R%u", reg);
446     break;
447     case WINED3DSPR_INPUT:
448         if (reg==0) {
449             strcpy(regstr, "fragment.color.primary");
450         } else {
451             strcpy(regstr, "fragment.color.secondary");
452         }
453     break;
454     case WINED3DSPR_CONST:
455         if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) {
456             sprintf(regstr, "C[%u]", reg);
457         } else {
458             sprintf(regstr, "C%u", reg);
459         }
460     break;
461     case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
462         sprintf(regstr,"T%u", reg);
463     break;
464     case WINED3DSPR_COLOROUT:
465         if (reg == 0)
466             sprintf(regstr, "TMP_COLOR");
467         else {
468             /* TODO: See GL_ARB_draw_buffers */
469             FIXME("Unsupported write to render target %u\n", reg);
470             sprintf(regstr, "unsupported_register");
471         }
472     break;
473     case WINED3DSPR_DEPTHOUT:
474         sprintf(regstr, "result.depth");
475     break;
476     case WINED3DSPR_ATTROUT:
477         sprintf(regstr, "oD[%u]", reg);
478     break;
479     case WINED3DSPR_TEXCRDOUT:
480         sprintf(regstr, "oT[%u]", reg);
481     break;
482     default:
483         FIXME("Unhandled register name Type(%d)\n", regtype);
484         sprintf(regstr, "unrecognized_register");
485     break;
486     }
487 }
488
489 /* TODO: merge with pixel shader */
490 static void vshader_program_add_param(const struct wined3d_shader_instruction *ins,
491         const DWORD param, BOOL is_input, char *hwLine)
492 {
493   IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *)ins->shader;
494
495   /* oPos, oFog and oPts in D3D */
496   static const char * const hwrastout_reg_names[] = { "TMP_OUT", "result.fogcoord", "result.pointsize" };
497
498   DWORD reg = param & WINED3DSP_REGNUM_MASK;
499   DWORD regtype = shader_get_regtype(param);
500   char  tmpReg[255];
501   BOOL is_color = FALSE;
502
503   if ((param & WINED3DSP_SRCMOD_MASK) == WINED3DSPSM_NEG) {
504       strcat(hwLine, " -");
505   } else {
506       strcat(hwLine, " ");
507   }
508
509   switch (regtype) {
510   case WINED3DSPR_TEMP:
511     sprintf(tmpReg, "R%u", reg);
512     strcat(hwLine, tmpReg);
513     break;
514   case WINED3DSPR_INPUT:
515
516     if (This->cur_args->swizzle_map & (1 << reg)) is_color = TRUE;
517
518     sprintf(tmpReg, "vertex.attrib[%u]", reg);
519     strcat(hwLine, tmpReg);
520     break;
521   case WINED3DSPR_CONST:
522       if(param & WINED3DSHADER_ADDRMODE_RELATIVE) {
523           if(reg >= This->rel_offset) {
524               sprintf(tmpReg, "C[A0.x + %u]", reg - This->rel_offset);
525           } else {
526               sprintf(tmpReg, "C[A0.x - %u]", -reg + This->rel_offset);
527           }
528       } else {
529           if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) {
530               sprintf(tmpReg, "C[%u]", reg);
531           } else {
532               sprintf(tmpReg, "C%u", reg);
533           }
534       }
535     strcat(hwLine, tmpReg);
536     break;
537   case WINED3DSPR_ADDR: /*case D3DSPR_TEXTURE:*/
538     sprintf(tmpReg, "A%u", reg);
539     strcat(hwLine, tmpReg);
540     break;
541   case WINED3DSPR_RASTOUT:
542     sprintf(tmpReg, "%s", hwrastout_reg_names[reg]);
543     strcat(hwLine, tmpReg);
544     break;
545   case WINED3DSPR_ATTROUT:
546     if (reg==0) {
547        strcat(hwLine, "result.color.primary");
548     } else {
549        strcat(hwLine, "result.color.secondary");
550     }
551     break;
552   case WINED3DSPR_TEXCRDOUT:
553     sprintf(tmpReg, "result.texcoord[%u]", reg);
554     strcat(hwLine, tmpReg);
555     break;
556   default:
557     FIXME("Unknown reg type %d %d\n", regtype, reg);
558     strcat(hwLine, "unrecognized_register");
559     break;
560   }
561
562   if (!is_input) {
563     char write_mask[6];
564     shader_arb_get_write_mask(ins, param, write_mask);
565     strcat(hwLine, write_mask);
566   } else {
567     char swizzle[6];
568     shader_arb_get_swizzle(param, is_color, swizzle);
569     strcat(hwLine, swizzle);
570   }
571 }
572
573 static const char *shader_arb_get_fixup_swizzle(enum fixup_channel_source channel_source)
574 {
575     switch(channel_source)
576     {
577         case CHANNEL_SOURCE_ZERO: return "0";
578         case CHANNEL_SOURCE_ONE: return "1";
579         case CHANNEL_SOURCE_X: return "x";
580         case CHANNEL_SOURCE_Y: return "y";
581         case CHANNEL_SOURCE_Z: return "z";
582         case CHANNEL_SOURCE_W: return "w";
583         default:
584             FIXME("Unhandled channel source %#x\n", channel_source);
585             return "undefined";
586     }
587 }
588
589 static void gen_color_correction(SHADER_BUFFER *buffer, const char *reg, DWORD dst_mask,
590                                  const char *one, const char *two, struct color_fixup_desc fixup)
591 {
592     DWORD mask;
593
594     if (is_yuv_fixup(fixup))
595     {
596         enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
597         FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
598         return;
599     }
600
601     mask = 0;
602     if (fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
603     if (fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
604     if (fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
605     if (fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
606     mask &= dst_mask;
607
608     if (mask)
609     {
610         shader_addline(buffer, "SWZ %s, %s, %s, %s, %s, %s;\n", reg, reg,
611                 shader_arb_get_fixup_swizzle(fixup.x_source), shader_arb_get_fixup_swizzle(fixup.y_source),
612                 shader_arb_get_fixup_swizzle(fixup.z_source), shader_arb_get_fixup_swizzle(fixup.w_source));
613     }
614
615     mask = 0;
616     if (fixup.x_sign_fixup) mask |= WINED3DSP_WRITEMASK_0;
617     if (fixup.y_sign_fixup) mask |= WINED3DSP_WRITEMASK_1;
618     if (fixup.z_sign_fixup) mask |= WINED3DSP_WRITEMASK_2;
619     if (fixup.w_sign_fixup) mask |= WINED3DSP_WRITEMASK_3;
620     mask &= dst_mask;
621
622     if (mask)
623     {
624         char reg_mask[6];
625         char *ptr = reg_mask;
626
627         if (mask != WINED3DSP_WRITEMASK_ALL)
628         {
629             *ptr++ = '.';
630             if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
631             if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
632             if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
633             if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
634         }
635         *ptr = '\0';
636
637         shader_addline(buffer, "MAD %s%s, %s, %s, -%s;\n", reg, reg_mask, reg, two, one);
638     }
639 }
640
641 static void shader_hw_sample(const struct wined3d_shader_instruction *ins, DWORD sampler_idx,
642         const char *dst_str, const char *coord_reg, BOOL projected, BOOL bias)
643 {
644     SHADER_BUFFER *buffer = ins->buffer;
645     DWORD sampler_type = ins->reg_maps->samplers[sampler_idx] & WINED3DSP_TEXTURETYPE_MASK;
646     const char *tex_type;
647     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->shader;
648     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
649
650     switch(sampler_type) {
651         case WINED3DSTT_1D:
652             tex_type = "1D";
653             break;
654
655         case WINED3DSTT_2D:
656             if(device->stateBlock->textures[sampler_idx] &&
657                IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
658                 tex_type = "RECT";
659             } else {
660                 tex_type = "2D";
661             }
662             break;
663
664         case WINED3DSTT_VOLUME:
665             tex_type = "3D";
666             break;
667
668         case WINED3DSTT_CUBE:
669             tex_type = "CUBE";
670             break;
671
672         default:
673             ERR("Unexpected texture type %d\n", sampler_type);
674             tex_type = "";
675     }
676
677     if (bias) {
678         /* Shouldn't be possible, but let's check for it */
679         if(projected) FIXME("Biased and Projected texture sampling\n");
680         /* TXB takes the 4th component of the source vector automatically, as d3d. Nothing more to do */
681         shader_addline(buffer, "TXB %s, %s, texture[%u], %s;\n", dst_str, coord_reg, sampler_idx, tex_type);
682     } else if (projected) {
683         shader_addline(buffer, "TXP %s, %s, texture[%u], %s;\n", dst_str, coord_reg, sampler_idx, tex_type);
684     } else {
685         shader_addline(buffer, "TEX %s, %s, texture[%u], %s;\n", dst_str, coord_reg, sampler_idx, tex_type);
686     }
687
688     if (shader_is_pshader_version(ins->reg_maps->shader_version))
689     {
690         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *)ins->shader;
691         gen_color_correction(buffer, dst_str, ins->dst[0].token & WINED3DSP_WRITEMASK_ALL,
692                 "one", "coefmul.x", ps->cur_args->color_fixup[sampler_idx]);
693     }
694 }
695
696 static void pshader_gen_input_modifier_line (
697     IWineD3DBaseShader *iface,
698     SHADER_BUFFER* buffer,
699     const DWORD instr,
700     int tmpreg,
701     char *outregstr) {
702
703     /* Generate a line that does the input modifier computation and return the input register to use */
704     char regstr[256];
705     char swzstr[20];
706     int insert_line;
707
708     /* Assume a new line will be added */
709     insert_line = 1;
710
711     /* Get register name */
712     pshader_get_register_name(iface, instr, regstr);
713     shader_arb_get_swizzle(instr, FALSE, swzstr);
714
715     switch (instr & WINED3DSP_SRCMOD_MASK) {
716     case WINED3DSPSM_NONE:
717         sprintf(outregstr, "%s%s", regstr, swzstr);
718         insert_line = 0;
719         break;
720     case WINED3DSPSM_NEG:
721         sprintf(outregstr, "-%s%s", regstr, swzstr);
722         insert_line = 0;
723         break;
724     case WINED3DSPSM_BIAS:
725         shader_addline(buffer, "ADD T%c, %s, -coefdiv.x;\n", 'A' + tmpreg, regstr);
726         break;
727     case WINED3DSPSM_BIASNEG:
728         shader_addline(buffer, "ADD T%c, -%s, coefdiv.x;\n", 'A' + tmpreg, regstr);
729         break;
730     case WINED3DSPSM_SIGN:
731         shader_addline(buffer, "MAD T%c, %s, coefmul.x, -one.x;\n", 'A' + tmpreg, regstr);
732         break;
733     case WINED3DSPSM_SIGNNEG:
734         shader_addline(buffer, "MAD T%c, %s, -coefmul.x, one.x;\n", 'A' + tmpreg, regstr);
735         break;
736     case WINED3DSPSM_COMP:
737         shader_addline(buffer, "SUB T%c, one.x, %s;\n", 'A' + tmpreg, regstr);
738         break;
739     case WINED3DSPSM_X2:
740         shader_addline(buffer, "ADD T%c, %s, %s;\n", 'A' + tmpreg, regstr, regstr);
741         break;
742     case WINED3DSPSM_X2NEG:
743         shader_addline(buffer, "ADD T%c, -%s, -%s;\n", 'A' + tmpreg, regstr, regstr);
744         break;
745     case WINED3DSPSM_DZ:
746         shader_addline(buffer, "RCP T%c, %s.z;\n", 'A' + tmpreg, regstr);
747         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
748         break;
749     case WINED3DSPSM_DW:
750         shader_addline(buffer, "RCP T%c, %s.w;\n", 'A' + tmpreg, regstr);
751         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
752         break;
753     default:
754         sprintf(outregstr, "%s%s", regstr, swzstr);
755         insert_line = 0;
756     }
757
758     /* Return modified or original register, with swizzle */
759     if (insert_line)
760         sprintf(outregstr, "T%c%s", 'A' + tmpreg, swzstr);
761 }
762
763 static inline void pshader_gen_output_modifier_line(SHADER_BUFFER *buffer, int saturate, const char *write_mask,
764         int shift, const char *regstr)
765 {
766     /* Generate a line that does the output modifier computation */
767     shader_addline(buffer, "MUL%s %s%s, %s, %s;\n", saturate ? "_SAT" : "",
768         regstr, write_mask, regstr, shift_tab[shift]);
769 }
770
771 static void pshader_hw_bem(const struct wined3d_shader_instruction *ins)
772 {
773     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->shader;
774     SHADER_BUFFER *buffer = ins->buffer;
775     char dst_name[50];
776     char src_name[2][50];
777     char dst_wmask[20];
778     DWORD sampler_code = ins->dst[0].register_idx;
779     BOOL has_bumpmat = FALSE;
780     int i;
781
782     for(i = 0; i < This->numbumpenvmatconsts; i++) {
783         if (This->bumpenvmatconst[i].const_num != WINED3D_CONST_NUM_UNUSED
784                 && This->bumpenvmatconst[i].texunit == sampler_code)
785         {
786             has_bumpmat = TRUE;
787             break;
788         }
789     }
790
791     pshader_get_register_name(ins->shader, ins->dst[0].token, dst_name);
792     shader_arb_get_write_mask(ins, ins->dst[0].token, dst_wmask);
793     strcat(dst_name, dst_wmask);
794
795     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src_name[0]);
796     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[1], 1, src_name[1]);
797
798     if(has_bumpmat) {
799         /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed */
800         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, x, z, 0, 0;\n", sampler_code);
801         shader_addline(buffer, "DP3 TMP.r, TMP2, %s;\n", src_name[1]);
802         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, y, w, 0, 0;\n", sampler_code);
803         shader_addline(buffer, "DP3 TMP.g, TMP2, %s;\n", src_name[1]);
804
805         shader_addline(buffer, "ADD %s, %s, TMP;\n", dst_name, src_name[0]);
806     } else {
807         shader_addline(buffer, "MOV %s, %s;\n", dst_name, src_name[0]);
808     }
809 }
810
811 static void pshader_hw_cnd(const struct wined3d_shader_instruction *ins)
812 {
813     SHADER_BUFFER *buffer = ins->buffer;
814     char dst_wmask[20];
815     char dst_name[50];
816     char src_name[3][50];
817     BOOL sat = (ins->dst[0].token & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
818     DWORD shift = (ins->dst[0].token & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
819
820     /* FIXME: support output modifiers */
821
822     /* Handle output register */
823     pshader_get_register_name(ins->shader, ins->dst[0].token, dst_name);
824     shader_arb_get_write_mask(ins, ins->dst[0].token, dst_wmask);
825
826     /* Generate input register names (with modifiers) */
827     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src_name[0]);
828     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[1], 1, src_name[1]);
829     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[2], 2, src_name[2]);
830
831     /* The coissue flag changes the semantic of the cnd instruction in <= 1.3 shaders */
832     if (ins->reg_maps->shader_version <= WINED3DPS_VERSION(1, 3) && ins->coissue)
833     {
834         shader_addline(buffer, "MOV%s %s%s, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask, src_name[1]);
835     } else {
836         shader_addline(buffer, "ADD TMP, -%s, coefdiv.x;\n", src_name[0]);
837         shader_addline(buffer, "CMP%s %s%s, TMP, %s, %s;\n",
838                                 sat ? "_SAT" : "", dst_name, dst_wmask, src_name[1], src_name[2]);
839     }
840     if (shift != 0)
841         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
842 }
843
844 static void pshader_hw_cmp(const struct wined3d_shader_instruction *ins)
845 {
846     SHADER_BUFFER *buffer = ins->buffer;
847     char dst_wmask[20];
848     char dst_name[50];
849     char src_name[3][50];
850     DWORD shift = (ins->dst[0].token & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
851     BOOL sat = (ins->dst[0].token & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
852
853     /* FIXME: support output modifiers */
854
855     /* Handle output register */
856     pshader_get_register_name(ins->shader, ins->dst[0].token, dst_name);
857     shader_arb_get_write_mask(ins, ins->dst[0].token, dst_wmask);
858
859     /* Generate input register names (with modifiers) */
860     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src_name[0]);
861     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[1], 1, src_name[1]);
862     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[2], 2, src_name[2]);
863
864     shader_addline(buffer, "CMP%s %s%s, %s, %s, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask,
865                    src_name[0], src_name[2], src_name[1]);
866
867     if (shift != 0)
868         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
869 }
870
871 /** Process the WINED3DSIO_DP2ADD instruction in ARB.
872  * dst = dot2(src0, src1) + src2 */
873 static void pshader_hw_dp2add(const struct wined3d_shader_instruction *ins)
874 {
875     SHADER_BUFFER *buffer = ins->buffer;
876     char dst_wmask[20];
877     char dst_name[50];
878     char src_name[3][50];
879     DWORD shift = (ins->dst[0].token & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
880     BOOL sat = (ins->dst[0].token & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
881
882     pshader_get_register_name(ins->shader, ins->dst[0].token, dst_name);
883     shader_arb_get_write_mask(ins, ins->dst[0].token, dst_wmask);
884
885     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src_name[0]);
886     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[1], 1, src_name[1]);
887     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[2], 2, src_name[2]);
888
889     /* Emulate a DP2 with a DP3 and 0.0 */
890     shader_addline(buffer, "MOV TMP, %s;\n", src_name[0]);
891     shader_addline(buffer, "MOV TMP.z, 0.0;\n");
892     shader_addline(buffer, "DP3 TMP2, TMP, %s;\n", src_name[1]);
893     shader_addline(buffer, "ADD%s %s%s, TMP2, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask, src_name[2]);
894
895     if (shift != 0)
896         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
897 }
898
899 /* Map the opcode 1-to-1 to the GL code */
900 static void shader_hw_map2gl(const struct wined3d_shader_instruction *ins)
901 {
902     SHADER_BUFFER *buffer = ins->buffer;
903     DWORD dst = ins->dst[0].token;
904     const DWORD *src = ins->src;
905     const char *instruction;
906     char arguments[256];
907     unsigned int i;
908
909     switch (ins->handler_idx)
910     {
911         case WINED3DSIH_ABS: instruction = "ABS"; break;
912         case WINED3DSIH_ADD: instruction = "ADD"; break;
913         case WINED3DSIH_CRS: instruction = "XPD"; break;
914         case WINED3DSIH_DP3: instruction = "DP3"; break;
915         case WINED3DSIH_DP4: instruction = "DP4"; break;
916         case WINED3DSIH_DST: instruction = "DST"; break;
917         case WINED3DSIH_EXP: instruction = "EX2"; break;
918         case WINED3DSIH_EXPP: instruction = "EXP"; break;
919         case WINED3DSIH_FRC: instruction = "FRC"; break;
920         case WINED3DSIH_LIT: instruction = "LIT"; break;
921         case WINED3DSIH_LOG: instruction = "LG2"; break;
922         case WINED3DSIH_LOGP: instruction = "LOG"; break;
923         case WINED3DSIH_LRP: instruction = "LRP"; break;
924         case WINED3DSIH_MAD: instruction = "MAD"; break;
925         case WINED3DSIH_MAX: instruction = "MAX"; break;
926         case WINED3DSIH_MIN: instruction = "MIN"; break;
927         case WINED3DSIH_MOV: instruction = "MOV"; break;
928         case WINED3DSIH_MUL: instruction = "MUL"; break;
929         case WINED3DSIH_NOP: instruction = "NOP"; break;
930         case WINED3DSIH_POW: instruction = "POW"; break;
931         case WINED3DSIH_SGE: instruction = "SGE"; break;
932         case WINED3DSIH_SLT: instruction = "SLT"; break;
933         case WINED3DSIH_SUB: instruction = "SUB"; break;
934         default: instruction = "";
935             FIXME("Unhandled opcode %#x\n", ins->handler_idx);
936             break;
937     }
938
939     if (shader_is_pshader_version(ins->reg_maps->shader_version))
940     {
941         /* Output token related */
942         char output_rname[256];
943         char output_wmask[20];
944         char operands[4][100];
945         BOOL saturate = FALSE;
946         BOOL centroid = FALSE;
947         BOOL partialprecision = FALSE;
948         const char *modifier;
949         DWORD shift;
950
951         if (!(ins->dst_count + ins->src_count))
952         {
953             ERR("Opcode \"%#x\" has no parameters\n", ins->handler_idx);
954             return;
955         }
956
957         /* Process modifiers */
958         if (dst & WINED3DSP_DSTMOD_MASK)
959         {
960             DWORD mask = dst & WINED3DSP_DSTMOD_MASK;
961
962             saturate = mask & WINED3DSPDM_SATURATE;
963             centroid = mask & WINED3DSPDM_MSAMPCENTROID;
964             partialprecision = mask & WINED3DSPDM_PARTIALPRECISION;
965             mask &= ~(WINED3DSPDM_MSAMPCENTROID | WINED3DSPDM_PARTIALPRECISION | WINED3DSPDM_SATURATE);
966             if (mask)
967                 FIXME("Unrecognized modifier(%#x)\n", mask >> WINED3DSP_DSTMOD_SHIFT);
968
969             if (centroid)
970                 FIXME("Unhandled modifier(%#x)\n", mask >> WINED3DSP_DSTMOD_SHIFT);
971         }
972         shift = (dst & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
973         modifier = (saturate && !shift) ? "_SAT" : "";
974
975         /* Generate input register names (with modifiers) */
976         for (i = 0; i < ins->src_count; ++i)
977         {
978             pshader_gen_input_modifier_line(ins->shader, buffer, src[i], i, operands[i + 1]);
979         }
980
981         /* Handle output register */
982         pshader_get_register_name(ins->shader, dst, output_rname);
983         strcpy(operands[0], output_rname);
984         shader_arb_get_write_mask(ins, dst, output_wmask);
985         strcat(operands[0], output_wmask);
986
987         arguments[0] = '\0';
988         strcat(arguments, operands[0]);
989         for (i = 0; i < ins->src_count; ++i)
990         {
991             strcat(arguments, ", ");
992             strcat(arguments, operands[i + 1]);
993         }
994         shader_addline(buffer, "%s%s %s;\n", instruction, modifier, arguments);
995
996         /* A shift requires another line. */
997         if (shift) pshader_gen_output_modifier_line(buffer, saturate, output_wmask, shift, output_rname);
998     } else {
999         /* Note that vshader_program_add_param() adds spaces. */
1000
1001         arguments[0] = '\0';
1002         if (ins->dst_count)
1003         {
1004             vshader_program_add_param(ins, dst, FALSE, arguments);
1005             for (i = 0; i < ins->src_count; ++i)
1006             {
1007                 strcat(arguments, ",");
1008                 vshader_program_add_param(ins, src[i], TRUE, arguments);
1009             }
1010         }
1011         shader_addline(buffer, "%s%s;\n", instruction, arguments);
1012     }
1013 }
1014
1015 static void shader_hw_mov(const struct wined3d_shader_instruction *ins)
1016 {
1017     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->shader;
1018
1019     if ((WINED3DSHADER_VERSION_MAJOR(ins->reg_maps->shader_version) == 1
1020             && !shader_is_pshader_version(ins->reg_maps->shader_version)
1021             && shader_get_regtype(ins->dst[0].token) == WINED3DSPR_ADDR)
1022             || ins->handler_idx == WINED3DSIH_MOVA)
1023     {
1024         SHADER_BUFFER *buffer = ins->buffer;
1025         char src0_param[256];
1026
1027         if (ins->handler_idx == WINED3DSIH_MOVA)
1028             FIXME("mova should round\n");
1029
1030         src0_param[0] = '\0';
1031         if (((IWineD3DVertexShaderImpl *)shader)->rel_offset)
1032         {
1033             vshader_program_add_param(ins, ins->src[0], TRUE, src0_param);
1034             shader_addline(buffer, "ADD TMP.x, %s, helper_const.z;\n", src0_param);
1035             shader_addline(buffer, "ARL A0.x, TMP.x;\n");
1036         }
1037         else
1038         {
1039             /* Apple's ARB_vertex_program implementation does not accept an ARL source argument
1040              * with more than one component. Thus replicate the first source argument over all
1041              * 4 components. For example, .xyzw -> .x (or better: .xxxx), .zwxy -> .z, etc)
1042              */
1043             DWORD parm = ins->src[0] & ~(WINED3DVS_SWIZZLE_MASK);
1044             if((ins->src[0] & WINED3DVS_X_W) == WINED3DVS_X_W)
1045                 parm |= WINED3DVS_X_W | WINED3DVS_Y_W | WINED3DVS_Z_W | WINED3DVS_W_W;
1046             else if((ins->src[0] & WINED3DVS_X_Z) == WINED3DVS_X_Z)
1047                 parm |= WINED3DVS_X_Z | WINED3DVS_Y_Z | WINED3DVS_Z_Z | WINED3DVS_W_Z;
1048             else if((ins->src[0] & WINED3DVS_X_Y) == WINED3DVS_X_Y)
1049                 parm |= WINED3DVS_X_Y | WINED3DVS_Y_Y | WINED3DVS_Z_Y | WINED3DVS_W_Y;
1050             else if((ins->src[0] & WINED3DVS_X_X) == WINED3DVS_X_X)
1051                 parm |= WINED3DVS_X_X | WINED3DVS_Y_X | WINED3DVS_Z_X | WINED3DVS_W_X;
1052             vshader_program_add_param(ins, parm, TRUE, src0_param);
1053             shader_addline(buffer, "ARL A0.x, %s;\n", src0_param);
1054         }
1055     }
1056     else
1057     {
1058         shader_hw_map2gl(ins);
1059     }
1060 }
1061
1062 static void pshader_hw_texkill(const struct wined3d_shader_instruction *ins)
1063 {
1064     DWORD shader_version = ins->reg_maps->shader_version;
1065     SHADER_BUFFER *buffer = ins->buffer;
1066     char reg_dest[40];
1067
1068     /* No swizzles are allowed in d3d's texkill. PS 1.x ignores the 4th component as documented,
1069      * but >= 2.0 honors it(undocumented, but tested by the d3d9 testsuit)
1070      */
1071     pshader_get_register_name(ins->shader, ins->dst[0].token, reg_dest);
1072
1073     if (shader_version >= WINED3DPS_VERSION(2,0))
1074     {
1075         /* The arb backend doesn't claim ps 2.0 support, but try to eat what the app feeds to us */
1076         shader_addline(buffer, "KIL %s;\n", reg_dest);
1077     } else {
1078         /* ARB fp doesn't like swizzles on the parameter of the KIL instruction. To mask the 4th component,
1079          * copy the register into our general purpose TMP variable, overwrite .w and pass TMP to KIL
1080          */
1081         shader_addline(buffer, "MOV TMP, %s;\n", reg_dest);
1082         shader_addline(buffer, "MOV TMP.w, one.w;\n");
1083         shader_addline(buffer, "KIL TMP;\n");
1084     }
1085 }
1086
1087 static void pshader_hw_tex(const struct wined3d_shader_instruction *ins)
1088 {
1089     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->shader;
1090     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1091
1092     DWORD dst = ins->dst[0].token;
1093     const DWORD *src = ins->src;
1094     SHADER_BUFFER* buffer = ins->buffer;
1095     DWORD shader_version = ins->reg_maps->shader_version;
1096     BOOL projected = FALSE, bias = FALSE;
1097
1098     char reg_dest[40];
1099     char reg_coord[40];
1100     DWORD reg_dest_code;
1101     DWORD reg_sampler_code;
1102
1103     /* All versions have a destination register */
1104     reg_dest_code = ins->dst[0].register_idx;
1105     pshader_get_register_name(ins->shader, dst, reg_dest);
1106
1107     /* 1.0-1.3: Use destination register as coordinate source.
1108        1.4+: Use provided coordinate source register. */
1109    if (shader_version < WINED3DPS_VERSION(1,4))
1110       strcpy(reg_coord, reg_dest);
1111    else
1112       pshader_gen_input_modifier_line(ins->shader, buffer, src[0], 0, reg_coord);
1113
1114   /* 1.0-1.4: Use destination register number as texture code.
1115      2.0+: Use provided sampler number as texure code. */
1116   if (shader_version < WINED3DPS_VERSION(2,0))
1117      reg_sampler_code = reg_dest_code;
1118   else
1119      reg_sampler_code = src[1] & WINED3DSP_REGNUM_MASK;
1120
1121   /* projection flag:
1122    * 1.1, 1.2, 1.3: Use WINED3DTSS_TEXTURETRANSFORMFLAGS
1123    * 1.4: Use WINED3DSPSM_DZ or WINED3DSPSM_DW on src[0]
1124    * 2.0+: Use WINED3DSI_TEXLD_PROJECT on the opcode
1125    */
1126   if (shader_version < WINED3DPS_VERSION(1,4))
1127   {
1128       DWORD flags = 0;
1129       if(reg_sampler_code < MAX_TEXTURES) {
1130         flags = deviceImpl->stateBlock->textureState[reg_sampler_code][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1131       }
1132       if (flags & WINED3DTTFF_PROJECTED) {
1133           projected = TRUE;
1134       }
1135   }
1136   else if (shader_version < WINED3DPS_VERSION(2,0))
1137   {
1138       DWORD src_mod = ins->src[0] & WINED3DSP_SRCMOD_MASK;
1139       if (src_mod == WINED3DSPSM_DZ) {
1140           projected = TRUE;
1141       } else if(src_mod == WINED3DSPSM_DW) {
1142           projected = TRUE;
1143       }
1144   } else {
1145       if (ins->flags & WINED3DSI_TEXLD_PROJECT) projected = TRUE;
1146       if (ins->flags & WINED3DSI_TEXLD_BIAS) bias = TRUE;
1147   }
1148   shader_hw_sample(ins, reg_sampler_code, reg_dest, reg_coord, projected, bias);
1149 }
1150
1151 static void pshader_hw_texcoord(const struct wined3d_shader_instruction *ins)
1152 {
1153     DWORD dst = ins->dst[0].token;
1154     SHADER_BUFFER *buffer = ins->buffer;
1155
1156     char tmp[20];
1157     shader_arb_get_write_mask(ins, dst, tmp);
1158     if (ins->reg_maps->shader_version != WINED3DPS_VERSION(1,4))
1159     {
1160         DWORD reg = ins->dst[0].register_idx;
1161         shader_addline(buffer, "MOV_SAT T%u%s, fragment.texcoord[%u];\n", reg, tmp, reg);
1162     } else {
1163         DWORD reg1 = ins->dst[0].register_idx;
1164         char reg_src[40];
1165
1166         pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, reg_src);
1167         shader_addline(buffer, "MOV R%u%s, %s;\n", reg1, tmp, reg_src);
1168    }
1169 }
1170
1171 static void pshader_hw_texreg2ar(const struct wined3d_shader_instruction *ins)
1172 {
1173      SHADER_BUFFER *buffer = ins->buffer;
1174      IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->shader;
1175      IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1176      DWORD flags;
1177
1178      DWORD reg1 = ins->dst[0].register_idx;
1179      char dst_str[8];
1180      char src_str[50];
1181
1182      sprintf(dst_str, "T%u", reg1);
1183      pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src_str);
1184      shader_addline(buffer, "MOV TMP.x, %s.w;\n", src_str);
1185      shader_addline(buffer, "MOV TMP.y, %s.x;\n", src_str);
1186      flags = reg1 < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg1][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1187      shader_hw_sample(ins, reg1, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1188 }
1189
1190 static void pshader_hw_texreg2gb(const struct wined3d_shader_instruction *ins)
1191 {
1192      SHADER_BUFFER *buffer = ins->buffer;
1193
1194      DWORD reg1 = ins->dst[0].register_idx;
1195      char dst_str[8];
1196      char src_str[50];
1197
1198      sprintf(dst_str, "T%u", reg1);
1199      pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src_str);
1200      shader_addline(buffer, "MOV TMP.x, %s.y;\n", src_str);
1201      shader_addline(buffer, "MOV TMP.y, %s.z;\n", src_str);
1202      shader_hw_sample(ins, reg1, dst_str, "TMP", FALSE, FALSE);
1203 }
1204
1205 static void pshader_hw_texreg2rgb(const struct wined3d_shader_instruction *ins)
1206 {
1207     SHADER_BUFFER *buffer = ins->buffer;
1208     DWORD reg1 = ins->dst[0].register_idx;
1209     char dst_str[8];
1210     char src_str[50];
1211
1212     sprintf(dst_str, "T%u", reg1);
1213     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src_str);
1214     shader_hw_sample(ins, reg1, dst_str, src_str, FALSE, FALSE);
1215 }
1216
1217 static void pshader_hw_texbem(const struct wined3d_shader_instruction *ins)
1218 {
1219     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->shader;
1220     BOOL has_bumpmat = FALSE;
1221     BOOL has_luminance = FALSE;
1222     int i;
1223
1224     DWORD dst = ins->dst[0].token;
1225     DWORD src = ins->src[0] & WINED3DSP_REGNUM_MASK;
1226     SHADER_BUFFER* buffer = ins->buffer;
1227
1228     char reg_coord[40];
1229     DWORD reg_dest_code;
1230
1231     /* All versions have a destination register */
1232     reg_dest_code = ins->dst[0].register_idx;
1233     /* Can directly use the name because texbem is only valid for <= 1.3 shaders */
1234     pshader_get_register_name(ins->shader, dst, reg_coord);
1235
1236     for(i = 0; i < This->numbumpenvmatconsts; i++) {
1237         if (This->bumpenvmatconst[i].const_num != WINED3D_CONST_NUM_UNUSED
1238                 && reg_dest_code == This->bumpenvmatconst[i].texunit)
1239         {
1240             has_bumpmat = TRUE;
1241             break;
1242         }
1243     }
1244     for(i = 0; i < This->numbumpenvmatconsts; i++) {
1245         if (This->luminanceconst[i].const_num != WINED3D_CONST_NUM_UNUSED
1246                 && reg_dest_code == This->luminanceconst[i].texunit)
1247         {
1248             has_luminance = TRUE;
1249             break;
1250         }
1251     }
1252
1253     if(has_bumpmat) {
1254         /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed */
1255
1256         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, x, z, 0, 0;\n", reg_dest_code);
1257         shader_addline(buffer, "DP3 TMP.x, TMP2, T%u;\n", src);
1258         shader_addline(buffer, "SWZ TMP2, bumpenvmat%d, y, w, 0, 0;\n", reg_dest_code);
1259         shader_addline(buffer, "DP3 TMP.y, TMP2, T%u;\n", src);
1260
1261         /* with projective textures, texbem only divides the static texture coord, not the displacement,
1262          * so we can't let the GL handle this.
1263          */
1264         if (((IWineD3DDeviceImpl*) This->baseShader.device)->stateBlock->textureState[reg_dest_code][WINED3DTSS_TEXTURETRANSFORMFLAGS]
1265               & WINED3DTTFF_PROJECTED) {
1266             shader_addline(buffer, "RCP TMP2.w, %s.w;\n", reg_coord);
1267             shader_addline(buffer, "MUL TMP2.xy, %s, TMP2.w;\n", reg_coord);
1268             shader_addline(buffer, "ADD TMP.xy, TMP, TMP2;\n");
1269         } else {
1270             shader_addline(buffer, "ADD TMP.xy, TMP, %s;\n", reg_coord);
1271         }
1272
1273         shader_hw_sample(ins, reg_dest_code, reg_coord, "TMP", FALSE, FALSE);
1274
1275         if (ins->handler_idx == WINED3DSIH_TEXBEML && has_luminance)
1276         {
1277             shader_addline(buffer, "MAD TMP, T%u.z, luminance%d.x, luminance%d.y;\n",
1278                            src, reg_dest_code, reg_dest_code);
1279             shader_addline(buffer, "MUL %s, %s, TMP;\n", reg_coord, reg_coord);
1280         }
1281
1282     } else {
1283         DWORD tf;
1284         if(reg_dest_code < MAX_TEXTURES) {
1285             tf = ((IWineD3DDeviceImpl*) This->baseShader.device)->stateBlock->textureState[reg_dest_code][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1286         } else {
1287             tf = 0;
1288         }
1289         /* Without a bump matrix loaded, just sample with the unmodified coordinates */
1290         shader_hw_sample(ins, reg_dest_code, reg_coord, reg_coord, tf & WINED3DTTFF_PROJECTED, FALSE);
1291     }
1292 }
1293
1294 static void pshader_hw_texm3x2pad(const struct wined3d_shader_instruction *ins)
1295 {
1296     DWORD reg = ins->dst[0].register_idx;
1297     SHADER_BUFFER *buffer = ins->buffer;
1298     char src0_name[50];
1299
1300     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0_name);
1301     shader_addline(buffer, "DP3 TMP.x, T%u, %s;\n", reg, src0_name);
1302 }
1303
1304 static void pshader_hw_texm3x2tex(const struct wined3d_shader_instruction *ins)
1305 {
1306     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->shader;
1307     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1308     DWORD flags;
1309     DWORD reg = ins->dst[0].register_idx;
1310     SHADER_BUFFER *buffer = ins->buffer;
1311     char dst_str[8];
1312     char src0_name[50];
1313
1314     sprintf(dst_str, "T%u", reg);
1315     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0_name);
1316     shader_addline(buffer, "DP3 TMP.y, T%u, %s;\n", reg, src0_name);
1317     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1318     shader_hw_sample(ins, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1319 }
1320
1321 static void pshader_hw_texm3x3pad(const struct wined3d_shader_instruction *ins)
1322 {
1323     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->shader;
1324     DWORD reg = ins->dst[0].register_idx;
1325     SHADER_BUFFER *buffer = ins->buffer;
1326     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1327     char src0_name[50];
1328
1329     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0_name);
1330     shader_addline(buffer, "DP3 TMP.%c, T%u, %s;\n", 'x' + current_state->current_row, reg, src0_name);
1331     current_state->texcoord_w[current_state->current_row++] = reg;
1332 }
1333
1334 static void pshader_hw_texm3x3tex(const struct wined3d_shader_instruction *ins)
1335 {
1336     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->shader;
1337     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1338     DWORD flags;
1339     DWORD reg = ins->dst[0].register_idx;
1340     SHADER_BUFFER *buffer = ins->buffer;
1341     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1342     char dst_str[8];
1343     char src0_name[50];
1344
1345     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0_name);
1346     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", reg, src0_name);
1347
1348     /* Sample the texture using the calculated coordinates */
1349     sprintf(dst_str, "T%u", reg);
1350     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1351     shader_hw_sample(ins, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1352     current_state->current_row = 0;
1353 }
1354
1355 static void pshader_hw_texm3x3vspec(const struct wined3d_shader_instruction *ins)
1356 {
1357     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->shader;
1358     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1359     DWORD flags;
1360     DWORD reg = ins->dst[0].register_idx;
1361     SHADER_BUFFER *buffer = ins->buffer;
1362     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1363     char dst_str[8];
1364     char src0_name[50];
1365
1366     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0_name);
1367     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", reg, src0_name);
1368
1369     /* Construct the eye-ray vector from w coordinates */
1370     shader_addline(buffer, "MOV TMP2.x, fragment.texcoord[%u].w;\n", current_state->texcoord_w[0]);
1371     shader_addline(buffer, "MOV TMP2.y, fragment.texcoord[%u].w;\n", current_state->texcoord_w[1]);
1372     shader_addline(buffer, "MOV TMP2.z, fragment.texcoord[%u].w;\n", reg);
1373
1374     /* Calculate reflection vector
1375      */
1376     shader_addline(buffer, "DP3 TMP.w, TMP, TMP2;\n");
1377     /* The .w is ignored when sampling, so I can use TMP2.w to calculate dot(N, N) */
1378     shader_addline(buffer, "DP3 TMP2.w, TMP, TMP;\n");
1379     shader_addline(buffer, "RCP TMP2.w, TMP2.w;\n");
1380     shader_addline(buffer, "MUL TMP.w, TMP.w, TMP2.w;\n");
1381     shader_addline(buffer, "MUL TMP, TMP.w, TMP;\n");
1382     shader_addline(buffer, "MAD TMP, coefmul.x, TMP, -TMP2;\n");
1383
1384     /* Sample the texture using the calculated coordinates */
1385     sprintf(dst_str, "T%u", reg);
1386     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1387     shader_hw_sample(ins, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1388     current_state->current_row = 0;
1389 }
1390
1391 static void pshader_hw_texm3x3spec(const struct wined3d_shader_instruction *ins)
1392 {
1393     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->shader;
1394     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1395     DWORD flags;
1396     DWORD reg = ins->dst[0].register_idx;
1397     DWORD reg3 = ins->src[1] & WINED3DSP_REGNUM_MASK;
1398     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1399     SHADER_BUFFER *buffer = ins->buffer;
1400     char dst_str[8];
1401     char src0_name[50];
1402
1403     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0_name);
1404     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", reg, src0_name);
1405
1406     /* Calculate reflection vector.
1407      *
1408      *               dot(N, E)
1409      * TMP.xyz = 2 * --------- * N - E
1410      *               dot(N, N)
1411      *
1412      * Which normalizes the normal vector
1413      */
1414     shader_addline(buffer, "DP3 TMP.w, TMP, C[%u];\n", reg3);
1415     shader_addline(buffer, "DP3 TMP2.w, TMP, TMP;\n");
1416     shader_addline(buffer, "RCP TMP2.w, TMP2.w;\n");
1417     shader_addline(buffer, "MUL TMP.w, TMP.w, TMP2.w;\n");
1418     shader_addline(buffer, "MUL TMP, TMP.w, TMP;\n");
1419     shader_addline(buffer, "MAD TMP, coefmul.x, TMP, -C[%u];\n", reg3);
1420
1421     /* Sample the texture using the calculated coordinates */
1422     sprintf(dst_str, "T%u", reg);
1423     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1424     shader_hw_sample(ins, reg, dst_str, "TMP", flags & WINED3DTTFF_PROJECTED, FALSE);
1425     current_state->current_row = 0;
1426 }
1427
1428 static void pshader_hw_texdepth(const struct wined3d_shader_instruction *ins)
1429 {
1430     SHADER_BUFFER *buffer = ins->buffer;
1431     char dst_name[50];
1432
1433     /* texdepth has an implicit destination, the fragment depth value. It's only parameter,
1434      * which is essentially an input, is the destination register because it is the first
1435      * parameter. According to the msdn, this must be register r5, but let's keep it more flexible
1436      * here
1437      */
1438     pshader_get_register_name(ins->shader, ins->dst[0].token, dst_name);
1439
1440     /* According to the msdn, the source register(must be r5) is unusable after
1441      * the texdepth instruction, so we're free to modify it
1442      */
1443     shader_addline(buffer, "MIN %s.y, %s.y, one.y;\n", dst_name, dst_name);
1444
1445     /* How to deal with the special case dst_name.g == 0? if r != 0, then
1446      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
1447      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
1448      */
1449     shader_addline(buffer, "RCP %s.y, %s.y;\n", dst_name, dst_name);
1450     shader_addline(buffer, "MUL TMP.x, %s.x, %s.y;\n", dst_name, dst_name);
1451     shader_addline(buffer, "MIN TMP.x, TMP.x, one.x;\n");
1452     shader_addline(buffer, "MAX result.depth, TMP.x, 0.0;\n");
1453 }
1454
1455 /** Process the WINED3DSIO_TEXDP3TEX instruction in ARB:
1456  * Take a 3-component dot product of the TexCoord[dstreg] and src,
1457  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
1458 static void pshader_hw_texdp3tex(const struct wined3d_shader_instruction *ins)
1459 {
1460     SHADER_BUFFER *buffer = ins->buffer;
1461     DWORD sampler_idx = ins->dst[0].register_idx;
1462     char src0[50];
1463     char dst_str[8];
1464
1465     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0);
1466     shader_addline(buffer, "MOV TMP, 0.0;\n");
1467     shader_addline(buffer, "DP3 TMP.x, T%u, %s;\n", sampler_idx, src0);
1468
1469     sprintf(dst_str, "T%u", sampler_idx);
1470     shader_hw_sample(ins, sampler_idx, dst_str, "TMP", FALSE /* Only one coord, can't be projected */, FALSE);
1471 }
1472
1473 /** Process the WINED3DSIO_TEXDP3 instruction in ARB:
1474  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
1475 static void pshader_hw_texdp3(const struct wined3d_shader_instruction *ins)
1476 {
1477     char src0[50];
1478     char dst_str[50];
1479     char dst_mask[6];
1480     DWORD dstreg = ins->dst[0].register_idx;
1481     SHADER_BUFFER *buffer = ins->buffer;
1482
1483     /* Handle output register */
1484     pshader_get_register_name(ins->shader, ins->dst[0].token, dst_str);
1485     shader_arb_get_write_mask(ins, ins->dst[0].token, dst_mask);
1486
1487     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0);
1488     shader_addline(buffer, "DP3 %s%s, T%u, %s;\n", dst_str, dst_mask, dstreg, src0);
1489
1490     /* TODO: Handle output modifiers */
1491 }
1492
1493 /** Process the WINED3DSIO_TEXM3X3 instruction in ARB
1494  * Perform the 3rd row of a 3x3 matrix multiply */
1495 static void pshader_hw_texm3x3(const struct wined3d_shader_instruction *ins)
1496 {
1497     SHADER_BUFFER *buffer = ins->buffer;
1498     char dst_str[50];
1499     char dst_mask[6];
1500     char src0[50];
1501     DWORD dst_reg = ins->dst[0].register_idx;
1502
1503     pshader_get_register_name(ins->shader, ins->dst[0].token, dst_str);
1504     shader_arb_get_write_mask(ins, ins->dst[0].token, dst_mask);
1505
1506     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0);
1507     shader_addline(buffer, "DP3 TMP.z, T%u, %s;\n", dst_reg, src0);
1508     shader_addline(buffer, "MOV %s%s, TMP;\n", dst_str, dst_mask);
1509
1510     /* TODO: Handle output modifiers */
1511 }
1512
1513 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in ARB:
1514  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
1515  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
1516  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
1517  */
1518 static void pshader_hw_texm3x2depth(const struct wined3d_shader_instruction *ins)
1519 {
1520     SHADER_BUFFER *buffer = ins->buffer;
1521     DWORD dst_reg = ins->dst[0].register_idx;
1522     char src0[50];
1523
1524     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src0);
1525     shader_addline(buffer, "DP3 TMP.y, T%u, %s;\n", dst_reg, src0);
1526
1527     /* How to deal with the special case dst_name.g == 0? if r != 0, then
1528      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
1529      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
1530      */
1531     shader_addline(buffer, "RCP TMP.y, TMP.y;\n");
1532     shader_addline(buffer, "MUL TMP.x, TMP.x, TMP.y;\n");
1533     shader_addline(buffer, "MIN TMP.x, TMP.x, one.x;\n");
1534     shader_addline(buffer, "MAX result.depth, TMP.x, 0.0;\n");
1535 }
1536
1537 /** Handles transforming all WINED3DSIO_M?x? opcodes for
1538     Vertex/Pixel shaders to ARB_vertex_program codes */
1539 static void shader_hw_mnxn(const struct wined3d_shader_instruction *ins)
1540 {
1541     int i;
1542     int nComponents = 0;
1543     struct wined3d_shader_dst_param tmp_dst = {0};
1544     struct wined3d_shader_instruction tmp_ins;
1545
1546     memset(&tmp_ins, 0, sizeof(tmp_ins));
1547
1548     /* Set constants for the temporary argument */
1549     tmp_ins.shader      = ins->shader;
1550     tmp_ins.buffer      = ins->buffer;
1551     tmp_ins.src[0]      = ins->src[0];
1552     tmp_ins.src_addr[0] = ins->src_addr[0];
1553     tmp_ins.src_addr[1] = ins->src_addr[1];
1554     tmp_ins.reg_maps = ins->reg_maps;
1555     tmp_ins.dst_count = 1;
1556     tmp_ins.dst = &tmp_dst;
1557     tmp_ins.src_count = 2;
1558
1559     switch(ins->handler_idx)
1560     {
1561         case WINED3DSIH_M4x4:
1562             nComponents = 4;
1563             tmp_ins.handler_idx = WINED3DSIH_DP4;
1564             break;
1565         case WINED3DSIH_M4x3:
1566             nComponents = 3;
1567             tmp_ins.handler_idx = WINED3DSIH_DP4;
1568             break;
1569         case WINED3DSIH_M3x4:
1570             nComponents = 4;
1571             tmp_ins.handler_idx = WINED3DSIH_DP3;
1572             break;
1573         case WINED3DSIH_M3x3:
1574             nComponents = 3;
1575             tmp_ins.handler_idx = WINED3DSIH_DP3;
1576             break;
1577         case WINED3DSIH_M3x2:
1578             nComponents = 2;
1579             tmp_ins.handler_idx = WINED3DSIH_DP3;
1580             break;
1581         default:
1582             FIXME("Unhandled opcode %#x\n", ins->handler_idx);
1583             break;
1584     }
1585
1586     for (i = 0; i < nComponents; i++) {
1587         tmp_dst.register_idx = ins->dst[0].register_idx;
1588         tmp_dst.token = ((ins->dst[0].token) & ~WINED3DSP_WRITEMASK_ALL) | (WINED3DSP_WRITEMASK_0 << i);
1589         tmp_ins.src[1] = ins->src[1]+i;
1590         shader_hw_map2gl(&tmp_ins);
1591     }
1592 }
1593
1594 static void vshader_hw_rsq_rcp(const struct wined3d_shader_instruction *ins)
1595 {
1596     SHADER_BUFFER *buffer = ins->buffer;
1597     DWORD dst = ins->dst[0].token;
1598     DWORD src = ins->src[0];
1599     DWORD swizzle = (src & WINED3DSP_SWIZZLE_MASK) >> WINED3DSP_SWIZZLE_SHIFT;
1600     const char *instruction;
1601
1602     char tmpLine[256];
1603
1604     switch(ins->handler_idx)
1605     {
1606         case WINED3DSIH_RSQ: instruction = "RSQ"; break;
1607         case WINED3DSIH_RCP: instruction = "RCP"; break;
1608         default: instruction = "";
1609             FIXME("Unhandled opcode %#x\n", ins->handler_idx);
1610             break;
1611     }
1612
1613     strcpy(tmpLine, instruction);
1614     vshader_program_add_param(ins, dst, FALSE, tmpLine); /* Destination */
1615     strcat(tmpLine, ",");
1616     vshader_program_add_param(ins, src, TRUE, tmpLine);
1617     if ((WINED3DSP_NOSWIZZLE >> WINED3DSP_SWIZZLE_SHIFT) == swizzle) {
1618         /* Dx sdk says .x is used if no swizzle is given, but our test shows that
1619          * .w is used
1620          */
1621         strcat(tmpLine, ".w");
1622     }
1623
1624     shader_addline(buffer, "%s;\n", tmpLine);
1625 }
1626
1627 static void shader_hw_nrm(const struct wined3d_shader_instruction *ins)
1628 {
1629     SHADER_BUFFER *buffer = ins->buffer;
1630     char dst_name[50];
1631     char src_name[50];
1632     char dst_wmask[20];
1633     DWORD shift = (ins->dst[0].token & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1634     BOOL sat = (ins->dst[0].token & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
1635
1636     pshader_get_register_name(ins->shader, ins->dst[0].token, dst_name);
1637     shader_arb_get_write_mask(ins, ins->dst[0].token, dst_wmask);
1638
1639     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src_name);
1640     shader_addline(buffer, "DP3 TMP, %s, %s;\n", src_name, src_name);
1641     shader_addline(buffer, "RSQ TMP, TMP.x;\n");
1642     /* dst.w = src[0].w * 1 / (src.x^2 + src.y^2 + src.z^2)^(1/2) according to msdn*/
1643     shader_addline(buffer, "MUL%s %s%s, %s, TMP;\n", sat ? "_SAT" : "", dst_name, dst_wmask,
1644                    src_name);
1645
1646     if (shift != 0)
1647         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1648 }
1649
1650 static void shader_hw_sincos(const struct wined3d_shader_instruction *ins)
1651 {
1652     /* This instruction exists in ARB, but the d3d instruction takes two extra parameters which
1653      * must contain fixed constants. So we need a separate function to filter those constants and
1654      * can't use map2gl
1655      */
1656     SHADER_BUFFER *buffer = ins->buffer;
1657     char dst_name[50];
1658     char src_name[50];
1659     char dst_wmask[20];
1660     DWORD shift = (ins->dst[0].token & WINED3DSP_DSTSHIFT_MASK) >> WINED3DSP_DSTSHIFT_SHIFT;
1661     BOOL sat = (ins->dst[0].token & WINED3DSP_DSTMOD_MASK) & WINED3DSPDM_SATURATE;
1662
1663     pshader_get_register_name(ins->shader, ins->dst[0].token, dst_name);
1664     shader_arb_get_write_mask(ins, ins->dst[0].token, dst_wmask);
1665
1666     pshader_gen_input_modifier_line(ins->shader, buffer, ins->src[0], 0, src_name);
1667     shader_addline(buffer, "SCS%s %s%s, %s;\n", sat ? "_SAT" : "", dst_name, dst_wmask,
1668                    src_name);
1669
1670     if (shift != 0)
1671         pshader_gen_output_modifier_line(buffer, FALSE, dst_wmask, shift, dst_name);
1672
1673 }
1674
1675 static GLuint create_arb_blt_vertex_program(const WineD3D_GL_Info *gl_info)
1676 {
1677     GLuint program_id = 0;
1678     const char *blt_vprogram =
1679         "!!ARBvp1.0\n"
1680         "PARAM c[1] = { { 1, 0.5 } };\n"
1681         "MOV result.position, vertex.position;\n"
1682         "MOV result.color, c[0].x;\n"
1683         "MOV result.texcoord[0], vertex.texcoord[0];\n"
1684         "END\n";
1685
1686     GL_EXTCALL(glGenProgramsARB(1, &program_id));
1687     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, program_id));
1688     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(blt_vprogram), blt_vprogram));
1689
1690     if (glGetError() == GL_INVALID_OPERATION) {
1691         GLint pos;
1692         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
1693         FIXME("Vertex program error at position %d: %s\n", pos,
1694             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
1695     }
1696
1697     return program_id;
1698 }
1699
1700 static GLuint create_arb_blt_fragment_program(const WineD3D_GL_Info *gl_info, enum tex_types tex_type)
1701 {
1702     GLuint program_id = 0;
1703     static const char * const blt_fprograms[tex_type_count] =
1704     {
1705         /* tex_1d */
1706         NULL,
1707         /* tex_2d */
1708         "!!ARBfp1.0\n"
1709         "TEMP R0;\n"
1710         "TEX R0.x, fragment.texcoord[0], texture[0], 2D;\n"
1711         "MOV result.depth.z, R0.x;\n"
1712         "END\n",
1713         /* tex_3d */
1714         NULL,
1715         /* tex_cube */
1716         "!!ARBfp1.0\n"
1717         "TEMP R0;\n"
1718         "TEX R0.x, fragment.texcoord[0], texture[0], CUBE;\n"
1719         "MOV result.depth.z, R0.x;\n"
1720         "END\n",
1721         /* tex_rect */
1722         "!!ARBfp1.0\n"
1723         "TEMP R0;\n"
1724         "TEX R0.x, fragment.texcoord[0], texture[0], RECT;\n"
1725         "MOV result.depth.z, R0.x;\n"
1726         "END\n",
1727     };
1728
1729     if (!blt_fprograms[tex_type])
1730     {
1731         FIXME("tex_type %#x not supported\n", tex_type);
1732         tex_type = tex_2d;
1733     }
1734
1735     GL_EXTCALL(glGenProgramsARB(1, &program_id));
1736     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, program_id));
1737     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(blt_fprograms[tex_type]), blt_fprograms[tex_type]));
1738
1739     if (glGetError() == GL_INVALID_OPERATION) {
1740         GLint pos;
1741         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
1742         FIXME("Fragment program error at position %d: %s\n", pos,
1743             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
1744     }
1745
1746     return program_id;
1747 }
1748
1749 static void shader_arb_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
1750     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1751     struct shader_arb_priv *priv = This->shader_priv;
1752     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1753
1754     if (useVS) {
1755         struct vs_compile_args compile_args;
1756
1757         TRACE("Using vertex shader\n");
1758         find_vs_compile_args((IWineD3DVertexShaderImpl *) This->stateBlock->vertexShader, This->stateBlock, &compile_args);
1759         priv->current_vprogram_id = find_gl_vshader((IWineD3DVertexShaderImpl *) This->stateBlock->vertexShader, &compile_args);
1760
1761         /* Bind the vertex program */
1762         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
1763         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id);");
1764
1765         /* Enable OpenGL vertex programs */
1766         glEnable(GL_VERTEX_PROGRAM_ARB);
1767         checkGLcall("glEnable(GL_VERTEX_PROGRAM_ARB);");
1768         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
1769     } else if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
1770         priv->current_vprogram_id = 0;
1771         glDisable(GL_VERTEX_PROGRAM_ARB);
1772         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
1773     }
1774
1775     if (usePS) {
1776         struct ps_compile_args compile_args;
1777         TRACE("Using pixel shader\n");
1778         find_ps_compile_args((IWineD3DPixelShaderImpl *) This->stateBlock->pixelShader, This->stateBlock, &compile_args);
1779         priv->current_fprogram_id = find_gl_pshader((IWineD3DPixelShaderImpl *) This->stateBlock->pixelShader,
1780                                                     &compile_args);
1781
1782         /* Bind the fragment program */
1783         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
1784         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id);");
1785
1786         if(!priv->use_arbfp_fixed_func) {
1787             /* Enable OpenGL fragment programs */
1788             glEnable(GL_FRAGMENT_PROGRAM_ARB);
1789             checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB);");
1790         }
1791         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
1792     } else if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM) && !priv->use_arbfp_fixed_func) {
1793         /* Disable only if we're not using arbfp fixed function fragment processing. If this is used,
1794          * keep GL_FRAGMENT_PROGRAM_ARB enabled, and the fixed function pipeline will bind the fixed function
1795          * replacement shader
1796          */
1797         glDisable(GL_FRAGMENT_PROGRAM_ARB);
1798         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
1799         priv->current_fprogram_id = 0;
1800     }
1801 }
1802
1803 static void shader_arb_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
1804     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1805     struct shader_arb_priv *priv = This->shader_priv;
1806     GLuint *blt_fprogram = &priv->depth_blt_fprogram_id[tex_type];
1807     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1808
1809     if (!priv->depth_blt_vprogram_id) priv->depth_blt_vprogram_id = create_arb_blt_vertex_program(gl_info);
1810     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->depth_blt_vprogram_id));
1811     glEnable(GL_VERTEX_PROGRAM_ARB);
1812
1813     if (!*blt_fprogram) *blt_fprogram = create_arb_blt_fragment_program(gl_info, tex_type);
1814     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, *blt_fprogram));
1815     glEnable(GL_FRAGMENT_PROGRAM_ARB);
1816 }
1817
1818 static void shader_arb_deselect_depth_blt(IWineD3DDevice *iface) {
1819     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1820     struct shader_arb_priv *priv = This->shader_priv;
1821     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1822
1823     if (priv->current_vprogram_id) {
1824         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
1825         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vertexShader->prgId);");
1826
1827         glEnable(GL_VERTEX_PROGRAM_ARB);
1828         checkGLcall("glEnable(GL_VERTEX_PROGRAM_ARB);");
1829
1830         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
1831     } else {
1832         glDisable(GL_VERTEX_PROGRAM_ARB);
1833         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
1834     }
1835
1836     if (priv->current_fprogram_id) {
1837         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
1838         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, pixelShader->prgId);");
1839
1840         glEnable(GL_FRAGMENT_PROGRAM_ARB);
1841         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB);");
1842
1843         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
1844     } else {
1845         glDisable(GL_FRAGMENT_PROGRAM_ARB);
1846         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
1847     }
1848 }
1849
1850 static void shader_arb_destroy(IWineD3DBaseShader *iface) {
1851     IWineD3DBaseShaderImpl *baseShader = (IWineD3DBaseShaderImpl *) iface;
1852     const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)baseShader->baseShader.device)->adapter->gl_info;
1853
1854     if (shader_is_pshader_version(baseShader->baseShader.reg_maps.shader_version))
1855     {
1856         IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *) iface;
1857         UINT i;
1858
1859         ENTER_GL();
1860         for(i = 0; i < This->num_gl_shaders; i++) {
1861             GL_EXTCALL(glDeleteProgramsARB(1, &This->gl_shaders[i].prgId));
1862             checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &This->gl_shaders[i].prgId))");
1863         }
1864         LEAVE_GL();
1865         HeapFree(GetProcessHeap(), 0, This->gl_shaders);
1866         This->gl_shaders = NULL;
1867         This->num_gl_shaders = 0;
1868         This->shader_array_size = 0;
1869     } else {
1870         IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *) iface;
1871         UINT i;
1872
1873         ENTER_GL();
1874         for(i = 0; i < This->num_gl_shaders; i++) {
1875             GL_EXTCALL(glDeleteProgramsARB(1, &This->gl_shaders[i].prgId));
1876             checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &This->gl_shaders[i].prgId))");
1877         }
1878         LEAVE_GL();
1879         HeapFree(GetProcessHeap(), 0, This->gl_shaders);
1880         This->gl_shaders = NULL;
1881         This->num_gl_shaders = 0;
1882         This->shader_array_size = 0;
1883     }
1884 }
1885
1886 static HRESULT shader_arb_alloc(IWineD3DDevice *iface) {
1887     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1888     This->shader_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_arb_priv));
1889     return WINED3D_OK;
1890 }
1891
1892 static void shader_arb_free(IWineD3DDevice *iface) {
1893     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1894     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
1895     struct shader_arb_priv *priv = This->shader_priv;
1896     int i;
1897
1898     if(priv->depth_blt_vprogram_id) {
1899         GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_vprogram_id));
1900     }
1901     for (i = 0; i < tex_type_count; ++i) {
1902         if (priv->depth_blt_fprogram_id[i]) {
1903             GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_fprogram_id[i]));
1904         }
1905     }
1906
1907     HeapFree(GetProcessHeap(), 0, This->shader_priv);
1908 }
1909
1910 static BOOL shader_arb_dirty_const(IWineD3DDevice *iface) {
1911     return TRUE;
1912 }
1913
1914 static void arbfp_add_sRGB_correction(SHADER_BUFFER *buffer, const char *fragcolor, const char *tmp1,
1915                                       const char *tmp2, const char *tmp3, const char *tmp4) {
1916     /* Perform sRGB write correction. See GLX_EXT_framebuffer_sRGB */
1917
1918     /* Calculate the > 0.0031308 case */
1919     shader_addline(buffer, "POW %s.x, %s.x, srgb_pow.x;\n", tmp1, fragcolor);
1920     shader_addline(buffer, "POW %s.y, %s.y, srgb_pow.y;\n", tmp1, fragcolor);
1921     shader_addline(buffer, "POW %s.z, %s.z, srgb_pow.z;\n", tmp1, fragcolor);
1922     shader_addline(buffer, "MUL %s, %s, srgb_mul_hi;\n", tmp1, tmp1);
1923     shader_addline(buffer, "SUB %s, %s, srgb_sub_hi;\n", tmp1, tmp1);
1924     /* Calculate the < case */
1925     shader_addline(buffer, "MUL %s, srgb_mul_low, %s;\n", tmp2, fragcolor);
1926     /* Get 1.0 / 0.0 masks for > 0.0031308 and < 0.0031308 */
1927     shader_addline(buffer, "SLT %s, srgb_comparison, %s;\n", tmp3, fragcolor);
1928     shader_addline(buffer, "SGE %s, srgb_comparison, %s;\n", tmp4, fragcolor);
1929     /* Store the components > 0.0031308 in the destination */
1930     shader_addline(buffer, "MUL %s, %s, %s;\n", fragcolor, tmp1, tmp3);
1931     /* Add the components that are < 0.0031308 */
1932     shader_addline(buffer, "MAD result.color.xyz, %s, %s, %s;\n", tmp2, tmp4, fragcolor);
1933     /* [0.0;1.0] clamping. Not needed, this is done implicitly */
1934 }
1935
1936 static GLuint shader_arb_generate_pshader(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer, const struct ps_compile_args *args) {
1937     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
1938     const shader_reg_maps* reg_maps = &This->baseShader.reg_maps;
1939     CONST DWORD *function = This->baseShader.function;
1940     DWORD shader_version = reg_maps->shader_version;
1941     const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
1942     const local_constant *lconst;
1943     GLuint retval;
1944     const char *fragcolor;
1945
1946     /*  Create the hw ARB shader */
1947     shader_addline(buffer, "!!ARBfp1.0\n");
1948
1949     if (shader_version < WINED3DPS_VERSION(3,0)) {
1950         switch(args->fog) {
1951             case FOG_OFF:
1952                 break;
1953             case FOG_LINEAR:
1954                 shader_addline(buffer, "OPTION ARB_fog_linear;\n");
1955                 break;
1956             case FOG_EXP:
1957                 shader_addline(buffer, "OPTION ARB_fog_exp;\n");
1958                 break;
1959             case FOG_EXP2:
1960                 shader_addline(buffer, "OPTION ARB_fog_exp2;\n");
1961                 break;
1962         }
1963     }
1964
1965     shader_addline(buffer, "TEMP TMP;\n");     /* Used in matrix ops */
1966     shader_addline(buffer, "TEMP TMP2;\n");    /* Used in matrix ops */
1967     shader_addline(buffer, "TEMP TA;\n");      /* Used for modifiers */
1968     shader_addline(buffer, "TEMP TB;\n");      /* Used for modifiers */
1969     shader_addline(buffer, "TEMP TC;\n");      /* Used for modifiers */
1970     shader_addline(buffer, "PARAM coefdiv = { 0.5, 0.25, 0.125, 0.0625 };\n");
1971     shader_addline(buffer, "PARAM coefmul = { 2, 4, 8, 16 };\n");
1972     shader_addline(buffer, "PARAM one = { 1.0, 1.0, 1.0, 1.0 };\n");
1973
1974     if (shader_version < WINED3DPS_VERSION(2,0)) {
1975         fragcolor = "R0";
1976     } else {
1977         shader_addline(buffer, "TEMP TMP_COLOR;\n");
1978         fragcolor = "TMP_COLOR";
1979     }
1980
1981     /* Base Declarations */
1982     shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION);
1983
1984     /* Base Shader Body */
1985     shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
1986
1987     if(args->srgb_correction) {
1988         arbfp_add_sRGB_correction(buffer, fragcolor, "TMP", "TMP2", "TA", "TB");
1989     }
1990     shader_addline(buffer, "MOV result.color, %s;\n", fragcolor);
1991     shader_addline(buffer, "END\n");
1992
1993     /* TODO: change to resource.glObjectHandle or something like that */
1994     GL_EXTCALL(glGenProgramsARB(1, &retval));
1995
1996     TRACE("Creating a hw pixel shader, prg=%d\n", retval);
1997     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, retval));
1998
1999     TRACE("Created hw pixel shader, prg=%d\n", retval);
2000     /* Create the program and check for errors */
2001     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
2002                buffer->bsize, buffer->buffer));
2003
2004     if (glGetError() == GL_INVALID_OPERATION) {
2005         GLint errPos;
2006         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
2007         FIXME("HW PixelShader Error at position %d: %s\n",
2008               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2009         retval = 0;
2010     }
2011
2012     /* Load immediate constants */
2013     if(!This->baseShader.load_local_constsF) {
2014         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
2015             const float *value = (const float *)lconst->value;
2016             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, lconst->idx, value));
2017             checkGLcall("glProgramLocalParameter4fvARB");
2018         }
2019     }
2020
2021     return retval;
2022 }
2023
2024 static GLuint shader_arb_generate_vshader(IWineD3DVertexShader *iface, SHADER_BUFFER *buffer, const struct vs_compile_args *args) {
2025     IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *)iface;
2026     const shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
2027     CONST DWORD *function = This->baseShader.function;
2028     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
2029     const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
2030     const local_constant *lconst;
2031     GLuint ret;
2032
2033     /*  Create the hw ARB shader */
2034     shader_addline(buffer, "!!ARBvp1.0\n");
2035     shader_addline(buffer, "PARAM helper_const = { 2.0, -1.0, %d.0, 0.0 };\n", This->rel_offset);
2036
2037     /* Mesa supports only 95 constants */
2038     if (GL_VEND(MESA) || GL_VEND(WINE))
2039         This->baseShader.limits.constant_float =
2040                 min(95, This->baseShader.limits.constant_float);
2041
2042     shader_addline(buffer, "TEMP TMP;\n");
2043
2044     /* Base Declarations */
2045     shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION);
2046
2047     /* We need a constant to fixup the final position */
2048     shader_addline(buffer, "PARAM posFixup = program.env[%d];\n", ARB_SHADER_PRIVCONST_POS);
2049
2050     /* Initialize output parameters. GL_ARB_vertex_program does not require special initialization values
2051      * for output parameters. D3D in theory does not do that either, but some applications depend on a
2052      * proper initialization of the secondary color, and programs using the fixed function pipeline without
2053      * a replacement shader depend on the texcoord.w being set properly.
2054      *
2055      * GL_NV_vertex_program defines that all output values are initialized to {0.0, 0.0, 0.0, 1.0}. This
2056      * assertion is in effect even when using GL_ARB_vertex_program without any NV specific additions. So
2057      * skip this if NV_vertex_program is supported. Otherwise, initialize the secondary color. For the tex-
2058      * coords, we have a flag in the opengl caps. Many cards do not require the texcoord being set, and
2059      * this can eat a number of instructions, so skip it unless this cap is set as well
2060      */
2061     if(!GL_SUPPORT(NV_VERTEX_PROGRAM)) {
2062         shader_addline(buffer, "MOV result.color.secondary, -helper_const.wwwy;\n");
2063
2064         if((GLINFO_LOCATION).set_texcoord_w && !device->frag_pipe->ffp_proj_control) {
2065             int i;
2066             for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
2067                 if(This->baseShader.reg_maps.texcoord_mask[i] != 0 &&
2068                 This->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
2069                     shader_addline(buffer, "MOV result.texcoord[%u].w, -helper_const.y;\n", i);
2070                 }
2071             }
2072         }
2073     }
2074
2075     /* Base Shader Body */
2076     shader_generate_main( (IWineD3DBaseShader*) This, buffer, reg_maps, function);
2077
2078     /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
2079      * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
2080      * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
2081      * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
2082      */
2083     if(args->fog_src == VS_FOG_Z) {
2084         shader_addline(buffer, "MOV result.fogcoord, TMP_OUT.z;\n");
2085     } else if (!reg_maps->fog) {
2086         shader_addline(buffer, "MOV result.fogcoord, 0.0;\n");
2087     }
2088
2089     /* Write the final position.
2090      *
2091      * OpenGL coordinates specify the center of the pixel while d3d coords specify
2092      * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
2093      * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
2094      * contains 1.0 to allow a mad, but arb vs swizzles are too restricted for that.
2095      */
2096     shader_addline(buffer, "MUL TMP, posFixup, TMP_OUT.w;\n");
2097     shader_addline(buffer, "ADD TMP_OUT.x, TMP_OUT.x, TMP.z;\n");
2098     shader_addline(buffer, "MAD TMP_OUT.y, TMP_OUT.y, posFixup.y, TMP.w;\n");
2099
2100     /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
2101      * and the glsl equivalent
2102      */
2103     shader_addline(buffer, "MAD TMP_OUT.z, TMP_OUT.z, helper_const.x, -TMP_OUT.w;\n");
2104
2105     shader_addline(buffer, "MOV result.position, TMP_OUT;\n");
2106
2107     shader_addline(buffer, "END\n");
2108
2109     /* TODO: change to resource.glObjectHandle or something like that */
2110     GL_EXTCALL(glGenProgramsARB(1, &ret));
2111
2112     TRACE("Creating a hw vertex shader, prg=%d\n", ret);
2113     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, ret));
2114
2115     TRACE("Created hw vertex shader, prg=%d\n", ret);
2116     /* Create the program and check for errors */
2117     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
2118                buffer->bsize, buffer->buffer));
2119
2120     if (glGetError() == GL_INVALID_OPERATION) {
2121         GLint errPos;
2122         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
2123         FIXME("HW VertexShader Error at position %d: %s\n",
2124               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2125         ret = -1;
2126     } else {
2127         /* Load immediate constants */
2128         if(!This->baseShader.load_local_constsF) {
2129             LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
2130                 const float *value = (const float *)lconst->value;
2131                 GL_EXTCALL(glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, lconst->idx, value));
2132             }
2133         }
2134     }
2135     return ret;
2136 }
2137
2138 static void shader_arb_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct shader_caps *pCaps)
2139 {
2140     /* We don't have an ARB fixed function pipeline yet, so let the none backend set its caps,
2141      * then overwrite the shader specific ones
2142      */
2143     none_shader_backend.shader_get_caps(devtype, gl_info, pCaps);
2144
2145     if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
2146         pCaps->VertexShaderVersion = WINED3DVS_VERSION(1,1);
2147         TRACE_(d3d_caps)("Hardware vertex shader version 1.1 enabled (ARB_PROGRAM)\n");
2148         pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF);
2149     }
2150
2151     if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
2152         pCaps->PixelShaderVersion    = WINED3DPS_VERSION(1,4);
2153         pCaps->PixelShader1xMaxValue = 8.0;
2154         TRACE_(d3d_caps)("Hardware pixel shader version 1.4 enabled (ARB_PROGRAM)\n");
2155     }
2156 }
2157
2158 static BOOL shader_arb_color_fixup_supported(struct color_fixup_desc fixup)
2159 {
2160     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
2161     {
2162         TRACE("Checking support for color_fixup:\n");
2163         dump_color_fixup_desc(fixup);
2164     }
2165
2166     /* We support everything except YUV conversions. */
2167     if (!is_yuv_fixup(fixup))
2168     {
2169         TRACE("[OK]\n");
2170         return TRUE;
2171     }
2172
2173     TRACE("[FAILED]\n");
2174     return FALSE;
2175 }
2176
2177 static const SHADER_HANDLER shader_arb_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
2178 {
2179     /* WINED3DSIH_ABS           */ shader_hw_map2gl,
2180     /* WINED3DSIH_ADD           */ shader_hw_map2gl,
2181     /* WINED3DSIH_BEM           */ pshader_hw_bem,
2182     /* WINED3DSIH_BREAK         */ NULL,
2183     /* WINED3DSIH_BREAKC        */ NULL,
2184     /* WINED3DSIH_BREAKP        */ NULL,
2185     /* WINED3DSIH_CALL          */ NULL,
2186     /* WINED3DSIH_CALLNZ        */ NULL,
2187     /* WINED3DSIH_CMP           */ pshader_hw_cmp,
2188     /* WINED3DSIH_CND           */ pshader_hw_cnd,
2189     /* WINED3DSIH_CRS           */ shader_hw_map2gl,
2190     /* WINED3DSIH_DCL           */ NULL,
2191     /* WINED3DSIH_DEF           */ NULL,
2192     /* WINED3DSIH_DEFB          */ NULL,
2193     /* WINED3DSIH_DEFI          */ NULL,
2194     /* WINED3DSIH_DP2ADD        */ pshader_hw_dp2add,
2195     /* WINED3DSIH_DP3           */ shader_hw_map2gl,
2196     /* WINED3DSIH_DP4           */ shader_hw_map2gl,
2197     /* WINED3DSIH_DST           */ shader_hw_map2gl,
2198     /* WINED3DSIH_DSX           */ NULL,
2199     /* WINED3DSIH_DSY           */ NULL,
2200     /* WINED3DSIH_ELSE          */ NULL,
2201     /* WINED3DSIH_ENDIF         */ NULL,
2202     /* WINED3DSIH_ENDLOOP       */ NULL,
2203     /* WINED3DSIH_ENDREP        */ NULL,
2204     /* WINED3DSIH_EXP           */ shader_hw_map2gl,
2205     /* WINED3DSIH_EXPP          */ shader_hw_map2gl,
2206     /* WINED3DSIH_FRC           */ shader_hw_map2gl,
2207     /* WINED3DSIH_IF            */ NULL,
2208     /* WINED3DSIH_IFC           */ NULL,
2209     /* WINED3DSIH_LABEL         */ NULL,
2210     /* WINED3DSIH_LIT           */ shader_hw_map2gl,
2211     /* WINED3DSIH_LOG           */ shader_hw_map2gl,
2212     /* WINED3DSIH_LOGP          */ shader_hw_map2gl,
2213     /* WINED3DSIH_LOOP          */ NULL,
2214     /* WINED3DSIH_LRP           */ shader_hw_map2gl,
2215     /* WINED3DSIH_M3x2          */ shader_hw_mnxn,
2216     /* WINED3DSIH_M3x3          */ shader_hw_mnxn,
2217     /* WINED3DSIH_M3x4          */ shader_hw_mnxn,
2218     /* WINED3DSIH_M4x3          */ shader_hw_mnxn,
2219     /* WINED3DSIH_M4x4          */ shader_hw_mnxn,
2220     /* WINED3DSIH_MAD           */ shader_hw_map2gl,
2221     /* WINED3DSIH_MAX           */ shader_hw_map2gl,
2222     /* WINED3DSIH_MIN           */ shader_hw_map2gl,
2223     /* WINED3DSIH_MOV           */ shader_hw_mov,
2224     /* WINED3DSIH_MOVA          */ shader_hw_mov,
2225     /* WINED3DSIH_MUL           */ shader_hw_map2gl,
2226     /* WINED3DSIH_NOP           */ shader_hw_map2gl,
2227     /* WINED3DSIH_NRM           */ shader_hw_nrm,
2228     /* WINED3DSIH_PHASE         */ NULL,
2229     /* WINED3DSIH_POW           */ shader_hw_map2gl,
2230     /* WINED3DSIH_RCP           */ vshader_hw_rsq_rcp,
2231     /* WINED3DSIH_REP           */ NULL,
2232     /* WINED3DSIH_RET           */ NULL,
2233     /* WINED3DSIH_RSQ           */ vshader_hw_rsq_rcp,
2234     /* WINED3DSIH_SETP          */ NULL,
2235     /* WINED3DSIH_SGE           */ shader_hw_map2gl,
2236     /* WINED3DSIH_SGN           */ NULL,
2237     /* WINED3DSIH_SINCOS        */ shader_hw_sincos,
2238     /* WINED3DSIH_SLT           */ shader_hw_map2gl,
2239     /* WINED3DSIH_SUB           */ shader_hw_map2gl,
2240     /* WINED3DSIH_TEX           */ pshader_hw_tex,
2241     /* WINED3DSIH_TEXBEM        */ pshader_hw_texbem,
2242     /* WINED3DSIH_TEXBEML       */ pshader_hw_texbem,
2243     /* WINED3DSIH_TEXCOORD      */ pshader_hw_texcoord,
2244     /* WINED3DSIH_TEXDEPTH      */ pshader_hw_texdepth,
2245     /* WINED3DSIH_TEXDP3        */ pshader_hw_texdp3,
2246     /* WINED3DSIH_TEXDP3TEX     */ pshader_hw_texdp3tex,
2247     /* WINED3DSIH_TEXKILL       */ pshader_hw_texkill,
2248     /* WINED3DSIH_TEXLDD        */ NULL,
2249     /* WINED3DSIH_TEXLDL        */ NULL,
2250     /* WINED3DSIH_TEXM3x2DEPTH  */ pshader_hw_texm3x2depth,
2251     /* WINED3DSIH_TEXM3x2PAD    */ pshader_hw_texm3x2pad,
2252     /* WINED3DSIH_TEXM3x2TEX    */ pshader_hw_texm3x2tex,
2253     /* WINED3DSIH_TEXM3x3       */ pshader_hw_texm3x3,
2254     /* WINED3DSIH_TEXM3x3DIFF   */ NULL,
2255     /* WINED3DSIH_TEXM3x3PAD    */ pshader_hw_texm3x3pad,
2256     /* WINED3DSIH_TEXM3x3SPEC   */ pshader_hw_texm3x3spec,
2257     /* WINED3DSIH_TEXM3x3TEX    */ pshader_hw_texm3x3tex,
2258     /* WINED3DSIH_TEXM3x3VSPEC  */ pshader_hw_texm3x3vspec,
2259     /* WINED3DSIH_TEXREG2AR     */ pshader_hw_texreg2ar,
2260     /* WINED3DSIH_TEXREG2GB     */ pshader_hw_texreg2gb,
2261     /* WINED3DSIH_TEXREG2RGB    */ pshader_hw_texreg2rgb,
2262 };
2263
2264 const shader_backend_t arb_program_shader_backend = {
2265     shader_arb_instruction_handler_table,
2266     shader_arb_select,
2267     shader_arb_select_depth_blt,
2268     shader_arb_deselect_depth_blt,
2269     shader_arb_update_float_vertex_constants,
2270     shader_arb_update_float_pixel_constants,
2271     shader_arb_load_constants,
2272     shader_arb_destroy,
2273     shader_arb_alloc,
2274     shader_arb_free,
2275     shader_arb_dirty_const,
2276     shader_arb_generate_pshader,
2277     shader_arb_generate_vshader,
2278     shader_arb_get_caps,
2279     shader_arb_color_fixup_supported,
2280 };
2281
2282 /* ARB_fragment_program fixed function pipeline replacement definitions */
2283 #define ARB_FFP_CONST_TFACTOR           0
2284 #define ARB_FFP_CONST_SPECULAR_ENABLE   ((ARB_FFP_CONST_TFACTOR) + 1)
2285 #define ARB_FFP_CONST_CONSTANT(i)       ((ARB_FFP_CONST_SPECULAR_ENABLE) + 1 + i)
2286 #define ARB_FFP_CONST_BUMPMAT(i)        ((ARB_FFP_CONST_CONSTANT(7)) + 1 + i)
2287 #define ARB_FFP_CONST_LUMINANCE(i)      ((ARB_FFP_CONST_BUMPMAT(7)) + 1 + i)
2288
2289 struct arbfp_ffp_desc
2290 {
2291     struct ffp_frag_desc parent;
2292     GLuint shader;
2293     unsigned int num_textures_used;
2294 };
2295
2296 static void arbfp_enable(IWineD3DDevice *iface, BOOL enable) {
2297     if(enable) {
2298         glEnable(GL_FRAGMENT_PROGRAM_ARB);
2299         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
2300     } else {
2301         glDisable(GL_FRAGMENT_PROGRAM_ARB);
2302         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
2303     }
2304 }
2305
2306 static HRESULT arbfp_alloc(IWineD3DDevice *iface) {
2307     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
2308     struct shader_arb_priv *priv;
2309     /* Share private data between the shader backend and the pipeline replacement, if both
2310      * are the arb implementation. This is needed to figure out whether ARBfp should be disabled
2311      * if no pixel shader is bound or not
2312      */
2313     if(This->shader_backend == &arb_program_shader_backend) {
2314         This->fragment_priv = This->shader_priv;
2315     } else {
2316         This->fragment_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_arb_priv));
2317         if(!This->fragment_priv) return E_OUTOFMEMORY;
2318     }
2319     priv = This->fragment_priv;
2320     priv->fragment_shaders = hash_table_create(ffp_frag_program_key_hash, ffp_frag_program_key_compare);
2321     priv->use_arbfp_fixed_func = TRUE;
2322     return WINED3D_OK;
2323 }
2324
2325 static void arbfp_free_ffpshader(void *value, void *gli) {
2326     const WineD3D_GL_Info *gl_info = gli;
2327     struct arbfp_ffp_desc *entry_arb = value;
2328
2329     ENTER_GL();
2330     GL_EXTCALL(glDeleteProgramsARB(1, &entry_arb->shader));
2331     checkGLcall("glDeleteProgramsARB(1, &entry_arb->shader)");
2332     HeapFree(GetProcessHeap(), 0, entry_arb);
2333     LEAVE_GL();
2334 }
2335
2336 static void arbfp_free(IWineD3DDevice *iface) {
2337     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
2338     struct shader_arb_priv *priv = This->fragment_priv;
2339
2340     hash_table_destroy(priv->fragment_shaders, arbfp_free_ffpshader, &This->adapter->gl_info);
2341     priv->use_arbfp_fixed_func = FALSE;
2342
2343     if(This->shader_backend != &arb_program_shader_backend) {
2344         HeapFree(GetProcessHeap(), 0, This->fragment_priv);
2345     }
2346 }
2347
2348 static void arbfp_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct fragment_caps *caps)
2349 {
2350     caps->TextureOpCaps =  WINED3DTEXOPCAPS_DISABLE                     |
2351                            WINED3DTEXOPCAPS_SELECTARG1                  |
2352                            WINED3DTEXOPCAPS_SELECTARG2                  |
2353                            WINED3DTEXOPCAPS_MODULATE4X                  |
2354                            WINED3DTEXOPCAPS_MODULATE2X                  |
2355                            WINED3DTEXOPCAPS_MODULATE                    |
2356                            WINED3DTEXOPCAPS_ADDSIGNED2X                 |
2357                            WINED3DTEXOPCAPS_ADDSIGNED                   |
2358                            WINED3DTEXOPCAPS_ADD                         |
2359                            WINED3DTEXOPCAPS_SUBTRACT                    |
2360                            WINED3DTEXOPCAPS_ADDSMOOTH                   |
2361                            WINED3DTEXOPCAPS_BLENDCURRENTALPHA           |
2362                            WINED3DTEXOPCAPS_BLENDFACTORALPHA            |
2363                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHA           |
2364                            WINED3DTEXOPCAPS_BLENDDIFFUSEALPHA           |
2365                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHAPM         |
2366                            WINED3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR      |
2367                            WINED3DTEXOPCAPS_MODULATECOLOR_ADDALPHA      |
2368                            WINED3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA   |
2369                            WINED3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR   |
2370                            WINED3DTEXOPCAPS_DOTPRODUCT3                 |
2371                            WINED3DTEXOPCAPS_MULTIPLYADD                 |
2372                            WINED3DTEXOPCAPS_LERP                        |
2373                            WINED3DTEXOPCAPS_BUMPENVMAP                  |
2374                            WINED3DTEXOPCAPS_BUMPENVMAPLUMINANCE;
2375
2376     /* TODO: Implement WINED3DTEXOPCAPS_PREMODULATE */
2377
2378     caps->MaxTextureBlendStages   = 8;
2379     caps->MaxSimultaneousTextures = min(GL_LIMITS(fragment_samplers), 8);
2380
2381     caps->PrimitiveMiscCaps |= WINED3DPMISCCAPS_TSSARGTEMP;
2382 }
2383 #undef GLINFO_LOCATION
2384
2385 #define GLINFO_LOCATION stateblock->wineD3DDevice->adapter->gl_info
2386 static void state_texfactor_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
2387     float col[4];
2388     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
2389
2390     /* Don't load the parameter if we're using an arbfp pixel shader, otherwise we'll overwrite
2391      * application provided constants
2392      */
2393     if(device->shader_backend == &arb_program_shader_backend) {
2394         if (use_ps(stateblock)) return;
2395
2396         device = stateblock->wineD3DDevice;
2397         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_TFACTOR] = 1;
2398         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_TFACTOR + 1);
2399     }
2400
2401     D3DCOLORTOGLFLOAT4(stateblock->renderState[WINED3DRS_TEXTUREFACTOR], col);
2402     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col));
2403     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col)");
2404
2405 }
2406
2407 static void state_arb_specularenable(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
2408     float col[4];
2409     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
2410
2411     /* Don't load the parameter if we're using an arbfp pixel shader, otherwise we'll overwrite
2412      * application provided constants
2413      */
2414     if(device->shader_backend == &arb_program_shader_backend) {
2415         if (use_ps(stateblock)) return;
2416
2417         device = stateblock->wineD3DDevice;
2418         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_SPECULAR_ENABLE] = 1;
2419         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_SPECULAR_ENABLE + 1);
2420     }
2421
2422     if(stateblock->renderState[WINED3DRS_SPECULARENABLE]) {
2423         /* The specular color has no alpha */
2424         col[0] = 1.0; col[1] = 1.0;
2425         col[2] = 1.0; col[3] = 0.0;
2426     } else {
2427         col[0] = 0.0; col[1] = 0.0;
2428         col[2] = 0.0; col[3] = 0.0;
2429     }
2430     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_SPECULAR_ENABLE, col));
2431     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_SPECULAR_ENABLE, col)");
2432 }
2433
2434 static void set_bumpmat_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
2435     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
2436     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
2437     float mat[2][2];
2438
2439     if (use_ps(stateblock))
2440     {
2441         if(stage != 0 &&
2442            ((IWineD3DPixelShaderImpl *) stateblock->pixelShader)->baseShader.reg_maps.bumpmat[stage]) {
2443             /* The pixel shader has to know the bump env matrix. Do a constants update if it isn't scheduled
2444              * anyway
2445              */
2446             if(!isStateDirty(context, STATE_PIXELSHADERCONSTANT)) {
2447                 device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
2448             }
2449         }
2450
2451         if(device->shader_backend == &arb_program_shader_backend) {
2452             /* Exit now, don't set the bumpmat below, otherwise we may overwrite pixel shader constants */
2453             return;
2454         }
2455     } else if(device->shader_backend == &arb_program_shader_backend) {
2456         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_BUMPMAT(stage)] = 1;
2457         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_BUMPMAT(stage) + 1);
2458     }
2459
2460     mat[0][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT00]);
2461     mat[0][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT01]);
2462     mat[1][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT10]);
2463     mat[1][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT11]);
2464
2465     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0]));
2466     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0])");
2467 }
2468
2469 static void tex_bumpenvlum_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
2470     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
2471     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
2472     float param[4];
2473
2474     if (use_ps(stateblock))
2475     {
2476         if(stage != 0 &&
2477            ((IWineD3DPixelShaderImpl *) stateblock->pixelShader)->baseShader.reg_maps.luminanceparams[stage]) {
2478             /* The pixel shader has to know the luminance offset. Do a constants update if it
2479              * isn't scheduled anyway
2480              */
2481             if(!isStateDirty(context, STATE_PIXELSHADERCONSTANT)) {
2482                 device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
2483             }
2484         }
2485
2486         if(device->shader_backend == &arb_program_shader_backend) {
2487             /* Exit now, don't set the bumpmat below, otherwise we may overwrite pixel shader constants */
2488             return;
2489         }
2490     } else if(device->shader_backend == &arb_program_shader_backend) {
2491         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_LUMINANCE(stage)] = 1;
2492         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_LUMINANCE(stage) + 1);
2493     }
2494
2495     param[0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVLSCALE]);
2496     param[1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET]);
2497     param[2] = 0.0;
2498     param[3] = 0.0;
2499
2500     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_LUMINANCE(stage), param));
2501     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_LUMINANCE(stage), param)");
2502 }
2503
2504 static const char *get_argreg(SHADER_BUFFER *buffer, DWORD argnum, unsigned int stage, DWORD arg) {
2505     const char *ret;
2506
2507     if(arg == ARG_UNUSED) return "unused"; /* This is the marker for unused registers */
2508
2509     switch(arg & WINED3DTA_SELECTMASK) {
2510         case WINED3DTA_DIFFUSE:
2511             ret = "fragment.color.primary"; break;
2512
2513         case WINED3DTA_CURRENT:
2514             if(stage == 0) ret = "fragment.color.primary";
2515             else ret = "ret";
2516             break;
2517
2518         case WINED3DTA_TEXTURE:
2519             switch(stage) {
2520                 case 0: ret = "tex0"; break;
2521                 case 1: ret = "tex1"; break;
2522                 case 2: ret = "tex2"; break;
2523                 case 3: ret = "tex3"; break;
2524                 case 4: ret = "tex4"; break;
2525                 case 5: ret = "tex5"; break;
2526                 case 6: ret = "tex6"; break;
2527                 case 7: ret = "tex7"; break;
2528                 default: ret = "unknown texture";
2529             }
2530             break;
2531
2532         case WINED3DTA_TFACTOR:
2533             ret = "tfactor"; break;
2534
2535         case WINED3DTA_SPECULAR:
2536             ret = "fragment.color.secondary"; break;
2537
2538         case WINED3DTA_TEMP:
2539             ret = "tempreg"; break;
2540
2541         case WINED3DTA_CONSTANT:
2542             FIXME("Implement perstage constants\n");
2543             switch(stage) {
2544                 case 0: ret = "const0"; break;
2545                 case 1: ret = "const1"; break;
2546                 case 2: ret = "const2"; break;
2547                 case 3: ret = "const3"; break;
2548                 case 4: ret = "const4"; break;
2549                 case 5: ret = "const5"; break;
2550                 case 6: ret = "const6"; break;
2551                 case 7: ret = "const7"; break;
2552                 default: ret = "unknown constant";
2553             }
2554             break;
2555
2556         default:
2557             return "unknown";
2558     }
2559
2560     if(arg & WINED3DTA_COMPLEMENT) {
2561         shader_addline(buffer, "SUB arg%u, const.x, %s;\n", argnum, ret);
2562         if(argnum == 0) ret = "arg0";
2563         if(argnum == 1) ret = "arg1";
2564         if(argnum == 2) ret = "arg2";
2565     }
2566     if(arg & WINED3DTA_ALPHAREPLICATE) {
2567         shader_addline(buffer, "MOV arg%u, %s.w;\n", argnum, ret);
2568         if(argnum == 0) ret = "arg0";
2569         if(argnum == 1) ret = "arg1";
2570         if(argnum == 2) ret = "arg2";
2571     }
2572     return ret;
2573 }
2574
2575 static void gen_ffp_instr(SHADER_BUFFER *buffer, unsigned int stage, BOOL color, BOOL alpha,
2576                           DWORD dst, DWORD op, DWORD dw_arg0, DWORD dw_arg1, DWORD dw_arg2) {
2577     const char *dstmask, *dstreg, *arg0, *arg1, *arg2;
2578     unsigned int mul = 1;
2579     BOOL mul_final_dest = FALSE;
2580
2581     if(color && alpha) dstmask = "";
2582     else if(color) dstmask = ".xyz";
2583     else dstmask = ".w";
2584
2585     if(dst == tempreg) dstreg = "tempreg";
2586     else dstreg = "ret";
2587
2588     arg0 = get_argreg(buffer, 0, stage, dw_arg0);
2589     arg1 = get_argreg(buffer, 1, stage, dw_arg1);
2590     arg2 = get_argreg(buffer, 2, stage, dw_arg2);
2591
2592     switch(op) {
2593         case WINED3DTOP_DISABLE:
2594             if(stage == 0) shader_addline(buffer, "MOV %s%s, fragment.color.primary;\n", dstreg, dstmask);
2595             break;
2596
2597         case WINED3DTOP_SELECTARG2:
2598             arg1 = arg2;
2599         case WINED3DTOP_SELECTARG1:
2600             shader_addline(buffer, "MOV %s%s, %s;\n", dstreg, dstmask, arg1);
2601             break;
2602
2603         case WINED3DTOP_MODULATE4X:
2604             mul = 2;
2605         case WINED3DTOP_MODULATE2X:
2606             mul *= 2;
2607             if(strcmp(dstreg, "result.color") == 0) {
2608                 dstreg = "ret";
2609                 mul_final_dest = TRUE;
2610             }
2611         case WINED3DTOP_MODULATE:
2612             shader_addline(buffer, "MUL %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
2613             break;
2614
2615         case WINED3DTOP_ADDSIGNED2X:
2616             mul = 2;
2617             if(strcmp(dstreg, "result.color") == 0) {
2618                 dstreg = "ret";
2619                 mul_final_dest = TRUE;
2620             }
2621         case WINED3DTOP_ADDSIGNED:
2622             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
2623             arg2 = "arg2";
2624         case WINED3DTOP_ADD:
2625             shader_addline(buffer, "ADD_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
2626             break;
2627
2628         case WINED3DTOP_SUBTRACT:
2629             shader_addline(buffer, "SUB_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
2630             break;
2631
2632         case WINED3DTOP_ADDSMOOTH:
2633             shader_addline(buffer, "SUB arg1, const.x, %s;\n", arg1);
2634             shader_addline(buffer, "MAD_SAT %s%s, arg1, %s, %s;\n", dstreg, dstmask, arg2, arg1);
2635             break;
2636
2637         case WINED3DTOP_BLENDCURRENTALPHA:
2638             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_CURRENT);
2639             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2640             break;
2641         case WINED3DTOP_BLENDFACTORALPHA:
2642             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TFACTOR);
2643             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2644             break;
2645         case WINED3DTOP_BLENDTEXTUREALPHA:
2646             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TEXTURE);
2647             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2648             break;
2649         case WINED3DTOP_BLENDDIFFUSEALPHA:
2650             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_DIFFUSE);
2651             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2652             break;
2653
2654         case WINED3DTOP_BLENDTEXTUREALPHAPM:
2655             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TEXTURE);
2656             shader_addline(buffer, "SUB arg0.w, const.x, %s.w;\n", arg0);
2657             shader_addline(buffer, "MAD_SAT %s%s, %s, arg0.w, %s;\n", dstreg, dstmask, arg2, arg1);
2658             break;
2659
2660         /* D3DTOP_PREMODULATE ???? */
2661
2662         case WINED3DTOP_MODULATEINVALPHA_ADDCOLOR:
2663             shader_addline(buffer, "SUB arg0.w, const.x, %s;\n", arg1);
2664             shader_addline(buffer, "MAD_SAT %s%s, arg0.w, %s, %s;\n", dstreg, dstmask, arg2, arg1);
2665             break;
2666         case WINED3DTOP_MODULATEALPHA_ADDCOLOR:
2667             shader_addline(buffer, "MAD_SAT %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg1);
2668             break;
2669         case WINED3DTOP_MODULATEINVCOLOR_ADDALPHA:
2670             shader_addline(buffer, "SUB arg0, const.x, %s;\n", arg1);
2671             shader_addline(buffer, "MAD_SAT %s%s, arg0, %s, %s.w;\n", dstreg, dstmask, arg2, arg1);
2672             break;
2673         case WINED3DTOP_MODULATECOLOR_ADDALPHA:
2674             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s.w;\n", dstreg, dstmask, arg1, arg2, arg1);
2675             break;
2676
2677         case WINED3DTOP_DOTPRODUCT3:
2678             mul = 4;
2679             if(strcmp(dstreg, "result.color") == 0) {
2680                 dstreg = "ret";
2681                 mul_final_dest = TRUE;
2682             }
2683             shader_addline(buffer, "SUB arg1, %s, const.w;\n", arg1);
2684             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
2685             shader_addline(buffer, "DP3_SAT %s%s, arg1, arg2;\n", dstreg, dstmask);
2686             break;
2687
2688         case WINED3DTOP_MULTIPLYADD:
2689             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg0);
2690             break;
2691
2692         case WINED3DTOP_LERP:
2693             /* The msdn is not quite right here */
2694             shader_addline(buffer, "LRP %s%s, %s, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
2695             break;
2696
2697         case WINED3DTOP_BUMPENVMAP:
2698         case WINED3DTOP_BUMPENVMAPLUMINANCE:
2699             /* Those are handled in the first pass of the shader(generation pass 1 and 2) already */
2700             break;
2701
2702         default:
2703             FIXME("Unhandled texture op %08x\n", op);
2704     }
2705
2706     if(mul == 2) {
2707         shader_addline(buffer, "MUL_SAT %s%s, %s, const.y;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
2708     } else if(mul == 4) {
2709         shader_addline(buffer, "MUL_SAT %s%s, %s, const.z;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
2710     }
2711 }
2712
2713 /* The stateblock is passed for GLINFO_LOCATION */
2714 static GLuint gen_arbfp_ffp_shader(const struct ffp_frag_settings *settings, IWineD3DStateBlockImpl *stateblock)
2715 {
2716     unsigned int stage;
2717     SHADER_BUFFER buffer;
2718     BOOL tex_read[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
2719     BOOL bump_used[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
2720     BOOL luminance_used[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
2721     const char *textype;
2722     const char *instr, *sat;
2723     char colorcor_dst[8];
2724     GLuint ret;
2725     DWORD arg0, arg1, arg2;
2726     BOOL tempreg_used = FALSE, tfactor_used = FALSE;
2727     BOOL op_equal;
2728     const char *final_combiner_src = "ret";
2729
2730     /* Find out which textures are read */
2731     for(stage = 0; stage < MAX_TEXTURES; stage++) {
2732         if(settings->op[stage].cop == WINED3DTOP_DISABLE) break;
2733         arg0 = settings->op[stage].carg0 & WINED3DTA_SELECTMASK;
2734         arg1 = settings->op[stage].carg1 & WINED3DTA_SELECTMASK;
2735         arg2 = settings->op[stage].carg2 & WINED3DTA_SELECTMASK;
2736         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2737         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2738         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2739
2740         if(settings->op[stage].cop == WINED3DTOP_BLENDTEXTUREALPHA) tex_read[stage] = TRUE;
2741         if(settings->op[stage].cop == WINED3DTOP_BLENDTEXTUREALPHAPM) tex_read[stage] = TRUE;
2742         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP) {
2743             bump_used[stage] = TRUE;
2744             tex_read[stage] = TRUE;
2745         }
2746         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
2747             bump_used[stage] = TRUE;
2748             tex_read[stage] = TRUE;
2749             luminance_used[stage] = TRUE;
2750         } else if(settings->op[stage].cop == WINED3DTOP_BLENDFACTORALPHA) {
2751             tfactor_used = TRUE;
2752         }
2753
2754         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
2755             tfactor_used = TRUE;
2756         }
2757
2758         if(settings->op[stage].dst == tempreg) tempreg_used = TRUE;
2759         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
2760             tempreg_used = TRUE;
2761         }
2762
2763         if(settings->op[stage].aop == WINED3DTOP_DISABLE) continue;
2764         arg0 = settings->op[stage].aarg0 & WINED3DTA_SELECTMASK;
2765         arg1 = settings->op[stage].aarg1 & WINED3DTA_SELECTMASK;
2766         arg2 = settings->op[stage].aarg2 & WINED3DTA_SELECTMASK;
2767         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2768         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2769         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
2770
2771         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
2772             tempreg_used = TRUE;
2773         }
2774         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
2775             tfactor_used = TRUE;
2776         }
2777     }
2778
2779     /* Shader header */
2780     shader_buffer_init(&buffer);
2781
2782     shader_addline(&buffer, "!!ARBfp1.0\n");
2783
2784     switch(settings->fog) {
2785         case FOG_OFF:                                                         break;
2786         case FOG_LINEAR: shader_addline(&buffer, "OPTION ARB_fog_linear;\n"); break;
2787         case FOG_EXP:    shader_addline(&buffer, "OPTION ARB_fog_exp;\n");    break;
2788         case FOG_EXP2:   shader_addline(&buffer, "OPTION ARB_fog_exp2;\n");   break;
2789         default: FIXME("Unexpected fog setting %d\n", settings->fog);
2790     }
2791
2792     shader_addline(&buffer, "PARAM const = {1, 2, 4, 0.5};\n");
2793     shader_addline(&buffer, "TEMP TMP;\n");
2794     shader_addline(&buffer, "TEMP ret;\n");
2795     if(tempreg_used || settings->sRGB_write) shader_addline(&buffer, "TEMP tempreg;\n");
2796     shader_addline(&buffer, "TEMP arg0;\n");
2797     shader_addline(&buffer, "TEMP arg1;\n");
2798     shader_addline(&buffer, "TEMP arg2;\n");
2799     for(stage = 0; stage < MAX_TEXTURES; stage++) {
2800         if(!tex_read[stage]) continue;
2801         shader_addline(&buffer, "TEMP tex%u;\n", stage);
2802         if(!bump_used[stage]) continue;
2803         shader_addline(&buffer, "PARAM bumpmat%u = program.env[%u];\n", stage, ARB_FFP_CONST_BUMPMAT(stage));
2804         if(!luminance_used[stage]) continue;
2805         shader_addline(&buffer, "PARAM luminance%u = program.env[%u];\n", stage, ARB_FFP_CONST_LUMINANCE(stage));
2806     }
2807     if(tfactor_used) {
2808         shader_addline(&buffer, "PARAM tfactor = program.env[%u];\n", ARB_FFP_CONST_TFACTOR);
2809     }
2810         shader_addline(&buffer, "PARAM specular_enable = program.env[%u];\n", ARB_FFP_CONST_SPECULAR_ENABLE);
2811
2812     if(settings->sRGB_write) {
2813         shader_addline(&buffer, "PARAM srgb_mul_low = {%f, %f, %f, 1.0};\n",
2814                        srgb_mul_low, srgb_mul_low, srgb_mul_low);
2815         shader_addline(&buffer, "PARAM srgb_comparison =  {%f, %f, %f, %f};\n",
2816                        srgb_cmp, srgb_cmp, srgb_cmp, srgb_cmp);
2817         shader_addline(&buffer, "PARAM srgb_pow =  {%f, %f, %f, 1.0};\n",
2818                        srgb_pow, srgb_pow, srgb_pow);
2819         shader_addline(&buffer, "PARAM srgb_mul_hi =  {%f, %f, %f, 1.0};\n",
2820                        srgb_mul_high, srgb_mul_high, srgb_mul_high);
2821         shader_addline(&buffer, "PARAM srgb_sub_hi =  {%f, %f, %f, 0.0};\n",
2822                        srgb_sub_high, srgb_sub_high, srgb_sub_high);
2823     }
2824
2825     /* Generate texture sampling instructions) */
2826     for(stage = 0; stage < MAX_TEXTURES && settings->op[stage].cop != WINED3DTOP_DISABLE; stage++) {
2827         if(!tex_read[stage]) continue;
2828
2829         switch(settings->op[stage].tex_type) {
2830             case tex_1d:                    textype = "1D";     break;
2831             case tex_2d:                    textype = "2D";     break;
2832             case tex_3d:                    textype = "3D";     break;
2833             case tex_cube:                  textype = "CUBE";   break;
2834             case tex_rect:                  textype = "RECT";   break;
2835             default: textype = "unexpected_textype";   break;
2836         }
2837
2838         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP ||
2839            settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
2840             sat = "";
2841         } else {
2842             sat = "_SAT";
2843         }
2844
2845         if(settings->op[stage].projected == proj_none) {
2846             instr = "TEX";
2847         } else if(settings->op[stage].projected == proj_count4 ||
2848                   settings->op[stage].projected == proj_count3) {
2849             instr = "TXP";
2850         } else {
2851             FIXME("Unexpected projection mode %d\n", settings->op[stage].projected);
2852             instr = "TXP";
2853         }
2854
2855         if(stage > 0 &&
2856            (settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAP ||
2857             settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAPLUMINANCE)) {
2858             shader_addline(&buffer, "SWZ arg1, bumpmat%u, x, z, 0, 0;\n", stage - 1);
2859             shader_addline(&buffer, "DP3 ret.x, arg1, tex%u;\n", stage - 1);
2860             shader_addline(&buffer, "SWZ arg1, bumpmat%u, y, w, 0, 0;\n", stage - 1);
2861             shader_addline(&buffer, "DP3 ret.y, arg1, tex%u;\n", stage - 1);
2862
2863             /* with projective textures, texbem only divides the static texture coord, not the displacement,
2864              * so multiply the displacement with the dividing parameter before passing it to TXP
2865              */
2866             if (settings->op[stage].projected != proj_none) {
2867                 if(settings->op[stage].projected == proj_count4) {
2868                     shader_addline(&buffer, "MOV ret.w, fragment.texcoord[%u].w;\n", stage);
2869                     shader_addline(&buffer, "MUL ret.xyz, ret, fragment.texcoord[%u].w, fragment.texcoord[%u];\n", stage, stage);
2870                 } else {
2871                     shader_addline(&buffer, "MOV ret.w, fragment.texcoord[%u].z;\n", stage);
2872                     shader_addline(&buffer, "MAD ret.xyz, ret, fragment.texcoord[%u].z, fragment.texcoord[%u];\n", stage, stage);
2873                 }
2874             } else {
2875                 shader_addline(&buffer, "ADD ret, ret, fragment.texcoord[%u];\n", stage);
2876             }
2877
2878             shader_addline(&buffer, "%s%s tex%u, ret, texture[%u], %s;\n",
2879                            instr, sat, stage, stage, textype);
2880             if(settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
2881                 shader_addline(&buffer, "MAD_SAT ret.x, tex%u.z, luminance%u.x, luminance%u.y;\n",
2882                                stage - 1, stage - 1, stage - 1);
2883                 shader_addline(&buffer, "MUL tex%u, tex%u, ret.x;\n", stage, stage);
2884             }
2885         } else if(settings->op[stage].projected == proj_count3) {
2886             shader_addline(&buffer, "MOV ret, fragment.texcoord[%u];\n", stage);
2887             shader_addline(&buffer, "MOV ret.w, ret.z;\n");
2888             shader_addline(&buffer, "%s%s tex%u, ret, texture[%u], %s;\n",
2889                             instr, sat, stage, stage, textype);
2890         } else {
2891             shader_addline(&buffer, "%s%s tex%u, fragment.texcoord[%u], texture[%u], %s;\n",
2892                             instr, sat, stage, stage, stage, textype);
2893         }
2894
2895         sprintf(colorcor_dst, "tex%u", stage);
2896         gen_color_correction(&buffer, colorcor_dst, WINED3DSP_WRITEMASK_ALL, "const.x", "const.y",
2897                 settings->op[stage].color_fixup);
2898     }
2899
2900     /* Generate the main shader */
2901     for(stage = 0; stage < MAX_TEXTURES; stage++) {
2902         if(settings->op[stage].cop == WINED3DTOP_DISABLE) {
2903             if(stage == 0) {
2904                 final_combiner_src = "fragment.color.primary";
2905             }
2906             break;
2907         }
2908
2909         if(settings->op[stage].cop == WINED3DTOP_SELECTARG1 &&
2910            settings->op[stage].aop == WINED3DTOP_SELECTARG1) {
2911             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg1;
2912         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG1 &&
2913                   settings->op[stage].aop == WINED3DTOP_SELECTARG2) {
2914             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg2;
2915         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG2 &&
2916                   settings->op[stage].aop == WINED3DTOP_SELECTARG1) {
2917             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg1;
2918         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG2 &&
2919                   settings->op[stage].aop == WINED3DTOP_SELECTARG2) {
2920             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg2;
2921         } else {
2922             op_equal = settings->op[stage].aop   == settings->op[stage].cop &&
2923                        settings->op[stage].carg0 == settings->op[stage].aarg0 &&
2924                        settings->op[stage].carg1 == settings->op[stage].aarg1 &&
2925                        settings->op[stage].carg2 == settings->op[stage].aarg2;
2926         }
2927
2928         if(settings->op[stage].aop == WINED3DTOP_DISABLE) {
2929             gen_ffp_instr(&buffer, stage, TRUE, FALSE, settings->op[stage].dst,
2930                           settings->op[stage].cop, settings->op[stage].carg0,
2931                           settings->op[stage].carg1, settings->op[stage].carg2);
2932             if(stage == 0) {
2933                 shader_addline(&buffer, "MOV ret.w, fragment.color.primary.w;\n");
2934             }
2935         } else if(op_equal) {
2936             gen_ffp_instr(&buffer, stage, TRUE, TRUE, settings->op[stage].dst,
2937                           settings->op[stage].cop, settings->op[stage].carg0,
2938                           settings->op[stage].carg1, settings->op[stage].carg2);
2939         } else {
2940             gen_ffp_instr(&buffer, stage, TRUE, FALSE, settings->op[stage].dst,
2941                           settings->op[stage].cop, settings->op[stage].carg0,
2942                           settings->op[stage].carg1, settings->op[stage].carg2);
2943             gen_ffp_instr(&buffer, stage, FALSE, TRUE, settings->op[stage].dst,
2944                           settings->op[stage].aop, settings->op[stage].aarg0,
2945                           settings->op[stage].aarg1, settings->op[stage].aarg2);
2946         }
2947     }
2948
2949     if(settings->sRGB_write) {
2950         shader_addline(&buffer, "MAD ret, fragment.color.secondary, specular_enable, %s;\n", final_combiner_src);
2951         arbfp_add_sRGB_correction(&buffer, "ret", "arg0", "arg1", "arg2", "tempreg");
2952         shader_addline(&buffer, "MOV result.color.w, ret.w;\n");
2953     } else {
2954         shader_addline(&buffer, "MAD result.color, fragment.color.secondary, specular_enable, %s;\n", final_combiner_src);
2955     }
2956
2957     /* Footer */
2958     shader_addline(&buffer, "END\n");
2959
2960     /* Generate the shader */
2961     GL_EXTCALL(glGenProgramsARB(1, &ret));
2962     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret));
2963     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(buffer.buffer), buffer.buffer));
2964
2965     if (glGetError() == GL_INVALID_OPERATION) {
2966         GLint pos;
2967         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
2968         FIXME("Fragment program error at position %d: %s\n", pos,
2969               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2970     }
2971     shader_buffer_free(&buffer);
2972     return ret;
2973 }
2974
2975 static void fragment_prog_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
2976     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
2977     struct shader_arb_priv *priv = device->fragment_priv;
2978     BOOL use_pshader = use_ps(stateblock);
2979     BOOL use_vshader = use_vs(stateblock);
2980     struct ffp_frag_settings settings;
2981     const struct arbfp_ffp_desc *desc;
2982     unsigned int i;
2983
2984     TRACE("state %#x, stateblock %p, context %p\n", state, stateblock, context);
2985
2986     if(isStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE))) {
2987         if(!use_pshader && device->shader_backend == &arb_program_shader_backend && context->last_was_pshader) {
2988             /* Reload fixed function constants since they collide with the pixel shader constants */
2989             for(i = 0; i < MAX_TEXTURES; i++) {
2990                 set_bumpmat_arbfp(STATE_TEXTURESTAGE(i, WINED3DTSS_BUMPENVMAT00), stateblock, context);
2991             }
2992             state_texfactor_arbfp(STATE_RENDER(WINED3DRS_TEXTUREFACTOR), stateblock, context);
2993             state_arb_specularenable(STATE_RENDER(WINED3DRS_SPECULARENABLE), stateblock, context);
2994         } else if(use_pshader && !isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
2995             device->shader_backend->shader_select((IWineD3DDevice *)stateblock->wineD3DDevice, use_pshader, use_vshader);
2996         }
2997         return;
2998     }
2999
3000     if(!use_pshader) {
3001         /* Find or create a shader implementing the fixed function pipeline settings, then activate it */
3002         gen_ffp_frag_op(stateblock, &settings, FALSE);
3003         desc = (const struct arbfp_ffp_desc *)find_ffp_frag_shader(priv->fragment_shaders, &settings);
3004         if(!desc) {
3005             struct arbfp_ffp_desc *new_desc = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_desc));
3006             if (!new_desc)
3007             {
3008                 ERR("Out of memory\n");
3009                 return;
3010             }
3011             new_desc->num_textures_used = 0;
3012             for(i = 0; i < GL_LIMITS(texture_stages); i++) {
3013                 if(settings.op[i].cop == WINED3DTOP_DISABLE) break;
3014                 new_desc->num_textures_used = i;
3015             }
3016
3017             memcpy(&new_desc->parent.settings, &settings, sizeof(settings));
3018             new_desc->shader = gen_arbfp_ffp_shader(&settings, stateblock);
3019             add_ffp_frag_shader(priv->fragment_shaders, &new_desc->parent);
3020             TRACE("Allocated fixed function replacement shader descriptor %p\n", new_desc);
3021             desc = new_desc;
3022         }
3023
3024         /* Now activate the replacement program. GL_FRAGMENT_PROGRAM_ARB is already active(however, note the
3025          * comment above the shader_select call below). If e.g. GLSL is active, the shader_select call will
3026          * deactivate it.
3027          */
3028         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader));
3029         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader)");
3030         priv->current_fprogram_id = desc->shader;
3031
3032         if(device->shader_backend == &arb_program_shader_backend && context->last_was_pshader) {
3033             /* Reload fixed function constants since they collide with the pixel shader constants */
3034             for(i = 0; i < MAX_TEXTURES; i++) {
3035                 set_bumpmat_arbfp(STATE_TEXTURESTAGE(i, WINED3DTSS_BUMPENVMAT00), stateblock, context);
3036             }
3037             state_texfactor_arbfp(STATE_RENDER(WINED3DRS_TEXTUREFACTOR), stateblock, context);
3038             state_arb_specularenable(STATE_RENDER(WINED3DRS_SPECULARENABLE), stateblock, context);
3039         }
3040         context->last_was_pshader = FALSE;
3041     } else {
3042         context->last_was_pshader = TRUE;
3043     }
3044
3045     /* Finally, select the shader. If a pixel shader is used, it will be set and enabled by the shader backend.
3046      * If this shader backend is arbfp(most likely), then it will simply overwrite the last fixed function replace-
3047      * ment shader. If the shader backend is not ARB, it currently is important that the opengl implementation
3048      * type overwrites GL_ARB_fragment_program. This is currently the case with GLSL. If we really want to use
3049      * atifs or nvrc pixel shaders with arb fragment programs we'd have to disable GL_FRAGMENT_PROGRAM_ARB here
3050      *
3051      * Don't call shader_select if the vertex shader is dirty, because it will be called later on by the vertex
3052      * shader handler
3053      */
3054     if(!isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
3055         device->shader_backend->shader_select((IWineD3DDevice *)stateblock->wineD3DDevice, use_pshader, use_vshader);
3056
3057         if (!isStateDirty(context, STATE_VERTEXSHADERCONSTANT) && (use_vshader || use_pshader)) {
3058             device->StateTable[STATE_VERTEXSHADERCONSTANT].apply(STATE_VERTEXSHADERCONSTANT, stateblock, context);
3059         }
3060     }
3061     if(use_pshader) {
3062         device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
3063     }
3064 }
3065
3066 /* We can't link the fog states to the fragment state directly since the vertex pipeline links them
3067  * to FOGENABLE. A different linking in different pipeline parts can't be expressed in the combined
3068  * state table, so we need to handle that with a forwarding function. The other invisible side effect
3069  * is that changing the fog start and fog end(which links to FOGENABLE in vertex) results in the
3070  * fragment_prog_arbfp function being called because FOGENABLE is dirty, which calls this function here
3071  */
3072 static void state_arbfp_fog(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
3073     enum fogsource new_source;
3074
3075     TRACE("state %#x, stateblock %p, context %p\n", state, stateblock, context);
3076
3077     if(!isStateDirty(context, STATE_PIXELSHADER)) {
3078         fragment_prog_arbfp(state, stateblock, context);
3079     }
3080
3081     if(!stateblock->renderState[WINED3DRS_FOGENABLE]) return;
3082
3083     if(stateblock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
3084         if(use_vs(stateblock)) {
3085             new_source = FOGSOURCE_VS;
3086         } else {
3087             if(stateblock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || context->last_was_rhw) {
3088                 new_source = FOGSOURCE_COORD;
3089             } else {
3090                 new_source = FOGSOURCE_FFP;
3091             }
3092         }
3093     } else {
3094         new_source = FOGSOURCE_FFP;
3095     }
3096     if(new_source != context->fog_source) {
3097         context->fog_source = new_source;
3098         state_fogstartend(STATE_RENDER(WINED3DRS_FOGSTART), stateblock, context);
3099     }
3100 }
3101
3102 static void textransform(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
3103     if(!isStateDirty(context, STATE_PIXELSHADER)) {
3104         fragment_prog_arbfp(state, stateblock, context);
3105     }
3106 }
3107
3108 #undef GLINFO_LOCATION
3109
3110 static const struct StateEntryTemplate arbfp_fragmentstate_template[] = {
3111     {STATE_RENDER(WINED3DRS_TEXTUREFACTOR),               { STATE_RENDER(WINED3DRS_TEXTUREFACTOR),              state_texfactor_arbfp   }, 0                               },
3112     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3113     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3114     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3115     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3116     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3117     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3118     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3119     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3120     {STATE_TEXTURESTAGE(0, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3121     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3122     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3123     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3124     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3125     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3126     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3127     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3128     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3129     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3130     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3131     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3132     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3133     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3134     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3135     {STATE_TEXTURESTAGE(1, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3136     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3137     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3138     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3139     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3140     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3141     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3142     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3143     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3144     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3145     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3146     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3147     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3148     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3149     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3150     {STATE_TEXTURESTAGE(2, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3151     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3152     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3153     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3154     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3155     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3156     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3157     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3158     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3159     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3160     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3161     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3162     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3163     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3164     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3165     {STATE_TEXTURESTAGE(3, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3166     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3167     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3168     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3169     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3170     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3171     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3172     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3173     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3174     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3175     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3176     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3177     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3178     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3179     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3180     {STATE_TEXTURESTAGE(4, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3181     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3182     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3183     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3184     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3185     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3186     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3187     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3188     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3189     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3190     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3191     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3192     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3193     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3194     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3195     {STATE_TEXTURESTAGE(5, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3196     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3197     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3198     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3199     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3200     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3201     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3202     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3203     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3204     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3205     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3206     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3207     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3208     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3209     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3210     {STATE_TEXTURESTAGE(6, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3211     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3212     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3213     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3214     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3215     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3216     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3217     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3218     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3219     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3220     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3221     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3222     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3223     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3224     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3225     {STATE_TEXTURESTAGE(7, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3226     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3227     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3228     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3229     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, 0                               },
3230     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3231     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, 0                               },
3232     {STATE_SAMPLER(0),                                    { STATE_SAMPLER(0),                                   sampler_texdim          }, 0                               },
3233     {STATE_SAMPLER(1),                                    { STATE_SAMPLER(1),                                   sampler_texdim          }, 0                               },
3234     {STATE_SAMPLER(2),                                    { STATE_SAMPLER(2),                                   sampler_texdim          }, 0                               },
3235     {STATE_SAMPLER(3),                                    { STATE_SAMPLER(3),                                   sampler_texdim          }, 0                               },
3236     {STATE_SAMPLER(4),                                    { STATE_SAMPLER(4),                                   sampler_texdim          }, 0                               },
3237     {STATE_SAMPLER(5),                                    { STATE_SAMPLER(5),                                   sampler_texdim          }, 0                               },
3238     {STATE_SAMPLER(6),                                    { STATE_SAMPLER(6),                                   sampler_texdim          }, 0                               },
3239     {STATE_SAMPLER(7),                                    { STATE_SAMPLER(7),                                   sampler_texdim          }, 0                               },
3240     {STATE_PIXELSHADER,                                   { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3241     {STATE_RENDER(WINED3DRS_FOGENABLE),                   { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, 0                               },
3242     {STATE_RENDER(WINED3DRS_FOGTABLEMODE),                { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, 0                               },
3243     {STATE_RENDER(WINED3DRS_FOGVERTEXMODE),               { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, 0                               },
3244     {STATE_RENDER(WINED3DRS_FOGSTART),                    { STATE_RENDER(WINED3DRS_FOGSTART),                   state_fogstartend       }, 0                               },
3245     {STATE_RENDER(WINED3DRS_FOGEND),                      { STATE_RENDER(WINED3DRS_FOGSTART),                   state_fogstartend       }, 0                               },
3246     {STATE_RENDER(WINED3DRS_SRGBWRITEENABLE),             { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, 0                               },
3247     {STATE_RENDER(WINED3DRS_FOGCOLOR),                    { STATE_RENDER(WINED3DRS_FOGCOLOR),                   state_fogcolor          }, 0                               },
3248     {STATE_RENDER(WINED3DRS_FOGDENSITY),                  { STATE_RENDER(WINED3DRS_FOGDENSITY),                 state_fogdensity        }, 0                               },
3249     {STATE_TEXTURESTAGE(0,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(0, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, 0                               },
3250     {STATE_TEXTURESTAGE(1,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(1, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, 0                               },
3251     {STATE_TEXTURESTAGE(2,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(2, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, 0                               },
3252     {STATE_TEXTURESTAGE(3,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(3, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, 0                               },
3253     {STATE_TEXTURESTAGE(4,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(4, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, 0                               },
3254     {STATE_TEXTURESTAGE(5,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(5, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, 0                               },
3255     {STATE_TEXTURESTAGE(6,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(6, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, 0                               },
3256     {STATE_TEXTURESTAGE(7,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(7, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, 0                               },
3257     {STATE_RENDER(WINED3DRS_SPECULARENABLE),              { STATE_RENDER(WINED3DRS_SPECULARENABLE),             state_arb_specularenable}, 0                               },
3258     {0 /* Terminate */,                                   { 0,                                                  0                       }, 0                               },
3259 };
3260
3261 const struct fragment_pipeline arbfp_fragment_pipeline = {
3262     arbfp_enable,
3263     arbfp_get_caps,
3264     arbfp_alloc,
3265     arbfp_free,
3266     shader_arb_color_fixup_supported,
3267     arbfp_fragmentstate_template,
3268     TRUE /* We can disable projected textures */
3269 };
3270
3271 #define GLINFO_LOCATION device->adapter->gl_info
3272
3273 struct arbfp_blit_priv {
3274     GLenum yuy2_rect_shader, yuy2_2d_shader;
3275     GLenum uyvy_rect_shader, uyvy_2d_shader;
3276     GLenum yv12_rect_shader, yv12_2d_shader;
3277 };
3278
3279 static HRESULT arbfp_blit_alloc(IWineD3DDevice *iface) {
3280     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
3281     device->blit_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct arbfp_blit_priv));
3282     if(!device->blit_priv) {
3283         ERR("Out of memory\n");
3284         return E_OUTOFMEMORY;
3285     }
3286     return WINED3D_OK;
3287 }
3288 static void arbfp_blit_free(IWineD3DDevice *iface) {
3289     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
3290     struct arbfp_blit_priv *priv = device->blit_priv;
3291
3292     ENTER_GL();
3293     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_rect_shader));
3294     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_2d_shader));
3295     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_rect_shader));
3296     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_2d_shader));
3297     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yv12_rect_shader));
3298     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yv12_2d_shader));
3299     checkGLcall("Delete yuv programs\n");
3300     LEAVE_GL();
3301 }
3302
3303 static BOOL gen_planar_yuv_read(SHADER_BUFFER *buffer, enum yuv_fixup yuv_fixup, GLenum textype, char *luminance)
3304 {
3305     char chroma;
3306     const char *tex, *texinstr;
3307
3308     if (yuv_fixup == YUV_FIXUP_UYVY) {
3309         chroma = 'x';
3310         *luminance = 'w';
3311     } else {
3312         chroma = 'w';
3313         *luminance = 'x';
3314     }
3315     switch(textype) {
3316         case GL_TEXTURE_2D:             tex = "2D";     texinstr = "TXP"; break;
3317         case GL_TEXTURE_RECTANGLE_ARB:  tex = "RECT";   texinstr = "TEX"; break;
3318         default:
3319             /* This is more tricky than just replacing the texture type - we have to navigate
3320              * properly in the texture to find the correct chroma values
3321              */
3322             FIXME("Implement yuv correction for non-2d, non-rect textures\n");
3323             return FALSE;
3324     }
3325
3326     /* First we have to read the chroma values. This means we need at least two pixels(no filtering),
3327      * or 4 pixels(with filtering). To get the unmodified chromas, we have to rid ourselves of the
3328      * filtering when we sample the texture.
3329      *
3330      * These are the rules for reading the chroma:
3331      *
3332      * Even pixel: Cr
3333      * Even pixel: U
3334      * Odd pixel: V
3335      *
3336      * So we have to get the sampling x position in non-normalized coordinates in integers
3337      */
3338     if(textype != GL_TEXTURE_RECTANGLE_ARB) {
3339         shader_addline(buffer, "MUL texcrd.xy, fragment.texcoord[0], size.x;\n");
3340         shader_addline(buffer, "MOV texcrd.w, size.x;\n");
3341     } else {
3342         shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
3343     }
3344     /* We must not allow filtering between pixel x and x+1, this would mix U and V
3345      * Vertical filtering is ok. However, bear in mind that the pixel center is at
3346      * 0.5, so add 0.5.
3347      */
3348     shader_addline(buffer, "FLR texcrd.x, texcrd.x;\n");
3349     shader_addline(buffer, "ADD texcrd.x, texcrd.x, coef.y;\n");
3350
3351     /* Divide the x coordinate by 0.5 and get the fraction. This gives 0.25 and 0.75 for the
3352      * even and odd pixels respectively
3353      */
3354     shader_addline(buffer, "MUL texcrd2, texcrd, coef.y;\n");
3355     shader_addline(buffer, "FRC texcrd2, texcrd2;\n");
3356
3357     /* Sample Pixel 1 */
3358     shader_addline(buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
3359
3360     /* Put the value into either of the chroma values */
3361     shader_addline(buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
3362     shader_addline(buffer, "MUL chroma.x, luminance.%c, temp.x;\n", chroma);
3363     shader_addline(buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
3364     shader_addline(buffer, "MUL chroma.y, luminance.%c, temp.x;\n", chroma);
3365
3366     /* Sample pixel 2. If we read an even pixel(SLT above returned 1), sample
3367      * the pixel right to the current one. Otherwise, sample the left pixel.
3368      * Bias and scale the SLT result to -1;1 and add it to the texcrd.x.
3369      */
3370     shader_addline(buffer, "MAD temp.x, temp.x, coef.z, -coef.x;\n");
3371     shader_addline(buffer, "ADD texcrd.x, texcrd, temp.x;\n");
3372     shader_addline(buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
3373
3374     /* Put the value into the other chroma */
3375     shader_addline(buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
3376     shader_addline(buffer, "MAD chroma.y, luminance.%c, temp.x, chroma.y;\n", chroma);
3377     shader_addline(buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
3378     shader_addline(buffer, "MAD chroma.x, luminance.%c, temp.x, chroma.x;\n", chroma);
3379
3380     /* TODO: If filtering is enabled, sample a 2nd pair of pixels left or right of
3381      * the current one and lerp the two U and V values
3382      */
3383
3384     /* This gives the correctly filtered luminance value */
3385     shader_addline(buffer, "TEX luminance, fragment.texcoord[0], texture[0], %s;\n", tex);
3386
3387     return TRUE;
3388 }
3389
3390 static BOOL gen_yv12_read(SHADER_BUFFER *buffer, GLenum textype, char *luminance)
3391 {
3392     const char *tex;
3393
3394     switch(textype) {
3395         case GL_TEXTURE_2D:             tex = "2D";     break;
3396         case GL_TEXTURE_RECTANGLE_ARB:  tex = "RECT";   break;
3397         default:
3398             FIXME("Implement yv12 correction for non-2d, non-rect textures\n");
3399             return FALSE;
3400     }
3401
3402     /* YV12 surfaces contain a WxH sized luminance plane, followed by a (W/2)x(H/2)
3403      * V and a (W/2)x(H/2) U plane, each with 8 bit per pixel. So the effective
3404      * bitdepth is 12 bits per pixel. Since the U and V planes have only half the
3405      * pitch of the luminance plane, the packing into the gl texture is a bit
3406      * unfortunate. If the whole texture is interpreted as luminance data it looks
3407      * approximately like this:
3408      *
3409      *        +----------------------------------+----
3410      *        |                                  |
3411      *        |                                  |
3412      *        |                                  |
3413      *        |                                  |
3414      *        |                                  |   2
3415      *        |            LUMINANCE             |   -
3416      *        |                                  |   3
3417      *        |                                  |
3418      *        |                                  |
3419      *        |                                  |
3420      *        |                                  |
3421      *        +----------------+-----------------+----
3422      *        |                |                 |
3423      *        |  U even rows   |  U odd rows     |
3424      *        |                |                 |   1
3425      *        +----------------+------------------   -
3426      *        |                |                 |   3
3427      *        |  V even rows   |  V odd rows     |
3428      *        |                |                 |
3429      *        +----------------+-----------------+----
3430      *        |                |                 |
3431      *        |     0.5        |       0.5       |
3432      *
3433      * So it appears as if there are 4 chroma images, but in fact the odd rows
3434      * in the chroma images are in the same row as the even ones. So its is
3435      * kinda tricky to read
3436      *
3437      * When reading from rectangle textures, keep in mind that the input y coordinates
3438      * go from 0 to d3d_height, whereas the opengl texture height is 1.5 * d3d_height
3439      */
3440     shader_addline(buffer, "PARAM yv12_coef = {%f, %f, %f, %f};\n",
3441                    2.0 / 3.0, 1.0 / 6.0, (2.0 / 3.0) + (1.0 / 6.0), 1.0 / 3.0);
3442
3443     shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
3444     /* the chroma planes have only half the width */
3445     shader_addline(buffer, "MUL texcrd.x, texcrd.x, coef.y;\n");
3446
3447     /* The first value is between 2/3 and 5/6th of the texture's height, so scale+bias
3448      * the coordinate. Also read the right side of the image when reading odd lines
3449      *
3450      * Don't forget to clamp the y values in into the range, otherwise we'll get filtering
3451      * bleeding
3452      */
3453     if(textype == GL_TEXTURE_2D) {
3454
3455         shader_addline(buffer, "RCP chroma.w, size.y;\n");
3456
3457         shader_addline(buffer, "MUL texcrd2.y, texcrd.y, size.y;\n");
3458
3459         shader_addline(buffer, "FLR texcrd2.y, texcrd2.y;\n");
3460         shader_addline(buffer, "MAD texcrd.y, texcrd.y, yv12_coef.y, yv12_coef.x;\n");
3461
3462         /* Read odd lines from the right side(add size * 0.5 to the x coordinate */
3463         shader_addline(buffer, "ADD texcrd2.x, texcrd2.y, yv12_coef.y;\n"); /* To avoid 0.5 == 0.5 comparisons */
3464         shader_addline(buffer, "FRC texcrd2.x, texcrd2.x;\n");
3465         shader_addline(buffer, "SGE texcrd2.x, texcrd2.x, coef.y;\n");
3466         shader_addline(buffer, "MAD texcrd.x, texcrd2.x, coef.y, texcrd.x;\n");
3467
3468         /* clamp, keep the half pixel origin in mind */
3469         shader_addline(buffer, "MAD temp.y, coef.y, chroma.w, yv12_coef.x;\n");
3470         shader_addline(buffer, "MAX texcrd.y, temp.y, texcrd.y;\n");
3471         shader_addline(buffer, "MAD temp.y, -coef.y, chroma.w, yv12_coef.z;\n");
3472         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
3473     } else {
3474         /* Read from [size - size+size/4] */
3475         shader_addline(buffer, "FLR texcrd.y, texcrd.y;\n");
3476         shader_addline(buffer, "MAD texcrd.y, texcrd.y, coef.w, size.y;\n");
3477
3478         /* Read odd lines from the right side(add size * 0.5 to the x coordinate */
3479         shader_addline(buffer, "ADD texcrd2.x, texcrd.y, yv12_coef.y;\n"); /* To avoid 0.5 == 0.5 comparisons */
3480         shader_addline(buffer, "FRC texcrd2.x, texcrd2.x;\n");
3481         shader_addline(buffer, "SGE texcrd2.x, texcrd2.x, coef.y;\n");
3482         shader_addline(buffer, "MUL texcrd2.x, texcrd2.x, size.x;\n");
3483         shader_addline(buffer, "MAD texcrd.x, texcrd2.x, coef.y, texcrd.x;\n");
3484
3485         /* Make sure to read exactly from the pixel center */
3486         shader_addline(buffer, "FLR texcrd.y, texcrd.y;\n");
3487         shader_addline(buffer, "ADD texcrd.y, texcrd.y, coef.y;\n");
3488
3489         /* Clamp */
3490         shader_addline(buffer, "MAD temp.y, size.y, coef.w, size.y;\n");
3491         shader_addline(buffer, "ADD temp.y, temp.y, -coef.y;\n");
3492         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
3493         shader_addline(buffer, "ADD temp.y, size.y, -coef.y;\n");
3494         shader_addline(buffer, "MAX texcrd.y, temp.y, texcrd.y;\n");
3495     }
3496     /* Read the texture, put the result into the output register */
3497     shader_addline(buffer, "TEX temp, texcrd, texture[0], %s;\n", tex);
3498     shader_addline(buffer, "MOV chroma.x, temp.w;\n");
3499
3500     /* The other chroma value is 1/6th of the texture lower, from 5/6th to 6/6th
3501      * No need to clamp because we're just reusing the already clamped value from above
3502      */
3503     if(textype == GL_TEXTURE_2D) {
3504         shader_addline(buffer, "ADD texcrd.y, texcrd.y, yv12_coef.y;\n");
3505     } else {
3506         shader_addline(buffer, "MAD texcrd.y, size.y, coef.w, texcrd.y;\n");
3507     }
3508     shader_addline(buffer, "TEX temp, texcrd, texture[0], %s;\n", tex);
3509     shader_addline(buffer, "MOV chroma.y, temp.w;\n");
3510
3511     /* Sample the luminance value. It is in the top 2/3rd of the texture, so scale the y coordinate.
3512      * Clamp the y coordinate to prevent the chroma values from bleeding into the sampled luminance
3513      * values due to filtering
3514      */
3515     shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
3516     if(textype == GL_TEXTURE_2D) {
3517         /* Multiply the y coordinate by 2/3 and clamp it */
3518         shader_addline(buffer, "MUL texcrd.y, texcrd.y, yv12_coef.x;\n");
3519         shader_addline(buffer, "MAD temp.y, -coef.y, chroma.w, yv12_coef.x;\n");
3520         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
3521         shader_addline(buffer, "TEX luminance, texcrd, texture[0], %s;\n", tex);
3522     } else {
3523         /* Reading from texture_rectangles is pretty straightforward, just use the unmodified
3524          * texture coordinate. It is still a good idea to clamp it though, since the opengl texture
3525          * is bigger
3526          */
3527         shader_addline(buffer, "ADD temp.x, size.y, -coef.y;\n");
3528         shader_addline(buffer, "MIN texcrd.y, texcrd.y, size.x;\n");
3529         shader_addline(buffer, "TEX luminance, texcrd, texture[0], %s;\n", tex);
3530     }
3531     *luminance = 'a';
3532
3533     return TRUE;
3534 }
3535
3536 static GLuint gen_yuv_shader(IWineD3DDeviceImpl *device, enum yuv_fixup yuv_fixup, GLenum textype)
3537 {
3538     GLenum shader;
3539     SHADER_BUFFER buffer;
3540     char luminance_component;
3541     struct arbfp_blit_priv *priv = device->blit_priv;
3542
3543     /* Shader header */
3544     shader_buffer_init(&buffer);
3545
3546     ENTER_GL();
3547     GL_EXTCALL(glGenProgramsARB(1, &shader));
3548     checkGLcall("GL_EXTCALL(glGenProgramsARB(1, &shader))");
3549     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
3550     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
3551     LEAVE_GL();
3552     if(!shader) {
3553         shader_buffer_free(&buffer);
3554         return 0;
3555     }
3556
3557     /* The YUY2 and UYVY formats contain two pixels packed into a 32 bit macropixel,
3558      * giving effectively 16 bit per pixel. The color consists of a luminance(Y) and
3559      * two chroma(U and V) values. Each macropixel has two luminance values, one for
3560      * each single pixel it contains, and one U and one V value shared between both
3561      * pixels.
3562      *
3563      * The data is loaded into an A8L8 texture. With YUY2, the luminance component
3564      * contains the luminance and alpha the chroma. With UYVY it is vice versa. Thus
3565      * take the format into account when generating the read swizzles
3566      *
3567      * Reading the Y value is straightforward - just sample the texture. The hardware
3568      * takes care of filtering in the horizontal and vertical direction.
3569      *
3570      * Reading the U and V values is harder. We have to avoid filtering horizontally,
3571      * because that would mix the U and V values of one pixel or two adjacent pixels.
3572      * Thus floor the texture coordinate and add 0.5 to get an unfiltered read,
3573      * regardless of the filtering setting. Vertical filtering works automatically
3574      * though - the U and V values of two rows are mixed nicely.
3575      *
3576      * Appart of avoiding filtering issues, the code has to know which value it just
3577      * read, and where it can find the other one. To determine this, it checks if
3578      * it sampled an even or odd pixel, and shifts the 2nd read accordingly.
3579      *
3580      * Handling horizontal filtering of U and V values requires reading a 2nd pair
3581      * of pixels, extracting U and V and mixing them. This is not implemented yet.
3582      *
3583      * An alternative implementation idea is to load the texture as A8R8G8B8 texture,
3584      * with width / 2. This way one read gives all 3 values, finding U and V is easy
3585      * in an unfiltered situation. Finding the luminance on the other hand requires
3586      * finding out if it is an odd or even pixel. The real drawback of this approach
3587      * is filtering. This would have to be emulated completely in the shader, reading
3588      * up two 2 packed pixels in up to 2 rows and interpolating both horizontally and
3589      * vertically. Beyond that it would require adjustments to the texture handling
3590      * code to deal with the width scaling
3591      */
3592     shader_addline(&buffer, "!!ARBfp1.0\n");
3593     shader_addline(&buffer, "TEMP luminance;\n");
3594     shader_addline(&buffer, "TEMP temp;\n");
3595     shader_addline(&buffer, "TEMP chroma;\n");
3596     shader_addline(&buffer, "TEMP texcrd;\n");
3597     shader_addline(&buffer, "TEMP texcrd2;\n");
3598     shader_addline(&buffer, "PARAM coef = {1.0, 0.5, 2.0, 0.25};\n");
3599     shader_addline(&buffer, "PARAM yuv_coef = {1.403, 0.344, 0.714, 1.770};\n");
3600     shader_addline(&buffer, "PARAM size = program.local[0];\n");
3601
3602     switch (yuv_fixup)
3603     {
3604         case YUV_FIXUP_UYVY:
3605         case YUV_FIXUP_YUY2:
3606             if (!gen_planar_yuv_read(&buffer, yuv_fixup, textype, &luminance_component))
3607             {
3608                 shader_buffer_free(&buffer);
3609                 return 0;
3610             }
3611             break;
3612
3613         case YUV_FIXUP_YV12:
3614             if (!gen_yv12_read(&buffer, textype, &luminance_component))
3615             {
3616                 shader_buffer_free(&buffer);
3617                 return 0;
3618             }
3619             break;
3620
3621         default:
3622             FIXME("Unsupported YUV fixup %#x\n", yuv_fixup);
3623             shader_buffer_free(&buffer);
3624             return 0;
3625     }
3626
3627     /* Calculate the final result. Formula is taken from
3628      * http://www.fourcc.org/fccyvrgb.php. Note that the chroma
3629      * ranges from -0.5 to 0.5
3630      */
3631     shader_addline(&buffer, "SUB chroma.xy, chroma, coef.y;\n");
3632
3633     shader_addline(&buffer, "MAD result.color.x, chroma.x, yuv_coef.x, luminance.%c;\n", luminance_component);
3634     shader_addline(&buffer, "MAD temp.x, -chroma.y, yuv_coef.y, luminance.%c;\n", luminance_component);
3635     shader_addline(&buffer, "MAD result.color.y, -chroma.x, yuv_coef.z, temp.x;\n");
3636     shader_addline(&buffer, "MAD result.color.z, chroma.y, yuv_coef.w, luminance.%c;\n", luminance_component);
3637     shader_addline(&buffer, "END\n");
3638
3639     ENTER_GL();
3640     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(buffer.buffer), buffer.buffer));
3641
3642     if (glGetError() == GL_INVALID_OPERATION) {
3643         GLint pos;
3644         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
3645         FIXME("Fragment program error at position %d: %s\n", pos,
3646               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
3647     }
3648     shader_buffer_free(&buffer);
3649     LEAVE_GL();
3650
3651     switch (yuv_fixup)
3652     {
3653         case YUV_FIXUP_YUY2:
3654             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->yuy2_rect_shader = shader;
3655             else priv->yuy2_2d_shader = shader;
3656             break;
3657
3658         case YUV_FIXUP_UYVY:
3659             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->uyvy_rect_shader = shader;
3660             else priv->uyvy_2d_shader = shader;
3661             break;
3662
3663         case YUV_FIXUP_YV12:
3664             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->yv12_rect_shader = shader;
3665             else priv->yv12_2d_shader = shader;
3666             break;
3667     }
3668
3669     return shader;
3670 }
3671
3672 static HRESULT arbfp_blit_set(IWineD3DDevice *iface, const struct GlPixelFormatDesc *format_desc,
3673         GLenum textype, UINT width, UINT height)
3674 {
3675     GLenum shader;
3676     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
3677     float size[4] = {width, height, 1, 1};
3678     struct arbfp_blit_priv *priv = device->blit_priv;
3679     enum yuv_fixup yuv_fixup;
3680
3681     if (!is_yuv_fixup(format_desc->color_fixup))
3682     {
3683         TRACE("Fixup:\n");
3684         dump_color_fixup_desc(format_desc->color_fixup);
3685         /* Don't bother setting up a shader for unconverted formats */
3686         ENTER_GL();
3687         glEnable(textype);
3688         checkGLcall("glEnable(textype)");
3689         LEAVE_GL();
3690         return WINED3D_OK;
3691     }
3692
3693     yuv_fixup = get_yuv_fixup(format_desc->color_fixup);
3694
3695     switch(yuv_fixup)
3696     {
3697         case YUV_FIXUP_YUY2:
3698             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->yuy2_rect_shader : priv->yuy2_2d_shader;
3699             break;
3700
3701         case YUV_FIXUP_UYVY:
3702             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->uyvy_rect_shader : priv->uyvy_2d_shader;
3703             break;
3704
3705         case YUV_FIXUP_YV12:
3706             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->yv12_rect_shader : priv->yv12_2d_shader;
3707             break;
3708
3709         default:
3710             FIXME("Unsupported YUV fixup %#x, not setting a shader\n", yuv_fixup);
3711             ENTER_GL();
3712             glEnable(textype);
3713             checkGLcall("glEnable(textype)");
3714             LEAVE_GL();
3715             return E_NOTIMPL;
3716     }
3717
3718     if (!shader) shader = gen_yuv_shader(device, yuv_fixup, textype);
3719
3720     ENTER_GL();
3721     glEnable(GL_FRAGMENT_PROGRAM_ARB);
3722     checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
3723     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
3724     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
3725     GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, 0, size));
3726     checkGLcall("glProgramLocalParameter4fvARB");
3727     LEAVE_GL();
3728
3729     return WINED3D_OK;
3730 }
3731
3732 static void arbfp_blit_unset(IWineD3DDevice *iface) {
3733     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
3734
3735     ENTER_GL();
3736     glDisable(GL_FRAGMENT_PROGRAM_ARB);
3737     checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
3738     glDisable(GL_TEXTURE_2D);
3739     checkGLcall("glDisable(GL_TEXTURE_2D)");
3740     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
3741         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
3742         checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
3743     }
3744     if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
3745         glDisable(GL_TEXTURE_RECTANGLE_ARB);
3746         checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
3747     }
3748     LEAVE_GL();
3749 }
3750
3751 static BOOL arbfp_blit_color_fixup_supported(struct color_fixup_desc fixup)
3752 {
3753     enum yuv_fixup yuv_fixup;
3754
3755     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
3756     {
3757         TRACE("Checking support for fixup:\n");
3758         dump_color_fixup_desc(fixup);
3759     }
3760
3761     if (is_identity_fixup(fixup))
3762     {
3763         TRACE("[OK]\n");
3764         return TRUE;
3765     }
3766
3767     /* We only support YUV conversions. */
3768     if (!is_yuv_fixup(fixup))
3769     {
3770         TRACE("[FAILED]\n");
3771         return FALSE;
3772     }
3773
3774     yuv_fixup = get_yuv_fixup(fixup);
3775     switch(yuv_fixup)
3776     {
3777         case YUV_FIXUP_YUY2:
3778         case YUV_FIXUP_UYVY:
3779         case YUV_FIXUP_YV12:
3780             TRACE("[OK]\n");
3781             return TRUE;
3782
3783         default:
3784             FIXME("Unsupported YUV fixup %#x\n", yuv_fixup);
3785             TRACE("[FAILED]\n");
3786             return FALSE;
3787     }
3788 }
3789
3790 const struct blit_shader arbfp_blit = {
3791     arbfp_blit_alloc,
3792     arbfp_blit_free,
3793     arbfp_blit_set,
3794     arbfp_blit_unset,
3795     arbfp_blit_color_fixup_supported,
3796 };
3797
3798 #undef GLINFO_LOCATION