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