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