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