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