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