ntoskrnl: Add FsRtlRegisterUncProvider stub.
[wine] / dlls / wined3d / arb_program_shader.c
1 /*
2  * Pixel and vertex shaders implementation using ARB_vertex_program
3  * and ARB_fragment_program GL extensions.
4  *
5  * Copyright 2002-2003 Jason Edmeades
6  * Copyright 2002-2003 Raphael Junqueira
7  * Copyright 2004 Christian Costa
8  * Copyright 2005 Oliver Stieber
9  * Copyright 2006 Ivan Gyurdiev
10  * Copyright 2006 Jason Green
11  * Copyright 2006 Henri Verbeet
12  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
13  * Copyright 2009 Henri Verbeet for CodeWeavers
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
28  */
29
30 #include "config.h"
31
32 #include <math.h>
33 #include <stdio.h>
34
35 #include "wined3d_private.h"
36
37 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
38 WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
39 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
40 WINE_DECLARE_DEBUG_CHANNEL(d3d);
41
42 #define GLINFO_LOCATION      (*gl_info)
43
44 /* GL locking for state handlers is done by the caller. */
45 static BOOL need_mova_const(IWineD3DBaseShader *shader, const WineD3D_GL_Info *gl_info) {
46     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) shader;
47     if(!This->baseShader.reg_maps.usesmova) return FALSE;
48     return !GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION);
49 }
50
51 static BOOL need_helper_const(const WineD3D_GL_Info *gl_info) {
52     if(!GL_SUPPORT(NV_VERTEX_PROGRAM)   || /* Need to init colors */
53        gl_info->arb_vs_offset_limit     || /* Have to init texcoords */
54        gl_info->set_texcoord_w) {          /* Load the immval offset */
55         return TRUE;
56     }
57     return FALSE;
58 }
59
60 static unsigned int reserved_vs_const(IWineD3DBaseShader *shader, const WineD3D_GL_Info *gl_info) {
61     unsigned int ret = 1;
62     /* We use one PARAM for the pos fixup, and in some cases one to load
63      * some immediate values into the shader
64      */
65     if(need_helper_const(gl_info)) ret++;
66     if(need_mova_const(shader, gl_info)) ret++;
67     return ret;
68 }
69
70 /* Internally used shader constants. Applications can use constants 0 to GL_LIMITS(vshader_constantsF) - 1,
71  * so upload them above that
72  */
73 #define ARB_SHADER_PRIVCONST_BASE (GL_LIMITS(vshader_constantsF) - 1)
74 #define ARB_SHADER_PRIVCONST_POS ARB_SHADER_PRIVCONST_BASE + 0
75
76 /* ARB_program_shader private data */
77 struct control_frame
78 {
79     struct                          list entry;
80     enum
81     {
82         IF,
83         IFC,
84         LOOP,
85         REP
86     } type;
87     BOOL                            muting;
88     BOOL                            outer_loop;
89     union
90     {
91         unsigned int                loop_no;
92         unsigned int                ifc_no;
93     };
94     DWORD                           loop_control[3];
95     BOOL                            had_else;
96 };
97
98 struct arb_ps_compile_args
99 {
100     struct ps_compile_args          super;
101     DWORD                           bools; /* WORD is enough, use DWORD for alignment */
102     unsigned char                   loop_ctrl[MAX_CONST_I][3];
103 };
104
105 struct stb_const_desc
106 {
107     unsigned char           texunit;
108     UINT                    const_num;
109 };
110
111 struct arb_ps_compiled_shader
112 {
113     struct arb_ps_compile_args      args;
114     GLuint                          prgId;
115     struct stb_const_desc           bumpenvmatconst[MAX_TEXTURES];
116     unsigned char                   numbumpenvmatconsts;
117     struct stb_const_desc           luminanceconst[MAX_TEXTURES];
118     UINT                            int_consts[MAX_CONST_I];
119     char                            num_int_consts;
120     UINT                            ycorrection;
121 };
122
123 struct arb_vs_compile_args
124 {
125     struct vs_compile_args          super;
126     DWORD                           bools; /* WORD is enough, use DWORD for alignment */
127     unsigned char                   loop_ctrl[MAX_CONST_I][3];
128 };
129
130 struct arb_vs_compiled_shader
131 {
132     struct arb_vs_compile_args      args;
133     GLuint                          prgId;
134     UINT                            int_consts[MAX_CONST_I];
135     char                            num_int_consts;
136 };
137
138 struct recorded_instruction
139 {
140     struct wined3d_shader_instruction ins;
141     struct list entry;
142 };
143
144 struct shader_arb_ctx_priv
145 {
146     char addr_reg[20];
147     enum
148     {
149         /* plain GL_ARB_vertex_program or GL_ARB_fragment_program */
150         ARB,
151         /* GL_NV_vertex_progam2_option or GL_NV_fragment_program_option */
152         NV2,
153         /* GL_NV_vertex_program3 or GL_NV_fragment_program2 */
154         NV3
155     } target_version;
156
157     const struct arb_vs_compile_args    *cur_vs_args;
158     const struct arb_ps_compile_args    *cur_ps_args;
159     const struct arb_ps_compiled_shader *compiled_fprog;
160     const struct arb_vs_compiled_shader *compiled_vprog;
161     struct list                         control_frames;
162     struct list                         record;
163     BOOL                                recording;
164     BOOL                                muted;
165     unsigned int                        num_loops, loop_depth, num_ifcs;
166     int                                 aL;
167 };
168
169 struct arb_pshader_private {
170     struct arb_ps_compiled_shader   *gl_shaders;
171     UINT                            num_gl_shaders, shader_array_size;
172 };
173
174 struct arb_vshader_private {
175     struct arb_vs_compiled_shader   *gl_shaders;
176     UINT                            num_gl_shaders, shader_array_size;
177 };
178
179 struct shader_arb_priv
180 {
181     GLuint                  current_vprogram_id;
182     GLuint                  current_fprogram_id;
183     const struct arb_ps_compiled_shader *compiled_fprog;
184     const struct arb_vs_compiled_shader *compiled_vprog;
185     GLuint                  depth_blt_vprogram_id;
186     GLuint                  depth_blt_fprogram_id[tex_type_count];
187     BOOL                    use_arbfp_fixed_func;
188     struct wine_rb_tree     fragment_shaders;
189 };
190
191 /********************************************************
192  * ARB_[vertex/fragment]_program helper functions follow
193  ********************************************************/
194
195 /** 
196  * Loads floating point constants into the currently set ARB_vertex/fragment_program.
197  * When constant_list == NULL, it will load all the constants.
198  *  
199  * @target_type should be either GL_VERTEX_PROGRAM_ARB (for vertex shaders)
200  *  or GL_FRAGMENT_PROGRAM_ARB (for pixel shaders)
201  */
202 /* GL locking is done by the caller */
203 static unsigned int shader_arb_load_constantsF(IWineD3DBaseShaderImpl* This, const WineD3D_GL_Info *gl_info,
204         GLuint target_type, unsigned int max_constants, const float *constants, char *dirty_consts)
205 {
206     local_constant* lconst;
207     DWORD i, j;
208     unsigned int ret;
209
210     if (TRACE_ON(d3d_shader)) {
211         for(i = 0; i < max_constants; i++) {
212             if(!dirty_consts[i]) continue;
213             TRACE_(d3d_constants)("Loading constants %i: %f, %f, %f, %f\n", i,
214                         constants[i * 4 + 0], constants[i * 4 + 1],
215                         constants[i * 4 + 2], constants[i * 4 + 3]);
216         }
217     }
218     /* In 1.X pixel shaders constants are implicitly clamped in the range [-1;1] */
219     if (target_type == GL_FRAGMENT_PROGRAM_ARB && This->baseShader.reg_maps.shader_version.major == 1)
220     {
221         float lcl_const[4];
222         for(i = 0; i < max_constants; i++) {
223             if(!dirty_consts[i]) continue;
224             dirty_consts[i] = 0;
225
226             j = 4 * i;
227             if(constants[j + 0] > 1.0) lcl_const[0] = 1.0;
228             else if(constants[j + 0] < -1.0) lcl_const[0] = -1.0;
229             else lcl_const[0] = constants[j + 0];
230
231             if(constants[j + 1] > 1.0) lcl_const[1] = 1.0;
232             else if(constants[j + 1] < -1.0) lcl_const[1] = -1.0;
233             else lcl_const[1] = constants[j + 1];
234
235             if(constants[j + 2] > 1.0) lcl_const[2] = 1.0;
236             else if(constants[j + 2] < -1.0) lcl_const[2] = -1.0;
237             else lcl_const[2] = constants[j + 2];
238
239             if(constants[j + 3] > 1.0) lcl_const[3] = 1.0;
240             else if(constants[j + 3] < -1.0) lcl_const[3] = -1.0;
241             else lcl_const[3] = constants[j + 3];
242
243             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, lcl_const));
244         }
245     } else {
246         if(GL_SUPPORT(EXT_GPU_PROGRAM_PARAMETERS)) {
247             /* TODO: Benchmark if we're better of with finding the dirty constants ourselves,
248              * or just reloading *all* constants at once
249              *
250             GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, 0, max_constants, constants));
251              */
252             for(i = 0; i < max_constants; i++) {
253                 if(!dirty_consts[i]) continue;
254
255                 /* Find the next block of dirty constants */
256                 dirty_consts[i] = 0;
257                 j = i;
258                 for(i++; (i < max_constants) && dirty_consts[i]; i++) {
259                     dirty_consts[i] = 0;
260                 }
261
262                 GL_EXTCALL(glProgramEnvParameters4fvEXT(target_type, j, i - j, constants + (j * 4)));
263             }
264         } else {
265             for(i = 0; i < max_constants; i++) {
266                 if(dirty_consts[i]) {
267                     dirty_consts[i] = 0;
268                     GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, i, constants + (i * 4)));
269                 }
270             }
271         }
272     }
273     checkGLcall("glProgramEnvParameter4fvARB()");
274
275     /* Load immediate constants */
276     if(This->baseShader.load_local_constsF) {
277         if (TRACE_ON(d3d_shader)) {
278             LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
279                 GLfloat* values = (GLfloat*)lconst->value;
280                 TRACE_(d3d_constants)("Loading local constants %i: %f, %f, %f, %f\n", lconst->idx,
281                         values[0], values[1], values[2], values[3]);
282             }
283         }
284         /* Immediate constants are clamped for 1.X shaders at loading times */
285         ret = 0;
286         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
287             dirty_consts[lconst->idx] = 1; /* Dirtify so the non-immediate constant overwrites it next time */
288             ret = max(ret, lconst->idx + 1);
289             GL_EXTCALL(glProgramEnvParameter4fvARB(target_type, lconst->idx, (GLfloat*)lconst->value));
290         }
291         checkGLcall("glProgramEnvParameter4fvARB()");
292         return ret; /* The loaded immediate constants need reloading for the next shader */
293     } else {
294         return 0; /* No constants are dirty now */
295     }
296 }
297
298 /**
299  * Loads the texture dimensions for NP2 fixup into the currently set ARB_[vertex/fragment]_programs.
300  */
301 static void shader_arb_load_np2fixup_constants(
302     IWineD3DDevice* device,
303     char usePixelShader,
304     char useVertexShader) {
305     /* not implemented */
306 }
307
308 static inline void shader_arb_ps_local_constants(IWineD3DDeviceImpl* deviceImpl)
309 {
310     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
311     const WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
312     unsigned char i;
313     struct shader_arb_priv *priv = deviceImpl->shader_priv;
314     const struct arb_ps_compiled_shader *gl_shader = priv->compiled_fprog;
315
316     for(i = 0; i < gl_shader->numbumpenvmatconsts; i++)
317     {
318         int texunit = gl_shader->bumpenvmatconst[i].texunit;
319
320         /* The state manager takes care that this function is always called if the bump env matrix changes */
321         const float *data = (const float *)&stateBlock->textureState[texunit][WINED3DTSS_BUMPENVMAT00];
322         GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, gl_shader->bumpenvmatconst[i].const_num, data));
323
324         if (gl_shader->luminanceconst[i].const_num != WINED3D_CONST_NUM_UNUSED)
325         {
326             /* WINED3DTSS_BUMPENVLSCALE and WINED3DTSS_BUMPENVLOFFSET are next to each other.
327              * point gl to the scale, and load 4 floats. x = scale, y = offset, z and w are junk, we
328              * don't care about them. The pointers are valid for sure because the stateblock is bigger.
329              * (they're WINED3DTSS_TEXTURETRANSFORMFLAGS and WINED3DTSS_ADDRESSW, so most likely 0 or NaN
330             */
331             const float *scale = (const float *)&stateBlock->textureState[texunit][WINED3DTSS_BUMPENVLSCALE];
332             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, gl_shader->luminanceconst[i].const_num, scale));
333         }
334     }
335     checkGLcall("Load bumpmap consts\n");
336
337     if(gl_shader->ycorrection != WINED3D_CONST_NUM_UNUSED)
338     {
339         /* ycorrection.x: Backbuffer height(onscreen) or 0(offscreen).
340         * ycorrection.y: -1.0(onscreen), 1.0(offscreen)
341         * ycorrection.z: 1.0
342         * ycorrection.w: 0.0
343         */
344         float val[4];
345         val[0] = deviceImpl->render_offscreen ? 0.0 : ((IWineD3DSurfaceImpl *) deviceImpl->render_targets[0])->currentDesc.Height;
346         val[1] = deviceImpl->render_offscreen ? 1.0 : -1.0;
347         val[2] = 1.0;
348         val[3] = 0.0;
349         GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, gl_shader->ycorrection, val));
350         checkGLcall("y correction loading\n");
351     }
352
353     if(gl_shader->num_int_consts == 0) return;
354
355     for(i = 0; i < MAX_CONST_I; i++)
356     {
357         if(gl_shader->int_consts[i] != WINED3D_CONST_NUM_UNUSED)
358         {
359             float val[4];
360             val[0] = stateBlock->pixelShaderConstantI[4 * i];
361             val[1] = stateBlock->pixelShaderConstantI[4 * i + 1];
362             val[2] = stateBlock->pixelShaderConstantI[4 * i + 2];
363             val[3] = -1.0;
364
365             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, gl_shader->int_consts[i], val));
366         }
367     }
368     checkGLcall("Load ps int consts\n");
369 }
370
371 static inline void shader_arb_vs_local_constants(IWineD3DDeviceImpl* deviceImpl)
372 {
373     IWineD3DStateBlockImpl* stateBlock;
374     const WineD3D_GL_Info *gl_info;
375     unsigned char i;
376     struct shader_arb_priv *priv = deviceImpl->shader_priv;
377     const struct arb_vs_compiled_shader *gl_shader = priv->compiled_vprog;
378
379     if(gl_shader->num_int_consts == 0) return;
380
381     gl_info = &deviceImpl->adapter->gl_info;
382     stateBlock = deviceImpl->stateBlock;
383
384     for(i = 0; i < MAX_CONST_I; i++)
385     {
386         if(gl_shader->int_consts[i] != WINED3D_CONST_NUM_UNUSED)
387         {
388             float val[4];
389             val[0] = stateBlock->vertexShaderConstantI[4 * i];
390             val[1] = stateBlock->vertexShaderConstantI[4 * i + 1];
391             val[2] = stateBlock->vertexShaderConstantI[4 * i + 2];
392             val[3] = -1.0;
393
394             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, gl_shader->int_consts[i], val));
395         }
396     }
397     checkGLcall("Load vs int consts\n");
398 }
399
400 /**
401  * Loads the app-supplied constants into the currently set ARB_[vertex/fragment]_programs.
402  * 
403  * We only support float constants in ARB at the moment, so don't 
404  * worry about the Integers or Booleans
405  */
406 /* GL locking is done by the caller (state handler) */
407 static void shader_arb_load_constants(
408     IWineD3DDevice* device,
409     char usePixelShader,
410     char useVertexShader) {
411    
412     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) device; 
413     IWineD3DStateBlockImpl* stateBlock = deviceImpl->stateBlock;
414     const WineD3D_GL_Info *gl_info = &deviceImpl->adapter->gl_info;
415
416     if (useVertexShader) {
417         IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
418
419         /* Load DirectX 9 float constants for vertex shader */
420         deviceImpl->highest_dirty_vs_const = shader_arb_load_constantsF(
421                 vshader, gl_info, GL_VERTEX_PROGRAM_ARB,
422                 deviceImpl->highest_dirty_vs_const,
423                 stateBlock->vertexShaderConstantF,
424                 deviceImpl->activeContext->vshader_const_dirty);
425
426         /* Upload the position fixup */
427         GL_EXTCALL(glProgramEnvParameter4fvARB(GL_VERTEX_PROGRAM_ARB, ARB_SHADER_PRIVCONST_POS, deviceImpl->posFixup));
428
429         shader_arb_vs_local_constants(deviceImpl);
430     }
431
432     if (usePixelShader) {
433         IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
434
435         /* Load DirectX 9 float constants for pixel shader */
436         deviceImpl->highest_dirty_ps_const = shader_arb_load_constantsF(
437                 pshader, gl_info, GL_FRAGMENT_PROGRAM_ARB,
438                 deviceImpl->highest_dirty_ps_const,
439                 stateBlock->pixelShaderConstantF,
440                 deviceImpl->activeContext->pshader_const_dirty);
441         shader_arb_ps_local_constants(deviceImpl);
442     }
443 }
444
445 static void shader_arb_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
446 {
447     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
448
449     /* We don't want shader constant dirtification to be an O(contexts), so just dirtify the active
450      * context. On a context switch the old context will be fully dirtified */
451     memset(This->activeContext->vshader_const_dirty + start, 1,
452             sizeof(*This->activeContext->vshader_const_dirty) * count);
453     This->highest_dirty_vs_const = max(This->highest_dirty_vs_const, start + count + 1);
454 }
455
456 static void shader_arb_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
457 {
458     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
459
460     /* We don't want shader constant dirtification to be an O(contexts), so just dirtify the active
461      * context. On a context switch the old context will be fully dirtified */
462     memset(This->activeContext->pshader_const_dirty + start, 1,
463             sizeof(*This->activeContext->pshader_const_dirty) * count);
464     This->highest_dirty_ps_const = max(This->highest_dirty_ps_const, start + count + 1);
465 }
466
467 static DWORD *local_const_mapping(IWineD3DBaseShaderImpl *This)
468 {
469     DWORD *ret;
470     DWORD idx = 0;
471     const local_constant *lconst;
472
473     if(This->baseShader.load_local_constsF || list_empty(&This->baseShader.constantsF)) return NULL;
474
475     ret = HeapAlloc(GetProcessHeap(), 0, sizeof(DWORD) * This->baseShader.limits.constant_float);
476     if(!ret) {
477         ERR("Out of memory\n");
478         return NULL;
479     }
480
481     LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
482         ret[lconst->idx] = idx++;
483     }
484     return ret;
485 }
486
487 /* Generate the variable & register declarations for the ARB_vertex_program output target */
488 static DWORD shader_generate_arb_declarations(IWineD3DBaseShader *iface, const shader_reg_maps *reg_maps,
489         SHADER_BUFFER *buffer, const WineD3D_GL_Info *gl_info, DWORD *lconst_map)
490 {
491     IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
492     DWORD i, next_local = 0;
493     char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
494     unsigned max_constantsF;
495     const local_constant *lconst;
496
497     /* In pixel shaders, all private constants are program local, we don't need anything
498      * from program.env. Thus we can advertise the full set of constants in pixel shaders.
499      * If we need a private constant the GL implementation will squeeze it in somewhere
500      *
501      * With vertex shaders we need the posFixup and on some GL implementations 4 helper
502      * immediate values. The posFixup is loaded using program.env for now, so always
503      * subtract one from the number of constants. If the shader uses indirect addressing,
504      * account for the helper const too because we have to declare all availabke d3d constants
505      * and don't know which are actually used.
506      */
507     if(pshader) {
508         max_constantsF = GL_LIMITS(pshader_constantsF);
509     } else {
510         if(This->baseShader.reg_maps.usesrelconstF) {
511             max_constantsF = GL_LIMITS(vshader_constantsF) - reserved_vs_const(iface, gl_info);
512             if(GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION)) max_constantsF -= GL_LIMITS(clipplanes);
513             max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
514         } else {
515             max_constantsF = GL_LIMITS(vshader_constantsF) - 1;
516         }
517     }
518
519     for(i = 0; i < This->baseShader.limits.temporary; i++) {
520         if (reg_maps->temporary[i])
521             shader_addline(buffer, "TEMP R%u;\n", i);
522     }
523
524     for (i = 0; i < This->baseShader.limits.address; i++) {
525         if (reg_maps->address[i])
526             shader_addline(buffer, "ADDRESS A%d;\n", i);
527     }
528
529     if(pshader && reg_maps->shader_version.major == 1 && reg_maps->shader_version.minor <= 3) {
530         for(i = 0; i < This->baseShader.limits.texcoord; i++) {
531             if (reg_maps->texcoord[i] && pshader)
532                 shader_addline(buffer,"TEMP T%u;\n", i);
533         }
534     }
535
536     /* Load local constants using the program-local space,
537      * this avoids reloading them each time the shader is used
538      */
539     if(lconst_map) {
540         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
541             shader_addline(buffer, "PARAM C%u = program.local[%u];\n", lconst->idx,
542                            lconst_map[lconst->idx]);
543             next_local = max(next_local, lconst_map[lconst->idx] + 1);
544         }
545     }
546
547     /* we use the array-based constants array if the local constants are marked for loading,
548      * because then we use indirect addressing, or when the local constant list is empty,
549      * because then we don't know if we're using indirect addressing or not. If we're hardcoding
550      * local constants do not declare the loaded constants as an array because ARB compilers usually
551      * do not optimize unused constants away
552      */
553     if(This->baseShader.reg_maps.usesrelconstF) {
554         /* Need to PARAM the environment parameters (constants) so we can use relative addressing */
555         shader_addline(buffer, "PARAM C[%d] = { program.env[0..%d] };\n",
556                     max_constantsF, max_constantsF - 1);
557     } else {
558         for(i = 0; i < max_constantsF; i++) {
559             DWORD idx, mask;
560             idx = i >> 5;
561             mask = 1 << (i & 0x1f);
562             if(!shader_constant_is_local(This, i) && (This->baseShader.reg_maps.constf[idx] & mask)) {
563                 shader_addline(buffer, "PARAM C%d = program.env[%d];\n",i, i);
564             }
565         }
566     }
567
568     return next_local;
569 }
570
571 static const char * const shift_tab[] = {
572     "dummy",     /*  0 (none) */
573     "coefmul.x", /*  1 (x2)   */
574     "coefmul.y", /*  2 (x4)   */
575     "coefmul.z", /*  3 (x8)   */
576     "coefmul.w", /*  4 (x16)  */
577     "dummy",     /*  5 (x32)  */
578     "dummy",     /*  6 (x64)  */
579     "dummy",     /*  7 (x128) */
580     "dummy",     /*  8 (d256) */
581     "dummy",     /*  9 (d128) */
582     "dummy",     /* 10 (d64)  */
583     "dummy",     /* 11 (d32)  */
584     "coefdiv.w", /* 12 (d16)  */
585     "coefdiv.z", /* 13 (d8)   */
586     "coefdiv.y", /* 14 (d4)   */
587     "coefdiv.x"  /* 15 (d2)   */
588 };
589
590 static void shader_arb_get_write_mask(const struct wined3d_shader_instruction *ins,
591         const struct wined3d_shader_dst_param *dst, char *write_mask)
592 {
593     char *ptr = write_mask;
594
595     if (dst->write_mask != WINED3DSP_WRITEMASK_ALL)
596     {
597         *ptr++ = '.';
598         if (dst->write_mask & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
599         if (dst->write_mask & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
600         if (dst->write_mask & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
601         if (dst->write_mask & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
602     }
603
604     *ptr = '\0';
605 }
606
607 static void shader_arb_get_swizzle(const struct wined3d_shader_src_param *param, BOOL fixup, char *swizzle_str)
608 {
609     /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
610      * but addressed as "rgba". To fix this we need to swap the register's x
611      * and z components. */
612     const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
613     char *ptr = swizzle_str;
614
615     /* swizzle bits fields: wwzzyyxx */
616     DWORD swizzle = param->swizzle;
617     DWORD swizzle_x = swizzle & 0x03;
618     DWORD swizzle_y = (swizzle >> 2) & 0x03;
619     DWORD swizzle_z = (swizzle >> 4) & 0x03;
620     DWORD swizzle_w = (swizzle >> 6) & 0x03;
621
622     /* If the swizzle is the default swizzle (ie, "xyzw"), we don't need to
623      * generate a swizzle string. Unless we need to our own swizzling. */
624     if (swizzle != WINED3DSP_NOSWIZZLE || fixup)
625     {
626         *ptr++ = '.';
627         if (swizzle_x == swizzle_y && swizzle_x == swizzle_z && swizzle_x == swizzle_w) {
628             *ptr++ = swizzle_chars[swizzle_x];
629         } else {
630             *ptr++ = swizzle_chars[swizzle_x];
631             *ptr++ = swizzle_chars[swizzle_y];
632             *ptr++ = swizzle_chars[swizzle_z];
633             *ptr++ = swizzle_chars[swizzle_w];
634         }
635     }
636
637     *ptr = '\0';
638 }
639
640 static void shader_arb_request_a0(const struct wined3d_shader_instruction *ins, const char *src)
641 {
642     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
643     SHADER_BUFFER *buffer = ins->ctx->buffer;
644
645     if(strcmp(priv->addr_reg, src) == 0) return;
646
647     strcpy(priv->addr_reg, src);
648     shader_addline(buffer, "ARL A0.x, %s;\n", src);
649 }
650
651 static void shader_arb_get_src_param(const struct wined3d_shader_instruction *ins,
652         const struct wined3d_shader_src_param *src, unsigned int tmpreg, char *outregstr);
653
654 static void shader_arb_get_register_name(const struct wined3d_shader_instruction *ins,
655         const struct wined3d_shader_register *reg, char *register_name, BOOL *is_color)
656 {
657     /* oPos, oFog and oPts in D3D */
658     static const char * const rastout_reg_names[] = {"TMP_OUT", "result.fogcoord", "result.pointsize"};
659     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
660     BOOL pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
661     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
662
663     *is_color = FALSE;
664
665     switch (reg->type)
666     {
667         case WINED3DSPR_TEMP:
668             sprintf(register_name, "R%u", reg->idx);
669             break;
670
671         case WINED3DSPR_INPUT:
672             if (pshader)
673             {
674                 if (reg->idx == 0) strcpy(register_name, "fragment.color.primary");
675                 else strcpy(register_name, "fragment.color.secondary");
676             }
677             else
678             {
679                 if (ctx->cur_vs_args->super.swizzle_map & (1 << reg->idx)) *is_color = TRUE;
680                 sprintf(register_name, "vertex.attrib[%u]", reg->idx);
681             }
682             break;
683
684         case WINED3DSPR_CONST:
685             if (!pshader && reg->rel_addr)
686             {
687                 BOOL aL = FALSE;
688                 char rel_reg[50];
689                 UINT rel_offset = ((IWineD3DVertexShaderImpl *)This)->rel_offset;
690                 if(This->baseShader.reg_maps.shader_version.major < 2) {
691                     sprintf(rel_reg, "A0.x");
692                 } else {
693                     shader_arb_get_src_param(ins, reg->rel_addr, 0, rel_reg);
694                     if(ctx->target_version == ARB) {
695                         if(strcmp(rel_reg, "**aL_emul**") == 0) {
696                             aL = TRUE;
697                         } else {
698                             shader_arb_request_a0(ins, rel_reg);
699                             sprintf(rel_reg, "A0.x");
700                         }
701                     }
702                 }
703                 if(aL)
704                     sprintf(register_name, "C[%u]", ctx->aL + reg->idx);
705                 else if (reg->idx >= rel_offset)
706                     sprintf(register_name, "C[%s + %u]", rel_reg, reg->idx - rel_offset);
707                 else
708                     sprintf(register_name, "C[%s - %u]", rel_reg, -reg->idx + rel_offset);
709             }
710             else
711             {
712                 if (This->baseShader.reg_maps.usesrelconstF)
713                     sprintf(register_name, "C[%u]", reg->idx);
714                 else
715                     sprintf(register_name, "C%u", reg->idx);
716             }
717             break;
718
719         case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
720             if (pshader) {
721                 if(This->baseShader.reg_maps.shader_version.major == 1 &&
722                    This->baseShader.reg_maps.shader_version.minor <= 3) {
723                     /* In ps <= 1.3, Tx is a temporary register as destination to all instructions,
724                      * and as source to most instructions. For some instructions it is the texcoord
725                      * input. Those instructions know about the special use
726                      */
727                     sprintf(register_name, "T%u", reg->idx);
728                 } else {
729                     /* in ps 1.4 and 2.x Tx is always a (read-only) varying */
730                     sprintf(register_name, "fragment.texcoord[%u]", reg->idx);
731                 }
732             }
733             else
734             {
735                 if(This->baseShader.reg_maps.shader_version.major == 1 || ctx->target_version >= NV2)
736                 {
737                     sprintf(register_name, "A%u", reg->idx);
738                 }
739                 else
740                 {
741                     sprintf(register_name, "A%u_SHADOW", reg->idx);
742                 }
743             }
744             break;
745
746         case WINED3DSPR_COLOROUT:
747             if (reg->idx == 0)
748             {
749                 if(ctx->cur_ps_args->super.srgb_correction)
750                 {
751                     strcpy(register_name, "TMP_COLOR");
752                 }
753                 else
754                 {
755                     strcpy(register_name, "result.color");
756                 }
757             }
758             else
759             {
760                 /* TODO: See GL_ARB_draw_buffers */
761                 FIXME("Unsupported write to render target %u\n", reg->idx);
762                 sprintf(register_name, "unsupported_register");
763             }
764             break;
765
766         case WINED3DSPR_RASTOUT:
767             sprintf(register_name, "%s", rastout_reg_names[reg->idx]);
768             break;
769
770         case WINED3DSPR_DEPTHOUT:
771             strcpy(register_name, "result.depth");
772             break;
773
774         case WINED3DSPR_ATTROUT:
775             if (pshader) sprintf(register_name, "oD[%u]", reg->idx);
776             else if (reg->idx == 0) strcpy(register_name, "result.color.primary");
777             else strcpy(register_name, "result.color.secondary");
778             break;
779
780         case WINED3DSPR_TEXCRDOUT:
781             if (pshader) sprintf(register_name, "oT[%u]", reg->idx);
782             else sprintf(register_name, "result.texcoord[%u]", reg->idx);
783             break;
784
785         case WINED3DSPR_LOOP:
786             if(ctx->target_version >= NV2)
787             {
788                 /* Pshader has an implicitly declared loop index counter A0.x that cannot be renamed */
789                 if(pshader) sprintf(register_name, "A0.x");
790                 else sprintf(register_name, "aL.y");
791             }
792             else
793             {
794                 /* Unfortunately this code cannot return the value of ctx->aL here. An immediate value
795                  * would be valid, but if aL is used for indexing(its only use), there's likely an offset,
796                  * thus the result would be something like C[15 + 30], which is not valid in the ARB program
797                  * grammar. So return a marker for the emulated aL and intercept it in constant and varying
798                  * indexing
799                  */
800                 sprintf(register_name, "**aL_emul**");
801             }
802
803             break;
804
805         case WINED3DSPR_CONSTINT:
806             sprintf(register_name, "I%u", reg->idx);
807             break;
808
809         case WINED3DSPR_MISCTYPE:
810             if(reg->idx == 0)
811             {
812                 sprintf(register_name, "vpos");
813             }
814             else if(reg->idx == 1)
815             {
816                 sprintf(register_name, "fragment.facing.x");
817             }
818             else
819             {
820                 FIXME("Unknown MISCTYPE register index %u\n", reg->idx);
821             }
822             break;
823
824         default:
825             FIXME("Unhandled register type %#x[%u]\n", reg->type, reg->idx);
826             sprintf(register_name, "unrecognized_register[%u]", reg->idx);
827             break;
828     }
829 }
830
831 static void shader_arb_get_dst_param(const struct wined3d_shader_instruction *ins,
832         const struct wined3d_shader_dst_param *wined3d_dst, char *str)
833 {
834     char register_name[255];
835     char write_mask[6];
836     BOOL is_color;
837
838     shader_arb_get_register_name(ins, &wined3d_dst->reg, register_name, &is_color);
839     strcpy(str, register_name);
840
841     shader_arb_get_write_mask(ins, wined3d_dst, write_mask);
842     strcat(str, write_mask);
843 }
844
845 static const char *shader_arb_get_fixup_swizzle(enum fixup_channel_source channel_source)
846 {
847     switch(channel_source)
848     {
849         case CHANNEL_SOURCE_ZERO: return "0";
850         case CHANNEL_SOURCE_ONE: return "1";
851         case CHANNEL_SOURCE_X: return "x";
852         case CHANNEL_SOURCE_Y: return "y";
853         case CHANNEL_SOURCE_Z: return "z";
854         case CHANNEL_SOURCE_W: return "w";
855         default:
856             FIXME("Unhandled channel source %#x\n", channel_source);
857             return "undefined";
858     }
859 }
860
861 static void gen_color_correction(SHADER_BUFFER *buffer, const char *reg, DWORD dst_mask,
862                                  const char *one, const char *two, struct color_fixup_desc fixup)
863 {
864     DWORD mask;
865
866     if (is_yuv_fixup(fixup))
867     {
868         enum yuv_fixup yuv_fixup = get_yuv_fixup(fixup);
869         FIXME("YUV fixup (%#x) not supported\n", yuv_fixup);
870         return;
871     }
872
873     mask = 0;
874     if (fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
875     if (fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
876     if (fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
877     if (fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
878     mask &= dst_mask;
879
880     if (mask)
881     {
882         shader_addline(buffer, "SWZ %s, %s, %s, %s, %s, %s;\n", reg, reg,
883                 shader_arb_get_fixup_swizzle(fixup.x_source), shader_arb_get_fixup_swizzle(fixup.y_source),
884                 shader_arb_get_fixup_swizzle(fixup.z_source), shader_arb_get_fixup_swizzle(fixup.w_source));
885     }
886
887     mask = 0;
888     if (fixup.x_sign_fixup) mask |= WINED3DSP_WRITEMASK_0;
889     if (fixup.y_sign_fixup) mask |= WINED3DSP_WRITEMASK_1;
890     if (fixup.z_sign_fixup) mask |= WINED3DSP_WRITEMASK_2;
891     if (fixup.w_sign_fixup) mask |= WINED3DSP_WRITEMASK_3;
892     mask &= dst_mask;
893
894     if (mask)
895     {
896         char reg_mask[6];
897         char *ptr = reg_mask;
898
899         if (mask != WINED3DSP_WRITEMASK_ALL)
900         {
901             *ptr++ = '.';
902             if (mask & WINED3DSP_WRITEMASK_0) *ptr++ = 'x';
903             if (mask & WINED3DSP_WRITEMASK_1) *ptr++ = 'y';
904             if (mask & WINED3DSP_WRITEMASK_2) *ptr++ = 'z';
905             if (mask & WINED3DSP_WRITEMASK_3) *ptr++ = 'w';
906         }
907         *ptr = '\0';
908
909         shader_addline(buffer, "MAD %s%s, %s, %s, -%s;\n", reg, reg_mask, reg, two, one);
910     }
911 }
912
913 static const char *shader_arb_get_modifier(const struct wined3d_shader_instruction *ins)
914 {
915     DWORD mod;
916     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
917     if (!ins->dst_count) return "";
918
919     mod = ins->dst[0].modifiers;
920
921     /* Silently ignore PARTIALPRECISION if its not supported */
922     if(priv->target_version == ARB) mod &= ~WINED3DSPDM_PARTIALPRECISION;
923
924     if(mod & WINED3DSPDM_MSAMPCENTROID)
925     {
926         FIXME("Unhandled modifier WINED3DSPDM_MSAMPCENTROID\n");
927         mod &= ~WINED3DSPDM_MSAMPCENTROID;
928     }
929
930     switch(mod)
931     {
932         case WINED3DSPDM_SATURATE | WINED3DSPDM_PARTIALPRECISION:
933             return "H_SAT";
934
935         case WINED3DSPDM_SATURATE:
936             return "_SAT";
937
938         case WINED3DSPDM_PARTIALPRECISION:
939             return "H";
940
941         case 0:
942             return "";
943
944         default:
945             FIXME("Unknown modifiers 0x%08x\n", mod);
946             return "";
947     }
948 }
949
950 #define TEX_PROJ        0x1
951 #define TEX_BIAS        0x2
952 #define TEX_LOD         0x4
953 #define TEX_DERIV       0x10
954
955 static void shader_hw_sample(const struct wined3d_shader_instruction *ins, DWORD sampler_idx,
956         const char *dst_str, const char *coord_reg, WORD flags, const char *dsx, const char *dsy)
957 {
958     SHADER_BUFFER *buffer = ins->ctx->buffer;
959     DWORD sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
960     const char *tex_type;
961     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
962     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
963     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
964     const char *mod;
965
966     switch(sampler_type) {
967         case WINED3DSTT_1D:
968             tex_type = "1D";
969             break;
970
971         case WINED3DSTT_2D:
972             if(device->stateBlock->textures[sampler_idx] &&
973                IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
974                 tex_type = "RECT";
975             } else {
976                 tex_type = "2D";
977             }
978             if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
979             {
980                 if(priv->cur_ps_args->super.np2_fixup & (1 << sampler_idx))
981                 {
982                     FIXME("NP2 texcoord fixup is currently not implemented in ARB mode (use GLSL instead).\n");
983                 }
984             }
985             break;
986
987         case WINED3DSTT_VOLUME:
988             tex_type = "3D";
989             break;
990
991         case WINED3DSTT_CUBE:
992             tex_type = "CUBE";
993             break;
994
995         default:
996             ERR("Unexpected texture type %d\n", sampler_type);
997             tex_type = "";
998     }
999
1000     /* TEX, TXL, TXD and TXP do not support the "H" modifier,
1001      * so don't use shader_arb_get_modifier
1002      */
1003     if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE) mod = "_SAT";
1004     else mod = "";
1005
1006     if (flags & TEX_DERIV)
1007     {
1008         if(flags & TEX_PROJ) FIXME("Projected texture sampling with custom derivates\n");
1009         if(flags & TEX_BIAS) FIXME("Biased texture sampling with custom derivates\n");
1010         shader_addline(buffer, "TXD%s %s, %s, %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg,
1011                        dsx, dsy,sampler_idx, tex_type);
1012     }
1013     else if(flags & TEX_LOD)
1014     {
1015         if(flags & TEX_PROJ) FIXME("Projected texture sampling with explicit lod\n");
1016         if(flags & TEX_BIAS) FIXME("Biased texture sampling with explicit lod\n");
1017         shader_addline(buffer, "TXL%s %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg,
1018                        sampler_idx, tex_type);
1019     }
1020     else if (flags & TEX_BIAS)
1021     {
1022         /* Shouldn't be possible, but let's check for it */
1023         if(flags & TEX_PROJ) FIXME("Biased and Projected texture sampling\n");
1024         /* TXB takes the 4th component of the source vector automatically, as d3d. Nothing more to do */
1025         shader_addline(buffer, "TXB%s %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg, sampler_idx, tex_type);
1026     }
1027     else if (flags & TEX_PROJ)
1028     {
1029         shader_addline(buffer, "TXP%s %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg, sampler_idx, tex_type);
1030     }
1031     else
1032     {
1033         shader_addline(buffer, "TEX%s %s, %s, texture[%u], %s;\n", mod, dst_str, coord_reg, sampler_idx, tex_type);
1034     }
1035
1036     if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
1037     {
1038         gen_color_correction(buffer, dst_str, ins->dst[0].write_mask,
1039                 "one", "coefmul.x", priv->cur_ps_args->super.color_fixup[sampler_idx]);
1040     }
1041 }
1042
1043 static void shader_arb_get_src_param(const struct wined3d_shader_instruction *ins,
1044         const struct wined3d_shader_src_param *src, unsigned int tmpreg, char *outregstr)
1045 {
1046     /* Generate a line that does the input modifier computation and return the input register to use */
1047     BOOL is_color = FALSE;
1048     char regstr[256];
1049     char swzstr[20];
1050     int insert_line;
1051     SHADER_BUFFER *buffer = ins->ctx->buffer;
1052     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
1053
1054     /* Assume a new line will be added */
1055     insert_line = 1;
1056
1057     /* Get register name */
1058     shader_arb_get_register_name(ins, &src->reg, regstr, &is_color);
1059     shader_arb_get_swizzle(src, is_color, swzstr);
1060
1061     switch (src->modifiers)
1062     {
1063     case WINED3DSPSM_NONE:
1064         sprintf(outregstr, "%s%s", regstr, swzstr);
1065         insert_line = 0;
1066         break;
1067     case WINED3DSPSM_NEG:
1068         sprintf(outregstr, "-%s%s", regstr, swzstr);
1069         insert_line = 0;
1070         break;
1071     case WINED3DSPSM_BIAS:
1072         shader_addline(buffer, "ADD T%c, %s, -coefdiv.x;\n", 'A' + tmpreg, regstr);
1073         break;
1074     case WINED3DSPSM_BIASNEG:
1075         shader_addline(buffer, "ADD T%c, -%s, coefdiv.x;\n", 'A' + tmpreg, regstr);
1076         break;
1077     case WINED3DSPSM_SIGN:
1078         shader_addline(buffer, "MAD T%c, %s, coefmul.x, -one.x;\n", 'A' + tmpreg, regstr);
1079         break;
1080     case WINED3DSPSM_SIGNNEG:
1081         shader_addline(buffer, "MAD T%c, %s, -coefmul.x, one.x;\n", 'A' + tmpreg, regstr);
1082         break;
1083     case WINED3DSPSM_COMP:
1084         shader_addline(buffer, "SUB T%c, one.x, %s;\n", 'A' + tmpreg, regstr);
1085         break;
1086     case WINED3DSPSM_X2:
1087         shader_addline(buffer, "ADD T%c, %s, %s;\n", 'A' + tmpreg, regstr, regstr);
1088         break;
1089     case WINED3DSPSM_X2NEG:
1090         shader_addline(buffer, "ADD T%c, -%s, -%s;\n", 'A' + tmpreg, regstr, regstr);
1091         break;
1092     case WINED3DSPSM_DZ:
1093         shader_addline(buffer, "RCP T%c, %s.z;\n", 'A' + tmpreg, regstr);
1094         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
1095         break;
1096     case WINED3DSPSM_DW:
1097         shader_addline(buffer, "RCP T%c, %s.w;\n", 'A' + tmpreg, regstr);
1098         shader_addline(buffer, "MUL T%c, %s, T%c;\n", 'A' + tmpreg, regstr, 'A' + tmpreg);
1099         break;
1100     case WINED3DSPSM_ABS:
1101         if(ctx->target_version >= NV2) {
1102             sprintf(outregstr, "|%s%s|", regstr, swzstr);
1103             insert_line = 0;
1104         } else {
1105             shader_addline(buffer, "ABS T%c, %s;\n", 'A' + tmpreg, regstr);
1106         }
1107         break;
1108     case WINED3DSPSM_ABSNEG:
1109         if(ctx->target_version >= NV2) {
1110             sprintf(outregstr, "-|%s%s|", regstr, swzstr);
1111         } else {
1112             shader_addline(buffer, "ABS T%c, %s;\n", 'A' + tmpreg, regstr);
1113             sprintf(outregstr, "-T%c%s", 'A' + tmpreg, swzstr);
1114         }
1115         insert_line = 0;
1116         break;
1117     default:
1118         sprintf(outregstr, "%s%s", regstr, swzstr);
1119         insert_line = 0;
1120     }
1121
1122     /* Return modified or original register, with swizzle */
1123     if (insert_line)
1124         sprintf(outregstr, "T%c%s", 'A' + tmpreg, swzstr);
1125 }
1126
1127 static void pshader_hw_bem(const struct wined3d_shader_instruction *ins)
1128 {
1129     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1130     SHADER_BUFFER *buffer = ins->ctx->buffer;
1131     char dst_name[50];
1132     char src_name[2][50];
1133     DWORD sampler_code = dst->reg.idx;
1134
1135     shader_arb_get_dst_param(ins, dst, dst_name);
1136
1137     /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed
1138      *
1139      * Keep in mind that src_name[1] can be "TB" and src_name[0] can be "TA" because modifiers like _x2 are valid
1140      * with bem. So delay loading the first parameter until after the perturbation calculation which needs two
1141      * temps is done.
1142      */
1143     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1144     shader_addline(buffer, "SWZ TA, bumpenvmat%d, x, z, 0, 0;\n", sampler_code);
1145     shader_addline(buffer, "DP3 TC.r, TA, %s;\n", src_name[1]);
1146     shader_addline(buffer, "SWZ TA, bumpenvmat%d, y, w, 0, 0;\n", sampler_code);
1147     shader_addline(buffer, "DP3 TC.g, TA, %s;\n", src_name[1]);
1148
1149     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name[0]);
1150     shader_addline(buffer, "ADD %s, %s, TC;\n", dst_name, src_name[0]);
1151 }
1152
1153 static void pshader_hw_cnd(const struct wined3d_shader_instruction *ins)
1154 {
1155     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1156     SHADER_BUFFER *buffer = ins->ctx->buffer;
1157     char dst_name[50];
1158     char src_name[3][50];
1159     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
1160             ins->ctx->reg_maps->shader_version.minor);
1161     BOOL is_color;
1162
1163     shader_arb_get_dst_param(ins, dst, dst_name);
1164     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1165
1166     /* The coissue flag changes the semantic of the cnd instruction in <= 1.3 shaders */
1167     if (shader_version <= WINED3D_SHADER_VERSION(1, 3) && ins->coissue)
1168     {
1169         shader_addline(buffer, "MOV%s %s, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name[1]);
1170     } else {
1171         shader_arb_get_src_param(ins, &ins->src[0], 0, src_name[0]);
1172         shader_arb_get_src_param(ins, &ins->src[2], 2, src_name[2]);
1173         shader_addline(buffer, "ADD TA, -%s, coefdiv.x;\n", src_name[0]);
1174         /* No modifiers supported on CMP */
1175         shader_addline(buffer, "CMP %s, TA, %s, %s;\n", dst_name, src_name[1], src_name[2]);
1176
1177         /* _SAT on CMP doesn't make much sense, but it is not a pure NOP */
1178         if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE)
1179         {
1180             shader_arb_get_register_name(ins, &dst->reg, src_name[0], &is_color);
1181             shader_addline(buffer, "MOV_SAT %s, %s;\n", dst_name, dst_name);
1182         }
1183     }
1184 }
1185
1186 static void pshader_hw_cmp(const struct wined3d_shader_instruction *ins)
1187 {
1188     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1189     SHADER_BUFFER *buffer = ins->ctx->buffer;
1190     char dst_name[50];
1191     char src_name[3][50];
1192     BOOL is_color;
1193
1194     shader_arb_get_dst_param(ins, dst, dst_name);
1195
1196     /* Generate input register names (with modifiers) */
1197     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name[0]);
1198     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1199     shader_arb_get_src_param(ins, &ins->src[2], 2, src_name[2]);
1200
1201     /* No modifiers are supported on CMP */
1202     shader_addline(buffer, "CMP %s, %s, %s, %s;\n", dst_name,
1203                    src_name[0], src_name[2], src_name[1]);
1204
1205     if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE)
1206     {
1207         shader_arb_get_register_name(ins, &dst->reg, src_name[0], &is_color);
1208         shader_addline(buffer, "MOV_SAT %s, %s;\n", dst_name, src_name[0]);
1209     }
1210 }
1211
1212 /** Process the WINED3DSIO_DP2ADD instruction in ARB.
1213  * dst = dot2(src0, src1) + src2 */
1214 static void pshader_hw_dp2add(const struct wined3d_shader_instruction *ins)
1215 {
1216     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1217     SHADER_BUFFER *buffer = ins->ctx->buffer;
1218     char dst_name[50];
1219     char src_name[3][50];
1220     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
1221
1222     shader_arb_get_dst_param(ins, dst, dst_name);
1223     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name[0]);
1224     shader_arb_get_src_param(ins, &ins->src[2], 2, src_name[2]);
1225
1226     if(ctx->target_version >= NV3)
1227     {
1228         /* GL_NV_fragment_program2 has a 1:1 matching instruction */
1229         shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1230         shader_addline(buffer, "DP2A%s %s, %s, %s, %s;\n", shader_arb_get_modifier(ins),
1231                        dst_name, src_name[0], src_name[1], src_name[2]);
1232     }
1233     else if(ctx->target_version >= NV2)
1234     {
1235         /* dst.x = src2.?, src0.x, src1.x + src0.y * src1.y
1236          * dst.y = src2.?, src0.x, src1.z + src0.y * src1.w
1237          * dst.z = src2.?, src0.x, src1.x + src0.y * src1.y
1238          * dst.z = src2.?, src0.x, src1.z + src0.y * src1.w
1239          *
1240          * Make sure that src1.zw = src1.xy, then we get a classic dp2add
1241          *
1242          * .xyxy and other swizzles that we could get with this are not valid in
1243          * plain ARBfp, but luckily the NV extension grammar lifts this limitation.
1244          */
1245         struct wined3d_shader_src_param tmp_param = ins->src[1];
1246         DWORD swizzle = tmp_param.swizzle & 0xf; /* Selects .xy */
1247         tmp_param.swizzle = swizzle | (swizzle << 4); /* Creates .xyxy */
1248
1249         shader_arb_get_src_param(ins, &tmp_param, 1, src_name[1]);
1250
1251         shader_addline(buffer, "X2D%s %s, %s, %s, %s;\n", shader_arb_get_modifier(ins),
1252                        dst_name, src_name[2], src_name[0], src_name[1]);
1253     }
1254     else
1255     {
1256         shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
1257         /* Emulate a DP2 with a DP3 and 0.0. Don't use the dest as temp register, it could be src[1] or src[2]
1258         * src_name[0] can be TA, but TA is a private temp for modifiers, so it is save to overwrite
1259         */
1260         shader_addline(buffer, "MOV TA, %s;\n", src_name[0]);
1261         shader_addline(buffer, "MOV TA.z, 0.0;\n");
1262         shader_addline(buffer, "DP3 TA, TA, %s;\n", src_name[1]);
1263         shader_addline(buffer, "ADD%s %s, TA, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name[2]);
1264     }
1265 }
1266
1267 /* Map the opcode 1-to-1 to the GL code */
1268 static void shader_hw_map2gl(const struct wined3d_shader_instruction *ins)
1269 {
1270     SHADER_BUFFER *buffer = ins->ctx->buffer;
1271     const char *instruction;
1272     char arguments[256], dst_str[50];
1273     unsigned int i;
1274     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1275
1276     switch (ins->handler_idx)
1277     {
1278         case WINED3DSIH_ABS: instruction = "ABS"; break;
1279         case WINED3DSIH_ADD: instruction = "ADD"; break;
1280         case WINED3DSIH_CRS: instruction = "XPD"; break;
1281         case WINED3DSIH_DP3: instruction = "DP3"; break;
1282         case WINED3DSIH_DP4: instruction = "DP4"; break;
1283         case WINED3DSIH_DST: instruction = "DST"; break;
1284         case WINED3DSIH_EXP: instruction = "EX2"; break;
1285         case WINED3DSIH_EXPP: instruction = "EXP"; break;
1286         case WINED3DSIH_FRC: instruction = "FRC"; break;
1287         case WINED3DSIH_LIT: instruction = "LIT"; break;
1288         case WINED3DSIH_LOG: instruction = "LG2"; break;
1289         case WINED3DSIH_LOGP: instruction = "LOG"; break;
1290         case WINED3DSIH_LRP: instruction = "LRP"; break;
1291         case WINED3DSIH_MAD: instruction = "MAD"; break;
1292         case WINED3DSIH_MAX: instruction = "MAX"; break;
1293         case WINED3DSIH_MIN: instruction = "MIN"; break;
1294         case WINED3DSIH_MOV: instruction = "MOV"; break;
1295         case WINED3DSIH_MUL: instruction = "MUL"; break;
1296         case WINED3DSIH_POW: instruction = "POW"; break;
1297         case WINED3DSIH_SGE: instruction = "SGE"; break;
1298         case WINED3DSIH_SLT: instruction = "SLT"; break;
1299         case WINED3DSIH_SUB: instruction = "SUB"; break;
1300         case WINED3DSIH_MOVA:instruction = "ARR"; break;
1301         case WINED3DSIH_SGN: instruction = "SSG"; break;
1302         case WINED3DSIH_DSX: instruction = "DDX"; break;
1303         default: instruction = "";
1304             FIXME("Unhandled opcode %#x\n", ins->handler_idx);
1305             break;
1306     }
1307
1308     /* Note that shader_arb_add_dst_param() adds spaces. */
1309     arguments[0] = '\0';
1310     shader_arb_get_dst_param(ins, dst, dst_str);
1311     for (i = 0; i < ins->src_count; ++i)
1312     {
1313         char operand[100];
1314         strcat(arguments, ", ");
1315         shader_arb_get_src_param(ins, &ins->src[i], i, operand);
1316         strcat(arguments, operand);
1317     }
1318     shader_addline(buffer, "%s%s %s%s;\n", instruction, shader_arb_get_modifier(ins), dst_str, arguments);
1319 }
1320
1321 static void shader_hw_nop(const struct wined3d_shader_instruction *ins)
1322 {
1323     SHADER_BUFFER *buffer = ins->ctx->buffer;
1324     shader_addline(buffer, "NOP;\n");
1325 }
1326
1327 static void shader_hw_mov(const struct wined3d_shader_instruction *ins)
1328 {
1329     IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1330     BOOL pshader = shader_is_pshader_version(shader->baseShader.reg_maps.shader_version.type);
1331     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
1332
1333     SHADER_BUFFER *buffer = ins->ctx->buffer;
1334     char src0_param[256];
1335
1336     if(ins->handler_idx == WINED3DSIH_MOVA) {
1337         struct wined3d_shader_src_param tmp_src = ins->src[0];
1338         char write_mask[6];
1339
1340         if(ctx->target_version >= NV2) {
1341             shader_hw_map2gl(ins);
1342             return;
1343         }
1344         tmp_src.swizzle = (tmp_src.swizzle & 0x3) * 0x55;
1345         shader_arb_get_src_param(ins, &tmp_src, 0, src0_param);
1346         shader_arb_get_write_mask(ins, &ins->dst[0], write_mask);
1347
1348         /* This implements the mova formula used in GLSL. The first two instructions
1349          * prepare the sign() part. Note that it is fine to have my_sign(0.0) = 1.0
1350          * in this case:
1351          * mova A0.x, 0.0
1352          *
1353          * A0.x = arl(floor(abs(0.0) + 0.5) * 1.0) = floor(0.5) = 0.0 since arl does a floor
1354          *
1355          * The ARL is performed when A0 is used - the requested component is read from A0_SHADOW into
1356          * A0.x. We can use the overwritten component of A0_shadow as temporary storage for the sign.
1357          */
1358         shader_addline(buffer, "SGE A0_SHADOW%s, %s, mova_const.y;\n", write_mask, src0_param);
1359         shader_addline(buffer, "MAD A0_SHADOW%s, A0_SHADOW, mova_const.z, -mova_const.w;\n", write_mask);
1360
1361         shader_addline(buffer, "ABS TA%s, %s;\n", write_mask, src0_param);
1362         shader_addline(buffer, "ADD TA%s, TA, mova_const.x;\n", write_mask);
1363         shader_addline(buffer, "FLR TA%s, TA;\n", write_mask);
1364         shader_addline(buffer, "MUL A0_SHADOW%s, TA, A0_SHADOW;\n", write_mask);
1365
1366         ((struct shader_arb_ctx_priv *)ins->ctx->backend_data)->addr_reg[0] = '\0';
1367     } else if (ins->ctx->reg_maps->shader_version.major == 1
1368           && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
1369           && ins->dst[0].reg.type == WINED3DSPR_ADDR)
1370     {
1371         src0_param[0] = '\0';
1372         if (((IWineD3DVertexShaderImpl *)shader)->rel_offset)
1373         {
1374             shader_arb_get_src_param(ins, &ins->src[0], 0, src0_param);
1375             shader_addline(buffer, "ADD TA.x, %s, helper_const.z;\n", src0_param);
1376             shader_addline(buffer, "ARL A0.x, TA.x;\n");
1377         }
1378         else
1379         {
1380             /* Apple's ARB_vertex_program implementation does not accept an ARL source argument
1381              * with more than one component. Thus replicate the first source argument over all
1382              * 4 components. For example, .xyzw -> .x (or better: .xxxx), .zwxy -> .z, etc) */
1383             struct wined3d_shader_src_param tmp_src = ins->src[0];
1384             tmp_src.swizzle = (tmp_src.swizzle & 0x3) * 0x55;
1385             shader_arb_get_src_param(ins, &tmp_src, 0, src0_param);
1386             shader_addline(buffer, "ARL A0.x, %s;\n", src0_param);
1387         }
1388     }
1389     else if(ins->dst[0].reg.type == WINED3DSPR_COLOROUT && ins->dst[0].reg.idx == 0 && pshader)
1390     {
1391         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) shader;
1392         if(ctx->cur_ps_args->super.srgb_correction && ps->color0_mov)
1393         {
1394             shader_addline(buffer, "#mov handled in srgb write code\n");
1395             return;
1396         }
1397         shader_hw_map2gl(ins);
1398     }
1399     else
1400     {
1401         shader_hw_map2gl(ins);
1402     }
1403 }
1404
1405 static void pshader_hw_texkill(const struct wined3d_shader_instruction *ins)
1406 {
1407     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1408     SHADER_BUFFER *buffer = ins->ctx->buffer;
1409     char reg_dest[40];
1410
1411     /* No swizzles are allowed in d3d's texkill. PS 1.x ignores the 4th component as documented,
1412      * but >= 2.0 honors it(undocumented, but tested by the d3d9 testsuit)
1413      */
1414     shader_arb_get_dst_param(ins, dst, reg_dest);
1415
1416     if (ins->ctx->reg_maps->shader_version.major >= 2)
1417     {
1418         /* The arb backend doesn't claim ps 2.0 support, but try to eat what the app feeds to us */
1419         shader_arb_get_dst_param(ins, dst, reg_dest);
1420         shader_addline(buffer, "KIL %s;\n", reg_dest);
1421     } else {
1422         /* ARB fp doesn't like swizzles on the parameter of the KIL instruction. To mask the 4th component,
1423          * copy the register into our general purpose TMP variable, overwrite .w and pass TMP to KIL
1424          *
1425          * ps_1_3 shaders use the texcoord incarnation of the Tx register. ps_1_4 shaders can use the same,
1426          * or pass in any temporary register(in shader phase 2)
1427          */
1428         if(ins->ctx->reg_maps->shader_version.minor <= 3) {
1429             sprintf(reg_dest, "fragment.texcoord[%u]", dst->reg.idx);
1430         } else {
1431             shader_arb_get_dst_param(ins, dst, reg_dest);
1432         }
1433         shader_addline(buffer, "SWZ TA, %s, x, y, z, 1;\n", reg_dest);
1434         shader_addline(buffer, "KIL TA;\n");
1435     }
1436 }
1437
1438 static void pshader_hw_tex(const struct wined3d_shader_instruction *ins)
1439 {
1440     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1441     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1442     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1443     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
1444             ins->ctx->reg_maps->shader_version.minor);
1445     struct wined3d_shader_src_param src;
1446
1447     char reg_dest[40];
1448     char reg_coord[40];
1449     DWORD reg_sampler_code;
1450     DWORD myflags = 0;
1451
1452     /* All versions have a destination register */
1453     shader_arb_get_dst_param(ins, dst, reg_dest);
1454
1455     /* 1.0-1.4: Use destination register number as texture code.
1456        2.0+: Use provided sampler number as texure code. */
1457     if (shader_version < WINED3D_SHADER_VERSION(2,0))
1458         reg_sampler_code = dst->reg.idx;
1459     else
1460         reg_sampler_code = ins->src[1].reg.idx;
1461
1462     /* 1.0-1.3: Use the texcoord varying.
1463        1.4+: Use provided coordinate source register. */
1464     if (shader_version < WINED3D_SHADER_VERSION(1,4))
1465         sprintf(reg_coord, "fragment.texcoord[%u]", reg_sampler_code);
1466     else {
1467         /* TEX is the only instruction that can handle DW and DZ natively */
1468         src = ins->src[0];
1469         if(src.modifiers == WINED3DSPSM_DW) src.modifiers = WINED3DSPSM_NONE;
1470         if(src.modifiers == WINED3DSPSM_DZ) src.modifiers = WINED3DSPSM_NONE;
1471         shader_arb_get_src_param(ins, &src, 0, reg_coord);
1472     }
1473
1474     /* projection flag:
1475      * 1.1, 1.2, 1.3: Use WINED3DTSS_TEXTURETRANSFORMFLAGS
1476      * 1.4: Use WINED3DSPSM_DZ or WINED3DSPSM_DW on src[0]
1477      * 2.0+: Use WINED3DSI_TEXLD_PROJECT on the opcode
1478      */
1479     if (shader_version < WINED3D_SHADER_VERSION(1,4))
1480     {
1481         DWORD flags = 0;
1482         if(reg_sampler_code < MAX_TEXTURES) {
1483             flags = deviceImpl->stateBlock->textureState[reg_sampler_code][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1484         }
1485         if (flags & WINED3DTTFF_PROJECTED) {
1486             myflags |= TEX_PROJ;
1487         }
1488     }
1489     else if (shader_version < WINED3D_SHADER_VERSION(2,0))
1490     {
1491         DWORD src_mod = ins->src[0].modifiers;
1492         if (src_mod == WINED3DSPSM_DZ) {
1493             /* TXP cannot handle DZ natively, so move the z coordinate to .w. reg_coord is a read-only
1494              * varying register, so we need a temp reg
1495              */
1496             shader_addline(ins->ctx->buffer, "SWZ TA, %s, x, y, z, z;\n", reg_coord);
1497             strcpy(reg_coord, "TA");
1498             myflags |= TEX_PROJ;
1499         } else if(src_mod == WINED3DSPSM_DW) {
1500             myflags |= TEX_PROJ;
1501         }
1502     } else {
1503         if (ins->flags & WINED3DSI_TEXLD_PROJECT) myflags |= TEX_PROJ;
1504         if (ins->flags & WINED3DSI_TEXLD_BIAS) myflags |= TEX_BIAS;
1505     }
1506     shader_hw_sample(ins, reg_sampler_code, reg_dest, reg_coord, myflags, NULL, NULL);
1507 }
1508
1509 static void pshader_hw_texcoord(const struct wined3d_shader_instruction *ins)
1510 {
1511     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1512     SHADER_BUFFER *buffer = ins->ctx->buffer;
1513     DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
1514             ins->ctx->reg_maps->shader_version.minor);
1515     char dst_str[50];
1516
1517     if (shader_version < WINED3D_SHADER_VERSION(1,4))
1518     {
1519         DWORD reg = dst->reg.idx;
1520
1521         shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1522         shader_addline(buffer, "MOV_SAT %s, fragment.texcoord[%u];\n", dst_str, reg);
1523     } else {
1524         char reg_src[40];
1525
1526         shader_arb_get_src_param(ins, &ins->src[0], 0, reg_src);
1527         shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1528         shader_addline(buffer, "MOV %s, %s;\n", dst_str, reg_src);
1529    }
1530 }
1531
1532 static void pshader_hw_texreg2ar(const struct wined3d_shader_instruction *ins)
1533 {
1534      SHADER_BUFFER *buffer = ins->ctx->buffer;
1535      IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1536      IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1537      DWORD flags;
1538
1539      DWORD reg1 = ins->dst[0].reg.idx;
1540      char dst_str[50];
1541      char src_str[50];
1542
1543      /* Note that texreg2ar treats Tx as a temporary register, not as a varying */
1544      shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1545      shader_arb_get_src_param(ins, &ins->src[0], 0, src_str);
1546      /* Move .x first in case src_str is "TA" */
1547      shader_addline(buffer, "MOV TA.y, %s.x;\n", src_str);
1548      shader_addline(buffer, "MOV TA.x, %s.w;\n", src_str);
1549      flags = reg1 < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg1][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1550      shader_hw_sample(ins, reg1, dst_str, "TA", flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
1551 }
1552
1553 static void pshader_hw_texreg2gb(const struct wined3d_shader_instruction *ins)
1554 {
1555      SHADER_BUFFER *buffer = ins->ctx->buffer;
1556
1557      DWORD reg1 = ins->dst[0].reg.idx;
1558      char dst_str[50];
1559      char src_str[50];
1560
1561      /* Note that texreg2gb treats Tx as a temporary register, not as a varying */
1562      shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1563      shader_arb_get_src_param(ins, &ins->src[0], 0, src_str);
1564      shader_addline(buffer, "MOV TA.x, %s.y;\n", src_str);
1565      shader_addline(buffer, "MOV TA.y, %s.z;\n", src_str);
1566      shader_hw_sample(ins, reg1, dst_str, "TA", 0, NULL, NULL);
1567 }
1568
1569 static void pshader_hw_texreg2rgb(const struct wined3d_shader_instruction *ins)
1570 {
1571     DWORD reg1 = ins->dst[0].reg.idx;
1572     char dst_str[50];
1573     char src_str[50];
1574
1575     /* Note that texreg2rg treats Tx as a temporary register, not as a varying */
1576     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1577     shader_arb_get_src_param(ins, &ins->src[0], 0, src_str);
1578     shader_hw_sample(ins, reg1, dst_str, src_str, 0, NULL, NULL);
1579 }
1580
1581 static void pshader_hw_texbem(const struct wined3d_shader_instruction *ins)
1582 {
1583     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1584     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1585     SHADER_BUFFER *buffer = ins->ctx->buffer;
1586     char reg_coord[40], dst_reg[50], src_reg[50];
1587     DWORD reg_dest_code;
1588
1589     /* All versions have a destination register. The Tx where the texture coordinates come
1590      * from is the varying incarnation of the texture register
1591      */
1592     reg_dest_code = dst->reg.idx;
1593     shader_arb_get_dst_param(ins, &ins->dst[0], dst_reg);
1594     shader_arb_get_src_param(ins, &ins->src[0], 0, src_reg);
1595     sprintf(reg_coord, "fragment.texcoord[%u]", reg_dest_code);
1596
1597     /* Sampling the perturbation map in Tsrc was done already, including the signedness correction if needed
1598      * The Tx in which the perturbation map is stored is the tempreg incarnation of the texture register
1599      *
1600      * GL_NV_fragment_program_option could handle this in one instruction via X2D:
1601      * X2D TA.xy, fragment.texcoord, T%u, bumpenvmat%u.xzyw
1602      *
1603      * However, the NV extensions are never enabled for <= 2.0 shaders because of the performance penalty that
1604      * comes with it, and texbem is an 1.x only instruction. No 1.x instruction forces us to enable the NV
1605      * extension.
1606      */
1607     shader_addline(buffer, "SWZ TB, bumpenvmat%d, x, z, 0, 0;\n", reg_dest_code);
1608     shader_addline(buffer, "DP3 TA.x, TB, %s;\n", src_reg);
1609     shader_addline(buffer, "SWZ TB, bumpenvmat%d, y, w, 0, 0;\n", reg_dest_code);
1610     shader_addline(buffer, "DP3 TA.y, TB, %s;\n", src_reg);
1611
1612     /* with projective textures, texbem only divides the static texture coord, not the displacement,
1613      * so we can't let the GL handle this.
1614      */
1615     if (((IWineD3DDeviceImpl*) This->baseShader.device)->stateBlock->textureState[reg_dest_code][WINED3DTSS_TEXTURETRANSFORMFLAGS]
1616             & WINED3DTTFF_PROJECTED) {
1617         shader_addline(buffer, "RCP TB.w, %s.w;\n", reg_coord);
1618         shader_addline(buffer, "MUL TB.xy, %s, TB.w;\n", reg_coord);
1619         shader_addline(buffer, "ADD TA.xy, TA, TB;\n");
1620     } else {
1621         shader_addline(buffer, "ADD TA.xy, TA, %s;\n", reg_coord);
1622     }
1623
1624     shader_hw_sample(ins, reg_dest_code, dst_reg, "TA", 0, NULL, NULL);
1625
1626     if (ins->handler_idx == WINED3DSIH_TEXBEML)
1627     {
1628         /* No src swizzles are allowed, so this is ok */
1629         shader_addline(buffer, "MAD TA, %s.z, luminance%d.x, luminance%d.y;\n",
1630                        src_reg, reg_dest_code, reg_dest_code);
1631         shader_addline(buffer, "MUL %s, %s, TA;\n", dst_reg, dst_reg);
1632     }
1633 }
1634
1635 static void pshader_hw_texm3x2pad(const struct wined3d_shader_instruction *ins)
1636 {
1637     DWORD reg = ins->dst[0].reg.idx;
1638     SHADER_BUFFER *buffer = ins->ctx->buffer;
1639     char src0_name[50], dst_name[50];
1640     BOOL is_color;
1641     struct wined3d_shader_register tmp_reg = ins->dst[0].reg;
1642
1643     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
1644     /* The next instruction will be a texm3x2tex or texm3x2depth that writes to the uninitialized
1645      * T<reg+1> register. Use this register to store the calculated vector
1646      */
1647     tmp_reg.idx = reg + 1;
1648     shader_arb_get_register_name(ins, &tmp_reg, dst_name, &is_color);
1649     shader_addline(buffer, "DP3 %s.x, fragment.texcoord[%u], %s;\n", dst_name, reg, src0_name);
1650 }
1651
1652 static void pshader_hw_texm3x2tex(const struct wined3d_shader_instruction *ins)
1653 {
1654     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1655     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1656     DWORD flags;
1657     DWORD reg = ins->dst[0].reg.idx;
1658     SHADER_BUFFER *buffer = ins->ctx->buffer;
1659     char dst_str[50];
1660     char src0_name[50];
1661     char dst_reg[50];
1662     BOOL is_color;
1663
1664     /* We know that we're writing to the uninitialized T<reg> register, so use it for temporary storage */
1665     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_reg, &is_color);
1666
1667     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1668     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
1669     shader_addline(buffer, "DP3 %s.y, fragment.texcoord[%u], %s;\n", dst_reg, reg, src0_name);
1670     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1671     shader_hw_sample(ins, reg, dst_str, dst_reg, flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
1672 }
1673
1674 static void pshader_hw_texm3x3pad(const struct wined3d_shader_instruction *ins)
1675 {
1676     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1677     DWORD reg = ins->dst[0].reg.idx;
1678     SHADER_BUFFER *buffer = ins->ctx->buffer;
1679     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1680     char src0_name[50], dst_name[50];
1681     struct wined3d_shader_register tmp_reg = ins->dst[0].reg;
1682     BOOL is_color;
1683
1684     /* There are always 2 texm3x3pad instructions followed by one texm3x3[tex,vspec, ...] instruction, with
1685      * incrementing ins->dst[0].register_idx numbers. So the pad instruction already knows the final destination
1686      * register, and this register is uninitialized(otherwise the assembler complains that it is 'redeclared')
1687      */
1688     tmp_reg.idx = reg + 2 - current_state->current_row;
1689     shader_arb_get_register_name(ins, &tmp_reg, dst_name, &is_color);
1690
1691     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
1692     shader_addline(buffer, "DP3 %s.%c, fragment.texcoord[%u], %s;\n",
1693                    dst_name, 'x' + current_state->current_row, reg, src0_name);
1694     current_state->texcoord_w[current_state->current_row++] = reg;
1695 }
1696
1697 static void pshader_hw_texm3x3tex(const struct wined3d_shader_instruction *ins)
1698 {
1699     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1700     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1701     DWORD flags;
1702     DWORD reg = ins->dst[0].reg.idx;
1703     SHADER_BUFFER *buffer = ins->ctx->buffer;
1704     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1705     char dst_str[50];
1706     char src0_name[50], dst_name[50];
1707     BOOL is_color;
1708
1709     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_name, &is_color);
1710     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
1711     shader_addline(buffer, "DP3 %s.z, fragment.texcoord[%u], %s;\n", dst_name, reg, src0_name);
1712
1713     /* Sample the texture using the calculated coordinates */
1714     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1715     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1716     shader_hw_sample(ins, reg, dst_str, dst_name, flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
1717     current_state->current_row = 0;
1718 }
1719
1720 static void pshader_hw_texm3x3vspec(const struct wined3d_shader_instruction *ins)
1721 {
1722     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1723     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1724     DWORD flags;
1725     DWORD reg = ins->dst[0].reg.idx;
1726     SHADER_BUFFER *buffer = ins->ctx->buffer;
1727     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1728     char dst_str[50];
1729     char src0_name[50];
1730     char dst_reg[8];
1731     BOOL is_color;
1732
1733     /* Get the dst reg without writemask strings. We know this register is uninitialized, so we can use all
1734      * components for temporary data storage
1735      */
1736     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_reg, &is_color);
1737     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
1738     shader_addline(buffer, "DP3 %s.z, fragment.texcoord[%u], %s;\n", dst_reg, reg, src0_name);
1739
1740     /* Construct the eye-ray vector from w coordinates */
1741     shader_addline(buffer, "MOV TB.x, fragment.texcoord[%u].w;\n", current_state->texcoord_w[0]);
1742     shader_addline(buffer, "MOV TB.y, fragment.texcoord[%u].w;\n", current_state->texcoord_w[1]);
1743     shader_addline(buffer, "MOV TB.z, fragment.texcoord[%u].w;\n", reg);
1744
1745     /* Calculate reflection vector
1746      */
1747     shader_addline(buffer, "DP3 %s.w, %s, TB;\n", dst_reg, dst_reg);
1748     /* The .w is ignored when sampling, so I can use TB.w to calculate dot(N, N) */
1749     shader_addline(buffer, "DP3 TB.w, %s, %s;\n", dst_reg, dst_reg);
1750     shader_addline(buffer, "RCP TB.w, TB.w;\n");
1751     shader_addline(buffer, "MUL %s.w, %s.w, TB.w;\n", dst_reg, dst_reg);
1752     shader_addline(buffer, "MUL %s, %s.w, %s;\n", dst_reg, dst_reg, dst_reg);
1753     shader_addline(buffer, "MAD %s, coefmul.x, %s, -TB;\n", dst_reg, dst_reg);
1754
1755     /* Sample the texture using the calculated coordinates */
1756     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1757     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1758     shader_hw_sample(ins, reg, dst_str, dst_reg, flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
1759     current_state->current_row = 0;
1760 }
1761
1762 static void pshader_hw_texm3x3spec(const struct wined3d_shader_instruction *ins)
1763 {
1764     IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)ins->ctx->shader;
1765     IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
1766     DWORD flags;
1767     DWORD reg = ins->dst[0].reg.idx;
1768     SHADER_PARSE_STATE* current_state = &This->baseShader.parse_state;
1769     SHADER_BUFFER *buffer = ins->ctx->buffer;
1770     char dst_str[50];
1771     char src0_name[50];
1772     char src1_name[50];
1773     char dst_reg[8];
1774     BOOL is_color;
1775
1776     shader_arb_get_src_param(ins, &ins->src[0], 0, src0_name);
1777     shader_arb_get_src_param(ins, &ins->src[0], 1, src1_name);
1778     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_reg, &is_color);
1779     /* Note: dst_reg.xy is input here, generated by two texm3x3pad instructions */
1780     shader_addline(buffer, "DP3 %s.z, fragment.texcoord[%u], %s;\n", dst_reg, reg, src0_name);
1781
1782     /* Calculate reflection vector.
1783      *
1784      *                   dot(N, E)
1785      * dst_reg.xyz = 2 * --------- * N - E
1786      *                   dot(N, N)
1787      *
1788      * Which normalizes the normal vector
1789      */
1790     shader_addline(buffer, "DP3 %s.w, %s, %s;\n", dst_reg, dst_reg, src1_name);
1791     shader_addline(buffer, "DP3 TC.w, %s, %s;\n", dst_reg, dst_reg);
1792     shader_addline(buffer, "RCP TC.w, TC.w;\n");
1793     shader_addline(buffer, "MUL %s.w, %s.w, TC.w;\n", dst_reg, dst_reg);
1794     shader_addline(buffer, "MUL %s, %s.w, %s;\n", dst_reg, dst_reg, dst_reg);
1795     shader_addline(buffer, "MAD %s, coefmul.x, %s, -%s;\n", dst_reg, dst_reg, src1_name);
1796
1797     /* Sample the texture using the calculated coordinates */
1798     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1799     flags = reg < MAX_TEXTURES ? deviceImpl->stateBlock->textureState[reg][WINED3DTSS_TEXTURETRANSFORMFLAGS] : 0;
1800     shader_hw_sample(ins, reg, dst_str, dst_reg, flags & WINED3DTTFF_PROJECTED ? TEX_PROJ : 0, NULL, NULL);
1801     current_state->current_row = 0;
1802 }
1803
1804 static void pshader_hw_texdepth(const struct wined3d_shader_instruction *ins)
1805 {
1806     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1807     SHADER_BUFFER *buffer = ins->ctx->buffer;
1808     char dst_name[50];
1809
1810     /* texdepth has an implicit destination, the fragment depth value. It's only parameter,
1811      * which is essentially an input, is the destination register because it is the first
1812      * parameter. According to the msdn, this must be register r5, but let's keep it more flexible
1813      * here(writemasks/swizzles are not valid on texdepth)
1814      */
1815     shader_arb_get_dst_param(ins, dst, dst_name);
1816
1817     /* According to the msdn, the source register(must be r5) is unusable after
1818      * the texdepth instruction, so we're free to modify it
1819      */
1820     shader_addline(buffer, "MIN %s.y, %s.y, one.y;\n", dst_name, dst_name);
1821
1822     /* How to deal with the special case dst_name.g == 0? if r != 0, then
1823      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
1824      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
1825      */
1826     shader_addline(buffer, "RCP %s.y, %s.y;\n", dst_name, dst_name);
1827     shader_addline(buffer, "MUL TA.x, %s.x, %s.y;\n", dst_name, dst_name);
1828     shader_addline(buffer, "MIN TA.x, TA.x, one.x;\n");
1829     shader_addline(buffer, "MAX result.depth, TA.x, 0.0;\n");
1830 }
1831
1832 /** Process the WINED3DSIO_TEXDP3TEX instruction in ARB:
1833  * Take a 3-component dot product of the TexCoord[dstreg] and src,
1834  * then perform a 1D texture lookup from stage dstregnum, place into dst. */
1835 static void pshader_hw_texdp3tex(const struct wined3d_shader_instruction *ins)
1836 {
1837     SHADER_BUFFER *buffer = ins->ctx->buffer;
1838     DWORD sampler_idx = ins->dst[0].reg.idx;
1839     char src0[50];
1840     char dst_str[50];
1841
1842     shader_arb_get_src_param(ins, &ins->src[0], 0, src0);
1843     shader_addline(buffer, "MOV TB, 0.0;\n");
1844     shader_addline(buffer, "DP3 TB.x, fragment.texcoord[%u], %s;\n", sampler_idx, src0);
1845
1846     shader_arb_get_dst_param(ins, &ins->dst[0], dst_str);
1847     shader_hw_sample(ins, sampler_idx, dst_str, "TB", 0 /* Only one coord, can't be projected */, NULL, NULL);
1848 }
1849
1850 /** Process the WINED3DSIO_TEXDP3 instruction in ARB:
1851  * Take a 3-component dot product of the TexCoord[dstreg] and src. */
1852 static void pshader_hw_texdp3(const struct wined3d_shader_instruction *ins)
1853 {
1854     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1855     char src0[50];
1856     char dst_str[50];
1857     SHADER_BUFFER *buffer = ins->ctx->buffer;
1858
1859     /* Handle output register */
1860     shader_arb_get_dst_param(ins, dst, dst_str);
1861     shader_arb_get_src_param(ins, &ins->src[0], 0, src0);
1862     shader_addline(buffer, "DP3 %s, fragment.texcoord[%u], %s;\n", dst_str, dst->reg.idx, src0);
1863 }
1864
1865 /** Process the WINED3DSIO_TEXM3X3 instruction in ARB
1866  * Perform the 3rd row of a 3x3 matrix multiply */
1867 static void pshader_hw_texm3x3(const struct wined3d_shader_instruction *ins)
1868 {
1869     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1870     SHADER_BUFFER *buffer = ins->ctx->buffer;
1871     char dst_str[50], dst_name[50];
1872     char src0[50];
1873     BOOL is_color;
1874
1875     shader_arb_get_dst_param(ins, dst, dst_str);
1876     shader_arb_get_src_param(ins, &ins->src[0], 0, src0);
1877     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_name, &is_color);
1878     shader_addline(buffer, "DP3 %s.z, fragment.texcoord[%u], %s;\n", dst_name, dst->reg.idx, src0);
1879     shader_addline(buffer, "MOV %s, %s;\n", dst_str, dst_name);
1880 }
1881
1882 /** Process the WINED3DSIO_TEXM3X2DEPTH instruction in ARB:
1883  * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
1884  * Calculate tmp0.y = TexCoord[dstreg] . src.xyz;  (tmp0.x has already been calculated)
1885  * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
1886  */
1887 static void pshader_hw_texm3x2depth(const struct wined3d_shader_instruction *ins)
1888 {
1889     SHADER_BUFFER *buffer = ins->ctx->buffer;
1890     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
1891     char src0[50], dst_name[50];
1892     BOOL is_color;
1893
1894     shader_arb_get_src_param(ins, &ins->src[0], 0, src0);
1895     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_name, &is_color);
1896     shader_addline(buffer, "DP3 %s.y, fragment.texcoord[%u], %s;\n", dst_name, dst->reg.idx, src0);
1897
1898     /* How to deal with the special case dst_name.g == 0? if r != 0, then
1899      * the r * (1 / 0) will give infinity, which is clamped to 1.0, the correct
1900      * result. But if r = 0.0, then 0 * inf = 0, which is incorrect.
1901      */
1902     shader_addline(buffer, "RCP %s.y, %s.y;\n", dst_name, dst_name);
1903     shader_addline(buffer, "MUL %s.x, %s.x, %s.y;\n", dst_name, dst_name, dst_name);
1904     shader_addline(buffer, "MIN %s.x, %s.x, one.x;\n", dst_name, dst_name);
1905     shader_addline(buffer, "MAX result.depth, %s.x, 0.0;\n", dst_name);
1906 }
1907
1908 /** Handles transforming all WINED3DSIO_M?x? opcodes for
1909     Vertex/Pixel shaders to ARB_vertex_program codes */
1910 static void shader_hw_mnxn(const struct wined3d_shader_instruction *ins)
1911 {
1912     int i;
1913     int nComponents = 0;
1914     struct wined3d_shader_dst_param tmp_dst = {{0}};
1915     struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
1916     struct wined3d_shader_instruction tmp_ins;
1917
1918     memset(&tmp_ins, 0, sizeof(tmp_ins));
1919
1920     /* Set constants for the temporary argument */
1921     tmp_ins.ctx = ins->ctx;
1922     tmp_ins.dst_count = 1;
1923     tmp_ins.dst = &tmp_dst;
1924     tmp_ins.src_count = 2;
1925     tmp_ins.src = tmp_src;
1926
1927     switch(ins->handler_idx)
1928     {
1929         case WINED3DSIH_M4x4:
1930             nComponents = 4;
1931             tmp_ins.handler_idx = WINED3DSIH_DP4;
1932             break;
1933         case WINED3DSIH_M4x3:
1934             nComponents = 3;
1935             tmp_ins.handler_idx = WINED3DSIH_DP4;
1936             break;
1937         case WINED3DSIH_M3x4:
1938             nComponents = 4;
1939             tmp_ins.handler_idx = WINED3DSIH_DP3;
1940             break;
1941         case WINED3DSIH_M3x3:
1942             nComponents = 3;
1943             tmp_ins.handler_idx = WINED3DSIH_DP3;
1944             break;
1945         case WINED3DSIH_M3x2:
1946             nComponents = 2;
1947             tmp_ins.handler_idx = WINED3DSIH_DP3;
1948             break;
1949         default:
1950             FIXME("Unhandled opcode %#x\n", ins->handler_idx);
1951             break;
1952     }
1953
1954     tmp_dst = ins->dst[0];
1955     tmp_src[0] = ins->src[0];
1956     tmp_src[1] = ins->src[1];
1957     for (i = 0; i < nComponents; i++) {
1958         tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
1959         shader_hw_map2gl(&tmp_ins);
1960         ++tmp_src[1].reg.idx;
1961     }
1962 }
1963
1964 static void shader_hw_rsq_rcp(const struct wined3d_shader_instruction *ins)
1965 {
1966     SHADER_BUFFER *buffer = ins->ctx->buffer;
1967     const char *instruction;
1968
1969     char dst[50];
1970     char src[50];
1971
1972     switch(ins->handler_idx)
1973     {
1974         case WINED3DSIH_RSQ: instruction = "RSQ"; break;
1975         case WINED3DSIH_RCP: instruction = "RCP"; break;
1976         default: instruction = "";
1977             FIXME("Unhandled opcode %#x\n", ins->handler_idx);
1978             break;
1979     }
1980
1981     shader_arb_get_dst_param(ins, &ins->dst[0], dst); /* Destination */
1982     shader_arb_get_src_param(ins, &ins->src[0], 0, src);
1983     if (ins->src[0].swizzle == WINED3DSP_NOSWIZZLE)
1984     {
1985         /* Dx sdk says .x is used if no swizzle is given, but our test shows that
1986          * .w is used
1987          */
1988         strcat(src, ".w");
1989     }
1990
1991     shader_addline(buffer, "%s%s %s, %s;\n", instruction, shader_arb_get_modifier(ins), dst, src);
1992 }
1993
1994 static void shader_hw_nrm(const struct wined3d_shader_instruction *ins)
1995 {
1996     SHADER_BUFFER *buffer = ins->ctx->buffer;
1997     char dst_name[50];
1998     char src_name[50];
1999     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2000     BOOL pshader = shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type);
2001
2002     shader_arb_get_dst_param(ins, &ins->dst[0], dst_name);
2003     shader_arb_get_src_param(ins, &ins->src[0], 1 /* Use TB */, src_name);
2004
2005     if(pshader && priv->target_version >= NV3)
2006     {
2007         shader_addline(buffer, "NRM%s %s, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name);
2008     }
2009     else
2010     {
2011         shader_addline(buffer, "DP3 TA, %s, %s;\n", src_name, src_name);
2012         shader_addline(buffer, "RSQ TA, TA.x;\n");
2013         /* dst.w = src[0].w * 1 / (src.x^2 + src.y^2 + src.z^2)^(1/2) according to msdn*/
2014         shader_addline(buffer, "MUL%s %s, %s, TA;\n", shader_arb_get_modifier(ins), dst_name,
2015                     src_name);
2016     }
2017 }
2018
2019 static void shader_hw_lrp(const struct wined3d_shader_instruction *ins)
2020 {
2021     SHADER_BUFFER *buffer = ins->ctx->buffer;
2022     char dst_name[50];
2023     char src_name[3][50];
2024
2025     /* ARB_fragment_program has a convenient LRP instruction */
2026     if(shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)) {
2027         shader_hw_map2gl(ins);
2028         return;
2029     }
2030
2031     shader_arb_get_dst_param(ins, &ins->dst[0], dst_name);
2032     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name[0]);
2033     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name[1]);
2034     shader_arb_get_src_param(ins, &ins->src[2], 2, src_name[2]);
2035
2036     shader_addline(buffer, "SUB TA, %s, %s;\n", src_name[1], src_name[2]);
2037     shader_addline(buffer, "MAD%s %s, %s, TA, %s;\n", shader_arb_get_modifier(ins),
2038                    dst_name, src_name[0], src_name[2]);
2039 }
2040
2041 static void shader_hw_sincos(const struct wined3d_shader_instruction *ins)
2042 {
2043     /* This instruction exists in ARB, but the d3d instruction takes two extra parameters which
2044      * must contain fixed constants. So we need a separate function to filter those constants and
2045      * can't use map2gl
2046      */
2047     SHADER_BUFFER *buffer = ins->ctx->buffer;
2048     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2049     const struct wined3d_shader_dst_param *dst = &ins->dst[0];
2050     char dst_name[50];
2051     char src_name0[50], src_name1[50], src_name2[50];
2052     BOOL is_color;
2053
2054     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name0);
2055     if(shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)) {
2056         shader_arb_get_dst_param(ins, &ins->dst[0], dst_name);
2057         /* No modifiers are supported on SCS */
2058         shader_addline(buffer, "SCS %s, %s;\n", dst_name, src_name0);
2059
2060         if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE)
2061         {
2062             shader_arb_get_register_name(ins, &dst->reg, src_name0, &is_color);
2063             shader_addline(buffer, "MOV_SAT %s, %s;\n", dst_name, src_name0);
2064         }
2065     } else if(priv->target_version >= NV2) {
2066         shader_arb_get_register_name(ins, &dst->reg, dst_name, &is_color);
2067
2068         /* Sincos writemask must be .x, .y or .xy */
2069         if(dst->write_mask & WINED3DSP_WRITEMASK_0)
2070             shader_addline(buffer, "COS%s %s.x, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name0);
2071         if(dst->write_mask & WINED3DSP_WRITEMASK_1)
2072             shader_addline(buffer, "SIN%s %s.y, %s;\n", shader_arb_get_modifier(ins), dst_name, src_name0);
2073     } else {
2074         /* Approximate sine and cosine with a taylor series, as per math textbook. The application passes 8
2075          * helper constants(D3DSINCOSCONST1 and D3DSINCOSCONST2) in src1 and src2.
2076          *
2077          * sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...
2078          * cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! + ...
2079          *
2080          * The constants we get are:
2081          *
2082          *  +1   +1,     -1     -1     +1      +1      -1       -1
2083          *      ---- ,  ---- , ---- , ----- , ----- , ----- , ------
2084          *      1!*2    2!*4   3!*8   4!*16   5!*32   6!*64   7!*128
2085          *
2086          * If used with x^2, x^3, x^4 etc they calculate sin(x/2) and cos(x/2):
2087          *
2088          * (x/2)^2 = x^2 / 4
2089          * (x/2)^3 = x^3 / 8
2090          * (x/2)^4 = x^4 / 16
2091          * (x/2)^5 = x^5 / 32
2092          * etc
2093          *
2094          * To get the final result:
2095          * sin(x) = 2 * sin(x/2) * cos(x/2)
2096          * cos(x) = cos(x/2)^2 - sin(x/2)^2
2097          * (from sin(x+y) and cos(x+y) rules)
2098          *
2099          * As per MSDN, dst.z is undefined after the operation, and so is
2100          * dst.x and dst.y if they're masked out by the writemask. Ie
2101          * sincos dst.y, src1, c0, c1
2102          * returns the sine in dst.y. dst.x and dst.z are undefined, dst.w is not touched. The assembler
2103          * vsa.exe also stops with an error if the dest register is the same register as the source
2104          * register. This means we can use dest.xyz as temporary storage. The assembler vsa.exe output also
2105          * indicates that sincos consumes 8 instruction slots in vs_2_0(and, strangely, in vs_3_0).
2106          */
2107         shader_arb_get_src_param(ins, &ins->src[1], 1, src_name1);
2108         shader_arb_get_src_param(ins, &ins->src[2], 2, src_name2);
2109         shader_arb_get_register_name(ins, &dst->reg, dst_name, &is_color);
2110
2111         shader_addline(buffer, "MUL %s.x, %s, %s;\n", dst_name, src_name0, src_name0);  /* x ^ 2 */
2112         shader_addline(buffer, "MUL TA.y, %s.x, %s;\n", dst_name, src_name0);           /* x ^ 3 */
2113         shader_addline(buffer, "MUL %s.y, TA.y, %s;\n", dst_name, src_name0);           /* x ^ 4 */
2114         shader_addline(buffer, "MUL TA.z, %s.y, %s;\n", dst_name, src_name0);           /* x ^ 5 */
2115         shader_addline(buffer, "MUL %s.z, TA.z, %s;\n", dst_name, src_name0);           /* x ^ 6 */
2116         shader_addline(buffer, "MUL TA.w, %s.z, %s;\n", dst_name, src_name0);           /* x ^ 7 */
2117
2118         /* sin(x/2)
2119          *
2120          * Unfortunately we don't get the constants in a DP4-capable form. Is there a way to
2121          * properly merge that with MULs in the code above?
2122          * The swizzles .yz and xw however fit into the .yzxw swizzle added to ps_2_0. Maybe
2123          * we can merge the sine and cosine MAD rows to calculate them together.
2124          */
2125         shader_addline(buffer, "MUL TA.x, %s, %s.w;\n", src_name0, src_name2); /* x^1, +1/(1!*2) */
2126         shader_addline(buffer, "MAD TA.x, TA.y, %s.x, TA.x;\n", src_name2); /* -1/(3!*8) */
2127         shader_addline(buffer, "MAD TA.x, TA.z, %s.w, TA.x;\n", src_name1); /* +1/(5!*32) */
2128         shader_addline(buffer, "MAD TA.x, TA.w, %s.x, TA.x;\n", src_name1); /* -1/(7!*128) */
2129
2130         /* cos(x/2) */
2131         shader_addline(buffer, "MAD TA.y, %s.x, %s.y, %s.z;\n", dst_name, src_name2, src_name2); /* -1/(2!*4), +1.0 */
2132         shader_addline(buffer, "MAD TA.y, %s.y, %s.z, TA.y;\n", dst_name, src_name1); /* +1/(4!*16) */
2133         shader_addline(buffer, "MAD TA.y, %s.z, %s.y, TA.y;\n", dst_name, src_name1); /* -1/(6!*64) */
2134
2135         if(dst->write_mask & WINED3DSP_WRITEMASK_0) {
2136             /* cos x */
2137             shader_addline(buffer, "MUL TA.z, TA.y, TA.y;\n");
2138             shader_addline(buffer, "MAD %s.x, -TA.x, TA.x, TA.z;\n", dst_name);
2139         }
2140         if(dst->write_mask & WINED3DSP_WRITEMASK_1) {
2141             /* sin x */
2142             shader_addline(buffer, "MUL %s.y, TA.x, TA.y;\n", dst_name);
2143             shader_addline(buffer, "ADD %s.y, %s.y, %s.y;\n", dst_name, dst_name, dst_name);
2144         }
2145     }
2146 }
2147
2148 /* GL locking is done by the caller */
2149 static void shader_hw_sgn(const struct wined3d_shader_instruction *ins)
2150 {
2151     SHADER_BUFFER *buffer = ins->ctx->buffer;
2152     char dst_name[50];
2153     char src_name[50];
2154     struct shader_arb_ctx_priv *ctx = ins->ctx->backend_data;
2155
2156     /* SGN is only valid in vertex shaders */
2157     if(ctx->target_version == NV2) {
2158         shader_hw_map2gl(ins);
2159         return;
2160     }
2161     shader_arb_get_dst_param(ins, &ins->dst[0], dst_name);
2162     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name);
2163
2164     FIXME("Emulated SGN untested\n");
2165     /* If SRC > 0.0, -SRC < SRC = TRUE, otherwise false.
2166      * if SRC < 0.0,  SRC < -SRC = TRUE. If neither is true, src = 0.0
2167      */
2168     if(ins->dst[0].modifiers & WINED3DSPDM_SATURATE) {
2169         shader_addline(buffer, "SLT %s, -%s, %s;\n", dst_name, src_name, src_name);
2170     } else {
2171         shader_addline(buffer, "SLT TB, -%s, %s;\n", src_name, src_name);
2172         shader_addline(buffer, "SLT TC,  %s, -%s;\n", src_name, src_name);
2173         shader_addline(buffer, "ADD %s, TB, -TC;\n", dst_name);
2174     }
2175 }
2176
2177 static void shader_hw_dsy(const struct wined3d_shader_instruction *ins)
2178 {
2179     SHADER_BUFFER *buffer = ins->ctx->buffer;
2180     char src[50];
2181     char dst[50];
2182     char dst_name[50];
2183     BOOL is_color;
2184
2185     shader_arb_get_dst_param(ins, &ins->dst[0], dst);
2186     shader_arb_get_src_param(ins, &ins->src[0], 0, src);
2187     shader_arb_get_register_name(ins, &ins->dst[0].reg, dst_name, &is_color);
2188
2189     shader_addline(buffer, "DDY %s, %s;\n", dst, src);
2190     shader_addline(buffer, "MUL%s %s, %s, ycorrection.y;\n", shader_arb_get_modifier(ins), dst, dst_name);
2191 }
2192
2193 static void shader_hw_loop(const struct wined3d_shader_instruction *ins)
2194 {
2195     SHADER_BUFFER *buffer = ins->ctx->buffer;
2196     char src_name[50];
2197     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2198
2199     /* src0 is aL */
2200     shader_arb_get_src_param(ins, &ins->src[1], 0, src_name);
2201
2202     if(vshader)
2203     {
2204         struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2205         struct list *e = list_head(&priv->control_frames);
2206         struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2207
2208         if(priv->loop_depth > 1) shader_addline(buffer, "PUSHA aL;\n");
2209         /* The constant loader makes sure to load -1 into iX.w */
2210         shader_addline(buffer, "ARLC aL, %s.xywz;\n", src_name);
2211         shader_addline(buffer, "BRA loop_%u_end (LE.x);\n", control_frame->loop_no);
2212         shader_addline(buffer, "loop_%u_start:\n", control_frame->loop_no);
2213     }
2214     else
2215     {
2216         shader_addline(buffer, "LOOP %s;\n", src_name);
2217     }
2218 }
2219
2220 static void shader_hw_rep(const struct wined3d_shader_instruction *ins)
2221 {
2222     SHADER_BUFFER *buffer = ins->ctx->buffer;
2223     char src_name[50];
2224     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2225
2226     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name);
2227
2228     /* The constant loader makes sure to load -1 into iX.w */
2229     if(vshader)
2230     {
2231         struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2232         struct list *e = list_head(&priv->control_frames);
2233         struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2234
2235         if(priv->loop_depth > 1) shader_addline(buffer, "PUSHA aL;\n");
2236
2237         shader_addline(buffer, "ARLC aL, %s.xywz;\n", src_name);
2238         shader_addline(buffer, "BRA loop_%u_end (LE.x);\n", control_frame->loop_no);
2239         shader_addline(buffer, "loop_%u_start:\n", control_frame->loop_no);
2240     }
2241     else
2242     {
2243         shader_addline(buffer, "REP %s;\n", src_name);
2244     }
2245 }
2246
2247 static void shader_hw_endloop(const struct wined3d_shader_instruction *ins)
2248 {
2249     SHADER_BUFFER *buffer = ins->ctx->buffer;
2250     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2251
2252     if(vshader)
2253     {
2254         struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2255         struct list *e = list_head(&priv->control_frames);
2256         struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2257
2258         shader_addline(buffer, "ARAC aL.xy, aL;\n");
2259         shader_addline(buffer, "BRA loop_%u_start (GT.x);\n", control_frame->loop_no);
2260         shader_addline(buffer, "loop_%u_end:\n", control_frame->loop_no);
2261
2262         if(priv->loop_depth > 1) shader_addline(buffer, "POPA aL;\n");
2263     }
2264     else
2265     {
2266         shader_addline(buffer, "ENDLOOP;\n");
2267     }
2268 }
2269
2270 static void shader_hw_endrep(const struct wined3d_shader_instruction *ins)
2271 {
2272     SHADER_BUFFER *buffer = ins->ctx->buffer;
2273     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2274
2275     if(vshader)
2276     {
2277         struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2278         struct list *e = list_head(&priv->control_frames);
2279         struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2280
2281         shader_addline(buffer, "ARAC aL.xy, aL;\n");
2282         shader_addline(buffer, "BRA loop_%u_start (GT.x);\n", control_frame->loop_no);
2283         shader_addline(buffer, "loop_%u_end:\n", control_frame->loop_no);
2284
2285         if(priv->loop_depth > 1) shader_addline(buffer, "POPA aL;\n");
2286     }
2287     else
2288     {
2289         shader_addline(buffer, "ENDREP;\n");
2290     }
2291 }
2292
2293 static const struct control_frame *find_last_loop(const struct shader_arb_ctx_priv *priv)
2294 {
2295     struct control_frame *control_frame;
2296
2297     LIST_FOR_EACH_ENTRY(control_frame, &priv->control_frames, struct control_frame, entry)
2298     {
2299         if(control_frame->type == LOOP || control_frame->type == REP) return control_frame;
2300     }
2301     ERR("Could not find loop for break\n");
2302     return NULL;
2303 }
2304
2305 static void shader_hw_break(const struct wined3d_shader_instruction *ins)
2306 {
2307     SHADER_BUFFER *buffer = ins->ctx->buffer;
2308     const struct control_frame *control_frame = find_last_loop(ins->ctx->backend_data);
2309     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2310
2311     if(vshader)
2312     {
2313         shader_addline(buffer, "BRA loop_%u_end;\n", control_frame->loop_no);
2314     }
2315     else
2316     {
2317         shader_addline(buffer, "BRK;\n");
2318     }
2319 }
2320
2321 static void shader_hw_breakc(const struct wined3d_shader_instruction *ins)
2322 {
2323     SHADER_BUFFER *buffer = ins->ctx->buffer;
2324     const struct control_frame *control_frame = find_last_loop(ins->ctx->backend_data);
2325     char src_name0[50];
2326     char src_name1[50];
2327     const char *comp;
2328     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2329
2330     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name0);
2331     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name1);
2332
2333     switch (ins->flags)
2334     {
2335         case COMPARISON_GT: comp = "GT"; break;
2336         case COMPARISON_EQ: comp = "EQ"; break;
2337         case COMPARISON_GE: comp = "GE"; break;
2338         case COMPARISON_LT: comp = "LT"; break;
2339         case COMPARISON_NE: comp = "NE"; break;
2340         case COMPARISON_LE: comp = "LE"; break;
2341         default:
2342             FIXME("Unrecognized comparison value: %u\n", ins->flags);
2343             comp = "(\?\?)";
2344     }
2345
2346     if(vshader)
2347     {
2348         /* SUBC CC, src0, src1" works only in pixel shaders, so use TA to throw
2349          * away the subtraction result
2350          */
2351         shader_addline(buffer, "SUBC TA, %s, %s;\n", src_name0, src_name1);
2352         shader_addline(buffer, "BRA loop_%u_end (%s.x);\n", control_frame->loop_no, comp);
2353     }
2354     else
2355     {
2356         shader_addline(buffer, "SUBC CC, %s, %s;\n", src_name0, src_name1);
2357         shader_addline(buffer, "BRK (%s.x);\n", comp);
2358     }
2359 }
2360
2361 static void shader_hw_ifc(const struct wined3d_shader_instruction *ins)
2362 {
2363     SHADER_BUFFER *buffer = ins->ctx->buffer;
2364     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2365     struct list *e = list_head(&priv->control_frames);
2366     struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2367     const char *comp;
2368     char src_name0[50];
2369     char src_name1[50];
2370     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2371
2372     /* Invert the flag. We jump to the else label if the condition is NOT true */
2373     switch(ins->flags)
2374     {
2375         case COMPARISON_GT: comp = "LE"; break;
2376         case COMPARISON_EQ: comp = "NE"; break;
2377         case COMPARISON_GE: comp = "LT"; break;
2378         case COMPARISON_LT: comp = "GE"; break;
2379         case COMPARISON_NE: comp = "EQ"; break;
2380         case COMPARISON_LE: comp = "GT"; break;
2381         default:
2382             FIXME("Unrecognized comparison value: %u\n", ins->flags);
2383             comp = "\?\?";
2384     }
2385
2386     shader_arb_get_src_param(ins, &ins->src[0], 0, src_name0);
2387     shader_arb_get_src_param(ins, &ins->src[1], 1, src_name1);
2388
2389     if(vshader)
2390     {
2391         shader_addline(buffer, "SUBC TA, %s, %s;\n", src_name0, src_name1);
2392         shader_addline(buffer, "BRA ifc_%u_endif (%s.x);\n", control_frame->ifc_no, comp);
2393     }
2394     else
2395     {
2396         shader_addline(buffer, "SUBC CC, %s, %s;\n", src_name0, src_name1);
2397         shader_addline(buffer, "IF %s.x;\n", comp);
2398     }
2399 }
2400
2401 static void shader_hw_else(const struct wined3d_shader_instruction *ins)
2402 {
2403     SHADER_BUFFER *buffer = ins->ctx->buffer;
2404     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2405     struct list *e = list_head(&priv->control_frames);
2406     struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2407     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2408
2409     if(vshader)
2410     {
2411         shader_addline(buffer, "BRA ifc_%u_endif;\n", control_frame->ifc_no);
2412         shader_addline(buffer, "ifc_%u_else:\n", control_frame->ifc_no);
2413         control_frame->had_else = TRUE;
2414     }
2415     else
2416     {
2417         shader_addline(buffer, "ELSE;\n");
2418     }
2419 }
2420
2421 static void shader_hw_endif(const struct wined3d_shader_instruction *ins)
2422 {
2423     SHADER_BUFFER *buffer = ins->ctx->buffer;
2424     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
2425     struct list *e = list_head(&priv->control_frames);
2426     struct control_frame *control_frame = LIST_ENTRY(e, struct control_frame, entry);
2427     BOOL vshader = shader_is_vshader_version(ins->ctx->reg_maps->shader_version.type);
2428
2429     if(vshader)
2430     {
2431         if(control_frame->had_else)
2432         {
2433             shader_addline(buffer, "ifc_%u_endif:\n", control_frame->ifc_no);
2434         }
2435         else
2436         {
2437             shader_addline(buffer, "#No else branch. else is endif\n");
2438             shader_addline(buffer, "ifc_%u_else:\n", control_frame->ifc_no);
2439         }
2440     }
2441     else
2442     {
2443         shader_addline(buffer, "ENDIF;\n");
2444     }
2445 }
2446
2447 static void shader_hw_texldd(const struct wined3d_shader_instruction *ins)
2448 {
2449     DWORD sampler_idx = ins->src[1].reg.idx;
2450     char reg_dest[40];
2451     char reg_src[3][40];
2452     DWORD flags = TEX_DERIV;
2453
2454     shader_arb_get_dst_param(ins, &ins->dst[0], reg_dest);
2455     shader_arb_get_src_param(ins, &ins->src[0], 0, reg_src[0]);
2456     shader_arb_get_src_param(ins, &ins->src[2], 1, reg_src[1]);
2457     shader_arb_get_src_param(ins, &ins->src[3], 2, reg_src[2]);
2458
2459     if (ins->flags & WINED3DSI_TEXLD_PROJECT) flags |= TEX_PROJ;
2460     if (ins->flags & WINED3DSI_TEXLD_BIAS) flags |= TEX_BIAS;
2461
2462     shader_hw_sample(ins, sampler_idx, reg_dest, reg_src[0], flags, reg_src[1], reg_src[2]);
2463 }
2464
2465 static void shader_hw_texldl(const struct wined3d_shader_instruction *ins)
2466 {
2467     DWORD sampler_idx = ins->src[1].reg.idx;
2468     char reg_dest[40];
2469     char reg_coord[40];
2470     DWORD flags = TEX_LOD;
2471
2472     shader_arb_get_dst_param(ins, &ins->dst[0], reg_dest);
2473     shader_arb_get_src_param(ins, &ins->src[0], 0, reg_coord);
2474
2475     if (ins->flags & WINED3DSI_TEXLD_PROJECT) flags |= TEX_PROJ;
2476     if (ins->flags & WINED3DSI_TEXLD_BIAS) flags |= TEX_BIAS;
2477
2478     shader_hw_sample(ins, sampler_idx, reg_dest, reg_coord, flags, NULL, NULL);
2479 }
2480
2481 static GLuint create_arb_blt_vertex_program(const WineD3D_GL_Info *gl_info)
2482 {
2483     GLuint program_id = 0;
2484     const char *blt_vprogram =
2485         "!!ARBvp1.0\n"
2486         "PARAM c[1] = { { 1, 0.5 } };\n"
2487         "MOV result.position, vertex.position;\n"
2488         "MOV result.color, c[0].x;\n"
2489         "MOV result.texcoord[0], vertex.texcoord[0];\n"
2490         "END\n";
2491
2492     GL_EXTCALL(glGenProgramsARB(1, &program_id));
2493     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, program_id));
2494     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(blt_vprogram), blt_vprogram));
2495
2496     if (glGetError() == GL_INVALID_OPERATION) {
2497         GLint pos;
2498         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
2499         FIXME("Vertex program error at position %d: %s\n", pos,
2500             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2501     }
2502
2503     return program_id;
2504 }
2505
2506 /* GL locking is done by the caller */
2507 static GLuint create_arb_blt_fragment_program(const WineD3D_GL_Info *gl_info, enum tex_types tex_type)
2508 {
2509     GLuint program_id = 0;
2510     static const char * const blt_fprograms[tex_type_count] =
2511     {
2512         /* tex_1d */
2513         NULL,
2514         /* tex_2d */
2515         "!!ARBfp1.0\n"
2516         "TEMP R0;\n"
2517         "TEX R0.x, fragment.texcoord[0], texture[0], 2D;\n"
2518         "MOV result.depth.z, R0.x;\n"
2519         "END\n",
2520         /* tex_3d */
2521         NULL,
2522         /* tex_cube */
2523         "!!ARBfp1.0\n"
2524         "TEMP R0;\n"
2525         "TEX R0.x, fragment.texcoord[0], texture[0], CUBE;\n"
2526         "MOV result.depth.z, R0.x;\n"
2527         "END\n",
2528         /* tex_rect */
2529         "!!ARBfp1.0\n"
2530         "TEMP R0;\n"
2531         "TEX R0.x, fragment.texcoord[0], texture[0], RECT;\n"
2532         "MOV result.depth.z, R0.x;\n"
2533         "END\n",
2534     };
2535
2536     if (!blt_fprograms[tex_type])
2537     {
2538         FIXME("tex_type %#x not supported\n", tex_type);
2539         tex_type = tex_2d;
2540     }
2541
2542     GL_EXTCALL(glGenProgramsARB(1, &program_id));
2543     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, program_id));
2544     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(blt_fprograms[tex_type]), blt_fprograms[tex_type]));
2545
2546     if (glGetError() == GL_INVALID_OPERATION) {
2547         GLint pos;
2548         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
2549         FIXME("Fragment program error at position %d: %s\n", pos,
2550             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2551     }
2552
2553     return program_id;
2554 }
2555
2556 static void arbfp_add_sRGB_correction(SHADER_BUFFER *buffer, const char *fragcolor, const char *tmp1,
2557                                       const char *tmp2, const char *tmp3, const char *tmp4, BOOL condcode) {
2558     /* Perform sRGB write correction. See GLX_EXT_framebuffer_sRGB */
2559
2560     if(condcode)
2561     {
2562         /* Sigh. MOVC CC doesn't work, so use one of the temps as dummy dest */
2563         shader_addline(buffer, "SUBC %s, %s.x, srgb_consts1.y;\n", tmp1, fragcolor);
2564         /* Calculate the > 0.0031308 case */
2565         shader_addline(buffer, "POW %s.x (GE), %s.x, srgb_consts1.z;\n", fragcolor, fragcolor);
2566         shader_addline(buffer, "POW %s.y (GE), %s.y, srgb_consts1.z;\n", fragcolor, fragcolor);
2567         shader_addline(buffer, "POW %s.z (GE), %s.z, srgb_consts1.z;\n", fragcolor, fragcolor);
2568         shader_addline(buffer, "MUL %s.xyz (GE), %s, srgb_consts1.w;\n", fragcolor, fragcolor);
2569         shader_addline(buffer, "SUB %s.xyz (GE), %s, srgb_consts2.x;\n", fragcolor, fragcolor);
2570         /* Calculate the < case */
2571         shader_addline(buffer, "MUL %s.xyz (LT), srgb_consts1.x, %s;\n", fragcolor, fragcolor);
2572     }
2573     else
2574     {
2575         /* Calculate the > 0.0031308 case */
2576         shader_addline(buffer, "POW %s.x, %s.x, srgb_consts1.z;\n", tmp1, fragcolor);
2577         shader_addline(buffer, "POW %s.y, %s.y, srgb_consts1.z;\n", tmp1, fragcolor);
2578         shader_addline(buffer, "POW %s.z, %s.z, srgb_consts1.z;\n", tmp1, fragcolor);
2579         shader_addline(buffer, "MUL %s, %s, srgb_consts1.w;\n", tmp1, tmp1);
2580         shader_addline(buffer, "SUB %s, %s, srgb_consts2.x;\n", tmp1, tmp1);
2581         /* Calculate the < case */
2582         shader_addline(buffer, "MUL %s, srgb_consts1.x, %s;\n", tmp2, fragcolor);
2583         /* Get 1.0 / 0.0 masks for > 0.0031308 and < 0.0031308 */
2584         shader_addline(buffer, "SLT %s, srgb_consts1.y, %s;\n", tmp3, fragcolor);
2585         shader_addline(buffer, "SGE %s, srgb_consts1.y, %s;\n", tmp4, fragcolor);
2586         /* Store the components > 0.0031308 in the destination */
2587         shader_addline(buffer, "MUL %s.xyz, %s, %s;\n", fragcolor, tmp1, tmp3);
2588         /* Add the components that are < 0.0031308 */
2589         shader_addline(buffer, "MAD %s.xyz, %s, %s, %s;\n", fragcolor, tmp2, tmp4, fragcolor);
2590         /* Move everything into result.color at once. Nvidia hardware cannot handle partial
2591         * result.color writes(.rgb first, then .a), or handle overwriting already written
2592         * components. The assembler uses a temporary register in this case, which is usually
2593         * not allocated from one of our registers that were used earlier.
2594         */
2595     }
2596     shader_addline(buffer, "MOV result.color, %s;\n", fragcolor);
2597     /* [0.0;1.0] clamping. Not needed, this is done implicitly */
2598 }
2599
2600 static const DWORD *find_loop_control_values(IWineD3DBaseShaderImpl *This, DWORD idx)
2601 {
2602     const local_constant *constant;
2603
2604     LIST_FOR_EACH_ENTRY(constant, &This->baseShader.constantsI, local_constant, entry)
2605     {
2606         if (constant->idx == idx)
2607         {
2608             return constant->value;
2609         }
2610     }
2611     return NULL;
2612 }
2613
2614 /* GL locking is done by the caller */
2615 static GLuint shader_arb_generate_pshader(IWineD3DPixelShaderImpl *This,
2616         SHADER_BUFFER *buffer, const struct arb_ps_compile_args *args, struct arb_ps_compiled_shader *compiled)
2617 {
2618     const shader_reg_maps* reg_maps = &This->baseShader.reg_maps;
2619     CONST DWORD *function = This->baseShader.function;
2620     const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
2621     const local_constant *lconst;
2622     GLuint retval;
2623     char fragcolor[16];
2624     DWORD *lconst_map = local_const_mapping((IWineD3DBaseShaderImpl *) This), next_local, cur;
2625     struct shader_arb_ctx_priv priv_ctx;
2626     BOOL dcl_tmp = args->super.srgb_correction, dcl_td = FALSE;
2627     BOOL want_nv_prog = FALSE;
2628
2629     char srgbtmp[4][4];
2630     unsigned int i, found = 0;
2631
2632     for(i = 0; i < This->baseShader.limits.temporary; i++) {
2633
2634         /* Don't overwrite the color source */
2635         if(This->color0_mov && i == This->color0_reg) continue;
2636         else if(reg_maps->shader_version.major < 2 && i == 0) continue;
2637
2638         if(reg_maps->temporary[i]) {
2639             sprintf(srgbtmp[found], "R%u", i);
2640             found++;
2641             if(found == 4) break;
2642         }
2643     }
2644
2645     switch(found) {
2646         case 4: dcl_tmp = FALSE; break;
2647         case 0:
2648             sprintf(srgbtmp[0], "TA");
2649             sprintf(srgbtmp[1], "TB");
2650             sprintf(srgbtmp[2], "TC");
2651             sprintf(srgbtmp[3], "TD");
2652             dcl_td = TRUE;
2653             break;
2654         case 1:
2655             sprintf(srgbtmp[1], "TA");
2656             sprintf(srgbtmp[2], "TB");
2657             sprintf(srgbtmp[3], "TC");
2658             break;
2659         case 2:
2660             sprintf(srgbtmp[2], "TA");
2661             sprintf(srgbtmp[3], "TB");
2662             break;
2663         case 3:
2664             sprintf(srgbtmp[3], "TA");
2665             break;
2666     }
2667
2668     /*  Create the hw ARB shader */
2669     memset(&priv_ctx, 0, sizeof(priv_ctx));
2670     priv_ctx.cur_ps_args = args;
2671     priv_ctx.compiled_fprog = compiled;
2672     list_init(&priv_ctx.control_frames);
2673
2674     /* Avoid enabling NV_fragment_program* if we do not need it.
2675      *
2676      * Enabling GL_NV_fragment_program_option causes the driver to occupy a temporary register,
2677      * and it slows down the shader execution noticeably(about 5%). Usually our instruction emulation
2678      * is faster than what we gain from using higher native instructions. There are some things though
2679      * that cannot be emulated. In that case enable the extensions.
2680      * If the extension is enabled, instruction handlers that support both ways will use it.
2681      *
2682      * Testing shows no performance difference between OPTION NV_fragment_program2 and NV_fragment_program.
2683      * So enable the best we can get.
2684      */
2685     if(reg_maps->usesdsx || reg_maps->usesdsy || reg_maps->loop_depth > 0 || reg_maps->usestexldd ||
2686        reg_maps->usestexldl || reg_maps->usesfacing)
2687     {
2688         want_nv_prog = TRUE;
2689     }
2690
2691     shader_addline(buffer, "!!ARBfp1.0\n");
2692     if(want_nv_prog && GL_SUPPORT(NV_FRAGMENT_PROGRAM2)) {
2693         shader_addline(buffer, "OPTION NV_fragment_program2;\n");
2694         priv_ctx.target_version = NV3;
2695     } else if(want_nv_prog && GL_SUPPORT(NV_FRAGMENT_PROGRAM_OPTION)) {
2696         shader_addline(buffer, "OPTION NV_fragment_program;\n");
2697         priv_ctx.target_version = NV2;
2698     } else {
2699         if(want_nv_prog)
2700         {
2701             /* This is an error - either we're advertising the wrong shader version, or aren't enforcing some
2702              * limits properly
2703              */
2704             ERR("The shader requires instructions that are not available in plain GL_ARB_fragment_program\n");
2705             ERR("Try GLSL\n");
2706         }
2707         priv_ctx.target_version = ARB;
2708     }
2709
2710     if (reg_maps->shader_version.major < 3)
2711     {
2712         switch(args->super.fog) {
2713             case FOG_OFF:
2714                 break;
2715             case FOG_LINEAR:
2716                 shader_addline(buffer, "OPTION ARB_fog_linear;\n");
2717                 break;
2718             case FOG_EXP:
2719                 shader_addline(buffer, "OPTION ARB_fog_exp;\n");
2720                 break;
2721             case FOG_EXP2:
2722                 shader_addline(buffer, "OPTION ARB_fog_exp2;\n");
2723                 break;
2724         }
2725     }
2726
2727     /* For now always declare the temps. At least the Nvidia assembler optimizes completely
2728      * unused temps away(but occupies them for the whole shader if they're used once). Always
2729      * declaring them avoids tricky bookkeeping work
2730      */
2731     shader_addline(buffer, "TEMP TA;\n");      /* Used for modifiers */
2732     shader_addline(buffer, "TEMP TB;\n");      /* Used for modifiers */
2733     shader_addline(buffer, "TEMP TC;\n");      /* Used for modifiers */
2734     if(dcl_td) shader_addline(buffer, "TEMP TD;\n"); /* Used for sRGB writing */
2735     shader_addline(buffer, "PARAM coefdiv = { 0.5, 0.25, 0.125, 0.0625 };\n");
2736     shader_addline(buffer, "PARAM coefmul = { 2, 4, 8, 16 };\n");
2737     shader_addline(buffer, "PARAM one = { 1.0, 1.0, 1.0, 1.0 };\n");
2738
2739     if (reg_maps->shader_version.major < 2)
2740     {
2741         strcpy(fragcolor, "R0");
2742     } else {
2743         if(args->super.srgb_correction) {
2744             if(This->color0_mov) {
2745                 sprintf(fragcolor, "R%u", This->color0_reg);
2746             } else {
2747                 shader_addline(buffer, "TEMP TMP_COLOR;\n");
2748                 strcpy(fragcolor, "TMP_COLOR");
2749             }
2750         } else {
2751             strcpy(fragcolor, "result.color");
2752         }
2753     }
2754
2755     if(args->super.srgb_correction) {
2756         shader_addline(buffer, "PARAM srgb_consts1 = {%f, %f, %f, %f};\n",
2757                        srgb_mul_low, srgb_cmp, srgb_pow, srgb_mul_high);
2758         shader_addline(buffer, "PARAM srgb_consts2 = {%f, %f, %f, %f};\n",
2759                        srgb_sub_high, 0.0, 0.0, 0.0);
2760     }
2761
2762     /* Base Declarations */
2763     next_local = shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, lconst_map);
2764
2765     for(i = 0; i < (sizeof(reg_maps->bumpmat) / sizeof(reg_maps->bumpmat[0])); i++) {
2766         if(!reg_maps->bumpmat[i]) continue;
2767
2768         cur = compiled->numbumpenvmatconsts;
2769         compiled->bumpenvmatconst[cur].const_num = WINED3D_CONST_NUM_UNUSED;
2770         compiled->bumpenvmatconst[cur].texunit = i;
2771         compiled->luminanceconst[cur].const_num = WINED3D_CONST_NUM_UNUSED;
2772         compiled->luminanceconst[cur].texunit = i;
2773
2774         /* We can fit the constants into the constant limit for sure because texbem, texbeml, bem and beml are only supported
2775          * in 1.x shaders, and GL_ARB_fragment_program has a constant limit of 24 constants. So in the worst case we're loading
2776          * 8 shader constants, 8 bump matrices and 8 luminance parameters and are perfectly fine. (No NP2 fixup on bumpmapped
2777          * textures due to conditional NP2 restrictions)
2778          *
2779          * Use local constants to load the bump env parameters, not program.env. This avoids collisions with d3d constants of
2780          * shaders in newer shader models. Since the bump env parameters have to share their space with NP2 fixup constants,
2781          * their location is shader dependent anyway and they cannot be loaded globally.
2782          */
2783         compiled->bumpenvmatconst[cur].const_num = next_local++;
2784         shader_addline(buffer, "PARAM bumpenvmat%d = program.local[%d];\n",
2785                        i, compiled->bumpenvmatconst[cur].const_num);
2786         compiled->numbumpenvmatconsts = cur + 1;
2787
2788         if(!reg_maps->luminanceparams[i]) continue;
2789
2790         compiled->luminanceconst[cur].const_num = next_local++;
2791         shader_addline(buffer, "PARAM luminance%d = program.local[%d];\n",
2792                        i, compiled->luminanceconst[cur].const_num);
2793     }
2794
2795     for(i = 0; i < MAX_CONST_I; i++)
2796     {
2797         compiled->int_consts[i] = WINED3D_CONST_NUM_UNUSED;
2798         if (reg_maps->integer_constants & (1 << i) && priv_ctx.target_version >= NV2)
2799         {
2800             const DWORD *control_values = find_loop_control_values((IWineD3DBaseShaderImpl *) This, i);
2801
2802             if(control_values)
2803             {
2804                 shader_addline(buffer, "PARAM I%u = {%u, %u, %u, -1};\n", i,
2805                                 control_values[0], control_values[1], control_values[2]);
2806             }
2807             else
2808             {
2809                 compiled->int_consts[i] = next_local;
2810                 compiled->num_int_consts++;
2811                 shader_addline(buffer, "PARAM I%u = program.local[%u];\n", i, next_local++);
2812             }
2813         }
2814     }
2815
2816     if(reg_maps->vpos || reg_maps->usesdsy)
2817     {
2818         compiled->ycorrection = next_local;
2819         shader_addline(buffer, "PARAM ycorrection = program.local[%u];\n", next_local++);
2820
2821         if(reg_maps->vpos)
2822         {
2823             shader_addline(buffer, "TEMP vpos;\n");
2824             /* ycorrection.x: Backbuffer height(onscreen) or 0(offscreen).
2825              * ycorrection.y: -1.0(onscreen), 1.0(offscreen)
2826              * ycorrection.z: 1.0
2827              * ycorrection.w: 0.0
2828              */
2829             shader_addline(buffer, "MAD vpos, fragment.position, ycorrection.zyww, ycorrection.wxww;\n");
2830             shader_addline(buffer, "FLR vpos.xy, vpos;\n");
2831         }
2832     }
2833     else
2834     {
2835         compiled->ycorrection = WINED3D_CONST_NUM_UNUSED;
2836     }
2837
2838     /* Base Shader Body */
2839     shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
2840
2841     if(args->super.srgb_correction) {
2842         arbfp_add_sRGB_correction(buffer, fragcolor, srgbtmp[0], srgbtmp[1], srgbtmp[2], srgbtmp[3],
2843                                   priv_ctx.target_version >= NV2);
2844     } else if(reg_maps->shader_version.major < 2) {
2845         shader_addline(buffer, "MOV result.color, %s;\n", fragcolor);
2846     }
2847     shader_addline(buffer, "END\n");
2848
2849     /* TODO: change to resource.glObjectHandle or something like that */
2850     GL_EXTCALL(glGenProgramsARB(1, &retval));
2851
2852     TRACE("Creating a hw pixel shader, prg=%d\n", retval);
2853     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, retval));
2854
2855     TRACE("Created hw pixel shader, prg=%d\n", retval);
2856     /* Create the program and check for errors */
2857     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
2858                buffer->bsize, buffer->buffer));
2859
2860     if (glGetError() == GL_INVALID_OPERATION) {
2861         GLint errPos;
2862         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
2863         FIXME("HW PixelShader Error at position %d: %s\n",
2864               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
2865         retval = 0;
2866     }
2867
2868     /* Load immediate constants */
2869     if(lconst_map) {
2870         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
2871             const float *value = (const float *)lconst->value;
2872             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, lconst_map[lconst->idx], value));
2873             checkGLcall("glProgramLocalParameter4fvARB");
2874         }
2875         HeapFree(GetProcessHeap(), 0, lconst_map);
2876     }
2877
2878     return retval;
2879 }
2880
2881 /* GL locking is done by the caller */
2882 static GLuint shader_arb_generate_vshader(IWineD3DVertexShaderImpl *This,
2883         SHADER_BUFFER *buffer, const struct arb_vs_compile_args *args, struct arb_vs_compiled_shader *compiled)
2884 {
2885     const shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
2886     CONST DWORD *function = This->baseShader.function;
2887     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
2888     const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
2889     const local_constant *lconst;
2890     GLuint ret;
2891     DWORD *lconst_map = local_const_mapping((IWineD3DBaseShaderImpl *) This), next_local;
2892     struct shader_arb_ctx_priv priv_ctx;
2893     unsigned int i;
2894
2895     memset(&priv_ctx, 0, sizeof(priv_ctx));
2896     priv_ctx.cur_vs_args = args;
2897     list_init(&priv_ctx.control_frames);
2898
2899     /*  Create the hw ARB shader */
2900     shader_addline(buffer, "!!ARBvp1.0\n");
2901
2902     /* Always enable the NV extension if available. Unlike fragment shaders, there is no
2903      * mesurable performance penalty, and we can always make use of it for clipplanes.
2904      */
2905     if(GL_SUPPORT(NV_VERTEX_PROGRAM3)) {
2906         shader_addline(buffer, "OPTION NV_vertex_program3;\n");
2907         priv_ctx.target_version = NV3;
2908         shader_addline(buffer, "ADDRESS aL;\n");
2909     } else if(GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION)) {
2910         shader_addline(buffer, "OPTION NV_vertex_program2;\n");
2911         priv_ctx.target_version = NV2;
2912         shader_addline(buffer, "ADDRESS aL;\n");
2913     } else {
2914         priv_ctx.target_version = ARB;
2915     }
2916
2917     shader_addline(buffer, "TEMP TMP_OUT;\n");
2918     if(need_helper_const(gl_info)) {
2919         shader_addline(buffer, "PARAM helper_const = { 2.0, -1.0, %d.0, 0.0 };\n", This->rel_offset);
2920     }
2921     if(need_mova_const((IWineD3DBaseShader *) This, gl_info)) {
2922         shader_addline(buffer, "PARAM mova_const = { 0.5, 0.0, 2.0, 1.0 };\n");
2923         shader_addline(buffer, "TEMP A0_SHADOW;\n");
2924     }
2925
2926     shader_addline(buffer, "TEMP TA;\n");
2927
2928     /* Base Declarations */
2929     next_local = shader_generate_arb_declarations( (IWineD3DBaseShader*) This, reg_maps, buffer, &GLINFO_LOCATION, lconst_map);
2930
2931     for(i = 0; i < MAX_CONST_I; i++)
2932     {
2933         compiled->int_consts[i] = WINED3D_CONST_NUM_UNUSED;
2934         if(reg_maps->integer_constants & (1 << i) && priv_ctx.target_version >= NV2)
2935         {
2936             const DWORD *control_values = find_loop_control_values((IWineD3DBaseShaderImpl *) This, i);
2937
2938             if(control_values)
2939             {
2940                 shader_addline(buffer, "PARAM I%u = {%u, %u, %u, -1};\n", i,
2941                                 control_values[0], control_values[1], control_values[2]);
2942             }
2943             else
2944             {
2945                 compiled->int_consts[i] = next_local;
2946                 compiled->num_int_consts++;
2947                 shader_addline(buffer, "PARAM I%u = program.local[%u];\n", i, next_local++);
2948             }
2949         }
2950     }
2951
2952     /* We need a constant to fixup the final position */
2953     shader_addline(buffer, "PARAM posFixup = program.env[%d];\n", ARB_SHADER_PRIVCONST_POS);
2954
2955     /* Initialize output parameters. GL_ARB_vertex_program does not require special initialization values
2956      * for output parameters. D3D in theory does not do that either, but some applications depend on a
2957      * proper initialization of the secondary color, and programs using the fixed function pipeline without
2958      * a replacement shader depend on the texcoord.w being set properly.
2959      *
2960      * GL_NV_vertex_program defines that all output values are initialized to {0.0, 0.0, 0.0, 1.0}. This
2961      * assertion is in effect even when using GL_ARB_vertex_program without any NV specific additions. So
2962      * skip this if NV_vertex_program is supported. Otherwise, initialize the secondary color. For the tex-
2963      * coords, we have a flag in the opengl caps. Many cards do not require the texcoord being set, and
2964      * this can eat a number of instructions, so skip it unless this cap is set as well
2965      */
2966     if(!GL_SUPPORT(NV_VERTEX_PROGRAM)) {
2967         shader_addline(buffer, "MOV result.color.secondary, -helper_const.wwwy;\n");
2968
2969         if((GLINFO_LOCATION).set_texcoord_w && !device->frag_pipe->ffp_proj_control) {
2970             int i;
2971             for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
2972                 if(This->baseShader.reg_maps.texcoord_mask[i] != 0 &&
2973                 This->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
2974                     shader_addline(buffer, "MOV result.texcoord[%u].w, -helper_const.y;\n", i);
2975                 }
2976             }
2977         }
2978     }
2979
2980     /* Base Shader Body */
2981     shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
2982
2983     /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
2984      * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
2985      * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
2986      * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
2987      */
2988     if(args->super.fog_src == VS_FOG_Z) {
2989         shader_addline(buffer, "MOV result.fogcoord, TMP_OUT.z;\n");
2990     } else if (!reg_maps->fog) {
2991         /* posFixup.x is always 1.0, so we can savely use it */
2992         shader_addline(buffer, "ADD result.fogcoord, posFixup.x, -posFixup.x;\n");
2993     }
2994
2995     /* Write the final position.
2996      *
2997      * OpenGL coordinates specify the center of the pixel while d3d coords specify
2998      * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
2999      * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
3000      * contains 1.0 to allow a mad, but arb vs swizzles are too restricted for that.
3001      */
3002     shader_addline(buffer, "MUL TA, posFixup, TMP_OUT.w;\n");
3003     shader_addline(buffer, "ADD TMP_OUT.x, TMP_OUT.x, TA.z;\n");
3004     shader_addline(buffer, "MAD TMP_OUT.y, TMP_OUT.y, posFixup.y, TA.w;\n");
3005
3006     if(priv_ctx.target_version >= NV2)
3007     {
3008         for(i = 0; i < GL_LIMITS(clipplanes); i++)
3009         {
3010             shader_addline(buffer, "DP4 result.clip[%u].x, TMP_OUT, state.clip[%u].plane;\n", i, i);
3011         }
3012     }
3013
3014     /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
3015      * and the glsl equivalent
3016      */
3017     if(need_helper_const(gl_info)) {
3018         shader_addline(buffer, "MAD TMP_OUT.z, TMP_OUT.z, helper_const.x, -TMP_OUT.w;\n");
3019     } else {
3020         shader_addline(buffer, "ADD TMP_OUT.z, TMP_OUT.z, TMP_OUT.z;\n");
3021         shader_addline(buffer, "ADD TMP_OUT.z, TMP_OUT.z, -TMP_OUT.w;\n");
3022     }
3023
3024     shader_addline(buffer, "MOV result.position, TMP_OUT;\n");
3025
3026     shader_addline(buffer, "END\n");
3027
3028     /* TODO: change to resource.glObjectHandle or something like that */
3029     GL_EXTCALL(glGenProgramsARB(1, &ret));
3030
3031     TRACE("Creating a hw vertex shader, prg=%d\n", ret);
3032     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, ret));
3033
3034     TRACE("Created hw vertex shader, prg=%d\n", ret);
3035     /* Create the program and check for errors */
3036     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
3037                buffer->bsize, buffer->buffer));
3038
3039     if (glGetError() == GL_INVALID_OPERATION) {
3040         GLint errPos;
3041         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
3042         FIXME("HW VertexShader Error at position %d: %s\n",
3043               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
3044         ret = -1;
3045     } else {
3046         /* Load immediate constants */
3047         if(lconst_map) {
3048             LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
3049                 const float *value = (const float *)lconst->value;
3050                 GL_EXTCALL(glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, lconst_map[lconst->idx], value));
3051             }
3052         }
3053     }
3054     HeapFree(GetProcessHeap(), 0, lconst_map);
3055
3056     return ret;
3057 }
3058
3059 /* GL locking is done by the caller */
3060 static struct arb_ps_compiled_shader *find_arb_pshader(IWineD3DPixelShaderImpl *shader, const struct arb_ps_compile_args *args)
3061 {
3062     UINT i;
3063     DWORD new_size;
3064     struct arb_ps_compiled_shader *new_array;
3065     SHADER_BUFFER buffer;
3066     struct arb_pshader_private *shader_data;
3067     GLuint ret;
3068
3069     if(!shader->backend_priv) {
3070         shader->backend_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3071     }
3072     shader_data = shader->backend_priv;
3073
3074     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3075      * so a linear search is more performant than a hashmap or a binary search
3076      * (cache coherency etc)
3077      */
3078     for(i = 0; i < shader_data->num_gl_shaders; i++) {
3079         if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
3080             return &shader_data->gl_shaders[i];
3081         }
3082     }
3083
3084     TRACE("No matching GL shader found, compiling a new shader\n");
3085     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
3086         if (shader_data->num_gl_shaders)
3087         {
3088             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
3089             new_array = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, shader_data->gl_shaders,
3090                                     new_size * sizeof(*shader_data->gl_shaders));
3091         } else {
3092             new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
3093             new_size = 1;
3094         }
3095
3096         if(!new_array) {
3097             ERR("Out of memory\n");
3098             return 0;
3099         }
3100         shader_data->gl_shaders = new_array;
3101         shader_data->shader_array_size = new_size;
3102     }
3103
3104     shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
3105
3106     pixelshader_update_samplers(&shader->baseShader.reg_maps,
3107             ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
3108
3109     shader_buffer_init(&buffer);
3110     ret = shader_arb_generate_pshader(shader, &buffer, args,
3111                                       &shader_data->gl_shaders[shader_data->num_gl_shaders]);
3112     shader_buffer_free(&buffer);
3113     shader_data->gl_shaders[shader_data->num_gl_shaders].prgId = ret;
3114
3115     return &shader_data->gl_shaders[shader_data->num_gl_shaders++];
3116 }
3117
3118 static inline BOOL vs_args_equal(const struct arb_vs_compile_args *stored, const struct arb_vs_compile_args *new,
3119                                  const DWORD use_map, BOOL skip_int) {
3120     if((stored->super.swizzle_map & use_map) != new->super.swizzle_map) return FALSE;
3121     if(stored->super.fog_src != new->super.fog_src) return FALSE;
3122     if(stored->bools != new->bools) return FALSE;
3123     if(skip_int) return TRUE;
3124
3125     return memcmp(stored->loop_ctrl, new->loop_ctrl, sizeof(stored->loop_ctrl)) == 0;
3126 }
3127
3128 static struct arb_vs_compiled_shader *find_arb_vshader(IWineD3DVertexShaderImpl *shader, const struct arb_vs_compile_args *args)
3129 {
3130     UINT i;
3131     DWORD new_size;
3132     struct arb_vs_compiled_shader *new_array;
3133     DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
3134     SHADER_BUFFER buffer;
3135     struct arb_vshader_private *shader_data;
3136     GLuint ret;
3137     const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)shader->baseShader.device)->adapter->gl_info;
3138
3139     if(!shader->backend_priv) {
3140         shader->backend_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
3141     }
3142     shader_data = shader->backend_priv;
3143
3144     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
3145      * so a linear search is more performant than a hashmap or a binary search
3146      * (cache coherency etc)
3147      */
3148     for(i = 0; i < shader_data->num_gl_shaders; i++) {
3149         if(vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map, GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION))) {
3150             return &shader_data->gl_shaders[i];
3151         }
3152     }
3153
3154     TRACE("No matching GL shader found, compiling a new shader\n");
3155
3156     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
3157         if (shader_data->num_gl_shaders)
3158         {
3159             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
3160             new_array = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, shader_data->gl_shaders,
3161                                     new_size * sizeof(*shader_data->gl_shaders));
3162         } else {
3163             new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
3164             new_size = 1;
3165         }
3166
3167         if(!new_array) {
3168             ERR("Out of memory\n");
3169             return 0;
3170         }
3171         shader_data->gl_shaders = new_array;
3172         shader_data->shader_array_size = new_size;
3173     }
3174
3175     shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
3176
3177     shader_buffer_init(&buffer);
3178     ret = shader_arb_generate_vshader(shader, &buffer, args,
3179             &shader_data->gl_shaders[shader_data->num_gl_shaders]);
3180     shader_buffer_free(&buffer);
3181     shader_data->gl_shaders[shader_data->num_gl_shaders].prgId = ret;
3182
3183     return &shader_data->gl_shaders[shader_data->num_gl_shaders++];
3184 }
3185
3186 static inline void find_arb_ps_compile_args(IWineD3DPixelShaderImpl *shader, IWineD3DStateBlockImpl *stateblock,
3187         struct arb_ps_compile_args *args)
3188 {
3189     int i;
3190     WORD int_skip;
3191     const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)shader->baseShader.device)->adapter->gl_info;
3192     find_ps_compile_args(shader, stateblock, &args->super);
3193
3194     /* This forces all local boolean constants to 1 to make them stateblock independent */
3195     args->bools = shader->baseShader.reg_maps.local_bool_consts;
3196
3197     for(i = 0; i < MAX_CONST_B; i++)
3198     {
3199         if(stateblock->pixelShaderConstantB[i]) args->bools |= ( 1 << i);
3200     }
3201
3202     /* Skip if unused or local, or supported natively */
3203     int_skip = ~shader->baseShader.reg_maps.integer_constants | shader->baseShader.reg_maps.local_int_consts;
3204     if(int_skip == 0xffff || GL_SUPPORT(NV_FRAGMENT_PROGRAM_OPTION))
3205     {
3206         memset(&args->loop_ctrl, 0, sizeof(args->loop_ctrl));
3207         return;
3208     }
3209
3210     for(i = 0; i < MAX_CONST_I; i++)
3211     {
3212         if(int_skip & (1 << i))
3213         {
3214             args->loop_ctrl[i][0] = 0;
3215             args->loop_ctrl[i][1] = 0;
3216             args->loop_ctrl[i][2] = 0;
3217         }
3218         else
3219         {
3220             args->loop_ctrl[i][0] = stateblock->pixelShaderConstantI[i * 4];
3221             args->loop_ctrl[i][1] = stateblock->pixelShaderConstantI[i * 4 + 1];
3222             args->loop_ctrl[i][2] = stateblock->pixelShaderConstantI[i * 4 + 2];
3223         }
3224     }
3225 }
3226
3227 static inline void find_arb_vs_compile_args(IWineD3DVertexShaderImpl *shader, IWineD3DStateBlockImpl *stateblock,
3228         struct arb_vs_compile_args *args)
3229 {
3230     int i;
3231     WORD int_skip;
3232     const WineD3D_GL_Info *gl_info = &((IWineD3DDeviceImpl *)shader->baseShader.device)->adapter->gl_info;
3233     find_vs_compile_args(shader, stateblock, &args->super);
3234
3235     /* This forces all local boolean constants to 1 to make them stateblock independent */
3236     args->bools = shader->baseShader.reg_maps.local_bool_consts;
3237
3238     /* TODO: Figure out if it would be better to store bool constants as bitmasks in the stateblock */
3239     for(i = 0; i < MAX_CONST_B; i++)
3240     {
3241         if(stateblock->vertexShaderConstantB[i]) args->bools |= ( 1 << i);
3242     }
3243
3244     /* Skip if unused or local */
3245     int_skip = ~shader->baseShader.reg_maps.integer_constants | shader->baseShader.reg_maps.local_int_consts;
3246     if(int_skip == 0xffff || GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION))
3247     {
3248         memset(&args->loop_ctrl, 0, sizeof(args->loop_ctrl));
3249         return;
3250     }
3251
3252     for(i = 0; i < MAX_CONST_I; i++)
3253     {
3254         if(int_skip & (1 << i))
3255         {
3256             args->loop_ctrl[i][0] = 0;
3257             args->loop_ctrl[i][1] = 0;
3258             args->loop_ctrl[i][2] = 0;
3259         }
3260         else
3261         {
3262             args->loop_ctrl[i][0] = stateblock->vertexShaderConstantI[i * 4];
3263             args->loop_ctrl[i][1] = stateblock->vertexShaderConstantI[i * 4 + 1];
3264             args->loop_ctrl[i][2] = stateblock->vertexShaderConstantI[i * 4 + 2];
3265         }
3266     }
3267 }
3268
3269 /* GL locking is done by the caller */
3270 static void shader_arb_select(IWineD3DDevice *iface, BOOL usePS, BOOL useVS) {
3271     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3272     struct shader_arb_priv *priv = This->shader_priv;
3273     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3274
3275     if (useVS) {
3276         struct arb_vs_compile_args compile_args;
3277         struct arb_vs_compiled_shader *compiled;
3278
3279         TRACE("Using vertex shader %p\n", This->stateBlock->vertexShader);
3280         find_arb_vs_compile_args((IWineD3DVertexShaderImpl *) This->stateBlock->vertexShader, This->stateBlock, &compile_args);
3281         compiled = find_arb_vshader((IWineD3DVertexShaderImpl *) This->stateBlock->vertexShader, &compile_args);
3282         priv->current_vprogram_id = compiled->prgId;
3283         priv->compiled_vprog = compiled;
3284
3285         /* Bind the vertex program */
3286         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
3287         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id);");
3288
3289         /* Enable OpenGL vertex programs */
3290         glEnable(GL_VERTEX_PROGRAM_ARB);
3291         checkGLcall("glEnable(GL_VERTEX_PROGRAM_ARB);");
3292         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
3293         shader_arb_vs_local_constants(This);
3294     } else if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
3295         priv->current_vprogram_id = 0;
3296         glDisable(GL_VERTEX_PROGRAM_ARB);
3297         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
3298     }
3299
3300     if (usePS) {
3301         struct arb_ps_compile_args compile_args;
3302         struct arb_ps_compiled_shader *compiled;
3303         TRACE("Using pixel shader\n");
3304         find_arb_ps_compile_args((IWineD3DPixelShaderImpl *) This->stateBlock->pixelShader, This->stateBlock, &compile_args);
3305         compiled = find_arb_pshader((IWineD3DPixelShaderImpl *) This->stateBlock->pixelShader,
3306                                     &compile_args);
3307         priv->current_fprogram_id = compiled->prgId;
3308         priv->compiled_fprog = compiled;
3309
3310         /* Bind the fragment program */
3311         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
3312         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id);");
3313
3314         if(!priv->use_arbfp_fixed_func) {
3315             /* Enable OpenGL fragment programs */
3316             glEnable(GL_FRAGMENT_PROGRAM_ARB);
3317             checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB);");
3318         }
3319         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
3320
3321         shader_arb_ps_local_constants(This);
3322     } else if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM) && !priv->use_arbfp_fixed_func) {
3323         /* Disable only if we're not using arbfp fixed function fragment processing. If this is used,
3324          * keep GL_FRAGMENT_PROGRAM_ARB enabled, and the fixed function pipeline will bind the fixed function
3325          * replacement shader
3326          */
3327         glDisable(GL_FRAGMENT_PROGRAM_ARB);
3328         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
3329         priv->current_fprogram_id = 0;
3330     }
3331 }
3332
3333 /* GL locking is done by the caller */
3334 static void shader_arb_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
3335     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3336     struct shader_arb_priv *priv = This->shader_priv;
3337     GLuint *blt_fprogram = &priv->depth_blt_fprogram_id[tex_type];
3338     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3339
3340     if (!priv->depth_blt_vprogram_id) priv->depth_blt_vprogram_id = create_arb_blt_vertex_program(gl_info);
3341     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->depth_blt_vprogram_id));
3342     glEnable(GL_VERTEX_PROGRAM_ARB);
3343
3344     if (!*blt_fprogram) *blt_fprogram = create_arb_blt_fragment_program(gl_info, tex_type);
3345     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, *blt_fprogram));
3346     glEnable(GL_FRAGMENT_PROGRAM_ARB);
3347 }
3348
3349 /* GL locking is done by the caller */
3350 static void shader_arb_deselect_depth_blt(IWineD3DDevice *iface) {
3351     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3352     struct shader_arb_priv *priv = This->shader_priv;
3353     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3354
3355     if (priv->current_vprogram_id) {
3356         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
3357         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vertexShader->prgId);");
3358
3359         glEnable(GL_VERTEX_PROGRAM_ARB);
3360         checkGLcall("glEnable(GL_VERTEX_PROGRAM_ARB);");
3361
3362         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
3363     } else {
3364         glDisable(GL_VERTEX_PROGRAM_ARB);
3365         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
3366     }
3367
3368     if (priv->current_fprogram_id) {
3369         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
3370         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, pixelShader->prgId);");
3371
3372         glEnable(GL_FRAGMENT_PROGRAM_ARB);
3373         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB);");
3374
3375         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
3376     } else {
3377         glDisable(GL_FRAGMENT_PROGRAM_ARB);
3378         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
3379     }
3380 }
3381
3382 static void shader_arb_destroy(IWineD3DBaseShader *iface) {
3383     IWineD3DBaseShaderImpl *baseShader = (IWineD3DBaseShaderImpl *) iface;
3384     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)baseShader->baseShader.device;
3385     const WineD3D_GL_Info *gl_info = &device->adapter->gl_info;
3386
3387     ActivateContext(device, device->lastActiveRenderTarget, CTXUSAGE_RESOURCELOAD);
3388
3389     if (shader_is_pshader_version(baseShader->baseShader.reg_maps.shader_version.type))
3390     {
3391         IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *) iface;
3392         struct arb_pshader_private *shader_data = This->backend_priv;
3393         UINT i;
3394
3395         if(!shader_data) return; /* This can happen if a shader was never compiled */
3396         ENTER_GL();
3397         for(i = 0; i < shader_data->num_gl_shaders; i++) {
3398             GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId));
3399             checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId))");
3400         }
3401         LEAVE_GL();
3402         HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
3403         HeapFree(GetProcessHeap(), 0, shader_data);
3404         This->backend_priv = NULL;
3405     } else {
3406         IWineD3DVertexShaderImpl *This = (IWineD3DVertexShaderImpl *) iface;
3407         struct arb_vshader_private *shader_data = This->backend_priv;
3408         UINT i;
3409
3410         if(!shader_data) return; /* This can happen if a shader was never compiled */
3411         ENTER_GL();
3412         for(i = 0; i < shader_data->num_gl_shaders; i++) {
3413             GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId));
3414             checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId))");
3415         }
3416         LEAVE_GL();
3417         HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
3418         HeapFree(GetProcessHeap(), 0, shader_data);
3419         This->backend_priv = NULL;
3420     }
3421 }
3422
3423 static HRESULT shader_arb_alloc(IWineD3DDevice *iface) {
3424     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3425     This->shader_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_arb_priv));
3426     return WINED3D_OK;
3427 }
3428
3429 static void shader_arb_free(IWineD3DDevice *iface) {
3430     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
3431     const WineD3D_GL_Info *gl_info = &This->adapter->gl_info;
3432     struct shader_arb_priv *priv = This->shader_priv;
3433     int i;
3434
3435     ENTER_GL();
3436     if(priv->depth_blt_vprogram_id) {
3437         GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_vprogram_id));
3438     }
3439     for (i = 0; i < tex_type_count; ++i) {
3440         if (priv->depth_blt_fprogram_id[i]) {
3441             GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_fprogram_id[i]));
3442         }
3443     }
3444     LEAVE_GL();
3445
3446     HeapFree(GetProcessHeap(), 0, This->shader_priv);
3447 }
3448
3449 static BOOL shader_arb_dirty_const(IWineD3DDevice *iface) {
3450     return TRUE;
3451 }
3452
3453 static void shader_arb_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct shader_caps *pCaps)
3454 {
3455     /* We don't have an ARB fixed function pipeline yet, so let the none backend set its caps,
3456      * then overwrite the shader specific ones
3457      */
3458     none_shader_backend.shader_get_caps(devtype, gl_info, pCaps);
3459
3460     if(GL_SUPPORT(ARB_VERTEX_PROGRAM)) {
3461         pCaps->VertexShaderVersion = WINED3DVS_VERSION(1,1);
3462         TRACE_(d3d_caps)("Hardware vertex shader version 1.1 enabled (ARB_PROGRAM)\n");
3463         pCaps->MaxVertexShaderConst = GL_LIMITS(vshader_constantsF) - 1;
3464     }
3465
3466     if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
3467         pCaps->PixelShaderVersion    = WINED3DPS_VERSION(1,4);
3468         pCaps->PixelShader1xMaxValue = 8.0;
3469         TRACE_(d3d_caps)("Hardware pixel shader version 1.4 enabled (ARB_PROGRAM)\n");
3470         pCaps->MaxPixelShaderConst = GL_LIMITS(pshader_constantsF);
3471     }
3472
3473     pCaps->VSClipping = GL_SUPPORT(NV_VERTEX_PROGRAM2_OPTION);
3474 }
3475
3476 static BOOL shader_arb_color_fixup_supported(struct color_fixup_desc fixup)
3477 {
3478     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
3479     {
3480         TRACE("Checking support for color_fixup:\n");
3481         dump_color_fixup_desc(fixup);
3482     }
3483
3484     /* We support everything except YUV conversions. */
3485     if (!is_yuv_fixup(fixup))
3486     {
3487         TRACE("[OK]\n");
3488         return TRUE;
3489     }
3490
3491     TRACE("[FAILED]\n");
3492     return FALSE;
3493 }
3494
3495 static void shader_arb_add_instruction_modifiers(const struct wined3d_shader_instruction *ins) {
3496     DWORD shift;
3497     char write_mask[20], regstr[50];
3498     SHADER_BUFFER *buffer = ins->ctx->buffer;
3499     BOOL is_color = FALSE;
3500     const struct wined3d_shader_dst_param *dst;
3501
3502     if (!ins->dst_count) return;
3503
3504     dst = &ins->dst[0];
3505     shift = dst->shift;
3506     if(shift == 0) return; /* Saturate alone is handled by the instructions */
3507
3508     shader_arb_get_write_mask(ins, dst, write_mask);
3509     shader_arb_get_register_name(ins, &dst->reg, regstr, &is_color);
3510
3511     /* Generate a line that does the output modifier computation
3512      * FIXME: _SAT vs shift? _SAT alone is already handled in the instructions, if this
3513      * maps problems in e.g. _d4_sat modify shader_arb_get_modifier
3514      */
3515     shader_addline(buffer, "MUL%s %s%s, %s, %s;\n", shader_arb_get_modifier(ins),
3516                    regstr, write_mask, regstr, shift_tab[shift]);
3517 }
3518
3519 static const SHADER_HANDLER shader_arb_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
3520 {
3521     /* WINED3DSIH_ABS           */ shader_hw_map2gl,
3522     /* WINED3DSIH_ADD           */ shader_hw_map2gl,
3523     /* WINED3DSIH_BEM           */ pshader_hw_bem,
3524     /* WINED3DSIH_BREAK         */ shader_hw_break,
3525     /* WINED3DSIH_BREAKC        */ shader_hw_breakc,
3526     /* WINED3DSIH_BREAKP        */ NULL,
3527     /* WINED3DSIH_CALL          */ NULL,
3528     /* WINED3DSIH_CALLNZ        */ NULL,
3529     /* WINED3DSIH_CMP           */ pshader_hw_cmp,
3530     /* WINED3DSIH_CND           */ pshader_hw_cnd,
3531     /* WINED3DSIH_CRS           */ shader_hw_map2gl,
3532     /* WINED3DSIH_DCL           */ NULL,
3533     /* WINED3DSIH_DEF           */ NULL,
3534     /* WINED3DSIH_DEFB          */ NULL,
3535     /* WINED3DSIH_DEFI          */ NULL,
3536     /* WINED3DSIH_DP2ADD        */ pshader_hw_dp2add,
3537     /* WINED3DSIH_DP3           */ shader_hw_map2gl,
3538     /* WINED3DSIH_DP4           */ shader_hw_map2gl,
3539     /* WINED3DSIH_DST           */ shader_hw_map2gl,
3540     /* WINED3DSIH_DSX           */ shader_hw_map2gl,
3541     /* WINED3DSIH_DSY           */ shader_hw_dsy,
3542     /* WINED3DSIH_ELSE          */ shader_hw_else,
3543     /* WINED3DSIH_ENDIF         */ shader_hw_endif,
3544     /* WINED3DSIH_ENDLOOP       */ shader_hw_endloop,
3545     /* WINED3DSIH_ENDREP        */ shader_hw_endrep,
3546     /* WINED3DSIH_EXP           */ shader_hw_map2gl,
3547     /* WINED3DSIH_EXPP          */ shader_hw_map2gl,
3548     /* WINED3DSIH_FRC           */ shader_hw_map2gl,
3549     /* WINED3DSIH_IF            */ NULL /* Hardcoded into the shader */,
3550     /* WINED3DSIH_IFC           */ shader_hw_ifc,
3551     /* WINED3DSIH_LABEL         */ NULL,
3552     /* WINED3DSIH_LIT           */ shader_hw_map2gl,
3553     /* WINED3DSIH_LOG           */ shader_hw_map2gl,
3554     /* WINED3DSIH_LOGP          */ shader_hw_map2gl,
3555     /* WINED3DSIH_LOOP          */ shader_hw_loop,
3556     /* WINED3DSIH_LRP           */ shader_hw_lrp,
3557     /* WINED3DSIH_M3x2          */ shader_hw_mnxn,
3558     /* WINED3DSIH_M3x3          */ shader_hw_mnxn,
3559     /* WINED3DSIH_M3x4          */ shader_hw_mnxn,
3560     /* WINED3DSIH_M4x3          */ shader_hw_mnxn,
3561     /* WINED3DSIH_M4x4          */ shader_hw_mnxn,
3562     /* WINED3DSIH_MAD           */ shader_hw_map2gl,
3563     /* WINED3DSIH_MAX           */ shader_hw_map2gl,
3564     /* WINED3DSIH_MIN           */ shader_hw_map2gl,
3565     /* WINED3DSIH_MOV           */ shader_hw_mov,
3566     /* WINED3DSIH_MOVA          */ shader_hw_mov,
3567     /* WINED3DSIH_MUL           */ shader_hw_map2gl,
3568     /* WINED3DSIH_NOP           */ shader_hw_nop,
3569     /* WINED3DSIH_NRM           */ shader_hw_nrm,
3570     /* WINED3DSIH_PHASE         */ NULL,
3571     /* WINED3DSIH_POW           */ shader_hw_map2gl,
3572     /* WINED3DSIH_RCP           */ shader_hw_rsq_rcp,
3573     /* WINED3DSIH_REP           */ shader_hw_rep,
3574     /* WINED3DSIH_RET           */ NULL,
3575     /* WINED3DSIH_RSQ           */ shader_hw_rsq_rcp,
3576     /* WINED3DSIH_SETP          */ NULL,
3577     /* WINED3DSIH_SGE           */ shader_hw_map2gl,
3578     /* WINED3DSIH_SGN           */ shader_hw_sgn,
3579     /* WINED3DSIH_SINCOS        */ shader_hw_sincos,
3580     /* WINED3DSIH_SLT           */ shader_hw_map2gl,
3581     /* WINED3DSIH_SUB           */ shader_hw_map2gl,
3582     /* WINED3DSIH_TEX           */ pshader_hw_tex,
3583     /* WINED3DSIH_TEXBEM        */ pshader_hw_texbem,
3584     /* WINED3DSIH_TEXBEML       */ pshader_hw_texbem,
3585     /* WINED3DSIH_TEXCOORD      */ pshader_hw_texcoord,
3586     /* WINED3DSIH_TEXDEPTH      */ pshader_hw_texdepth,
3587     /* WINED3DSIH_TEXDP3        */ pshader_hw_texdp3,
3588     /* WINED3DSIH_TEXDP3TEX     */ pshader_hw_texdp3tex,
3589     /* WINED3DSIH_TEXKILL       */ pshader_hw_texkill,
3590     /* WINED3DSIH_TEXLDD        */ shader_hw_texldd,
3591     /* WINED3DSIH_TEXLDL        */ shader_hw_texldl,
3592     /* WINED3DSIH_TEXM3x2DEPTH  */ pshader_hw_texm3x2depth,
3593     /* WINED3DSIH_TEXM3x2PAD    */ pshader_hw_texm3x2pad,
3594     /* WINED3DSIH_TEXM3x2TEX    */ pshader_hw_texm3x2tex,
3595     /* WINED3DSIH_TEXM3x3       */ pshader_hw_texm3x3,
3596     /* WINED3DSIH_TEXM3x3DIFF   */ NULL,
3597     /* WINED3DSIH_TEXM3x3PAD    */ pshader_hw_texm3x3pad,
3598     /* WINED3DSIH_TEXM3x3SPEC   */ pshader_hw_texm3x3spec,
3599     /* WINED3DSIH_TEXM3x3TEX    */ pshader_hw_texm3x3tex,
3600     /* WINED3DSIH_TEXM3x3VSPEC  */ pshader_hw_texm3x3vspec,
3601     /* WINED3DSIH_TEXREG2AR     */ pshader_hw_texreg2ar,
3602     /* WINED3DSIH_TEXREG2GB     */ pshader_hw_texreg2gb,
3603     /* WINED3DSIH_TEXREG2RGB    */ pshader_hw_texreg2rgb,
3604 };
3605
3606 static inline BOOL get_bool_const(const struct wined3d_shader_instruction *ins, IWineD3DBaseShaderImpl *This, DWORD idx)
3607 {
3608     BOOL vshader = shader_is_vshader_version(This->baseShader.reg_maps.shader_version.type);
3609     WORD bools = 0;
3610     WORD flag = (1 << idx);
3611     const local_constant *constant;
3612     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
3613
3614     if(This->baseShader.reg_maps.local_bool_consts & flag)
3615     {
3616         /* What good is a if(bool) with a hardcoded local constant? I don't know, but handle it */
3617         LIST_FOR_EACH_ENTRY(constant, &This->baseShader.constantsB, local_constant, entry)
3618         {
3619             if (constant->idx == idx)
3620             {
3621                 return constant->value[0];
3622             }
3623         }
3624         ERR("Local constant not found\n");
3625         return FALSE;
3626     }
3627     else
3628     {
3629         if(vshader) bools = priv->cur_vs_args->bools;
3630         else bools = priv->cur_ps_args->bools;
3631         return bools & flag;
3632     }
3633 }
3634
3635 static inline void get_int_const(const struct wined3d_shader_instruction *ins, IWineD3DBaseShaderImpl *This, DWORD idx, int *ret)
3636 {
3637     BOOL vshader = shader_is_vshader_version(This->baseShader.reg_maps.shader_version.type);
3638     WORD flag = (1 << idx);
3639     const local_constant *constant;
3640     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
3641
3642     /* Integer constants can either be a local constant, or they can be stored in the shader
3643      * type specific compile args
3644      */
3645     if(This->baseShader.reg_maps.local_int_consts & flag)
3646     {
3647         LIST_FOR_EACH_ENTRY(constant, &This->baseShader.constantsI, local_constant, entry)
3648         {
3649             if (constant->idx == idx)
3650             {
3651                 ret[0] = constant->value[0];
3652                 ret[1] = constant->value[1];
3653                 /* Step / stride is signed */
3654                 ret[2] = (int) constant->value[2];
3655                 return;
3656             }
3657         }
3658         /* If this happens the flag was set incorrectly */
3659         ERR("Local constant not found\n");
3660         ret[0] = 0;
3661         ret[1] = 0;
3662         ret[2] = 0;
3663         return;
3664     }
3665     else
3666     {
3667         if(vshader)
3668         {
3669             /* Count and aL start value are unsigned */
3670             ret[0] = priv->cur_vs_args->loop_ctrl[idx][0];
3671             ret[1] = priv->cur_vs_args->loop_ctrl[idx][1];
3672             /* The step/stride is signed */
3673             ret[2] = ((char) priv->cur_vs_args->loop_ctrl[idx][2]);
3674         }
3675         else
3676         {
3677             ret[0] = priv->cur_ps_args->loop_ctrl[idx][0];
3678             ret[1] = priv->cur_ps_args->loop_ctrl[idx][1];
3679             ret[2] = ((char) priv->cur_ps_args->loop_ctrl[idx][2]);
3680         }
3681         return;
3682     }
3683 }
3684
3685 static void record_instruction(struct list *list, const struct wined3d_shader_instruction *ins)
3686 {
3687     unsigned int i;
3688     struct wined3d_shader_dst_param *dst_param = NULL;
3689     struct wined3d_shader_src_param *src_param = NULL, *rel_addr = NULL;
3690     struct recorded_instruction *rec = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rec));
3691     if(!rec)
3692     {
3693         ERR("Out of memory\n");
3694         return;
3695     }
3696
3697     rec->ins = *ins;
3698     dst_param = HeapAlloc(GetProcessHeap(), 0, sizeof(*dst_param));
3699     if(!dst_param) goto free;
3700     *dst_param = *ins->dst;
3701     if(ins->dst->reg.rel_addr)
3702     {
3703         rel_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(*dst_param->reg.rel_addr));
3704         if(!rel_addr) goto free;
3705         *rel_addr = *ins->dst->reg.rel_addr;
3706         dst_param->reg.rel_addr = rel_addr;
3707     }
3708     rec->ins.dst = dst_param;
3709
3710     src_param = HeapAlloc(GetProcessHeap(), 0, sizeof(*src_param) * ins->src_count);
3711     if(!src_param) goto free;
3712     for(i = 0; i < ins->src_count; i++)
3713     {
3714         src_param[i] = ins->src[i];
3715         if(ins->src[i].reg.rel_addr)
3716         {
3717             rel_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(*rel_addr));
3718             if(!rel_addr) goto free;
3719             *rel_addr = *ins->src[i].reg.rel_addr;
3720             src_param[i].reg.rel_addr = rel_addr;
3721         }
3722     }
3723     rec->ins.src = src_param;
3724     list_add_tail(list, &rec->entry);
3725     return;
3726
3727 free:
3728     ERR("Out of memory\n");
3729     if(dst_param)
3730     {
3731         HeapFree(GetProcessHeap(), 0, (void *) dst_param->reg.rel_addr);
3732         HeapFree(GetProcessHeap(), 0, dst_param);
3733     }
3734     if(src_param)
3735     {
3736         for(i = 0; i < ins->src_count; i++)
3737         {
3738             HeapFree(GetProcessHeap(), 0, (void *) src_param[i].reg.rel_addr);
3739         }
3740         HeapFree(GetProcessHeap(), 0, src_param);
3741     }
3742     HeapFree(GetProcessHeap(), 0, rec);
3743 }
3744
3745 static void free_recorded_instruction(struct list *list)
3746 {
3747     struct recorded_instruction *rec_ins, *entry2;
3748     unsigned int i;
3749
3750     LIST_FOR_EACH_ENTRY_SAFE(rec_ins, entry2, list, struct recorded_instruction, entry)
3751     {
3752         list_remove(&rec_ins->entry);
3753         if(rec_ins->ins.dst)
3754         {
3755             HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.dst->reg.rel_addr);
3756             HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.dst);
3757         }
3758         if(rec_ins->ins.src)
3759         {
3760             for(i = 0; i < rec_ins->ins.src_count; i++)
3761             {
3762                 HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.src[i].reg.rel_addr);
3763             }
3764             HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.src);
3765         }
3766         HeapFree(GetProcessHeap(), 0, rec_ins);
3767     }
3768 }
3769
3770 static void shader_arb_handle_instruction(const struct wined3d_shader_instruction *ins) {
3771     SHADER_HANDLER hw_fct;
3772     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
3773     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3774     struct control_frame *control_frame;
3775     SHADER_BUFFER *buffer = ins->ctx->buffer;
3776
3777     if(ins->handler_idx == WINED3DSIH_LOOP || ins->handler_idx == WINED3DSIH_REP)
3778     {
3779         control_frame = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*control_frame));
3780         list_add_head(&priv->control_frames, &control_frame->entry);
3781
3782         if(ins->handler_idx == WINED3DSIH_LOOP) control_frame->type = LOOP;
3783         if(ins->handler_idx == WINED3DSIH_REP) control_frame->type = REP;
3784
3785         if(priv->target_version >= NV2)
3786         {
3787             control_frame->loop_no = priv->num_loops++;
3788             priv->loop_depth++;
3789         }
3790         else
3791         {
3792             /* Don't bother recording when we're in a not used if branch */
3793             if(priv->muted)
3794             {
3795                 return;
3796             }
3797
3798             if(!priv->recording)
3799             {
3800                 int control_values[3];
3801                 get_int_const(ins, This, ins->src[0].reg.idx, control_values);
3802                 list_init(&priv->record);
3803                 priv->recording = TRUE;
3804                 control_frame->outer_loop = TRUE;
3805                 control_frame->loop_control[0] = control_values[0];
3806                 control_frame->loop_control[1] = control_values[1];
3807                 control_frame->loop_control[2] = control_values[2];
3808                 return; /* Instruction is handled */
3809             }
3810             /* Record this loop in the outer loop's recording */
3811         }
3812     }
3813     else if(ins->handler_idx == WINED3DSIH_ENDLOOP || ins->handler_idx == WINED3DSIH_ENDREP)
3814     {
3815         if(priv->target_version >= NV2)
3816         {
3817             /* Nothing to do. The control frame is popped after the HW instr handler */
3818         }
3819         else
3820         {
3821             struct list *e = list_head(&priv->control_frames);
3822             control_frame = LIST_ENTRY(e, struct control_frame, entry);
3823             list_remove(&control_frame->entry);
3824
3825             if(control_frame->outer_loop)
3826             {
3827                 int iteration, aL = 0;
3828                 struct list copy;
3829
3830                 /* Turn off recording before playback */
3831                 priv->recording = FALSE;
3832
3833                 /* Move the recorded instructions to a separate list and get them out of the private data
3834                  * structure. If there are nested loops, the shader_arb_handle_instruction below will
3835                  * be recorded again, thus priv->record might be overwritten
3836                  */
3837                 list_init(&copy);
3838                 list_move_tail(&copy, &priv->record);
3839                 list_init(&priv->record);
3840
3841                 if(ins->handler_idx == WINED3DSIH_ENDLOOP)
3842                 {
3843                     shader_addline(buffer, "#unrolling loop: %d iterations, aL=%d, inc %d\n",
3844                                    control_frame->loop_control[0], control_frame->loop_control[1],
3845                                    control_frame->loop_control[2]);
3846                     aL = control_frame->loop_control[1];
3847                 }
3848                 else
3849                 {
3850                     shader_addline(buffer, "#unrolling rep: %d iterations\n", control_frame->loop_control[0]);
3851                 }
3852
3853                 for(iteration = 0; iteration < control_frame->loop_control[0]; iteration++)
3854                 {
3855                     struct recorded_instruction *rec_ins;
3856                     if(ins->handler_idx == WINED3DSIH_ENDLOOP)
3857                     {
3858                         priv->aL = aL;
3859                         shader_addline(buffer, "#Iteration %d, aL=%d\n", iteration, aL);
3860                     }
3861                     else
3862                     {
3863                         shader_addline(buffer, "#Iteration %d\n", iteration);
3864                     }
3865
3866                     LIST_FOR_EACH_ENTRY(rec_ins, &copy, struct recorded_instruction, entry)
3867                     {
3868                         shader_arb_handle_instruction(&rec_ins->ins);
3869                     }
3870
3871                     if(ins->handler_idx == WINED3DSIH_ENDLOOP)
3872                     {
3873                         aL += control_frame->loop_control[2];
3874                     }
3875                 }
3876                 shader_addline(buffer, "#end loop/rep\n");
3877
3878                 free_recorded_instruction(&copy);
3879                 HeapFree(GetProcessHeap(), 0, control_frame);
3880                 return; /* Instruction is handled */
3881             }
3882             else
3883             {
3884                 /* This is a nested loop. Proceed to the normal recording function */
3885                 HeapFree(GetProcessHeap(), 0, control_frame);
3886             }
3887         }
3888     }
3889
3890     if(priv->recording)
3891     {
3892         record_instruction(&priv->record, ins);
3893         return;
3894     }
3895
3896     /* boolean if */
3897     if(ins->handler_idx == WINED3DSIH_IF)
3898     {
3899         control_frame = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*control_frame));
3900         list_add_head(&priv->control_frames, &control_frame->entry);
3901         control_frame->type = IF;
3902
3903         if(!priv->muted && get_bool_const(ins, This, ins->src[0].reg.idx) == FALSE)
3904         {
3905             shader_addline(buffer, "#if(FALSE){\n");
3906             priv->muted = TRUE;
3907             control_frame->muting = TRUE;
3908         }
3909         else shader_addline(buffer, "#if(TRUE) {\n");
3910
3911         return; /* Instruction is handled */
3912     }
3913     else if(ins->handler_idx == WINED3DSIH_IFC)
3914     {
3915         /* IF(bool) and if_cond(a, b) use the same ELSE and ENDIF tokens */
3916         control_frame = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*control_frame));
3917         control_frame->type = IFC;
3918         control_frame->ifc_no = priv->num_ifcs++;
3919         list_add_head(&priv->control_frames, &control_frame->entry);
3920     }
3921     else if(ins->handler_idx == WINED3DSIH_ELSE)
3922     {
3923         struct list *e = list_head(&priv->control_frames);
3924         control_frame = LIST_ENTRY(e, struct control_frame, entry);
3925
3926         if(control_frame->type == IF)
3927         {
3928             shader_addline(buffer, "#} else {\n");
3929             if(!priv->muted && !control_frame->muting)
3930             {
3931                 priv->muted = TRUE;
3932                 control_frame->muting = TRUE;
3933             }
3934             else if(control_frame->muting) priv->muted = FALSE;
3935             return; /* Instruction is handled. */
3936         }
3937         /* In case of an ifc, generate a HW shader instruction */
3938     }
3939     else if(ins->handler_idx == WINED3DSIH_ENDIF)
3940     {
3941         struct list *e = list_head(&priv->control_frames);
3942         control_frame = LIST_ENTRY(e, struct control_frame, entry);
3943
3944         if(control_frame->type == IF)
3945         {
3946             shader_addline(buffer, "#} endif\n");
3947             if(control_frame->muting) priv->muted = FALSE;
3948             list_remove(&control_frame->entry);
3949             HeapFree(GetProcessHeap(), 0, control_frame);
3950             return; /* Instruction is handled */
3951         }
3952     }
3953
3954     if(priv->muted) return;
3955
3956     /* Select handler */
3957     hw_fct = shader_arb_instruction_handler_table[ins->handler_idx];
3958
3959     /* Unhandled opcode */
3960     if (!hw_fct)
3961     {
3962         FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
3963         return;
3964     }
3965     hw_fct(ins);
3966
3967     if(ins->handler_idx == WINED3DSIH_ENDLOOP || ins->handler_idx == WINED3DSIH_ENDREP)
3968     {
3969         struct list *e = list_head(&priv->control_frames);
3970         control_frame = LIST_ENTRY(e, struct control_frame, entry);
3971         list_remove(&control_frame->entry);
3972         HeapFree(GetProcessHeap(), 0, control_frame);
3973         priv->loop_depth--;
3974     }
3975     else if(ins->handler_idx == WINED3DSIH_ENDIF)
3976     {
3977         /* Non-ifc ENDIFs don't reach that place because of the return in the if block above */
3978         struct list *e = list_head(&priv->control_frames);
3979         control_frame = LIST_ENTRY(e, struct control_frame, entry);
3980         list_remove(&control_frame->entry);
3981         HeapFree(GetProcessHeap(), 0, control_frame);
3982     }
3983
3984
3985     shader_arb_add_instruction_modifiers(ins);
3986 }
3987
3988 const shader_backend_t arb_program_shader_backend = {
3989     shader_arb_handle_instruction,
3990     shader_arb_select,
3991     shader_arb_select_depth_blt,
3992     shader_arb_deselect_depth_blt,
3993     shader_arb_update_float_vertex_constants,
3994     shader_arb_update_float_pixel_constants,
3995     shader_arb_load_constants,
3996     shader_arb_load_np2fixup_constants,
3997     shader_arb_destroy,
3998     shader_arb_alloc,
3999     shader_arb_free,
4000     shader_arb_dirty_const,
4001     shader_arb_get_caps,
4002     shader_arb_color_fixup_supported,
4003 };
4004
4005 /* ARB_fragment_program fixed function pipeline replacement definitions */
4006 #define ARB_FFP_CONST_TFACTOR           0
4007 #define ARB_FFP_CONST_SPECULAR_ENABLE   ((ARB_FFP_CONST_TFACTOR) + 1)
4008 #define ARB_FFP_CONST_CONSTANT(i)       ((ARB_FFP_CONST_SPECULAR_ENABLE) + 1 + i)
4009 #define ARB_FFP_CONST_BUMPMAT(i)        ((ARB_FFP_CONST_CONSTANT(7)) + 1 + i)
4010 #define ARB_FFP_CONST_LUMINANCE(i)      ((ARB_FFP_CONST_BUMPMAT(7)) + 1 + i)
4011
4012 struct arbfp_ffp_desc
4013 {
4014     struct ffp_frag_desc parent;
4015     GLuint shader;
4016     unsigned int num_textures_used;
4017 };
4018
4019 static void arbfp_enable(IWineD3DDevice *iface, BOOL enable) {
4020     ENTER_GL();
4021     if(enable) {
4022         glEnable(GL_FRAGMENT_PROGRAM_ARB);
4023         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
4024     } else {
4025         glDisable(GL_FRAGMENT_PROGRAM_ARB);
4026         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
4027     }
4028     LEAVE_GL();
4029 }
4030
4031 static HRESULT arbfp_alloc(IWineD3DDevice *iface) {
4032     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
4033     struct shader_arb_priv *priv;
4034     /* Share private data between the shader backend and the pipeline replacement, if both
4035      * are the arb implementation. This is needed to figure out whether ARBfp should be disabled
4036      * if no pixel shader is bound or not
4037      */
4038     if(This->shader_backend == &arb_program_shader_backend) {
4039         This->fragment_priv = This->shader_priv;
4040     } else {
4041         This->fragment_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_arb_priv));
4042         if(!This->fragment_priv) return E_OUTOFMEMORY;
4043     }
4044     priv = This->fragment_priv;
4045     if (wine_rb_init(&priv->fragment_shaders, &wined3d_ffp_frag_program_rb_functions) == -1)
4046     {
4047         ERR("Failed to initialize rbtree.\n");
4048         HeapFree(GetProcessHeap(), 0, This->fragment_priv);
4049         return E_OUTOFMEMORY;
4050     }
4051     priv->use_arbfp_fixed_func = TRUE;
4052     return WINED3D_OK;
4053 }
4054
4055 static void arbfp_free_ffpshader(struct wine_rb_entry *entry, void *context)
4056 {
4057     const WineD3D_GL_Info *gl_info = context;
4058     struct arbfp_ffp_desc *entry_arb = WINE_RB_ENTRY_VALUE(entry, struct arbfp_ffp_desc, parent.entry);
4059
4060     ENTER_GL();
4061     GL_EXTCALL(glDeleteProgramsARB(1, &entry_arb->shader));
4062     checkGLcall("glDeleteProgramsARB(1, &entry_arb->shader)");
4063     HeapFree(GetProcessHeap(), 0, entry_arb);
4064     LEAVE_GL();
4065 }
4066
4067 static void arbfp_free(IWineD3DDevice *iface) {
4068     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
4069     struct shader_arb_priv *priv = This->fragment_priv;
4070
4071     wine_rb_destroy(&priv->fragment_shaders, arbfp_free_ffpshader, &This->adapter->gl_info);
4072     priv->use_arbfp_fixed_func = FALSE;
4073
4074     if(This->shader_backend != &arb_program_shader_backend) {
4075         HeapFree(GetProcessHeap(), 0, This->fragment_priv);
4076     }
4077 }
4078
4079 static void arbfp_get_caps(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct fragment_caps *caps)
4080 {
4081     caps->TextureOpCaps =  WINED3DTEXOPCAPS_DISABLE                     |
4082                            WINED3DTEXOPCAPS_SELECTARG1                  |
4083                            WINED3DTEXOPCAPS_SELECTARG2                  |
4084                            WINED3DTEXOPCAPS_MODULATE4X                  |
4085                            WINED3DTEXOPCAPS_MODULATE2X                  |
4086                            WINED3DTEXOPCAPS_MODULATE                    |
4087                            WINED3DTEXOPCAPS_ADDSIGNED2X                 |
4088                            WINED3DTEXOPCAPS_ADDSIGNED                   |
4089                            WINED3DTEXOPCAPS_ADD                         |
4090                            WINED3DTEXOPCAPS_SUBTRACT                    |
4091                            WINED3DTEXOPCAPS_ADDSMOOTH                   |
4092                            WINED3DTEXOPCAPS_BLENDCURRENTALPHA           |
4093                            WINED3DTEXOPCAPS_BLENDFACTORALPHA            |
4094                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHA           |
4095                            WINED3DTEXOPCAPS_BLENDDIFFUSEALPHA           |
4096                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHAPM         |
4097                            WINED3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR      |
4098                            WINED3DTEXOPCAPS_MODULATECOLOR_ADDALPHA      |
4099                            WINED3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA   |
4100                            WINED3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR   |
4101                            WINED3DTEXOPCAPS_DOTPRODUCT3                 |
4102                            WINED3DTEXOPCAPS_MULTIPLYADD                 |
4103                            WINED3DTEXOPCAPS_LERP                        |
4104                            WINED3DTEXOPCAPS_BUMPENVMAP                  |
4105                            WINED3DTEXOPCAPS_BUMPENVMAPLUMINANCE;
4106
4107     /* TODO: Implement WINED3DTEXOPCAPS_PREMODULATE */
4108
4109     caps->MaxTextureBlendStages   = 8;
4110     caps->MaxSimultaneousTextures = min(GL_LIMITS(fragment_samplers), 8);
4111
4112     caps->PrimitiveMiscCaps |= WINED3DPMISCCAPS_TSSARGTEMP;
4113 }
4114 #undef GLINFO_LOCATION
4115
4116 #define GLINFO_LOCATION stateblock->wineD3DDevice->adapter->gl_info
4117 static void state_texfactor_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
4118     float col[4];
4119     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
4120
4121     /* Don't load the parameter if we're using an arbfp pixel shader, otherwise we'll overwrite
4122      * application provided constants
4123      */
4124     if(device->shader_backend == &arb_program_shader_backend) {
4125         if (use_ps(stateblock)) return;
4126
4127         device = stateblock->wineD3DDevice;
4128         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_TFACTOR] = 1;
4129         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_TFACTOR + 1);
4130     }
4131
4132     D3DCOLORTOGLFLOAT4(stateblock->renderState[WINED3DRS_TEXTUREFACTOR], col);
4133     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col));
4134     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col)");
4135
4136 }
4137
4138 static void state_arb_specularenable(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
4139     float col[4];
4140     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
4141
4142     /* Don't load the parameter if we're using an arbfp pixel shader, otherwise we'll overwrite
4143      * application provided constants
4144      */
4145     if(device->shader_backend == &arb_program_shader_backend) {
4146         if (use_ps(stateblock)) return;
4147
4148         device = stateblock->wineD3DDevice;
4149         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_SPECULAR_ENABLE] = 1;
4150         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_SPECULAR_ENABLE + 1);
4151     }
4152
4153     if(stateblock->renderState[WINED3DRS_SPECULARENABLE]) {
4154         /* The specular color has no alpha */
4155         col[0] = 1.0; col[1] = 1.0;
4156         col[2] = 1.0; col[3] = 0.0;
4157     } else {
4158         col[0] = 0.0; col[1] = 0.0;
4159         col[2] = 0.0; col[3] = 0.0;
4160     }
4161     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_SPECULAR_ENABLE, col));
4162     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_SPECULAR_ENABLE, col)");
4163 }
4164
4165 static void set_bumpmat_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
4166     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
4167     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
4168     float mat[2][2];
4169
4170     if (use_ps(stateblock))
4171     {
4172         if(stage != 0 &&
4173            ((IWineD3DPixelShaderImpl *) stateblock->pixelShader)->baseShader.reg_maps.bumpmat[stage]) {
4174             /* The pixel shader has to know the bump env matrix. Do a constants update if it isn't scheduled
4175              * anyway
4176              */
4177             if(!isStateDirty(context, STATE_PIXELSHADERCONSTANT)) {
4178                 device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
4179             }
4180         }
4181
4182         if(device->shader_backend == &arb_program_shader_backend) {
4183             /* Exit now, don't set the bumpmat below, otherwise we may overwrite pixel shader constants */
4184             return;
4185         }
4186     } else if(device->shader_backend == &arb_program_shader_backend) {
4187         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_BUMPMAT(stage)] = 1;
4188         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_BUMPMAT(stage) + 1);
4189     }
4190
4191     mat[0][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT00]);
4192     mat[0][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT01]);
4193     mat[1][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT10]);
4194     mat[1][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT11]);
4195
4196     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0]));
4197     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0])");
4198 }
4199
4200 static void tex_bumpenvlum_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
4201     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
4202     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
4203     float param[4];
4204
4205     if (use_ps(stateblock))
4206     {
4207         if(stage != 0 &&
4208            ((IWineD3DPixelShaderImpl *) stateblock->pixelShader)->baseShader.reg_maps.luminanceparams[stage]) {
4209             /* The pixel shader has to know the luminance offset. Do a constants update if it
4210              * isn't scheduled anyway
4211              */
4212             if(!isStateDirty(context, STATE_PIXELSHADERCONSTANT)) {
4213                 device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
4214             }
4215         }
4216
4217         if(device->shader_backend == &arb_program_shader_backend) {
4218             /* Exit now, don't set the bumpmat below, otherwise we may overwrite pixel shader constants */
4219             return;
4220         }
4221     } else if(device->shader_backend == &arb_program_shader_backend) {
4222         device->activeContext->pshader_const_dirty[ARB_FFP_CONST_LUMINANCE(stage)] = 1;
4223         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_LUMINANCE(stage) + 1);
4224     }
4225
4226     param[0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVLSCALE]);
4227     param[1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET]);
4228     param[2] = 0.0;
4229     param[3] = 0.0;
4230
4231     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_LUMINANCE(stage), param));
4232     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_LUMINANCE(stage), param)");
4233 }
4234
4235 static const char *get_argreg(SHADER_BUFFER *buffer, DWORD argnum, unsigned int stage, DWORD arg) {
4236     const char *ret;
4237
4238     if(arg == ARG_UNUSED) return "unused"; /* This is the marker for unused registers */
4239
4240     switch(arg & WINED3DTA_SELECTMASK) {
4241         case WINED3DTA_DIFFUSE:
4242             ret = "fragment.color.primary"; break;
4243
4244         case WINED3DTA_CURRENT:
4245             if(stage == 0) ret = "fragment.color.primary";
4246             else ret = "ret";
4247             break;
4248
4249         case WINED3DTA_TEXTURE:
4250             switch(stage) {
4251                 case 0: ret = "tex0"; break;
4252                 case 1: ret = "tex1"; break;
4253                 case 2: ret = "tex2"; break;
4254                 case 3: ret = "tex3"; break;
4255                 case 4: ret = "tex4"; break;
4256                 case 5: ret = "tex5"; break;
4257                 case 6: ret = "tex6"; break;
4258                 case 7: ret = "tex7"; break;
4259                 default: ret = "unknown texture";
4260             }
4261             break;
4262
4263         case WINED3DTA_TFACTOR:
4264             ret = "tfactor"; break;
4265
4266         case WINED3DTA_SPECULAR:
4267             ret = "fragment.color.secondary"; break;
4268
4269         case WINED3DTA_TEMP:
4270             ret = "tempreg"; break;
4271
4272         case WINED3DTA_CONSTANT:
4273             FIXME("Implement perstage constants\n");
4274             switch(stage) {
4275                 case 0: ret = "const0"; break;
4276                 case 1: ret = "const1"; break;
4277                 case 2: ret = "const2"; break;
4278                 case 3: ret = "const3"; break;
4279                 case 4: ret = "const4"; break;
4280                 case 5: ret = "const5"; break;
4281                 case 6: ret = "const6"; break;
4282                 case 7: ret = "const7"; break;
4283                 default: ret = "unknown constant";
4284             }
4285             break;
4286
4287         default:
4288             return "unknown";
4289     }
4290
4291     if(arg & WINED3DTA_COMPLEMENT) {
4292         shader_addline(buffer, "SUB arg%u, const.x, %s;\n", argnum, ret);
4293         if(argnum == 0) ret = "arg0";
4294         if(argnum == 1) ret = "arg1";
4295         if(argnum == 2) ret = "arg2";
4296     }
4297     if(arg & WINED3DTA_ALPHAREPLICATE) {
4298         shader_addline(buffer, "MOV arg%u, %s.w;\n", argnum, ret);
4299         if(argnum == 0) ret = "arg0";
4300         if(argnum == 1) ret = "arg1";
4301         if(argnum == 2) ret = "arg2";
4302     }
4303     return ret;
4304 }
4305
4306 static void gen_ffp_instr(SHADER_BUFFER *buffer, unsigned int stage, BOOL color, BOOL alpha,
4307                           DWORD dst, DWORD op, DWORD dw_arg0, DWORD dw_arg1, DWORD dw_arg2) {
4308     const char *dstmask, *dstreg, *arg0, *arg1, *arg2;
4309     unsigned int mul = 1;
4310     BOOL mul_final_dest = FALSE;
4311
4312     if(color && alpha) dstmask = "";
4313     else if(color) dstmask = ".xyz";
4314     else dstmask = ".w";
4315
4316     if(dst == tempreg) dstreg = "tempreg";
4317     else dstreg = "ret";
4318
4319     arg0 = get_argreg(buffer, 0, stage, dw_arg0);
4320     arg1 = get_argreg(buffer, 1, stage, dw_arg1);
4321     arg2 = get_argreg(buffer, 2, stage, dw_arg2);
4322
4323     switch(op) {
4324         case WINED3DTOP_DISABLE:
4325             if(stage == 0) shader_addline(buffer, "MOV %s%s, fragment.color.primary;\n", dstreg, dstmask);
4326             break;
4327
4328         case WINED3DTOP_SELECTARG2:
4329             arg1 = arg2;
4330         case WINED3DTOP_SELECTARG1:
4331             shader_addline(buffer, "MOV %s%s, %s;\n", dstreg, dstmask, arg1);
4332             break;
4333
4334         case WINED3DTOP_MODULATE4X:
4335             mul = 2;
4336         case WINED3DTOP_MODULATE2X:
4337             mul *= 2;
4338             if(strcmp(dstreg, "result.color") == 0) {
4339                 dstreg = "ret";
4340                 mul_final_dest = TRUE;
4341             }
4342         case WINED3DTOP_MODULATE:
4343             shader_addline(buffer, "MUL %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
4344             break;
4345
4346         case WINED3DTOP_ADDSIGNED2X:
4347             mul = 2;
4348             if(strcmp(dstreg, "result.color") == 0) {
4349                 dstreg = "ret";
4350                 mul_final_dest = TRUE;
4351             }
4352         case WINED3DTOP_ADDSIGNED:
4353             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
4354             arg2 = "arg2";
4355         case WINED3DTOP_ADD:
4356             shader_addline(buffer, "ADD_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
4357             break;
4358
4359         case WINED3DTOP_SUBTRACT:
4360             shader_addline(buffer, "SUB_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
4361             break;
4362
4363         case WINED3DTOP_ADDSMOOTH:
4364             shader_addline(buffer, "SUB arg1, const.x, %s;\n", arg1);
4365             shader_addline(buffer, "MAD_SAT %s%s, arg1, %s, %s;\n", dstreg, dstmask, arg2, arg1);
4366             break;
4367
4368         case WINED3DTOP_BLENDCURRENTALPHA:
4369             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_CURRENT);
4370             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
4371             break;
4372         case WINED3DTOP_BLENDFACTORALPHA:
4373             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TFACTOR);
4374             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
4375             break;
4376         case WINED3DTOP_BLENDTEXTUREALPHA:
4377             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TEXTURE);
4378             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
4379             break;
4380         case WINED3DTOP_BLENDDIFFUSEALPHA:
4381             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_DIFFUSE);
4382             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
4383             break;
4384
4385         case WINED3DTOP_BLENDTEXTUREALPHAPM:
4386             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TEXTURE);
4387             shader_addline(buffer, "SUB arg0.w, const.x, %s.w;\n", arg0);
4388             shader_addline(buffer, "MAD_SAT %s%s, %s, arg0.w, %s;\n", dstreg, dstmask, arg2, arg1);
4389             break;
4390
4391         /* D3DTOP_PREMODULATE ???? */
4392
4393         case WINED3DTOP_MODULATEINVALPHA_ADDCOLOR:
4394             shader_addline(buffer, "SUB arg0.w, const.x, %s;\n", arg1);
4395             shader_addline(buffer, "MAD_SAT %s%s, arg0.w, %s, %s;\n", dstreg, dstmask, arg2, arg1);
4396             break;
4397         case WINED3DTOP_MODULATEALPHA_ADDCOLOR:
4398             shader_addline(buffer, "MAD_SAT %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg1);
4399             break;
4400         case WINED3DTOP_MODULATEINVCOLOR_ADDALPHA:
4401             shader_addline(buffer, "SUB arg0, const.x, %s;\n", arg1);
4402             shader_addline(buffer, "MAD_SAT %s%s, arg0, %s, %s.w;\n", dstreg, dstmask, arg2, arg1);
4403             break;
4404         case WINED3DTOP_MODULATECOLOR_ADDALPHA:
4405             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s.w;\n", dstreg, dstmask, arg1, arg2, arg1);
4406             break;
4407
4408         case WINED3DTOP_DOTPRODUCT3:
4409             mul = 4;
4410             if(strcmp(dstreg, "result.color") == 0) {
4411                 dstreg = "ret";
4412                 mul_final_dest = TRUE;
4413             }
4414             shader_addline(buffer, "SUB arg1, %s, const.w;\n", arg1);
4415             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
4416             shader_addline(buffer, "DP3_SAT %s%s, arg1, arg2;\n", dstreg, dstmask);
4417             break;
4418
4419         case WINED3DTOP_MULTIPLYADD:
4420             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg0);
4421             break;
4422
4423         case WINED3DTOP_LERP:
4424             /* The msdn is not quite right here */
4425             shader_addline(buffer, "LRP %s%s, %s, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
4426             break;
4427
4428         case WINED3DTOP_BUMPENVMAP:
4429         case WINED3DTOP_BUMPENVMAPLUMINANCE:
4430             /* Those are handled in the first pass of the shader(generation pass 1 and 2) already */
4431             break;
4432
4433         default:
4434             FIXME("Unhandled texture op %08x\n", op);
4435     }
4436
4437     if(mul == 2) {
4438         shader_addline(buffer, "MUL_SAT %s%s, %s, const.y;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
4439     } else if(mul == 4) {
4440         shader_addline(buffer, "MUL_SAT %s%s, %s, const.z;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
4441     }
4442 }
4443
4444 /* The stateblock is passed for GLINFO_LOCATION */
4445 static GLuint gen_arbfp_ffp_shader(const struct ffp_frag_settings *settings, IWineD3DStateBlockImpl *stateblock)
4446 {
4447     unsigned int stage;
4448     SHADER_BUFFER buffer;
4449     BOOL tex_read[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
4450     BOOL bump_used[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
4451     BOOL luminance_used[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
4452     const char *textype;
4453     const char *instr, *sat;
4454     char colorcor_dst[8];
4455     GLuint ret;
4456     DWORD arg0, arg1, arg2;
4457     BOOL tempreg_used = FALSE, tfactor_used = FALSE;
4458     BOOL op_equal;
4459     const char *final_combiner_src = "ret";
4460
4461     /* Find out which textures are read */
4462     for(stage = 0; stage < MAX_TEXTURES; stage++) {
4463         if(settings->op[stage].cop == WINED3DTOP_DISABLE) break;
4464         arg0 = settings->op[stage].carg0 & WINED3DTA_SELECTMASK;
4465         arg1 = settings->op[stage].carg1 & WINED3DTA_SELECTMASK;
4466         arg2 = settings->op[stage].carg2 & WINED3DTA_SELECTMASK;
4467         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
4468         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
4469         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
4470
4471         if(settings->op[stage].cop == WINED3DTOP_BLENDTEXTUREALPHA) tex_read[stage] = TRUE;
4472         if(settings->op[stage].cop == WINED3DTOP_BLENDTEXTUREALPHAPM) tex_read[stage] = TRUE;
4473         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP) {
4474             bump_used[stage] = TRUE;
4475             tex_read[stage] = TRUE;
4476         }
4477         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
4478             bump_used[stage] = TRUE;
4479             tex_read[stage] = TRUE;
4480             luminance_used[stage] = TRUE;
4481         } else if(settings->op[stage].cop == WINED3DTOP_BLENDFACTORALPHA) {
4482             tfactor_used = TRUE;
4483         }
4484
4485         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
4486             tfactor_used = TRUE;
4487         }
4488
4489         if(settings->op[stage].dst == tempreg) tempreg_used = TRUE;
4490         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
4491             tempreg_used = TRUE;
4492         }
4493
4494         if(settings->op[stage].aop == WINED3DTOP_DISABLE) continue;
4495         arg0 = settings->op[stage].aarg0 & WINED3DTA_SELECTMASK;
4496         arg1 = settings->op[stage].aarg1 & WINED3DTA_SELECTMASK;
4497         arg2 = settings->op[stage].aarg2 & WINED3DTA_SELECTMASK;
4498         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
4499         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
4500         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
4501
4502         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
4503             tempreg_used = TRUE;
4504         }
4505         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
4506             tfactor_used = TRUE;
4507         }
4508     }
4509
4510     /* Shader header */
4511     shader_buffer_init(&buffer);
4512
4513     shader_addline(&buffer, "!!ARBfp1.0\n");
4514
4515     switch(settings->fog) {
4516         case FOG_OFF:                                                         break;
4517         case FOG_LINEAR: shader_addline(&buffer, "OPTION ARB_fog_linear;\n"); break;
4518         case FOG_EXP:    shader_addline(&buffer, "OPTION ARB_fog_exp;\n");    break;
4519         case FOG_EXP2:   shader_addline(&buffer, "OPTION ARB_fog_exp2;\n");   break;
4520         default: FIXME("Unexpected fog setting %d\n", settings->fog);
4521     }
4522
4523     shader_addline(&buffer, "PARAM const = {1, 2, 4, 0.5};\n");
4524     shader_addline(&buffer, "TEMP TMP;\n");
4525     shader_addline(&buffer, "TEMP ret;\n");
4526     if(tempreg_used || settings->sRGB_write) shader_addline(&buffer, "TEMP tempreg;\n");
4527     shader_addline(&buffer, "TEMP arg0;\n");
4528     shader_addline(&buffer, "TEMP arg1;\n");
4529     shader_addline(&buffer, "TEMP arg2;\n");
4530     for(stage = 0; stage < MAX_TEXTURES; stage++) {
4531         if(!tex_read[stage]) continue;
4532         shader_addline(&buffer, "TEMP tex%u;\n", stage);
4533         if(!bump_used[stage]) continue;
4534         shader_addline(&buffer, "PARAM bumpmat%u = program.env[%u];\n", stage, ARB_FFP_CONST_BUMPMAT(stage));
4535         if(!luminance_used[stage]) continue;
4536         shader_addline(&buffer, "PARAM luminance%u = program.env[%u];\n", stage, ARB_FFP_CONST_LUMINANCE(stage));
4537     }
4538     if(tfactor_used) {
4539         shader_addline(&buffer, "PARAM tfactor = program.env[%u];\n", ARB_FFP_CONST_TFACTOR);
4540     }
4541         shader_addline(&buffer, "PARAM specular_enable = program.env[%u];\n", ARB_FFP_CONST_SPECULAR_ENABLE);
4542
4543     if(settings->sRGB_write) {
4544         shader_addline(&buffer, "PARAM srgb_consts1 = {%f, %f, %f, %f};\n",
4545                        srgb_mul_low, srgb_cmp, srgb_pow, srgb_mul_high);
4546         shader_addline(&buffer, "PARAM srgb_consts2 = {%f, %f, %f, %f};\n",
4547                        srgb_sub_high, 0.0, 0.0, 0.0);
4548     }
4549
4550     /* Generate texture sampling instructions) */
4551     for(stage = 0; stage < MAX_TEXTURES && settings->op[stage].cop != WINED3DTOP_DISABLE; stage++) {
4552         if(!tex_read[stage]) continue;
4553
4554         switch(settings->op[stage].tex_type) {
4555             case tex_1d:                    textype = "1D";     break;
4556             case tex_2d:                    textype = "2D";     break;
4557             case tex_3d:                    textype = "3D";     break;
4558             case tex_cube:                  textype = "CUBE";   break;
4559             case tex_rect:                  textype = "RECT";   break;
4560             default: textype = "unexpected_textype";   break;
4561         }
4562
4563         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP ||
4564            settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
4565             sat = "";
4566         } else {
4567             sat = "_SAT";
4568         }
4569
4570         if(settings->op[stage].projected == proj_none) {
4571             instr = "TEX";
4572         } else if(settings->op[stage].projected == proj_count4 ||
4573                   settings->op[stage].projected == proj_count3) {
4574             instr = "TXP";
4575         } else {
4576             FIXME("Unexpected projection mode %d\n", settings->op[stage].projected);
4577             instr = "TXP";
4578         }
4579
4580         if(stage > 0 &&
4581            (settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAP ||
4582             settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAPLUMINANCE)) {
4583             shader_addline(&buffer, "SWZ arg1, bumpmat%u, x, z, 0, 0;\n", stage - 1);
4584             shader_addline(&buffer, "DP3 ret.x, arg1, tex%u;\n", stage - 1);
4585             shader_addline(&buffer, "SWZ arg1, bumpmat%u, y, w, 0, 0;\n", stage - 1);
4586             shader_addline(&buffer, "DP3 ret.y, arg1, tex%u;\n", stage - 1);
4587
4588             /* with projective textures, texbem only divides the static texture coord, not the displacement,
4589              * so multiply the displacement with the dividing parameter before passing it to TXP
4590              */
4591             if (settings->op[stage].projected != proj_none) {
4592                 if(settings->op[stage].projected == proj_count4) {
4593                     shader_addline(&buffer, "MOV ret.w, fragment.texcoord[%u].w;\n", stage);
4594                     shader_addline(&buffer, "MUL ret.xyz, ret, fragment.texcoord[%u].w, fragment.texcoord[%u];\n", stage, stage);
4595                 } else {
4596                     shader_addline(&buffer, "MOV ret.w, fragment.texcoord[%u].z;\n", stage);
4597                     shader_addline(&buffer, "MAD ret.xyz, ret, fragment.texcoord[%u].z, fragment.texcoord[%u];\n", stage, stage);
4598                 }
4599             } else {
4600                 shader_addline(&buffer, "ADD ret, ret, fragment.texcoord[%u];\n", stage);
4601             }
4602
4603             shader_addline(&buffer, "%s%s tex%u, ret, texture[%u], %s;\n",
4604                            instr, sat, stage, stage, textype);
4605             if(settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
4606                 shader_addline(&buffer, "MAD_SAT ret.x, tex%u.z, luminance%u.x, luminance%u.y;\n",
4607                                stage - 1, stage - 1, stage - 1);
4608                 shader_addline(&buffer, "MUL tex%u, tex%u, ret.x;\n", stage, stage);
4609             }
4610         } else if(settings->op[stage].projected == proj_count3) {
4611             shader_addline(&buffer, "MOV ret, fragment.texcoord[%u];\n", stage);
4612             shader_addline(&buffer, "MOV ret.w, ret.z;\n");
4613             shader_addline(&buffer, "%s%s tex%u, ret, texture[%u], %s;\n",
4614                             instr, sat, stage, stage, textype);
4615         } else {
4616             shader_addline(&buffer, "%s%s tex%u, fragment.texcoord[%u], texture[%u], %s;\n",
4617                             instr, sat, stage, stage, stage, textype);
4618         }
4619
4620         sprintf(colorcor_dst, "tex%u", stage);
4621         gen_color_correction(&buffer, colorcor_dst, WINED3DSP_WRITEMASK_ALL, "const.x", "const.y",
4622                 settings->op[stage].color_fixup);
4623     }
4624
4625     /* Generate the main shader */
4626     for(stage = 0; stage < MAX_TEXTURES; stage++) {
4627         if(settings->op[stage].cop == WINED3DTOP_DISABLE) {
4628             if(stage == 0) {
4629                 final_combiner_src = "fragment.color.primary";
4630             }
4631             break;
4632         }
4633
4634         if(settings->op[stage].cop == WINED3DTOP_SELECTARG1 &&
4635            settings->op[stage].aop == WINED3DTOP_SELECTARG1) {
4636             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg1;
4637         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG1 &&
4638                   settings->op[stage].aop == WINED3DTOP_SELECTARG2) {
4639             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg2;
4640         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG2 &&
4641                   settings->op[stage].aop == WINED3DTOP_SELECTARG1) {
4642             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg1;
4643         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG2 &&
4644                   settings->op[stage].aop == WINED3DTOP_SELECTARG2) {
4645             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg2;
4646         } else {
4647             op_equal = settings->op[stage].aop   == settings->op[stage].cop &&
4648                        settings->op[stage].carg0 == settings->op[stage].aarg0 &&
4649                        settings->op[stage].carg1 == settings->op[stage].aarg1 &&
4650                        settings->op[stage].carg2 == settings->op[stage].aarg2;
4651         }
4652
4653         if(settings->op[stage].aop == WINED3DTOP_DISABLE) {
4654             gen_ffp_instr(&buffer, stage, TRUE, FALSE, settings->op[stage].dst,
4655                           settings->op[stage].cop, settings->op[stage].carg0,
4656                           settings->op[stage].carg1, settings->op[stage].carg2);
4657             if(stage == 0) {
4658                 shader_addline(&buffer, "MOV ret.w, fragment.color.primary.w;\n");
4659             }
4660         } else if(op_equal) {
4661             gen_ffp_instr(&buffer, stage, TRUE, TRUE, settings->op[stage].dst,
4662                           settings->op[stage].cop, settings->op[stage].carg0,
4663                           settings->op[stage].carg1, settings->op[stage].carg2);
4664         } else {
4665             gen_ffp_instr(&buffer, stage, TRUE, FALSE, settings->op[stage].dst,
4666                           settings->op[stage].cop, settings->op[stage].carg0,
4667                           settings->op[stage].carg1, settings->op[stage].carg2);
4668             gen_ffp_instr(&buffer, stage, FALSE, TRUE, settings->op[stage].dst,
4669                           settings->op[stage].aop, settings->op[stage].aarg0,
4670                           settings->op[stage].aarg1, settings->op[stage].aarg2);
4671         }
4672     }
4673
4674     if(settings->sRGB_write) {
4675         shader_addline(&buffer, "MAD ret, fragment.color.secondary, specular_enable, %s;\n", final_combiner_src);
4676         arbfp_add_sRGB_correction(&buffer, "ret", "arg0", "arg1", "arg2", "tempreg", FALSE);
4677     } else {
4678         shader_addline(&buffer, "MAD result.color, fragment.color.secondary, specular_enable, %s;\n", final_combiner_src);
4679     }
4680
4681     /* Footer */
4682     shader_addline(&buffer, "END\n");
4683
4684     /* Generate the shader */
4685     GL_EXTCALL(glGenProgramsARB(1, &ret));
4686     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret));
4687     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(buffer.buffer), buffer.buffer));
4688
4689     if (glGetError() == GL_INVALID_OPERATION) {
4690         GLint pos;
4691         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
4692         FIXME("Fragment program error at position %d: %s\n", pos,
4693               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
4694     }
4695     shader_buffer_free(&buffer);
4696     return ret;
4697 }
4698
4699 static void fragment_prog_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
4700     IWineD3DDeviceImpl *device = stateblock->wineD3DDevice;
4701     struct shader_arb_priv *priv = device->fragment_priv;
4702     BOOL use_pshader = use_ps(stateblock);
4703     BOOL use_vshader = use_vs(stateblock);
4704     struct ffp_frag_settings settings;
4705     const struct arbfp_ffp_desc *desc;
4706     unsigned int i;
4707
4708     TRACE("state %#x, stateblock %p, context %p\n", state, stateblock, context);
4709
4710     if(isStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE))) {
4711         if(!use_pshader && device->shader_backend == &arb_program_shader_backend && context->last_was_pshader) {
4712             /* Reload fixed function constants since they collide with the pixel shader constants */
4713             for(i = 0; i < MAX_TEXTURES; i++) {
4714                 set_bumpmat_arbfp(STATE_TEXTURESTAGE(i, WINED3DTSS_BUMPENVMAT00), stateblock, context);
4715             }
4716             state_texfactor_arbfp(STATE_RENDER(WINED3DRS_TEXTUREFACTOR), stateblock, context);
4717             state_arb_specularenable(STATE_RENDER(WINED3DRS_SPECULARENABLE), stateblock, context);
4718         } else if(use_pshader && !isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
4719             device->shader_backend->shader_select((IWineD3DDevice *)stateblock->wineD3DDevice, use_pshader, use_vshader);
4720         }
4721         return;
4722     }
4723
4724     if(!use_pshader) {
4725         /* Find or create a shader implementing the fixed function pipeline settings, then activate it */
4726         gen_ffp_frag_op(stateblock, &settings, FALSE);
4727         desc = (const struct arbfp_ffp_desc *)find_ffp_frag_shader(&priv->fragment_shaders, &settings);
4728         if(!desc) {
4729             struct arbfp_ffp_desc *new_desc = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_desc));
4730             if (!new_desc)
4731             {
4732                 ERR("Out of memory\n");
4733                 return;
4734             }
4735             new_desc->num_textures_used = 0;
4736             for(i = 0; i < GL_LIMITS(texture_stages); i++) {
4737                 if(settings.op[i].cop == WINED3DTOP_DISABLE) break;
4738                 new_desc->num_textures_used = i;
4739             }
4740
4741             memcpy(&new_desc->parent.settings, &settings, sizeof(settings));
4742             new_desc->shader = gen_arbfp_ffp_shader(&settings, stateblock);
4743             add_ffp_frag_shader(&priv->fragment_shaders, &new_desc->parent);
4744             TRACE("Allocated fixed function replacement shader descriptor %p\n", new_desc);
4745             desc = new_desc;
4746         }
4747
4748         /* Now activate the replacement program. GL_FRAGMENT_PROGRAM_ARB is already active(however, note the
4749          * comment above the shader_select call below). If e.g. GLSL is active, the shader_select call will
4750          * deactivate it.
4751          */
4752         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader));
4753         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader)");
4754         priv->current_fprogram_id = desc->shader;
4755
4756         if(device->shader_backend == &arb_program_shader_backend && context->last_was_pshader) {
4757             /* Reload fixed function constants since they collide with the pixel shader constants */
4758             for(i = 0; i < MAX_TEXTURES; i++) {
4759                 set_bumpmat_arbfp(STATE_TEXTURESTAGE(i, WINED3DTSS_BUMPENVMAT00), stateblock, context);
4760             }
4761             state_texfactor_arbfp(STATE_RENDER(WINED3DRS_TEXTUREFACTOR), stateblock, context);
4762             state_arb_specularenable(STATE_RENDER(WINED3DRS_SPECULARENABLE), stateblock, context);
4763         }
4764         context->last_was_pshader = FALSE;
4765     } else {
4766         context->last_was_pshader = TRUE;
4767     }
4768
4769     /* Finally, select the shader. If a pixel shader is used, it will be set and enabled by the shader backend.
4770      * If this shader backend is arbfp(most likely), then it will simply overwrite the last fixed function replace-
4771      * ment shader. If the shader backend is not ARB, it currently is important that the opengl implementation
4772      * type overwrites GL_ARB_fragment_program. This is currently the case with GLSL. If we really want to use
4773      * atifs or nvrc pixel shaders with arb fragment programs we'd have to disable GL_FRAGMENT_PROGRAM_ARB here
4774      *
4775      * Don't call shader_select if the vertex shader is dirty, because it will be called later on by the vertex
4776      * shader handler
4777      */
4778     if(!isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
4779         device->shader_backend->shader_select((IWineD3DDevice *)stateblock->wineD3DDevice, use_pshader, use_vshader);
4780
4781         if (!isStateDirty(context, STATE_VERTEXSHADERCONSTANT) && (use_vshader || use_pshader)) {
4782             device->StateTable[STATE_VERTEXSHADERCONSTANT].apply(STATE_VERTEXSHADERCONSTANT, stateblock, context);
4783         }
4784     }
4785     if(use_pshader) {
4786         device->StateTable[STATE_PIXELSHADERCONSTANT].apply(STATE_PIXELSHADERCONSTANT, stateblock, context);
4787     }
4788 }
4789
4790 /* We can't link the fog states to the fragment state directly since the vertex pipeline links them
4791  * to FOGENABLE. A different linking in different pipeline parts can't be expressed in the combined
4792  * state table, so we need to handle that with a forwarding function. The other invisible side effect
4793  * is that changing the fog start and fog end(which links to FOGENABLE in vertex) results in the
4794  * fragment_prog_arbfp function being called because FOGENABLE is dirty, which calls this function here
4795  */
4796 static void state_arbfp_fog(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
4797     enum fogsource new_source;
4798
4799     TRACE("state %#x, stateblock %p, context %p\n", state, stateblock, context);
4800
4801     if(!isStateDirty(context, STATE_PIXELSHADER)) {
4802         fragment_prog_arbfp(state, stateblock, context);
4803     }
4804
4805     if(!stateblock->renderState[WINED3DRS_FOGENABLE]) return;
4806
4807     if(stateblock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
4808         if(use_vs(stateblock)) {
4809             new_source = FOGSOURCE_VS;
4810         } else {
4811             if(stateblock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || context->last_was_rhw) {
4812                 new_source = FOGSOURCE_COORD;
4813             } else {
4814                 new_source = FOGSOURCE_FFP;
4815             }
4816         }
4817     } else {
4818         new_source = FOGSOURCE_FFP;
4819     }
4820     if(new_source != context->fog_source) {
4821         context->fog_source = new_source;
4822         state_fogstartend(STATE_RENDER(WINED3DRS_FOGSTART), stateblock, context);
4823     }
4824 }
4825
4826 static void textransform(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context) {
4827     if(!isStateDirty(context, STATE_PIXELSHADER)) {
4828         fragment_prog_arbfp(state, stateblock, context);
4829     }
4830 }
4831
4832 #undef GLINFO_LOCATION
4833
4834 static const struct StateEntryTemplate arbfp_fragmentstate_template[] = {
4835     {STATE_RENDER(WINED3DRS_TEXTUREFACTOR),               { STATE_RENDER(WINED3DRS_TEXTUREFACTOR),              state_texfactor_arbfp   }, WINED3D_GL_EXT_NONE             },
4836     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4837     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4838     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4839     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4840     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4841     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4842     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4843     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4844     {STATE_TEXTURESTAGE(0, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4845     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4846     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4847     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4848     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4849     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4850     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4851     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4852     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4853     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4854     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4855     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4856     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4857     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4858     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4859     {STATE_TEXTURESTAGE(1, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4860     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4861     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4862     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4863     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4864     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4865     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4866     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4867     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4868     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4869     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4870     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4871     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4872     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4873     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4874     {STATE_TEXTURESTAGE(2, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4875     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4876     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4877     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4878     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4879     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4880     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4881     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4882     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4883     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4884     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4885     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4886     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4887     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4888     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4889     {STATE_TEXTURESTAGE(3, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4890     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4891     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4892     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4893     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4894     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4895     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4896     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4897     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4898     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4899     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4900     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4901     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4902     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4903     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4904     {STATE_TEXTURESTAGE(4, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4905     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4906     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4907     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4908     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4909     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4910     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4911     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4912     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4913     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4914     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4915     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4916     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4917     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4918     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4919     {STATE_TEXTURESTAGE(5, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4920     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4921     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4922     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4923     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4924     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4925     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4926     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4927     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4928     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4929     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4930     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4931     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4932     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4933     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4934     {STATE_TEXTURESTAGE(6, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4935     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4936     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4937     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4938     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4939     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4940     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4941     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4942     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4943     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4944     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4945     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4946     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4947     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4948     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4949     {STATE_TEXTURESTAGE(7, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4950     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4951     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4952     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4953     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
4954     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4955     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
4956     {STATE_SAMPLER(0),                                    { STATE_SAMPLER(0),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
4957     {STATE_SAMPLER(1),                                    { STATE_SAMPLER(1),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
4958     {STATE_SAMPLER(2),                                    { STATE_SAMPLER(2),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
4959     {STATE_SAMPLER(3),                                    { STATE_SAMPLER(3),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
4960     {STATE_SAMPLER(4),                                    { STATE_SAMPLER(4),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
4961     {STATE_SAMPLER(5),                                    { STATE_SAMPLER(5),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
4962     {STATE_SAMPLER(6),                                    { STATE_SAMPLER(6),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
4963     {STATE_SAMPLER(7),                                    { STATE_SAMPLER(7),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
4964     {STATE_PIXELSHADER,                                   { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4965     {STATE_RENDER(WINED3DRS_FOGENABLE),                   { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, WINED3D_GL_EXT_NONE             },
4966     {STATE_RENDER(WINED3DRS_FOGTABLEMODE),                { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, WINED3D_GL_EXT_NONE             },
4967     {STATE_RENDER(WINED3DRS_FOGVERTEXMODE),               { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, WINED3D_GL_EXT_NONE             },
4968     {STATE_RENDER(WINED3DRS_FOGSTART),                    { STATE_RENDER(WINED3DRS_FOGSTART),                   state_fogstartend       }, WINED3D_GL_EXT_NONE             },
4969     {STATE_RENDER(WINED3DRS_FOGEND),                      { STATE_RENDER(WINED3DRS_FOGSTART),                   state_fogstartend       }, WINED3D_GL_EXT_NONE             },
4970     {STATE_RENDER(WINED3DRS_SRGBWRITEENABLE),             { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
4971     {STATE_RENDER(WINED3DRS_FOGCOLOR),                    { STATE_RENDER(WINED3DRS_FOGCOLOR),                   state_fogcolor          }, WINED3D_GL_EXT_NONE             },
4972     {STATE_RENDER(WINED3DRS_FOGDENSITY),                  { STATE_RENDER(WINED3DRS_FOGDENSITY),                 state_fogdensity        }, WINED3D_GL_EXT_NONE             },
4973     {STATE_TEXTURESTAGE(0,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(0, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
4974     {STATE_TEXTURESTAGE(1,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(1, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
4975     {STATE_TEXTURESTAGE(2,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(2, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
4976     {STATE_TEXTURESTAGE(3,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(3, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
4977     {STATE_TEXTURESTAGE(4,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(4, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
4978     {STATE_TEXTURESTAGE(5,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(5, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
4979     {STATE_TEXTURESTAGE(6,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(6, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
4980     {STATE_TEXTURESTAGE(7,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(7, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
4981     {STATE_RENDER(WINED3DRS_SPECULARENABLE),              { STATE_RENDER(WINED3DRS_SPECULARENABLE),             state_arb_specularenable}, WINED3D_GL_EXT_NONE             },
4982     {0 /* Terminate */,                                   { 0,                                                  0                       }, WINED3D_GL_EXT_NONE             },
4983 };
4984
4985 const struct fragment_pipeline arbfp_fragment_pipeline = {
4986     arbfp_enable,
4987     arbfp_get_caps,
4988     arbfp_alloc,
4989     arbfp_free,
4990     shader_arb_color_fixup_supported,
4991     arbfp_fragmentstate_template,
4992     TRUE /* We can disable projected textures */
4993 };
4994
4995 #define GLINFO_LOCATION device->adapter->gl_info
4996
4997 struct arbfp_blit_priv {
4998     GLenum yuy2_rect_shader, yuy2_2d_shader;
4999     GLenum uyvy_rect_shader, uyvy_2d_shader;
5000     GLenum yv12_rect_shader, yv12_2d_shader;
5001 };
5002
5003 static HRESULT arbfp_blit_alloc(IWineD3DDevice *iface) {
5004     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
5005     device->blit_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct arbfp_blit_priv));
5006     if(!device->blit_priv) {
5007         ERR("Out of memory\n");
5008         return E_OUTOFMEMORY;
5009     }
5010     return WINED3D_OK;
5011 }
5012 static void arbfp_blit_free(IWineD3DDevice *iface) {
5013     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
5014     struct arbfp_blit_priv *priv = device->blit_priv;
5015
5016     ENTER_GL();
5017     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_rect_shader));
5018     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_2d_shader));
5019     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_rect_shader));
5020     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_2d_shader));
5021     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yv12_rect_shader));
5022     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yv12_2d_shader));
5023     checkGLcall("Delete yuv programs\n");
5024     LEAVE_GL();
5025 }
5026
5027 static BOOL gen_planar_yuv_read(SHADER_BUFFER *buffer, enum yuv_fixup yuv_fixup, GLenum textype, char *luminance)
5028 {
5029     char chroma;
5030     const char *tex, *texinstr;
5031
5032     if (yuv_fixup == YUV_FIXUP_UYVY) {
5033         chroma = 'x';
5034         *luminance = 'w';
5035     } else {
5036         chroma = 'w';
5037         *luminance = 'x';
5038     }
5039     switch(textype) {
5040         case GL_TEXTURE_2D:             tex = "2D";     texinstr = "TXP"; break;
5041         case GL_TEXTURE_RECTANGLE_ARB:  tex = "RECT";   texinstr = "TEX"; break;
5042         default:
5043             /* This is more tricky than just replacing the texture type - we have to navigate
5044              * properly in the texture to find the correct chroma values
5045              */
5046             FIXME("Implement yuv correction for non-2d, non-rect textures\n");
5047             return FALSE;
5048     }
5049
5050     /* First we have to read the chroma values. This means we need at least two pixels(no filtering),
5051      * or 4 pixels(with filtering). To get the unmodified chromas, we have to rid ourselves of the
5052      * filtering when we sample the texture.
5053      *
5054      * These are the rules for reading the chroma:
5055      *
5056      * Even pixel: Cr
5057      * Even pixel: U
5058      * Odd pixel: V
5059      *
5060      * So we have to get the sampling x position in non-normalized coordinates in integers
5061      */
5062     if(textype != GL_TEXTURE_RECTANGLE_ARB) {
5063         shader_addline(buffer, "MUL texcrd.xy, fragment.texcoord[0], size.x;\n");
5064         shader_addline(buffer, "MOV texcrd.w, size.x;\n");
5065     } else {
5066         shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
5067     }
5068     /* We must not allow filtering between pixel x and x+1, this would mix U and V
5069      * Vertical filtering is ok. However, bear in mind that the pixel center is at
5070      * 0.5, so add 0.5.
5071      */
5072     shader_addline(buffer, "FLR texcrd.x, texcrd.x;\n");
5073     shader_addline(buffer, "ADD texcrd.x, texcrd.x, coef.y;\n");
5074
5075     /* Divide the x coordinate by 0.5 and get the fraction. This gives 0.25 and 0.75 for the
5076      * even and odd pixels respectively
5077      */
5078     shader_addline(buffer, "MUL texcrd2, texcrd, coef.y;\n");
5079     shader_addline(buffer, "FRC texcrd2, texcrd2;\n");
5080
5081     /* Sample Pixel 1 */
5082     shader_addline(buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
5083
5084     /* Put the value into either of the chroma values */
5085     shader_addline(buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
5086     shader_addline(buffer, "MUL chroma.x, luminance.%c, temp.x;\n", chroma);
5087     shader_addline(buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
5088     shader_addline(buffer, "MUL chroma.y, luminance.%c, temp.x;\n", chroma);
5089
5090     /* Sample pixel 2. If we read an even pixel(SLT above returned 1), sample
5091      * the pixel right to the current one. Otherwise, sample the left pixel.
5092      * Bias and scale the SLT result to -1;1 and add it to the texcrd.x.
5093      */
5094     shader_addline(buffer, "MAD temp.x, temp.x, coef.z, -coef.x;\n");
5095     shader_addline(buffer, "ADD texcrd.x, texcrd, temp.x;\n");
5096     shader_addline(buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
5097
5098     /* Put the value into the other chroma */
5099     shader_addline(buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
5100     shader_addline(buffer, "MAD chroma.y, luminance.%c, temp.x, chroma.y;\n", chroma);
5101     shader_addline(buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
5102     shader_addline(buffer, "MAD chroma.x, luminance.%c, temp.x, chroma.x;\n", chroma);
5103
5104     /* TODO: If filtering is enabled, sample a 2nd pair of pixels left or right of
5105      * the current one and lerp the two U and V values
5106      */
5107
5108     /* This gives the correctly filtered luminance value */
5109     shader_addline(buffer, "TEX luminance, fragment.texcoord[0], texture[0], %s;\n", tex);
5110
5111     return TRUE;
5112 }
5113
5114 static BOOL gen_yv12_read(SHADER_BUFFER *buffer, GLenum textype, char *luminance)
5115 {
5116     const char *tex;
5117
5118     switch(textype) {
5119         case GL_TEXTURE_2D:             tex = "2D";     break;
5120         case GL_TEXTURE_RECTANGLE_ARB:  tex = "RECT";   break;
5121         default:
5122             FIXME("Implement yv12 correction for non-2d, non-rect textures\n");
5123             return FALSE;
5124     }
5125
5126     /* YV12 surfaces contain a WxH sized luminance plane, followed by a (W/2)x(H/2)
5127      * V and a (W/2)x(H/2) U plane, each with 8 bit per pixel. So the effective
5128      * bitdepth is 12 bits per pixel. Since the U and V planes have only half the
5129      * pitch of the luminance plane, the packing into the gl texture is a bit
5130      * unfortunate. If the whole texture is interpreted as luminance data it looks
5131      * approximately like this:
5132      *
5133      *        +----------------------------------+----
5134      *        |                                  |
5135      *        |                                  |
5136      *        |                                  |
5137      *        |                                  |
5138      *        |                                  |   2
5139      *        |            LUMINANCE             |   -
5140      *        |                                  |   3
5141      *        |                                  |
5142      *        |                                  |
5143      *        |                                  |
5144      *        |                                  |
5145      *        +----------------+-----------------+----
5146      *        |                |                 |
5147      *        |  U even rows   |  U odd rows     |
5148      *        |                |                 |   1
5149      *        +----------------+------------------   -
5150      *        |                |                 |   3
5151      *        |  V even rows   |  V odd rows     |
5152      *        |                |                 |
5153      *        +----------------+-----------------+----
5154      *        |                |                 |
5155      *        |     0.5        |       0.5       |
5156      *
5157      * So it appears as if there are 4 chroma images, but in fact the odd rows
5158      * in the chroma images are in the same row as the even ones. So its is
5159      * kinda tricky to read
5160      *
5161      * When reading from rectangle textures, keep in mind that the input y coordinates
5162      * go from 0 to d3d_height, whereas the opengl texture height is 1.5 * d3d_height
5163      */
5164     shader_addline(buffer, "PARAM yv12_coef = {%f, %f, %f, %f};\n",
5165                    2.0 / 3.0, 1.0 / 6.0, (2.0 / 3.0) + (1.0 / 6.0), 1.0 / 3.0);
5166
5167     shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
5168     /* the chroma planes have only half the width */
5169     shader_addline(buffer, "MUL texcrd.x, texcrd.x, coef.y;\n");
5170
5171     /* The first value is between 2/3 and 5/6th of the texture's height, so scale+bias
5172      * the coordinate. Also read the right side of the image when reading odd lines
5173      *
5174      * Don't forget to clamp the y values in into the range, otherwise we'll get filtering
5175      * bleeding
5176      */
5177     if(textype == GL_TEXTURE_2D) {
5178
5179         shader_addline(buffer, "RCP chroma.w, size.y;\n");
5180
5181         shader_addline(buffer, "MUL texcrd2.y, texcrd.y, size.y;\n");
5182
5183         shader_addline(buffer, "FLR texcrd2.y, texcrd2.y;\n");
5184         shader_addline(buffer, "MAD texcrd.y, texcrd.y, yv12_coef.y, yv12_coef.x;\n");
5185
5186         /* Read odd lines from the right side(add size * 0.5 to the x coordinate */
5187         shader_addline(buffer, "ADD texcrd2.x, texcrd2.y, yv12_coef.y;\n"); /* To avoid 0.5 == 0.5 comparisons */
5188         shader_addline(buffer, "FRC texcrd2.x, texcrd2.x;\n");
5189         shader_addline(buffer, "SGE texcrd2.x, texcrd2.x, coef.y;\n");
5190         shader_addline(buffer, "MAD texcrd.x, texcrd2.x, coef.y, texcrd.x;\n");
5191
5192         /* clamp, keep the half pixel origin in mind */
5193         shader_addline(buffer, "MAD temp.y, coef.y, chroma.w, yv12_coef.x;\n");
5194         shader_addline(buffer, "MAX texcrd.y, temp.y, texcrd.y;\n");
5195         shader_addline(buffer, "MAD temp.y, -coef.y, chroma.w, yv12_coef.z;\n");
5196         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
5197     } else {
5198         /* Read from [size - size+size/4] */
5199         shader_addline(buffer, "FLR texcrd.y, texcrd.y;\n");
5200         shader_addline(buffer, "MAD texcrd.y, texcrd.y, coef.w, size.y;\n");
5201
5202         /* Read odd lines from the right side(add size * 0.5 to the x coordinate */
5203         shader_addline(buffer, "ADD texcrd2.x, texcrd.y, yv12_coef.y;\n"); /* To avoid 0.5 == 0.5 comparisons */
5204         shader_addline(buffer, "FRC texcrd2.x, texcrd2.x;\n");
5205         shader_addline(buffer, "SGE texcrd2.x, texcrd2.x, coef.y;\n");
5206         shader_addline(buffer, "MUL texcrd2.x, texcrd2.x, size.x;\n");
5207         shader_addline(buffer, "MAD texcrd.x, texcrd2.x, coef.y, texcrd.x;\n");
5208
5209         /* Make sure to read exactly from the pixel center */
5210         shader_addline(buffer, "FLR texcrd.y, texcrd.y;\n");
5211         shader_addline(buffer, "ADD texcrd.y, texcrd.y, coef.y;\n");
5212
5213         /* Clamp */
5214         shader_addline(buffer, "MAD temp.y, size.y, coef.w, size.y;\n");
5215         shader_addline(buffer, "ADD temp.y, temp.y, -coef.y;\n");
5216         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
5217         shader_addline(buffer, "ADD temp.y, size.y, -coef.y;\n");
5218         shader_addline(buffer, "MAX texcrd.y, temp.y, texcrd.y;\n");
5219     }
5220     /* Read the texture, put the result into the output register */
5221     shader_addline(buffer, "TEX temp, texcrd, texture[0], %s;\n", tex);
5222     shader_addline(buffer, "MOV chroma.x, temp.w;\n");
5223
5224     /* The other chroma value is 1/6th of the texture lower, from 5/6th to 6/6th
5225      * No need to clamp because we're just reusing the already clamped value from above
5226      */
5227     if(textype == GL_TEXTURE_2D) {
5228         shader_addline(buffer, "ADD texcrd.y, texcrd.y, yv12_coef.y;\n");
5229     } else {
5230         shader_addline(buffer, "MAD texcrd.y, size.y, coef.w, texcrd.y;\n");
5231     }
5232     shader_addline(buffer, "TEX temp, texcrd, texture[0], %s;\n", tex);
5233     shader_addline(buffer, "MOV chroma.y, temp.w;\n");
5234
5235     /* Sample the luminance value. It is in the top 2/3rd of the texture, so scale the y coordinate.
5236      * Clamp the y coordinate to prevent the chroma values from bleeding into the sampled luminance
5237      * values due to filtering
5238      */
5239     shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
5240     if(textype == GL_TEXTURE_2D) {
5241         /* Multiply the y coordinate by 2/3 and clamp it */
5242         shader_addline(buffer, "MUL texcrd.y, texcrd.y, yv12_coef.x;\n");
5243         shader_addline(buffer, "MAD temp.y, -coef.y, chroma.w, yv12_coef.x;\n");
5244         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
5245         shader_addline(buffer, "TEX luminance, texcrd, texture[0], %s;\n", tex);
5246     } else {
5247         /* Reading from texture_rectangles is pretty straightforward, just use the unmodified
5248          * texture coordinate. It is still a good idea to clamp it though, since the opengl texture
5249          * is bigger
5250          */
5251         shader_addline(buffer, "ADD temp.x, size.y, -coef.y;\n");
5252         shader_addline(buffer, "MIN texcrd.y, texcrd.y, size.x;\n");
5253         shader_addline(buffer, "TEX luminance, texcrd, texture[0], %s;\n", tex);
5254     }
5255     *luminance = 'a';
5256
5257     return TRUE;
5258 }
5259
5260 static GLuint gen_yuv_shader(IWineD3DDeviceImpl *device, enum yuv_fixup yuv_fixup, GLenum textype)
5261 {
5262     GLenum shader;
5263     SHADER_BUFFER buffer;
5264     char luminance_component;
5265     struct arbfp_blit_priv *priv = device->blit_priv;
5266
5267     /* Shader header */
5268     shader_buffer_init(&buffer);
5269
5270     ENTER_GL();
5271     GL_EXTCALL(glGenProgramsARB(1, &shader));
5272     checkGLcall("GL_EXTCALL(glGenProgramsARB(1, &shader))");
5273     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
5274     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
5275     LEAVE_GL();
5276     if(!shader) {
5277         shader_buffer_free(&buffer);
5278         return 0;
5279     }
5280
5281     /* The YUY2 and UYVY formats contain two pixels packed into a 32 bit macropixel,
5282      * giving effectively 16 bit per pixel. The color consists of a luminance(Y) and
5283      * two chroma(U and V) values. Each macropixel has two luminance values, one for
5284      * each single pixel it contains, and one U and one V value shared between both
5285      * pixels.
5286      *
5287      * The data is loaded into an A8L8 texture. With YUY2, the luminance component
5288      * contains the luminance and alpha the chroma. With UYVY it is vice versa. Thus
5289      * take the format into account when generating the read swizzles
5290      *
5291      * Reading the Y value is straightforward - just sample the texture. The hardware
5292      * takes care of filtering in the horizontal and vertical direction.
5293      *
5294      * Reading the U and V values is harder. We have to avoid filtering horizontally,
5295      * because that would mix the U and V values of one pixel or two adjacent pixels.
5296      * Thus floor the texture coordinate and add 0.5 to get an unfiltered read,
5297      * regardless of the filtering setting. Vertical filtering works automatically
5298      * though - the U and V values of two rows are mixed nicely.
5299      *
5300      * Appart of avoiding filtering issues, the code has to know which value it just
5301      * read, and where it can find the other one. To determine this, it checks if
5302      * it sampled an even or odd pixel, and shifts the 2nd read accordingly.
5303      *
5304      * Handling horizontal filtering of U and V values requires reading a 2nd pair
5305      * of pixels, extracting U and V and mixing them. This is not implemented yet.
5306      *
5307      * An alternative implementation idea is to load the texture as A8R8G8B8 texture,
5308      * with width / 2. This way one read gives all 3 values, finding U and V is easy
5309      * in an unfiltered situation. Finding the luminance on the other hand requires
5310      * finding out if it is an odd or even pixel. The real drawback of this approach
5311      * is filtering. This would have to be emulated completely in the shader, reading
5312      * up two 2 packed pixels in up to 2 rows and interpolating both horizontally and
5313      * vertically. Beyond that it would require adjustments to the texture handling
5314      * code to deal with the width scaling
5315      */
5316     shader_addline(&buffer, "!!ARBfp1.0\n");
5317     shader_addline(&buffer, "TEMP luminance;\n");
5318     shader_addline(&buffer, "TEMP temp;\n");
5319     shader_addline(&buffer, "TEMP chroma;\n");
5320     shader_addline(&buffer, "TEMP texcrd;\n");
5321     shader_addline(&buffer, "TEMP texcrd2;\n");
5322     shader_addline(&buffer, "PARAM coef = {1.0, 0.5, 2.0, 0.25};\n");
5323     shader_addline(&buffer, "PARAM yuv_coef = {1.403, 0.344, 0.714, 1.770};\n");
5324     shader_addline(&buffer, "PARAM size = program.local[0];\n");
5325
5326     switch (yuv_fixup)
5327     {
5328         case YUV_FIXUP_UYVY:
5329         case YUV_FIXUP_YUY2:
5330             if (!gen_planar_yuv_read(&buffer, yuv_fixup, textype, &luminance_component))
5331             {
5332                 shader_buffer_free(&buffer);
5333                 return 0;
5334             }
5335             break;
5336
5337         case YUV_FIXUP_YV12:
5338             if (!gen_yv12_read(&buffer, textype, &luminance_component))
5339             {
5340                 shader_buffer_free(&buffer);
5341                 return 0;
5342             }
5343             break;
5344
5345         default:
5346             FIXME("Unsupported YUV fixup %#x\n", yuv_fixup);
5347             shader_buffer_free(&buffer);
5348             return 0;
5349     }
5350
5351     /* Calculate the final result. Formula is taken from
5352      * http://www.fourcc.org/fccyvrgb.php. Note that the chroma
5353      * ranges from -0.5 to 0.5
5354      */
5355     shader_addline(&buffer, "SUB chroma.xy, chroma, coef.y;\n");
5356
5357     shader_addline(&buffer, "MAD result.color.x, chroma.x, yuv_coef.x, luminance.%c;\n", luminance_component);
5358     shader_addline(&buffer, "MAD temp.x, -chroma.y, yuv_coef.y, luminance.%c;\n", luminance_component);
5359     shader_addline(&buffer, "MAD result.color.y, -chroma.x, yuv_coef.z, temp.x;\n");
5360     shader_addline(&buffer, "MAD result.color.z, chroma.y, yuv_coef.w, luminance.%c;\n", luminance_component);
5361     shader_addline(&buffer, "END\n");
5362
5363     ENTER_GL();
5364     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(buffer.buffer), buffer.buffer));
5365
5366     if (glGetError() == GL_INVALID_OPERATION) {
5367         GLint pos;
5368         glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
5369         FIXME("Fragment program error at position %d: %s\n", pos,
5370               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
5371     }
5372     shader_buffer_free(&buffer);
5373     LEAVE_GL();
5374
5375     switch (yuv_fixup)
5376     {
5377         case YUV_FIXUP_YUY2:
5378             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->yuy2_rect_shader = shader;
5379             else priv->yuy2_2d_shader = shader;
5380             break;
5381
5382         case YUV_FIXUP_UYVY:
5383             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->uyvy_rect_shader = shader;
5384             else priv->uyvy_2d_shader = shader;
5385             break;
5386
5387         case YUV_FIXUP_YV12:
5388             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->yv12_rect_shader = shader;
5389             else priv->yv12_2d_shader = shader;
5390             break;
5391     }
5392
5393     return shader;
5394 }
5395
5396 static HRESULT arbfp_blit_set(IWineD3DDevice *iface, const struct GlPixelFormatDesc *format_desc,
5397         GLenum textype, UINT width, UINT height)
5398 {
5399     GLenum shader;
5400     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
5401     float size[4] = {width, height, 1, 1};
5402     struct arbfp_blit_priv *priv = device->blit_priv;
5403     enum yuv_fixup yuv_fixup;
5404
5405     if (!is_yuv_fixup(format_desc->color_fixup))
5406     {
5407         TRACE("Fixup:\n");
5408         dump_color_fixup_desc(format_desc->color_fixup);
5409         /* Don't bother setting up a shader for unconverted formats */
5410         ENTER_GL();
5411         glEnable(textype);
5412         checkGLcall("glEnable(textype)");
5413         LEAVE_GL();
5414         return WINED3D_OK;
5415     }
5416
5417     yuv_fixup = get_yuv_fixup(format_desc->color_fixup);
5418
5419     switch(yuv_fixup)
5420     {
5421         case YUV_FIXUP_YUY2:
5422             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->yuy2_rect_shader : priv->yuy2_2d_shader;
5423             break;
5424
5425         case YUV_FIXUP_UYVY:
5426             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->uyvy_rect_shader : priv->uyvy_2d_shader;
5427             break;
5428
5429         case YUV_FIXUP_YV12:
5430             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->yv12_rect_shader : priv->yv12_2d_shader;
5431             break;
5432
5433         default:
5434             FIXME("Unsupported YUV fixup %#x, not setting a shader\n", yuv_fixup);
5435             ENTER_GL();
5436             glEnable(textype);
5437             checkGLcall("glEnable(textype)");
5438             LEAVE_GL();
5439             return E_NOTIMPL;
5440     }
5441
5442     if (!shader) shader = gen_yuv_shader(device, yuv_fixup, textype);
5443
5444     ENTER_GL();
5445     glEnable(GL_FRAGMENT_PROGRAM_ARB);
5446     checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
5447     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
5448     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
5449     GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, 0, size));
5450     checkGLcall("glProgramLocalParameter4fvARB");
5451     LEAVE_GL();
5452
5453     return WINED3D_OK;
5454 }
5455
5456 static void arbfp_blit_unset(IWineD3DDevice *iface) {
5457     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
5458
5459     ENTER_GL();
5460     glDisable(GL_FRAGMENT_PROGRAM_ARB);
5461     checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
5462     glDisable(GL_TEXTURE_2D);
5463     checkGLcall("glDisable(GL_TEXTURE_2D)");
5464     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
5465         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
5466         checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
5467     }
5468     if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
5469         glDisable(GL_TEXTURE_RECTANGLE_ARB);
5470         checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
5471     }
5472     LEAVE_GL();
5473 }
5474
5475 static BOOL arbfp_blit_color_fixup_supported(struct color_fixup_desc fixup)
5476 {
5477     enum yuv_fixup yuv_fixup;
5478
5479     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
5480     {
5481         TRACE("Checking support for fixup:\n");
5482         dump_color_fixup_desc(fixup);
5483     }
5484
5485     if (is_identity_fixup(fixup))
5486     {
5487         TRACE("[OK]\n");
5488         return TRUE;
5489     }
5490
5491     /* We only support YUV conversions. */
5492     if (!is_yuv_fixup(fixup))
5493     {
5494         TRACE("[FAILED]\n");
5495         return FALSE;
5496     }
5497
5498     yuv_fixup = get_yuv_fixup(fixup);
5499     switch(yuv_fixup)
5500     {
5501         case YUV_FIXUP_YUY2:
5502         case YUV_FIXUP_UYVY:
5503         case YUV_FIXUP_YV12:
5504             TRACE("[OK]\n");
5505             return TRUE;
5506
5507         default:
5508             FIXME("Unsupported YUV fixup %#x\n", yuv_fixup);
5509             TRACE("[FAILED]\n");
5510             return FALSE;
5511     }
5512 }
5513
5514 const struct blit_shader arbfp_blit = {
5515     arbfp_blit_alloc,
5516     arbfp_blit_free,
5517     arbfp_blit_set,
5518     arbfp_blit_unset,
5519     arbfp_blit_color_fixup_supported,
5520 };
5521
5522 #undef GLINFO_LOCATION