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