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