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