wined3d: Explicitly pass GL info to buffer_create_buffer_object().
[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, falling back to tex_2d\n", tex_type);
3192         tex_type = tex_2d;
3193         fprogram = masked ? blt_fprograms_masked[tex_type] : blt_fprograms_full[tex_type];
3194     }
3195
3196     GL_EXTCALL(glGenProgramsARB(1, &program_id));
3197     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, program_id));
3198     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(fprogram), fprogram));
3199     checkGLcall("glProgramStringARB()");
3200
3201     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
3202     if (pos != -1)
3203     {
3204         FIXME("Fragment program error at position %d: %s\n\n", pos,
3205             debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
3206         shader_arb_dump_program_source(fprogram);
3207     }
3208     else
3209     {
3210         GLint native;
3211
3212         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
3213         checkGLcall("glGetProgramivARB()");
3214         if (!native) WARN("Program exceeds native resource limits.\n");
3215     }
3216
3217     return program_id;
3218 }
3219
3220 static void arbfp_add_sRGB_correction(struct wined3d_shader_buffer *buffer, const char *fragcolor,
3221         const char *tmp1, const char *tmp2, const char *tmp3, const char *tmp4, BOOL condcode)
3222 {
3223     /* Perform sRGB write correction. See GLX_EXT_framebuffer_sRGB */
3224
3225     if(condcode)
3226     {
3227         /* Sigh. MOVC CC doesn't work, so use one of the temps as dummy dest */
3228         shader_addline(buffer, "SUBC %s, %s.x, srgb_consts1.y;\n", tmp1, fragcolor);
3229         /* Calculate the > 0.0031308 case */
3230         shader_addline(buffer, "POW %s.x (GE), %s.x, srgb_consts1.z;\n", fragcolor, fragcolor);
3231         shader_addline(buffer, "POW %s.y (GE), %s.y, srgb_consts1.z;\n", fragcolor, fragcolor);
3232         shader_addline(buffer, "POW %s.z (GE), %s.z, srgb_consts1.z;\n", fragcolor, fragcolor);
3233         shader_addline(buffer, "MUL %s.xyz (GE), %s, srgb_consts1.w;\n", fragcolor, fragcolor);
3234         shader_addline(buffer, "SUB %s.xyz (GE), %s, srgb_consts2.x;\n", fragcolor, fragcolor);
3235         /* Calculate the < case */
3236         shader_addline(buffer, "MUL %s.xyz (LT), srgb_consts1.x, %s;\n", fragcolor, fragcolor);
3237     }
3238     else
3239     {
3240         /* Calculate the > 0.0031308 case */
3241         shader_addline(buffer, "POW %s.x, %s.x, srgb_consts1.z;\n", tmp1, fragcolor);
3242         shader_addline(buffer, "POW %s.y, %s.y, srgb_consts1.z;\n", tmp1, fragcolor);
3243         shader_addline(buffer, "POW %s.z, %s.z, srgb_consts1.z;\n", tmp1, fragcolor);
3244         shader_addline(buffer, "MUL %s, %s, srgb_consts1.w;\n", tmp1, tmp1);
3245         shader_addline(buffer, "SUB %s, %s, srgb_consts2.x;\n", tmp1, tmp1);
3246         /* Calculate the < case */
3247         shader_addline(buffer, "MUL %s, srgb_consts1.x, %s;\n", tmp2, fragcolor);
3248         /* Get 1.0 / 0.0 masks for > 0.0031308 and < 0.0031308 */
3249         shader_addline(buffer, "SLT %s, srgb_consts1.y, %s;\n", tmp3, fragcolor);
3250         shader_addline(buffer, "SGE %s, srgb_consts1.y, %s;\n", tmp4, fragcolor);
3251         /* Store the components > 0.0031308 in the destination */
3252         shader_addline(buffer, "MUL %s.xyz, %s, %s;\n", fragcolor, tmp1, tmp3);
3253         /* Add the components that are < 0.0031308 */
3254         shader_addline(buffer, "MAD %s.xyz, %s, %s, %s;\n", fragcolor, tmp2, tmp4, fragcolor);
3255         /* Move everything into result.color at once. Nvidia hardware cannot handle partial
3256         * result.color writes(.rgb first, then .a), or handle overwriting already written
3257         * components. The assembler uses a temporary register in this case, which is usually
3258         * not allocated from one of our registers that were used earlier.
3259         */
3260     }
3261     /* [0.0;1.0] clamping. Not needed, this is done implicitly */
3262 }
3263
3264 static const DWORD *find_loop_control_values(IWineD3DBaseShaderImpl *This, DWORD idx)
3265 {
3266     const local_constant *constant;
3267
3268     LIST_FOR_EACH_ENTRY(constant, &This->baseShader.constantsI, local_constant, entry)
3269     {
3270         if (constant->idx == idx)
3271         {
3272             return constant->value;
3273         }
3274     }
3275     return NULL;
3276 }
3277
3278 static void init_ps_input(const IWineD3DPixelShaderImpl *This, const struct arb_ps_compile_args *args,
3279                           struct shader_arb_ctx_priv *priv)
3280 {
3281     const char *texcoords[8] =
3282     {
3283         "fragment.texcoord[0]", "fragment.texcoord[1]", "fragment.texcoord[2]", "fragment.texcoord[3]",
3284         "fragment.texcoord[4]", "fragment.texcoord[5]", "fragment.texcoord[6]", "fragment.texcoord[7]"
3285     };
3286     unsigned int i;
3287     const struct wined3d_shader_signature_element *sig = This->baseShader.input_signature;
3288     const char *semantic_name;
3289     DWORD semantic_idx;
3290
3291     switch(args->super.vp_mode)
3292     {
3293         case pretransformed:
3294         case fixedfunction:
3295             /* The pixelshader has to collect the varyings on its own. In any case properly load
3296              * color0 and color1. In the case of pretransformed vertices also load texcoords. Set
3297              * other attribs to 0.0.
3298              *
3299              * For fixedfunction this behavior is correct, according to the tests. For pretransformed
3300              * we'd either need a replacement shader that can load other attribs like BINORMAL, or
3301              * load the texcoord attrib pointers to match the pixel shader signature
3302              */
3303             for(i = 0; i < MAX_REG_INPUT; i++)
3304             {
3305                 semantic_name = sig[i].semantic_name;
3306                 semantic_idx = sig[i].semantic_idx;
3307                 if(semantic_name == NULL) continue;
3308
3309                 if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3310                 {
3311                     if(semantic_idx == 0) priv->ps_input[i] = "fragment.color.primary";
3312                     else if(semantic_idx == 1) priv->ps_input[i] = "fragment.color.secondary";
3313                     else priv->ps_input[i] = "0.0";
3314                 }
3315                 else if(args->super.vp_mode == fixedfunction)
3316                 {
3317                     priv->ps_input[i] = "0.0";
3318                 }
3319                 else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3320                 {
3321                     if(semantic_idx < 8) priv->ps_input[i] = texcoords[semantic_idx];
3322                     else priv->ps_input[i] = "0.0";
3323                 }
3324                 else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3325                 {
3326                     if(semantic_idx == 0) priv->ps_input[i] = "fragment.fogcoord";
3327                     else priv->ps_input[i] = "0.0";
3328                 }
3329                 else
3330                 {
3331                     priv->ps_input[i] = "0.0";
3332                 }
3333
3334                 TRACE("v%u, semantic %s%u is %s\n", i, semantic_name, semantic_idx, priv->ps_input[i]);
3335             }
3336             break;
3337
3338         case vertexshader:
3339             /* That one is easy. The vertex shaders provide v0-v7 in fragment.texcoord and v8 and v9 in
3340              * fragment.color
3341              */
3342             for(i = 0; i < 8; i++)
3343             {
3344                 priv->ps_input[i] = texcoords[i];
3345             }
3346             priv->ps_input[8] = "fragment.color.primary";
3347             priv->ps_input[9] = "fragment.color.secondary";
3348             break;
3349     }
3350 }
3351
3352 /* GL locking is done by the caller */
3353 static GLuint shader_arb_generate_pshader(IWineD3DPixelShaderImpl *This, struct wined3d_shader_buffer *buffer,
3354         const struct arb_ps_compile_args *args, struct arb_ps_compiled_shader *compiled)
3355 {
3356     const shader_reg_maps* reg_maps = &This->baseShader.reg_maps;
3357     CONST DWORD *function = This->baseShader.function;
3358     const struct wined3d_gl_info *gl_info = &((IWineD3DDeviceImpl *)This->baseShader.device)->adapter->gl_info;
3359     const local_constant *lconst;
3360     GLuint retval;
3361     char fragcolor[16];
3362     DWORD *lconst_map = local_const_mapping((IWineD3DBaseShaderImpl *) This), next_local, cur;
3363     struct shader_arb_ctx_priv priv_ctx;
3364     BOOL dcl_td = FALSE;
3365     BOOL want_nv_prog = FALSE;
3366     struct arb_pshader_private *shader_priv = This->baseShader.backend_data;
3367     GLint errPos;
3368     DWORD map;
3369
3370     char srgbtmp[4][4];
3371     unsigned int i, found = 0;
3372
3373     for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
3374     {
3375         if (!(map & 1)
3376                 || (This->color0_mov && i == This->color0_reg)
3377                 || (reg_maps->shader_version.major < 2 && i == 0))
3378             continue;
3379
3380         sprintf(srgbtmp[found], "R%u", i);
3381         ++found;
3382         if (found == 4) break;
3383     }
3384
3385     switch(found) {
3386         case 0:
3387             sprintf(srgbtmp[0], "TA");
3388             sprintf(srgbtmp[1], "TB");
3389             sprintf(srgbtmp[2], "TC");
3390             sprintf(srgbtmp[3], "TD");
3391             dcl_td = TRUE;
3392             break;
3393         case 1:
3394             sprintf(srgbtmp[1], "TA");
3395             sprintf(srgbtmp[2], "TB");
3396             sprintf(srgbtmp[3], "TC");
3397             break;
3398         case 2:
3399             sprintf(srgbtmp[2], "TA");
3400             sprintf(srgbtmp[3], "TB");
3401             break;
3402         case 3:
3403             sprintf(srgbtmp[3], "TA");
3404             break;
3405         case 4:
3406             break;
3407     }
3408
3409     /*  Create the hw ARB shader */
3410     memset(&priv_ctx, 0, sizeof(priv_ctx));
3411     priv_ctx.cur_ps_args = args;
3412     priv_ctx.compiled_fprog = compiled;
3413     priv_ctx.cur_np2fixup_info = &compiled->np2fixup_info;
3414     init_ps_input(This, args, &priv_ctx);
3415     list_init(&priv_ctx.control_frames);
3416
3417     /* Avoid enabling NV_fragment_program* if we do not need it.
3418      *
3419      * Enabling GL_NV_fragment_program_option causes the driver to occupy a temporary register,
3420      * and it slows down the shader execution noticeably(about 5%). Usually our instruction emulation
3421      * is faster than what we gain from using higher native instructions. There are some things though
3422      * that cannot be emulated. In that case enable the extensions.
3423      * If the extension is enabled, instruction handlers that support both ways will use it.
3424      *
3425      * Testing shows no performance difference between OPTION NV_fragment_program2 and NV_fragment_program.
3426      * So enable the best we can get.
3427      */
3428     if(reg_maps->usesdsx || reg_maps->usesdsy || reg_maps->loop_depth > 0 || reg_maps->usestexldd ||
3429        reg_maps->usestexldl || reg_maps->usesfacing || reg_maps->usesifc || reg_maps->usescall)
3430     {
3431         want_nv_prog = TRUE;
3432     }
3433
3434     shader_addline(buffer, "!!ARBfp1.0\n");
3435     if (want_nv_prog && gl_info->supported[NV_FRAGMENT_PROGRAM2])
3436     {
3437         shader_addline(buffer, "OPTION NV_fragment_program2;\n");
3438         priv_ctx.target_version = NV3;
3439     }
3440     else if (want_nv_prog && gl_info->supported[NV_FRAGMENT_PROGRAM_OPTION])
3441     {
3442         shader_addline(buffer, "OPTION NV_fragment_program;\n");
3443         priv_ctx.target_version = NV2;
3444     } else {
3445         if(want_nv_prog)
3446         {
3447             /* This is an error - either we're advertising the wrong shader version, or aren't enforcing some
3448              * limits properly
3449              */
3450             ERR("The shader requires instructions that are not available in plain GL_ARB_fragment_program\n");
3451             ERR("Try GLSL\n");
3452         }
3453         priv_ctx.target_version = ARB;
3454     }
3455
3456     if(This->baseShader.reg_maps.highest_render_target > 0)
3457     {
3458         shader_addline(buffer, "OPTION ARB_draw_buffers;\n");
3459     }
3460
3461     if (reg_maps->shader_version.major < 3)
3462     {
3463         switch(args->super.fog) {
3464             case FOG_OFF:
3465                 break;
3466             case FOG_LINEAR:
3467                 shader_addline(buffer, "OPTION ARB_fog_linear;\n");
3468                 break;
3469             case FOG_EXP:
3470                 shader_addline(buffer, "OPTION ARB_fog_exp;\n");
3471                 break;
3472             case FOG_EXP2:
3473                 shader_addline(buffer, "OPTION ARB_fog_exp2;\n");
3474                 break;
3475         }
3476     }
3477
3478     /* For now always declare the temps. At least the Nvidia assembler optimizes completely
3479      * unused temps away(but occupies them for the whole shader if they're used once). Always
3480      * declaring them avoids tricky bookkeeping work
3481      */
3482     shader_addline(buffer, "TEMP TA;\n");      /* Used for modifiers */
3483     shader_addline(buffer, "TEMP TB;\n");      /* Used for modifiers */
3484     shader_addline(buffer, "TEMP TC;\n");      /* Used for modifiers */
3485     if(dcl_td) shader_addline(buffer, "TEMP TD;\n"); /* Used for sRGB writing */
3486     shader_addline(buffer, "PARAM coefdiv = { 0.5, 0.25, 0.125, 0.0625 };\n");
3487     shader_addline(buffer, "PARAM coefmul = { 2, 4, 8, 16 };\n");
3488     shader_addline(buffer, "PARAM one = { 1.0, 1.0, 1.0, 1.0 };\n");
3489
3490     if (reg_maps->shader_version.major < 2)
3491     {
3492         strcpy(fragcolor, "R0");
3493     } else {
3494         if(args->super.srgb_correction) {
3495             if(This->color0_mov) {
3496                 sprintf(fragcolor, "R%u", This->color0_reg);
3497             } else {
3498                 shader_addline(buffer, "TEMP TMP_COLOR;\n");
3499                 strcpy(fragcolor, "TMP_COLOR");
3500             }
3501         } else {
3502             strcpy(fragcolor, "result.color");
3503         }
3504     }
3505
3506     if(args->super.srgb_correction) {
3507         shader_addline(buffer, "PARAM srgb_consts1 = {%f, %f, %f, %f};\n",
3508                        srgb_mul_low, srgb_cmp, srgb_pow, srgb_mul_high);
3509         shader_addline(buffer, "PARAM srgb_consts2 = {%f, %f, %f, %f};\n",
3510                        srgb_sub_high, 0.0, 0.0, 0.0);
3511     }
3512
3513     /* Base Declarations */
3514     next_local = shader_generate_arb_declarations((IWineD3DBaseShader *)This,
3515             reg_maps, buffer, gl_info, lconst_map, NULL, &priv_ctx);
3516
3517     for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
3518     {
3519         if (!(map & 1)) continue;
3520
3521         cur = compiled->numbumpenvmatconsts;
3522         compiled->bumpenvmatconst[cur].const_num = WINED3D_CONST_NUM_UNUSED;
3523         compiled->bumpenvmatconst[cur].texunit = i;
3524         compiled->luminanceconst[cur].const_num = WINED3D_CONST_NUM_UNUSED;
3525         compiled->luminanceconst[cur].texunit = i;
3526
3527         /* We can fit the constants into the constant limit for sure because texbem, texbeml, bem and beml are only supported
3528          * in 1.x shaders, and GL_ARB_fragment_program has a constant limit of 24 constants. So in the worst case we're loading
3529          * 8 shader constants, 8 bump matrices and 8 luminance parameters and are perfectly fine. (No NP2 fixup on bumpmapped
3530          * textures due to conditional NP2 restrictions)
3531          *
3532          * Use local constants to load the bump env parameters, not program.env. This avoids collisions with d3d constants of
3533          * shaders in newer shader models. Since the bump env parameters have to share their space with NP2 fixup constants,
3534          * their location is shader dependent anyway and they cannot be loaded globally.
3535          */
3536         compiled->bumpenvmatconst[cur].const_num = next_local++;
3537         shader_addline(buffer, "PARAM bumpenvmat%d = program.local[%d];\n",
3538                        i, compiled->bumpenvmatconst[cur].const_num);
3539         compiled->numbumpenvmatconsts = cur + 1;
3540
3541         if (!(reg_maps->luminanceparams & (1 << i))) continue;
3542
3543         compiled->luminanceconst[cur].const_num = next_local++;
3544         shader_addline(buffer, "PARAM luminance%d = program.local[%d];\n",
3545                        i, compiled->luminanceconst[cur].const_num);
3546     }
3547
3548     for(i = 0; i < MAX_CONST_I; i++)
3549     {
3550         compiled->int_consts[i] = WINED3D_CONST_NUM_UNUSED;
3551         if (reg_maps->integer_constants & (1 << i) && priv_ctx.target_version >= NV2)
3552         {
3553             const DWORD *control_values = find_loop_control_values((IWineD3DBaseShaderImpl *) This, i);
3554
3555             if(control_values)
3556             {
3557                 shader_addline(buffer, "PARAM I%u = {%u, %u, %u, -1};\n", i,
3558                                 control_values[0], control_values[1], control_values[2]);
3559             }
3560             else
3561             {
3562                 compiled->int_consts[i] = next_local;
3563                 compiled->num_int_consts++;
3564                 shader_addline(buffer, "PARAM I%u = program.local[%u];\n", i, next_local++);
3565             }
3566         }
3567     }
3568
3569     if(reg_maps->vpos || reg_maps->usesdsy)
3570     {
3571         compiled->ycorrection = next_local;
3572         shader_addline(buffer, "PARAM ycorrection = program.local[%u];\n", next_local++);
3573
3574         if(reg_maps->vpos)
3575         {
3576             shader_addline(buffer, "TEMP vpos;\n");
3577             /* ycorrection.x: Backbuffer height(onscreen) or 0(offscreen).
3578              * ycorrection.y: -1.0(onscreen), 1.0(offscreen)
3579              * ycorrection.z: 1.0
3580              * ycorrection.w: 0.0
3581              */
3582             shader_addline(buffer, "MAD vpos, fragment.position, ycorrection.zyww, ycorrection.wxww;\n");
3583             shader_addline(buffer, "FLR vpos.xy, vpos;\n");
3584         }
3585     }
3586     else
3587     {
3588         compiled->ycorrection = WINED3D_CONST_NUM_UNUSED;
3589     }
3590
3591     /* Load constants to fixup NP2 texcoords if there are still free constants left:
3592      * Constants (texture dimensions) for the NP2 fixup are loaded as local program parameters. This will consume
3593      * at most 8 (MAX_FRAGMENT_SAMPLERS / 2) parameters, which is highly unlikely, since the application had to
3594      * use 16 NP2 textures at the same time. In case that we run out of constants the fixup is simply not
3595      * applied / activated. This will probably result in wrong rendering of the texture, but will save us from
3596      * shader compilation errors and the subsequent errors when drawing with this shader. */
3597     if (priv_ctx.cur_ps_args->super.np2_fixup) {
3598
3599         struct arb_ps_np2fixup_info* const fixup = priv_ctx.cur_np2fixup_info;
3600         const WORD map = priv_ctx.cur_ps_args->super.np2_fixup;
3601         const UINT max_lconsts = gl_info->limits.arb_ps_local_constants;
3602
3603         fixup->offset = next_local;
3604         fixup->super.active = 0;
3605
3606         cur = 0;
3607         for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
3608             if (!(map & (1 << i))) continue;
3609
3610             if (fixup->offset + (cur >> 1) < max_lconsts) {
3611                 fixup->super.active |= (1 << i);
3612                 fixup->super.idx[i] = cur++;
3613             } else {
3614                 FIXME("No free constant found to load NP2 fixup data into shader. "
3615                       "Sampling from this texture will probably look wrong.\n");
3616                 break;
3617             }
3618         }
3619
3620         fixup->super.num_consts = (cur + 1) >> 1;
3621         if (fixup->super.num_consts) {
3622             shader_addline(buffer, "PARAM np2fixup[%u] = { program.env[%u..%u] };\n",
3623                            fixup->super.num_consts, fixup->offset, fixup->super.num_consts + fixup->offset - 1);
3624         }
3625
3626         next_local += fixup->super.num_consts;
3627     }
3628
3629     if (shader_priv->clipplane_emulation != ~0U && args->clip)
3630     {
3631         shader_addline(buffer, "KIL fragment.texcoord[%u];\n", shader_priv->clipplane_emulation);
3632     }
3633
3634     /* Base Shader Body */
3635     shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
3636
3637     if(args->super.srgb_correction) {
3638         arbfp_add_sRGB_correction(buffer, fragcolor, srgbtmp[0], srgbtmp[1], srgbtmp[2], srgbtmp[3],
3639                                   priv_ctx.target_version >= NV2);
3640     }
3641
3642     if(strcmp(fragcolor, "result.color")) {
3643         shader_addline(buffer, "MOV result.color, %s;\n", fragcolor);
3644     }
3645     shader_addline(buffer, "END\n");
3646
3647     /* TODO: change to resource.glObjectHandle or something like that */
3648     GL_EXTCALL(glGenProgramsARB(1, &retval));
3649
3650     TRACE("Creating a hw pixel shader, prg=%d\n", retval);
3651     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, retval));
3652
3653     TRACE("Created hw pixel shader, prg=%d\n", retval);
3654     /* Create the program and check for errors */
3655     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
3656                buffer->bsize, buffer->buffer));
3657     checkGLcall("glProgramStringARB()");
3658
3659     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
3660     if (errPos != -1)
3661     {
3662         FIXME("HW PixelShader Error at position %d: %s\n\n",
3663               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
3664         shader_arb_dump_program_source(buffer->buffer);
3665         retval = 0;
3666     }
3667     else
3668     {
3669         GLint native;
3670
3671         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
3672         checkGLcall("glGetProgramivARB()");
3673         if (!native) WARN("Program exceeds native resource limits.\n");
3674     }
3675
3676     /* Load immediate constants */
3677     if(lconst_map) {
3678         LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
3679             const float *value = (const float *)lconst->value;
3680             GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, lconst_map[lconst->idx], value));
3681             checkGLcall("glProgramLocalParameter4fvARB");
3682         }
3683         HeapFree(GetProcessHeap(), 0, lconst_map);
3684     }
3685
3686     return retval;
3687 }
3688
3689 static int compare_sig(const struct wined3d_shader_signature_element *sig1, const struct wined3d_shader_signature_element *sig2)
3690 {
3691     unsigned int i;
3692     int ret;
3693
3694     for(i = 0; i < MAX_REG_INPUT; i++)
3695     {
3696         if(sig1[i].semantic_name == NULL || sig2[i].semantic_name == NULL)
3697         {
3698             /* Compare pointers, not contents. One string is NULL(element does not exist), the other one is not NULL */
3699             if(sig1[i].semantic_name != sig2[i].semantic_name) return sig1[i].semantic_name < sig2[i].semantic_name ? -1 : 1;
3700             continue;
3701         }
3702
3703         ret = strcmp(sig1[i].semantic_name, sig2[i].semantic_name);
3704         if(ret != 0) return ret;
3705         if(sig1[i].semantic_idx    != sig2[i].semantic_idx)    return sig1[i].semantic_idx    < sig2[i].semantic_idx    ? -1 : 1;
3706         if(sig1[i].sysval_semantic != sig2[i].sysval_semantic) return sig1[i].sysval_semantic < sig2[i].sysval_semantic ? -1 : 1;
3707         if(sig1[i].component_type  != sig2[i].component_type)  return sig1[i].sysval_semantic < sig2[i].component_type  ? -1 : 1;
3708         if(sig1[i].register_idx    != sig2[i].register_idx)    return sig1[i].register_idx    < sig2[i].register_idx    ? -1 : 1;
3709         if(sig1[i].mask            != sig2->mask)              return sig1[i].mask            < sig2[i].mask            ? -1 : 1;
3710     }
3711     return 0;
3712 }
3713
3714 static struct wined3d_shader_signature_element *clone_sig(const struct wined3d_shader_signature_element *sig)
3715 {
3716     struct wined3d_shader_signature_element *new;
3717     int i;
3718     char *name;
3719
3720     new = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*new) * MAX_REG_INPUT);
3721     for(i = 0; i < MAX_REG_INPUT; i++)
3722     {
3723         if(sig[i].semantic_name == NULL)
3724         {
3725             continue;
3726         }
3727
3728         new[i] = sig[i];
3729         /* Clone the semantic string */
3730         name = HeapAlloc(GetProcessHeap(), 0, strlen(sig[i].semantic_name) + 1);
3731         strcpy(name, sig[i].semantic_name);
3732         new[i].semantic_name = name;
3733     }
3734     return new;
3735 }
3736
3737 static DWORD find_input_signature(struct shader_arb_priv *priv, const struct wined3d_shader_signature_element *sig)
3738 {
3739     struct wine_rb_entry *entry = wine_rb_get(&priv->signature_tree, sig);
3740     struct ps_signature *found_sig;
3741
3742     if(entry != NULL)
3743     {
3744         found_sig = WINE_RB_ENTRY_VALUE(entry, struct ps_signature, entry);
3745         TRACE("Found existing signature %u\n", found_sig->idx);
3746         return found_sig->idx;
3747     }
3748     found_sig = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*sig));
3749     found_sig->sig = clone_sig(sig);
3750     found_sig->idx = priv->ps_sig_number++;
3751     TRACE("New signature stored and assigned number %u\n", found_sig->idx);
3752     if(wine_rb_put(&priv->signature_tree, sig, &found_sig->entry) == -1)
3753     {
3754         ERR("Failed to insert program entry.\n");
3755     }
3756     return found_sig->idx;
3757 }
3758
3759 static void init_output_registers(IWineD3DVertexShaderImpl *shader, DWORD sig_num, struct shader_arb_ctx_priv *priv_ctx,
3760                                   struct arb_vs_compiled_shader *compiled)
3761 {
3762     unsigned int i, j;
3763     static const char *texcoords[8] =
3764     {
3765         "result.texcoord[0]", "result.texcoord[1]", "result.texcoord[2]", "result.texcoord[3]",
3766         "result.texcoord[4]", "result.texcoord[5]", "result.texcoord[6]", "result.texcoord[7]"
3767     };
3768     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) shader->baseShader.device;
3769     IWineD3DBaseShaderClass *baseshader = &shader->baseShader;
3770     const struct wined3d_shader_signature_element *sig;
3771     const char *semantic_name;
3772     DWORD semantic_idx, reg_idx;
3773
3774     /* Write generic input varyings 0 to 7 to result.texcoord[], varying 8 to result.color.primary
3775      * and varying 9 to result.color.secondary
3776      */
3777     const char *decl_idx_to_string[MAX_REG_INPUT] =
3778     {
3779         texcoords[0], texcoords[1], texcoords[2], texcoords[3],
3780         texcoords[4], texcoords[5], texcoords[6], texcoords[7],
3781         "result.color.primary", "result.color.secondary"
3782     };
3783
3784     if(sig_num == ~0)
3785     {
3786         TRACE("Pixel shader uses builtin varyings\n");
3787         /* Map builtins to builtins */
3788         for(i = 0; i < 8; i++)
3789         {
3790             priv_ctx->texcrd_output[i] = texcoords[i];
3791         }
3792         priv_ctx->color_output[0] = "result.color.primary";
3793         priv_ctx->color_output[1] = "result.color.secondary";
3794         priv_ctx->fog_output = "result.fogcoord";
3795
3796         /* Map declared regs to builtins. Use "TA" to /dev/null unread output */
3797         for (i = 0; i < (sizeof(baseshader->output_signature) / sizeof(*baseshader->output_signature)); ++i)
3798         {
3799             semantic_name = baseshader->output_signature[i].semantic_name;
3800             if(semantic_name == NULL) continue;
3801
3802             if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
3803             {
3804                 TRACE("o%u is TMP_OUT\n", i);
3805                 if (baseshader->output_signature[i].semantic_idx == 0) priv_ctx->vs_output[i] = "TMP_OUT";
3806                 else priv_ctx->vs_output[i] = "TA";
3807             }
3808             else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
3809             {
3810                 TRACE("o%u is result.pointsize\n", i);
3811                 if (baseshader->output_signature[i].semantic_idx == 0) priv_ctx->vs_output[i] = "result.pointsize";
3812                 else priv_ctx->vs_output[i] = "TA";
3813             }
3814             else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3815             {
3816                 TRACE("o%u is result.color.?, idx %u\n", i, baseshader->output_signature[i].semantic_idx);
3817                 if (baseshader->output_signature[i].semantic_idx == 0)
3818                     priv_ctx->vs_output[i] = "result.color.primary";
3819                 else if (baseshader->output_signature[i].semantic_idx == 1)
3820                     priv_ctx->vs_output[i] = "result.color.secondary";
3821                 else priv_ctx->vs_output[i] = "TA";
3822             }
3823             else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3824             {
3825                 TRACE("o%u is %s\n", i, texcoords[baseshader->output_signature[i].semantic_idx]);
3826                 if (baseshader->output_signature[i].semantic_idx >= 8) priv_ctx->vs_output[i] = "TA";
3827                 else priv_ctx->vs_output[i] = texcoords[baseshader->output_signature[i].semantic_idx];
3828             }
3829             else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3830             {
3831                 TRACE("o%u is result.fogcoord\n", i);
3832                 if (baseshader->output_signature[i].semantic_idx > 0) priv_ctx->vs_output[i] = "TA";
3833                 else priv_ctx->vs_output[i] = "result.fogcoord";
3834             }
3835             else
3836             {
3837                 priv_ctx->vs_output[i] = "TA";
3838             }
3839         }
3840         return;
3841     }
3842
3843     /* Instead of searching for the signature in the signature list, read the one from the current pixel shader.
3844      * Its maybe not the shader where the signature came from, but it is the same signature and faster to find
3845      */
3846     sig = ((IWineD3DPixelShaderImpl *)device->stateBlock->pixelShader)->baseShader.input_signature;
3847     TRACE("Pixel shader uses declared varyings\n");
3848
3849     /* Map builtin to declared. /dev/null the results by default to the TA temp reg */
3850     for(i = 0; i < 8; i++)
3851     {
3852         priv_ctx->texcrd_output[i] = "TA";
3853     }
3854     priv_ctx->color_output[0] = "TA";
3855     priv_ctx->color_output[1] = "TA";
3856     priv_ctx->fog_output = "TA";
3857
3858     for(i = 0; i < MAX_REG_INPUT; i++)
3859     {
3860         semantic_name = sig[i].semantic_name;
3861         semantic_idx = sig[i].semantic_idx;
3862         reg_idx = sig[i].register_idx;
3863         if(semantic_name == NULL) continue;
3864
3865         /* If a declared input register is not written by builtin arguments, don't write to it.
3866          * GL_NV_vertex_program makes sure the input defaults to 0.0, which is correct with D3D
3867          *
3868          * Don't care about POSITION and PSIZE here - this is a builtin vertex shader, position goes
3869          * to TMP_OUT in any case
3870          */
3871         if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3872         {
3873             if(semantic_idx < 8) priv_ctx->texcrd_output[semantic_idx] = decl_idx_to_string[reg_idx];
3874         }
3875         else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3876         {
3877             if(semantic_idx < 2) priv_ctx->color_output[semantic_idx] = decl_idx_to_string[reg_idx];
3878         }
3879         else if(shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
3880         {
3881             if(semantic_idx == 0) priv_ctx->fog_output = decl_idx_to_string[reg_idx];
3882         }
3883         else
3884         {
3885             continue;
3886         }
3887
3888         if(strcmp(decl_idx_to_string[reg_idx], "result.color.primary") == 0 ||
3889            strcmp(decl_idx_to_string[reg_idx], "result.color.secondary") == 0)
3890         {
3891             compiled->need_color_unclamp = TRUE;
3892         }
3893     }
3894
3895     /* Map declared to declared */
3896     for (i = 0; i < (sizeof(baseshader->output_signature) / sizeof(*baseshader->output_signature)); ++i)
3897     {
3898         /* Write unread output to TA to throw them away */
3899         priv_ctx->vs_output[i] = "TA";
3900         semantic_name = baseshader->output_signature[i].semantic_name;
3901         if(semantic_name == NULL)
3902         {
3903             continue;
3904         }
3905
3906         if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION)
3907                 && baseshader->output_signature[i].semantic_idx == 0)
3908         {
3909             priv_ctx->vs_output[i] = "TMP_OUT";
3910             continue;
3911         }
3912         else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE)
3913                 && baseshader->output_signature[i].semantic_idx == 0)
3914         {
3915             priv_ctx->vs_output[i] = "result.pointsize";
3916             continue;
3917         }
3918
3919         for(j = 0; j < MAX_REG_INPUT; j++)
3920         {
3921             if(sig[j].semantic_name == NULL)
3922             {
3923                 continue;
3924             }
3925
3926             if (strcmp(sig[j].semantic_name, semantic_name) == 0
3927                     && sig[j].semantic_idx == baseshader->output_signature[i].semantic_idx)
3928             {
3929                 priv_ctx->vs_output[i] = decl_idx_to_string[sig[j].register_idx];
3930
3931                 if(strcmp(priv_ctx->vs_output[i], "result.color.primary") == 0 ||
3932                    strcmp(priv_ctx->vs_output[i], "result.color.secondary") == 0)
3933                 {
3934                     compiled->need_color_unclamp = TRUE;
3935                 }
3936             }
3937         }
3938     }
3939 }
3940
3941 /* GL locking is done by the caller */
3942 static GLuint shader_arb_generate_vshader(IWineD3DVertexShaderImpl *This, struct wined3d_shader_buffer *buffer,
3943         const struct arb_vs_compile_args *args, struct arb_vs_compiled_shader *compiled)
3944 {
3945     const shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
3946     CONST DWORD *function = This->baseShader.function;
3947     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
3948     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
3949     const local_constant *lconst;
3950     GLuint ret;
3951     DWORD next_local, *lconst_map = local_const_mapping((IWineD3DBaseShaderImpl *) This);
3952     struct shader_arb_ctx_priv priv_ctx;
3953     unsigned int i;
3954     GLint errPos;
3955
3956     memset(&priv_ctx, 0, sizeof(priv_ctx));
3957     priv_ctx.cur_vs_args = args;
3958     list_init(&priv_ctx.control_frames);
3959     init_output_registers(This, args->ps_signature, &priv_ctx, compiled);
3960
3961     /*  Create the hw ARB shader */
3962     shader_addline(buffer, "!!ARBvp1.0\n");
3963
3964     /* Always enable the NV extension if available. Unlike fragment shaders, there is no
3965      * mesurable performance penalty, and we can always make use of it for clipplanes.
3966      */
3967     if (gl_info->supported[NV_VERTEX_PROGRAM3])
3968     {
3969         shader_addline(buffer, "OPTION NV_vertex_program3;\n");
3970         priv_ctx.target_version = NV3;
3971         shader_addline(buffer, "ADDRESS aL;\n");
3972     }
3973     else if (gl_info->supported[NV_VERTEX_PROGRAM2_OPTION])
3974     {
3975         shader_addline(buffer, "OPTION NV_vertex_program2;\n");
3976         priv_ctx.target_version = NV2;
3977         shader_addline(buffer, "ADDRESS aL;\n");
3978     } else {
3979         priv_ctx.target_version = ARB;
3980     }
3981
3982     shader_addline(buffer, "TEMP TMP_OUT;\n");
3983     if(need_helper_const(gl_info)) {
3984         shader_addline(buffer, "PARAM helper_const = { 2.0, -1.0, %d.0, 0.0 };\n", This->rel_offset);
3985     }
3986     if(need_mova_const((IWineD3DBaseShader *) This, gl_info)) {
3987         shader_addline(buffer, "PARAM mova_const = { 0.5, 0.0, 2.0, 1.0 };\n");
3988         shader_addline(buffer, "TEMP A0_SHADOW;\n");
3989     }
3990
3991     shader_addline(buffer, "TEMP TA;\n");
3992
3993     /* Base Declarations */
3994     next_local = shader_generate_arb_declarations((IWineD3DBaseShader *)This,
3995             reg_maps, buffer, gl_info, lconst_map, &priv_ctx.vs_clipplanes, &priv_ctx);
3996
3997     for(i = 0; i < MAX_CONST_I; i++)
3998     {
3999         compiled->int_consts[i] = WINED3D_CONST_NUM_UNUSED;
4000         if(reg_maps->integer_constants & (1 << i) && priv_ctx.target_version >= NV2)
4001         {
4002             const DWORD *control_values = find_loop_control_values((IWineD3DBaseShaderImpl *) This, i);
4003
4004             if(control_values)
4005             {
4006                 shader_addline(buffer, "PARAM I%u = {%u, %u, %u, -1};\n", i,
4007                                 control_values[0], control_values[1], control_values[2]);
4008             }
4009             else
4010             {
4011                 compiled->int_consts[i] = next_local;
4012                 compiled->num_int_consts++;
4013                 shader_addline(buffer, "PARAM I%u = program.local[%u];\n", i, next_local++);
4014             }
4015         }
4016     }
4017
4018     /* We need a constant to fixup the final position */
4019     shader_addline(buffer, "PARAM posFixup = program.local[%u];\n", next_local);
4020     compiled->pos_fixup = next_local++;
4021
4022     /* Initialize output parameters. GL_ARB_vertex_program does not require special initialization values
4023      * for output parameters. D3D in theory does not do that either, but some applications depend on a
4024      * proper initialization of the secondary color, and programs using the fixed function pipeline without
4025      * a replacement shader depend on the texcoord.w being set properly.
4026      *
4027      * GL_NV_vertex_program defines that all output values are initialized to {0.0, 0.0, 0.0, 1.0}. This
4028      * assertion is in effect even when using GL_ARB_vertex_program without any NV specific additions. So
4029      * skip this if NV_vertex_program is supported. Otherwise, initialize the secondary color. For the tex-
4030      * coords, we have a flag in the opengl caps. Many cards do not require the texcoord being set, and
4031      * this can eat a number of instructions, so skip it unless this cap is set as well
4032      */
4033     if (!gl_info->supported[NV_VERTEX_PROGRAM])
4034     {
4035         shader_addline(buffer, "MOV result.color.secondary, -helper_const.wwwy;\n");
4036
4037         if (gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W && !device->frag_pipe->ffp_proj_control)
4038         {
4039             int i;
4040             for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
4041                 if(This->baseShader.reg_maps.texcoord_mask[i] != 0 &&
4042                 This->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
4043                     shader_addline(buffer, "MOV result.texcoord[%u].w, -helper_const.y;\n", i);
4044                 }
4045             }
4046         }
4047     }
4048
4049     /* The shader starts with the main function */
4050     priv_ctx.in_main_func = TRUE;
4051     /* Base Shader Body */
4052     shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
4053
4054     if(!priv_ctx.footer_written) vshader_add_footer(This, buffer, args, &priv_ctx);
4055
4056     shader_addline(buffer, "END\n");
4057
4058     /* TODO: change to resource.glObjectHandle or something like that */
4059     GL_EXTCALL(glGenProgramsARB(1, &ret));
4060
4061     TRACE("Creating a hw vertex shader, prg=%d\n", ret);
4062     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, ret));
4063
4064     TRACE("Created hw vertex shader, prg=%d\n", ret);
4065     /* Create the program and check for errors */
4066     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
4067                buffer->bsize, buffer->buffer));
4068     checkGLcall("glProgramStringARB()");
4069
4070     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
4071     if (errPos != -1)
4072     {
4073         FIXME("HW VertexShader Error at position %d: %s\n\n",
4074               errPos, debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
4075         shader_arb_dump_program_source(buffer->buffer);
4076         ret = -1;
4077     }
4078     else
4079     {
4080         GLint native;
4081
4082         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
4083         checkGLcall("glGetProgramivARB()");
4084         if (!native) WARN("Program exceeds native resource limits.\n");
4085
4086         /* Load immediate constants */
4087         if(lconst_map) {
4088             LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
4089                 const float *value = (const float *)lconst->value;
4090                 GL_EXTCALL(glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, lconst_map[lconst->idx], value));
4091             }
4092         }
4093     }
4094     HeapFree(GetProcessHeap(), 0, lconst_map);
4095
4096     return ret;
4097 }
4098
4099 /* GL locking is done by the caller */
4100 static struct arb_ps_compiled_shader *find_arb_pshader(IWineD3DPixelShaderImpl *shader, const struct arb_ps_compile_args *args)
4101 {
4102     UINT i;
4103     DWORD new_size;
4104     struct arb_ps_compiled_shader *new_array;
4105     struct wined3d_shader_buffer buffer;
4106     struct arb_pshader_private *shader_data;
4107     GLuint ret;
4108
4109     if (!shader->baseShader.backend_data)
4110     {
4111         IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) shader->baseShader.device;
4112         const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4113         struct shader_arb_priv *priv = device->shader_priv;
4114
4115         shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4116         shader_data = shader->baseShader.backend_data;
4117         shader_data->clamp_consts = shader->baseShader.reg_maps.shader_version.major == 1;
4118
4119         if(shader->baseShader.reg_maps.shader_version.major < 3) shader_data->input_signature_idx = ~0;
4120         else shader_data->input_signature_idx = find_input_signature(priv, shader->baseShader.input_signature);
4121
4122         shader_data->has_signature_idx = TRUE;
4123         TRACE("Shader got assigned input signature index %u\n", shader_data->input_signature_idx);
4124
4125         if (!device->vs_clipping)
4126             shader_data->clipplane_emulation = shader_find_free_input_register(&shader->baseShader.reg_maps,
4127                     gl_info->limits.texture_stages - 1);
4128         else
4129             shader_data->clipplane_emulation = ~0U;
4130     }
4131     shader_data = shader->baseShader.backend_data;
4132
4133     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4134      * so a linear search is more performant than a hashmap or a binary search
4135      * (cache coherency etc)
4136      */
4137     for(i = 0; i < shader_data->num_gl_shaders; i++) {
4138         if(memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
4139             return &shader_data->gl_shaders[i];
4140         }
4141     }
4142
4143     TRACE("No matching GL shader found, compiling a new shader\n");
4144     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4145         if (shader_data->num_gl_shaders)
4146         {
4147             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4148             new_array = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, shader_data->gl_shaders,
4149                                     new_size * sizeof(*shader_data->gl_shaders));
4150         } else {
4151             new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
4152             new_size = 1;
4153         }
4154
4155         if(!new_array) {
4156             ERR("Out of memory\n");
4157             return 0;
4158         }
4159         shader_data->gl_shaders = new_array;
4160         shader_data->shader_array_size = new_size;
4161     }
4162
4163     shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4164
4165     pixelshader_update_samplers(&shader->baseShader.reg_maps,
4166             ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
4167
4168     if (!shader_buffer_init(&buffer))
4169     {
4170         ERR("Failed to initialize shader buffer.\n");
4171         return 0;
4172     }
4173
4174     ret = shader_arb_generate_pshader(shader, &buffer, args,
4175                                       &shader_data->gl_shaders[shader_data->num_gl_shaders]);
4176     shader_buffer_free(&buffer);
4177     shader_data->gl_shaders[shader_data->num_gl_shaders].prgId = ret;
4178
4179     return &shader_data->gl_shaders[shader_data->num_gl_shaders++];
4180 }
4181
4182 static inline BOOL vs_args_equal(const struct arb_vs_compile_args *stored, const struct arb_vs_compile_args *new,
4183                                  const DWORD use_map, BOOL skip_int) {
4184     if((stored->super.swizzle_map & use_map) != new->super.swizzle_map) return FALSE;
4185     if(stored->super.clip_enabled != new->super.clip_enabled) return FALSE;
4186     if(stored->super.fog_src != new->super.fog_src) return FALSE;
4187     if(stored->clip.boolclip_compare != new->clip.boolclip_compare) return FALSE;
4188     if(stored->ps_signature != new->ps_signature) return FALSE;
4189     if(stored->vertex.samplers_compare != new->vertex.samplers_compare) return FALSE;
4190     if(skip_int) return TRUE;
4191
4192     return memcmp(stored->loop_ctrl, new->loop_ctrl, sizeof(stored->loop_ctrl)) == 0;
4193 }
4194
4195 static struct arb_vs_compiled_shader *find_arb_vshader(IWineD3DVertexShaderImpl *shader, const struct arb_vs_compile_args *args)
4196 {
4197     UINT i;
4198     DWORD new_size;
4199     struct arb_vs_compiled_shader *new_array;
4200     DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
4201     struct wined3d_shader_buffer buffer;
4202     struct arb_vshader_private *shader_data;
4203     GLuint ret;
4204     const struct wined3d_gl_info *gl_info = &((IWineD3DDeviceImpl *)shader->baseShader.device)->adapter->gl_info;
4205
4206     if (!shader->baseShader.backend_data)
4207     {
4208         shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4209     }
4210     shader_data = shader->baseShader.backend_data;
4211
4212     /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4213      * so a linear search is more performant than a hashmap or a binary search
4214      * (cache coherency etc)
4215      */
4216     for(i = 0; i < shader_data->num_gl_shaders; i++) {
4217         if (vs_args_equal(&shader_data->gl_shaders[i].args, args,
4218                 use_map, gl_info->supported[NV_VERTEX_PROGRAM2_OPTION]))
4219         {
4220             return &shader_data->gl_shaders[i];
4221         }
4222     }
4223
4224     TRACE("No matching GL shader found, compiling a new shader\n");
4225
4226     if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4227         if (shader_data->num_gl_shaders)
4228         {
4229             new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4230             new_array = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, shader_data->gl_shaders,
4231                                     new_size * sizeof(*shader_data->gl_shaders));
4232         } else {
4233             new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
4234             new_size = 1;
4235         }
4236
4237         if(!new_array) {
4238             ERR("Out of memory\n");
4239             return 0;
4240         }
4241         shader_data->gl_shaders = new_array;
4242         shader_data->shader_array_size = new_size;
4243     }
4244
4245     shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4246
4247     if (!shader_buffer_init(&buffer))
4248     {
4249         ERR("Failed to initialize shader buffer.\n");
4250         return 0;
4251     }
4252
4253     ret = shader_arb_generate_vshader(shader, &buffer, args,
4254             &shader_data->gl_shaders[shader_data->num_gl_shaders]);
4255     shader_buffer_free(&buffer);
4256     shader_data->gl_shaders[shader_data->num_gl_shaders].prgId = ret;
4257
4258     return &shader_data->gl_shaders[shader_data->num_gl_shaders++];
4259 }
4260
4261 static inline void find_arb_ps_compile_args(IWineD3DPixelShaderImpl *shader, IWineD3DStateBlockImpl *stateblock,
4262         struct arb_ps_compile_args *args)
4263 {
4264     int i;
4265     WORD int_skip;
4266     const struct wined3d_gl_info *gl_info = &((IWineD3DDeviceImpl *)shader->baseShader.device)->adapter->gl_info;
4267     find_ps_compile_args(shader, stateblock, &args->super);
4268
4269     /* This forces all local boolean constants to 1 to make them stateblock independent */
4270     args->bools = shader->baseShader.reg_maps.local_bool_consts;
4271
4272     for(i = 0; i < MAX_CONST_B; i++)
4273     {
4274         if(stateblock->pixelShaderConstantB[i]) args->bools |= ( 1 << i);
4275     }
4276
4277     /* Only enable the clip plane emulation KIL if at least one clipplane is enabled. The KIL instruction
4278      * is quite expensive because it forces the driver to disable early Z discards. It is cheaper to
4279      * duplicate the shader than have a no-op KIL instruction in every shader
4280      */
4281     if((!((IWineD3DDeviceImpl *) shader->baseShader.device)->vs_clipping) && use_vs(stateblock) &&
4282        stateblock->renderState[WINED3DRS_CLIPPING] && stateblock->renderState[WINED3DRS_CLIPPLANEENABLE])
4283     {
4284         args->clip = 1;
4285     }
4286     else
4287     {
4288         args->clip = 0;
4289     }
4290
4291     /* Skip if unused or local, or supported natively */
4292     int_skip = ~shader->baseShader.reg_maps.integer_constants | shader->baseShader.reg_maps.local_int_consts;
4293     if (int_skip == 0xffff || gl_info->supported[NV_FRAGMENT_PROGRAM_OPTION])
4294     {
4295         memset(&args->loop_ctrl, 0, sizeof(args->loop_ctrl));
4296         return;
4297     }
4298
4299     for(i = 0; i < MAX_CONST_I; i++)
4300     {
4301         if(int_skip & (1 << i))
4302         {
4303             args->loop_ctrl[i][0] = 0;
4304             args->loop_ctrl[i][1] = 0;
4305             args->loop_ctrl[i][2] = 0;
4306         }
4307         else
4308         {
4309             args->loop_ctrl[i][0] = stateblock->pixelShaderConstantI[i * 4];
4310             args->loop_ctrl[i][1] = stateblock->pixelShaderConstantI[i * 4 + 1];
4311             args->loop_ctrl[i][2] = stateblock->pixelShaderConstantI[i * 4 + 2];
4312         }
4313     }
4314 }
4315
4316 static inline void find_arb_vs_compile_args(IWineD3DVertexShaderImpl *shader, IWineD3DStateBlockImpl *stateblock,
4317         struct arb_vs_compile_args *args)
4318 {
4319     int i;
4320     WORD int_skip;
4321     IWineD3DDeviceImpl *dev = (IWineD3DDeviceImpl *)shader->baseShader.device;
4322     const struct wined3d_gl_info *gl_info = &dev->adapter->gl_info;
4323     find_vs_compile_args(shader, stateblock, &args->super);
4324
4325     args->clip.boolclip_compare = 0;
4326     if(use_ps(stateblock))
4327     {
4328         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) stateblock->pixelShader;
4329         struct arb_pshader_private *shader_priv = ps->baseShader.backend_data;
4330         args->ps_signature = shader_priv->input_signature_idx;
4331
4332         args->clip.boolclip.clip_texcoord = shader_priv->clipplane_emulation + 1;
4333     }
4334     else
4335     {
4336         args->ps_signature = ~0;
4337         if(!dev->vs_clipping)
4338         {
4339             args->clip.boolclip.clip_texcoord = ffp_clip_emul(stateblock) ? gl_info->limits.texture_stages : 0;
4340         }
4341         /* Otherwise: Setting boolclip_compare set clip_texcoord to 0 */
4342     }
4343
4344     if(args->clip.boolclip.clip_texcoord)
4345     {
4346         if(stateblock->renderState[WINED3DRS_CLIPPING])
4347         {
4348             args->clip.boolclip.clipplane_mask = stateblock->renderState[WINED3DRS_CLIPPLANEENABLE];
4349         }
4350         /* clipplane_mask was set to 0 by setting boolclip_compare to 0 */
4351     }
4352
4353     /* This forces all local boolean constants to 1 to make them stateblock independent */
4354     args->clip.boolclip.bools = shader->baseShader.reg_maps.local_bool_consts;
4355     /* TODO: Figure out if it would be better to store bool constants as bitmasks in the stateblock */
4356     for(i = 0; i < MAX_CONST_B; i++)
4357     {
4358         if(stateblock->vertexShaderConstantB[i]) args->clip.boolclip.bools |= ( 1 << i);
4359     }
4360
4361     args->vertex.samplers[0] = dev->texUnitMap[MAX_FRAGMENT_SAMPLERS + 0];
4362     args->vertex.samplers[1] = dev->texUnitMap[MAX_FRAGMENT_SAMPLERS + 1];
4363     args->vertex.samplers[2] = dev->texUnitMap[MAX_FRAGMENT_SAMPLERS + 2];
4364     args->vertex.samplers[3] = 0;
4365
4366     /* Skip if unused or local */
4367     int_skip = ~shader->baseShader.reg_maps.integer_constants | shader->baseShader.reg_maps.local_int_consts;
4368     /* This is about flow control, not clipping. */
4369     if (int_skip == 0xffff || gl_info->supported[NV_VERTEX_PROGRAM2_OPTION])
4370     {
4371         memset(&args->loop_ctrl, 0, sizeof(args->loop_ctrl));
4372         return;
4373     }
4374
4375     for(i = 0; i < MAX_CONST_I; i++)
4376     {
4377         if(int_skip & (1 << i))
4378         {
4379             args->loop_ctrl[i][0] = 0;
4380             args->loop_ctrl[i][1] = 0;
4381             args->loop_ctrl[i][2] = 0;
4382         }
4383         else
4384         {
4385             args->loop_ctrl[i][0] = stateblock->vertexShaderConstantI[i * 4];
4386             args->loop_ctrl[i][1] = stateblock->vertexShaderConstantI[i * 4 + 1];
4387             args->loop_ctrl[i][2] = stateblock->vertexShaderConstantI[i * 4 + 2];
4388         }
4389     }
4390 }
4391
4392 /* GL locking is done by the caller */
4393 static void shader_arb_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4394 {
4395     IWineD3DDeviceImpl *This = context->swapchain->device;
4396     struct shader_arb_priv *priv = This->shader_priv;
4397     const struct wined3d_gl_info *gl_info = context->gl_info;
4398     int i;
4399
4400     /* Deal with pixel shaders first so the vertex shader arg function has the input signature ready */
4401     if (usePS) {
4402         struct arb_ps_compile_args compile_args;
4403         struct arb_ps_compiled_shader *compiled;
4404         IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) This->stateBlock->pixelShader;
4405
4406         TRACE("Using pixel shader %p\n", This->stateBlock->pixelShader);
4407         find_arb_ps_compile_args(ps, This->stateBlock, &compile_args);
4408         compiled = find_arb_pshader(ps, &compile_args);
4409         priv->current_fprogram_id = compiled->prgId;
4410         priv->compiled_fprog = compiled;
4411
4412         /* Bind the fragment program */
4413         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
4414         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id);");
4415
4416         if(!priv->use_arbfp_fixed_func) {
4417             /* Enable OpenGL fragment programs */
4418             glEnable(GL_FRAGMENT_PROGRAM_ARB);
4419             checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB);");
4420         }
4421         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
4422
4423         /* Pixel Shader 1.x constants are clamped to [-1;1], Pixel Shader 2.0 constants are not. If switching between
4424          * a 1.x and newer shader, reload the first 8 constants
4425          */
4426         if(priv->last_ps_const_clamped != ((struct arb_pshader_private *)ps->baseShader.backend_data)->clamp_consts)
4427         {
4428             priv->last_ps_const_clamped = ((struct arb_pshader_private *)ps->baseShader.backend_data)->clamp_consts;
4429             This->highest_dirty_ps_const = max(This->highest_dirty_ps_const, 8);
4430             for(i = 0; i < 8; i++)
4431             {
4432                 context->pshader_const_dirty[i] = 1;
4433             }
4434             /* Also takes care of loading local constants */
4435             shader_arb_load_constants(context, TRUE, FALSE);
4436         }
4437         else
4438         {
4439             shader_arb_ps_local_constants(This);
4440         }
4441
4442         /* Force constant reloading for the NP2 fixup (see comment in shader_glsl_select for more info) */
4443         if (compiled->np2fixup_info.super.active)
4444             shader_arb_load_np2fixup_constants((IWineD3DDevice *)This, usePS, useVS);
4445     }
4446     else if (gl_info->supported[ARB_FRAGMENT_PROGRAM] && !priv->use_arbfp_fixed_func)
4447     {
4448         /* Disable only if we're not using arbfp fixed function fragment processing. If this is used,
4449         * keep GL_FRAGMENT_PROGRAM_ARB enabled, and the fixed function pipeline will bind the fixed function
4450         * replacement shader
4451         */
4452         glDisable(GL_FRAGMENT_PROGRAM_ARB);
4453         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
4454         priv->current_fprogram_id = 0;
4455     }
4456
4457     if (useVS) {
4458         struct arb_vs_compile_args compile_args;
4459         struct arb_vs_compiled_shader *compiled;
4460         IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) This->stateBlock->vertexShader;
4461
4462         TRACE("Using vertex shader %p\n", This->stateBlock->vertexShader);
4463         find_arb_vs_compile_args(vs, This->stateBlock, &compile_args);
4464         compiled = find_arb_vshader(vs, &compile_args);
4465         priv->current_vprogram_id = compiled->prgId;
4466         priv->compiled_vprog = compiled;
4467
4468         /* Bind the vertex program */
4469         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
4470         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id);");
4471
4472         /* Enable OpenGL vertex programs */
4473         glEnable(GL_VERTEX_PROGRAM_ARB);
4474         checkGLcall("glEnable(GL_VERTEX_PROGRAM_ARB);");
4475         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
4476         shader_arb_vs_local_constants(This);
4477
4478         if(priv->last_vs_color_unclamp != compiled->need_color_unclamp) {
4479             priv->last_vs_color_unclamp = compiled->need_color_unclamp;
4480
4481             if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4482             {
4483                 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, !compiled->need_color_unclamp));
4484                 checkGLcall("glClampColorARB");
4485             } else {
4486                 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4487             }
4488         }
4489     }
4490     else if (gl_info->supported[ARB_VERTEX_PROGRAM])
4491     {
4492         priv->current_vprogram_id = 0;
4493         glDisable(GL_VERTEX_PROGRAM_ARB);
4494         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
4495     }
4496 }
4497
4498 /* GL locking is done by the caller */
4499 static void shader_arb_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type, const SIZE *ds_mask_size)
4500 {
4501     const float mask[] = {0.0f, 0.0f, (float)ds_mask_size->cx, (float)ds_mask_size->cy};
4502     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4503     BOOL masked = ds_mask_size->cx && ds_mask_size->cy;
4504     struct shader_arb_priv *priv = This->shader_priv;
4505     const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4506     GLuint *blt_fprogram;
4507
4508     if (!priv->depth_blt_vprogram_id) priv->depth_blt_vprogram_id = create_arb_blt_vertex_program(gl_info);
4509     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->depth_blt_vprogram_id));
4510     glEnable(GL_VERTEX_PROGRAM_ARB);
4511
4512     blt_fprogram = masked ? &priv->depth_blt_fprogram_id_masked[tex_type] : &priv->depth_blt_fprogram_id_full[tex_type];
4513     if (!*blt_fprogram) *blt_fprogram = create_arb_blt_fragment_program(gl_info, tex_type, masked);
4514     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, *blt_fprogram));
4515     if (masked) GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, 0, mask));
4516     glEnable(GL_FRAGMENT_PROGRAM_ARB);
4517 }
4518
4519 /* GL locking is done by the caller */
4520 static void shader_arb_deselect_depth_blt(IWineD3DDevice *iface) {
4521     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4522     struct shader_arb_priv *priv = This->shader_priv;
4523     const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4524
4525     if (priv->current_vprogram_id) {
4526         GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, priv->current_vprogram_id));
4527         checkGLcall("glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vertexShader->prgId);");
4528
4529         TRACE("(%p) : Bound vertex program %u and enabled GL_VERTEX_PROGRAM_ARB\n", This, priv->current_vprogram_id);
4530     } else {
4531         glDisable(GL_VERTEX_PROGRAM_ARB);
4532         checkGLcall("glDisable(GL_VERTEX_PROGRAM_ARB)");
4533     }
4534
4535     if (priv->current_fprogram_id) {
4536         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, priv->current_fprogram_id));
4537         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, pixelShader->prgId);");
4538
4539         TRACE("(%p) : Bound fragment program %u and enabled GL_FRAGMENT_PROGRAM_ARB\n", This, priv->current_fprogram_id);
4540     } else if(!priv->use_arbfp_fixed_func) {
4541         glDisable(GL_FRAGMENT_PROGRAM_ARB);
4542         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
4543     }
4544 }
4545
4546 static void shader_arb_destroy(IWineD3DBaseShader *iface) {
4547     IWineD3DBaseShaderImpl *baseShader = (IWineD3DBaseShaderImpl *) iface;
4548     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)baseShader->baseShader.device;
4549     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
4550
4551     if (shader_is_pshader_version(baseShader->baseShader.reg_maps.shader_version.type))
4552     {
4553         struct arb_pshader_private *shader_data = baseShader->baseShader.backend_data;
4554         UINT i;
4555
4556         if(!shader_data) return; /* This can happen if a shader was never compiled */
4557
4558         if (shader_data->num_gl_shaders)
4559         {
4560             struct wined3d_context *context = context_acquire(device, NULL);
4561
4562             ENTER_GL();
4563             for (i = 0; i < shader_data->num_gl_shaders; ++i)
4564             {
4565                 GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId));
4566                 checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId))");
4567             }
4568             LEAVE_GL();
4569
4570             context_release(context);
4571         }
4572
4573         HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4574         HeapFree(GetProcessHeap(), 0, shader_data);
4575         baseShader->baseShader.backend_data = NULL;
4576     }
4577     else
4578     {
4579         struct arb_vshader_private *shader_data = baseShader->baseShader.backend_data;
4580         UINT i;
4581
4582         if(!shader_data) return; /* This can happen if a shader was never compiled */
4583
4584         if (shader_data->num_gl_shaders)
4585         {
4586             struct wined3d_context *context = context_acquire(device, NULL);
4587
4588             ENTER_GL();
4589             for (i = 0; i < shader_data->num_gl_shaders; ++i)
4590             {
4591                 GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId));
4592                 checkGLcall("GL_EXTCALL(glDeleteProgramsARB(1, &shader_data->gl_shaders[i].prgId))");
4593             }
4594             LEAVE_GL();
4595
4596             context_release(context);
4597         }
4598
4599         HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
4600         HeapFree(GetProcessHeap(), 0, shader_data);
4601         baseShader->baseShader.backend_data = NULL;
4602     }
4603 }
4604
4605 static int sig_tree_compare(const void *key, const struct wine_rb_entry *entry)
4606 {
4607     struct ps_signature *e = WINE_RB_ENTRY_VALUE(entry, struct ps_signature, entry);
4608     return compare_sig(key, e->sig);
4609 }
4610
4611 static const struct wine_rb_functions sig_tree_functions =
4612 {
4613     wined3d_rb_alloc,
4614     wined3d_rb_realloc,
4615     wined3d_rb_free,
4616     sig_tree_compare
4617 };
4618
4619 static HRESULT shader_arb_alloc(IWineD3DDevice *iface) {
4620     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4621     struct shader_arb_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*priv));
4622     if(wine_rb_init(&priv->signature_tree, &sig_tree_functions) == -1)
4623     {
4624         ERR("RB tree init failed\n");
4625         HeapFree(GetProcessHeap(), 0, priv);
4626         return E_OUTOFMEMORY;
4627     }
4628     This->shader_priv = priv;
4629     return WINED3D_OK;
4630 }
4631
4632 static void release_signature(struct wine_rb_entry *entry, void *context)
4633 {
4634     struct ps_signature *sig = WINE_RB_ENTRY_VALUE(entry, struct ps_signature, entry);
4635     int i;
4636     for(i = 0; i < MAX_REG_INPUT; i++)
4637     {
4638         HeapFree(GetProcessHeap(), 0, (char *) sig->sig[i].semantic_name);
4639     }
4640     HeapFree(GetProcessHeap(), 0, sig->sig);
4641     HeapFree(GetProcessHeap(), 0, sig);
4642 }
4643
4644 /* Context activation is done by the caller. */
4645 static void shader_arb_free(IWineD3DDevice *iface) {
4646     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
4647     const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
4648     struct shader_arb_priv *priv = This->shader_priv;
4649     int i;
4650
4651     ENTER_GL();
4652     if(priv->depth_blt_vprogram_id) {
4653         GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_vprogram_id));
4654     }
4655     for (i = 0; i < tex_type_count; ++i)
4656     {
4657         if (priv->depth_blt_fprogram_id_full[i])
4658         {
4659             GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_fprogram_id_full[i]));
4660         }
4661         if (priv->depth_blt_fprogram_id_masked[i])
4662         {
4663             GL_EXTCALL(glDeleteProgramsARB(1, &priv->depth_blt_fprogram_id_masked[i]));
4664         }
4665     }
4666     LEAVE_GL();
4667
4668     wine_rb_destroy(&priv->signature_tree, release_signature, NULL);
4669     HeapFree(GetProcessHeap(), 0, This->shader_priv);
4670 }
4671
4672 static BOOL shader_arb_dirty_const(IWineD3DDevice *iface) {
4673     return TRUE;
4674 }
4675
4676 static void shader_arb_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *pCaps)
4677 {
4678     if (gl_info->supported[ARB_VERTEX_PROGRAM])
4679     {
4680         DWORD vs_consts;
4681
4682         /* 96 is the minimum allowed value of MAX_PROGRAM_ENV_PARAMETERS_ARB
4683          * for vertex programs. If the native limit is less than that it's
4684          * not very useful, and e.g. Mesa swrast returns 0, probably to
4685          * indicate it's a software implementation. */
4686         if (gl_info->limits.arb_vs_native_constants < 96)
4687             vs_consts = gl_info->limits.arb_vs_float_constants;
4688         else
4689             vs_consts = min(gl_info->limits.arb_vs_float_constants, gl_info->limits.arb_vs_native_constants);
4690
4691         if (gl_info->supported[NV_VERTEX_PROGRAM3])
4692         {
4693             pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
4694             TRACE_(d3d_caps)("Hardware vertex shader version 3.0 enabled (NV_VERTEX_PROGRAM3)\n");
4695         }
4696         else if (vs_consts >= 256)
4697         {
4698             /* Shader Model 2.0 requires at least 256 vertex shader constants */
4699             pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
4700             TRACE_(d3d_caps)("Hardware vertex shader version 2.0 enabled (ARB_PROGRAM)\n");
4701         }
4702         else
4703         {
4704             pCaps->VertexShaderVersion = WINED3DVS_VERSION(1,1);
4705             TRACE_(d3d_caps)("Hardware vertex shader version 1.1 enabled (ARB_PROGRAM)\n");
4706         }
4707         pCaps->MaxVertexShaderConst = vs_consts;
4708     }
4709     else
4710     {
4711         pCaps->VertexShaderVersion = 0;
4712         pCaps->MaxVertexShaderConst = 0;
4713     }
4714
4715     if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
4716     {
4717         DWORD ps_consts;
4718
4719         /* Similar as above for vertex programs, but the minimum for fragment
4720          * programs is 24. */
4721         if (gl_info->limits.arb_ps_native_constants < 24)
4722             ps_consts = gl_info->limits.arb_ps_float_constants;
4723         else
4724             ps_consts = min(gl_info->limits.arb_ps_float_constants, gl_info->limits.arb_ps_native_constants);
4725
4726         if (gl_info->supported[NV_FRAGMENT_PROGRAM2])
4727         {
4728             pCaps->PixelShaderVersion    = WINED3DPS_VERSION(3,0);
4729             TRACE_(d3d_caps)("Hardware pixel shader version 3.0 enabled (NV_FRAGMENT_PROGRAM2)\n");
4730         }
4731         else if (ps_consts >= 32)
4732         {
4733             /* Shader Model 2.0 requires at least 32 pixel shader constants */
4734             pCaps->PixelShaderVersion    = WINED3DPS_VERSION(2,0);
4735             TRACE_(d3d_caps)("Hardware pixel shader version 2.0 enabled (ARB_PROGRAM)\n");
4736         }
4737         else
4738         {
4739             pCaps->PixelShaderVersion    = WINED3DPS_VERSION(1,4);
4740             TRACE_(d3d_caps)("Hardware pixel shader version 1.4 enabled (ARB_PROGRAM)\n");
4741         }
4742         pCaps->PixelShader1xMaxValue = 8.0f;
4743         pCaps->MaxPixelShaderConst = ps_consts;
4744     }
4745     else
4746     {
4747         pCaps->PixelShaderVersion = 0;
4748         pCaps->PixelShader1xMaxValue = 0.0f;
4749         pCaps->MaxPixelShaderConst = 0;
4750     }
4751
4752     pCaps->VSClipping = use_nv_clip(gl_info);
4753 }
4754
4755 static BOOL shader_arb_color_fixup_supported(struct color_fixup_desc fixup)
4756 {
4757     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
4758     {
4759         TRACE("Checking support for color_fixup:\n");
4760         dump_color_fixup_desc(fixup);
4761     }
4762
4763     /* We support everything except complex conversions. */
4764     if (!is_complex_fixup(fixup))
4765     {
4766         TRACE("[OK]\n");
4767         return TRUE;
4768     }
4769
4770     TRACE("[FAILED]\n");
4771     return FALSE;
4772 }
4773
4774 static void shader_arb_add_instruction_modifiers(const struct wined3d_shader_instruction *ins) {
4775     DWORD shift;
4776     char write_mask[20], regstr[50];
4777     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
4778     BOOL is_color = FALSE;
4779     const struct wined3d_shader_dst_param *dst;
4780
4781     if (!ins->dst_count) return;
4782
4783     dst = &ins->dst[0];
4784     shift = dst->shift;
4785     if(shift == 0) return; /* Saturate alone is handled by the instructions */
4786
4787     shader_arb_get_write_mask(ins, dst, write_mask);
4788     shader_arb_get_register_name(ins, &dst->reg, regstr, &is_color);
4789
4790     /* Generate a line that does the output modifier computation
4791      * FIXME: _SAT vs shift? _SAT alone is already handled in the instructions, if this
4792      * maps problems in e.g. _d4_sat modify shader_arb_get_modifier
4793      */
4794     shader_addline(buffer, "MUL%s %s%s, %s, %s;\n", shader_arb_get_modifier(ins),
4795                    regstr, write_mask, regstr, shift_tab[shift]);
4796 }
4797
4798 static const SHADER_HANDLER shader_arb_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
4799 {
4800     /* WINED3DSIH_ABS           */ shader_hw_map2gl,
4801     /* WINED3DSIH_ADD           */ shader_hw_map2gl,
4802     /* WINED3DSIH_BEM           */ pshader_hw_bem,
4803     /* WINED3DSIH_BREAK         */ shader_hw_break,
4804     /* WINED3DSIH_BREAKC        */ shader_hw_breakc,
4805     /* WINED3DSIH_BREAKP        */ NULL,
4806     /* WINED3DSIH_CALL          */ shader_hw_call,
4807     /* WINED3DSIH_CALLNZ        */ NULL,
4808     /* WINED3DSIH_CMP           */ pshader_hw_cmp,
4809     /* WINED3DSIH_CND           */ pshader_hw_cnd,
4810     /* WINED3DSIH_CRS           */ shader_hw_map2gl,
4811     /* WINED3DSIH_CUT           */ NULL,
4812     /* WINED3DSIH_DCL           */ NULL,
4813     /* WINED3DSIH_DEF           */ NULL,
4814     /* WINED3DSIH_DEFB          */ NULL,
4815     /* WINED3DSIH_DEFI          */ NULL,
4816     /* WINED3DSIH_DP2ADD        */ pshader_hw_dp2add,
4817     /* WINED3DSIH_DP3           */ shader_hw_map2gl,
4818     /* WINED3DSIH_DP4           */ shader_hw_map2gl,
4819     /* WINED3DSIH_DST           */ shader_hw_map2gl,
4820     /* WINED3DSIH_DSX           */ shader_hw_map2gl,
4821     /* WINED3DSIH_DSY           */ shader_hw_dsy,
4822     /* WINED3DSIH_ELSE          */ shader_hw_else,
4823     /* WINED3DSIH_EMIT          */ NULL,
4824     /* WINED3DSIH_ENDIF         */ shader_hw_endif,
4825     /* WINED3DSIH_ENDLOOP       */ shader_hw_endloop,
4826     /* WINED3DSIH_ENDREP        */ shader_hw_endrep,
4827     /* WINED3DSIH_EXP           */ shader_hw_scalar_op,
4828     /* WINED3DSIH_EXPP          */ shader_hw_scalar_op,
4829     /* WINED3DSIH_FRC           */ shader_hw_map2gl,
4830     /* WINED3DSIH_IADD          */ NULL,
4831     /* WINED3DSIH_IF            */ NULL /* Hardcoded into the shader */,
4832     /* WINED3DSIH_IFC           */ shader_hw_ifc,
4833     /* WINED3DSIH_IGE           */ NULL,
4834     /* WINED3DSIH_LABEL         */ shader_hw_label,
4835     /* WINED3DSIH_LIT           */ shader_hw_map2gl,
4836     /* WINED3DSIH_LOG           */ shader_hw_log_pow,
4837     /* WINED3DSIH_LOGP          */ shader_hw_log_pow,
4838     /* WINED3DSIH_LOOP          */ shader_hw_loop,
4839     /* WINED3DSIH_LRP           */ shader_hw_lrp,
4840     /* WINED3DSIH_LT            */ NULL,
4841     /* WINED3DSIH_M3x2          */ shader_hw_mnxn,
4842     /* WINED3DSIH_M3x3          */ shader_hw_mnxn,
4843     /* WINED3DSIH_M3x4          */ shader_hw_mnxn,
4844     /* WINED3DSIH_M4x3          */ shader_hw_mnxn,
4845     /* WINED3DSIH_M4x4          */ shader_hw_mnxn,
4846     /* WINED3DSIH_MAD           */ shader_hw_map2gl,
4847     /* WINED3DSIH_MAX           */ shader_hw_map2gl,
4848     /* WINED3DSIH_MIN           */ shader_hw_map2gl,
4849     /* WINED3DSIH_MOV           */ shader_hw_mov,
4850     /* WINED3DSIH_MOVA          */ shader_hw_mov,
4851     /* WINED3DSIH_MUL           */ shader_hw_map2gl,
4852     /* WINED3DSIH_NOP           */ shader_hw_nop,
4853     /* WINED3DSIH_NRM           */ shader_hw_nrm,
4854     /* WINED3DSIH_PHASE         */ NULL,
4855     /* WINED3DSIH_POW           */ shader_hw_log_pow,
4856     /* WINED3DSIH_RCP           */ shader_hw_scalar_op,
4857     /* WINED3DSIH_REP           */ shader_hw_rep,
4858     /* WINED3DSIH_RET           */ shader_hw_ret,
4859     /* WINED3DSIH_RSQ           */ shader_hw_scalar_op,
4860     /* WINED3DSIH_SETP          */ NULL,
4861     /* WINED3DSIH_SGE           */ shader_hw_map2gl,
4862     /* WINED3DSIH_SGN           */ shader_hw_sgn,
4863     /* WINED3DSIH_SINCOS        */ shader_hw_sincos,
4864     /* WINED3DSIH_SLT           */ shader_hw_map2gl,
4865     /* WINED3DSIH_SUB           */ shader_hw_map2gl,
4866     /* WINED3DSIH_TEX           */ pshader_hw_tex,
4867     /* WINED3DSIH_TEXBEM        */ pshader_hw_texbem,
4868     /* WINED3DSIH_TEXBEML       */ pshader_hw_texbem,
4869     /* WINED3DSIH_TEXCOORD      */ pshader_hw_texcoord,
4870     /* WINED3DSIH_TEXDEPTH      */ pshader_hw_texdepth,
4871     /* WINED3DSIH_TEXDP3        */ pshader_hw_texdp3,
4872     /* WINED3DSIH_TEXDP3TEX     */ pshader_hw_texdp3tex,
4873     /* WINED3DSIH_TEXKILL       */ pshader_hw_texkill,
4874     /* WINED3DSIH_TEXLDD        */ shader_hw_texldd,
4875     /* WINED3DSIH_TEXLDL        */ shader_hw_texldl,
4876     /* WINED3DSIH_TEXM3x2DEPTH  */ pshader_hw_texm3x2depth,
4877     /* WINED3DSIH_TEXM3x2PAD    */ pshader_hw_texm3x2pad,
4878     /* WINED3DSIH_TEXM3x2TEX    */ pshader_hw_texm3x2tex,
4879     /* WINED3DSIH_TEXM3x3       */ pshader_hw_texm3x3,
4880     /* WINED3DSIH_TEXM3x3DIFF   */ NULL,
4881     /* WINED3DSIH_TEXM3x3PAD    */ pshader_hw_texm3x3pad,
4882     /* WINED3DSIH_TEXM3x3SPEC   */ pshader_hw_texm3x3spec,
4883     /* WINED3DSIH_TEXM3x3TEX    */ pshader_hw_texm3x3tex,
4884     /* WINED3DSIH_TEXM3x3VSPEC  */ pshader_hw_texm3x3vspec,
4885     /* WINED3DSIH_TEXREG2AR     */ pshader_hw_texreg2ar,
4886     /* WINED3DSIH_TEXREG2GB     */ pshader_hw_texreg2gb,
4887     /* WINED3DSIH_TEXREG2RGB    */ pshader_hw_texreg2rgb,
4888 };
4889
4890 static inline BOOL get_bool_const(const struct wined3d_shader_instruction *ins, IWineD3DBaseShaderImpl *This, DWORD idx)
4891 {
4892     BOOL vshader = shader_is_vshader_version(This->baseShader.reg_maps.shader_version.type);
4893     WORD bools = 0;
4894     WORD flag = (1 << idx);
4895     const local_constant *constant;
4896     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
4897
4898     if(This->baseShader.reg_maps.local_bool_consts & flag)
4899     {
4900         /* What good is a if(bool) with a hardcoded local constant? I don't know, but handle it */
4901         LIST_FOR_EACH_ENTRY(constant, &This->baseShader.constantsB, local_constant, entry)
4902         {
4903             if (constant->idx == idx)
4904             {
4905                 return constant->value[0];
4906             }
4907         }
4908         ERR("Local constant not found\n");
4909         return FALSE;
4910     }
4911     else
4912     {
4913         if(vshader) bools = priv->cur_vs_args->clip.boolclip.bools;
4914         else bools = priv->cur_ps_args->bools;
4915         return bools & flag;
4916     }
4917 }
4918
4919 static void get_loop_control_const(const struct wined3d_shader_instruction *ins,
4920         IWineD3DBaseShaderImpl *This, UINT idx, struct wined3d_shader_loop_control *loop_control)
4921 {
4922     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
4923
4924     /* Integer constants can either be a local constant, or they can be stored in the shader
4925      * type specific compile args. */
4926     if (This->baseShader.reg_maps.local_int_consts & (1 << idx))
4927     {
4928         const local_constant *constant;
4929
4930         LIST_FOR_EACH_ENTRY(constant, &This->baseShader.constantsI, local_constant, entry)
4931         {
4932             if (constant->idx == idx)
4933             {
4934                 loop_control->count = constant->value[0];
4935                 loop_control->start = constant->value[1];
4936                 /* Step is signed. */
4937                 loop_control->step = (int)constant->value[2];
4938                 return;
4939             }
4940         }
4941         /* If this happens the flag was set incorrectly */
4942         ERR("Local constant not found\n");
4943         loop_control->count = 0;
4944         loop_control->start = 0;
4945         loop_control->step = 0;
4946         return;
4947     }
4948
4949     switch (This->baseShader.reg_maps.shader_version.type)
4950     {
4951         case WINED3D_SHADER_TYPE_VERTEX:
4952             /* Count and aL start value are unsigned */
4953             loop_control->count = priv->cur_vs_args->loop_ctrl[idx][0];
4954             loop_control->start = priv->cur_vs_args->loop_ctrl[idx][1];
4955             /* Step is signed. */
4956             loop_control->step = ((char)priv->cur_vs_args->loop_ctrl[idx][2]);
4957             break;
4958
4959         case WINED3D_SHADER_TYPE_PIXEL:
4960             loop_control->count = priv->cur_ps_args->loop_ctrl[idx][0];
4961             loop_control->start = priv->cur_ps_args->loop_ctrl[idx][1];
4962             loop_control->step = ((char)priv->cur_ps_args->loop_ctrl[idx][2]);
4963             break;
4964
4965         default:
4966             FIXME("Unhandled shader type %#x.\n", This->baseShader.reg_maps.shader_version.type);
4967             break;
4968     }
4969 }
4970
4971 static void record_instruction(struct list *list, const struct wined3d_shader_instruction *ins)
4972 {
4973     unsigned int i;
4974     struct wined3d_shader_dst_param *dst_param = NULL;
4975     struct wined3d_shader_src_param *src_param = NULL, *rel_addr = NULL;
4976     struct recorded_instruction *rec = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rec));
4977     if(!rec)
4978     {
4979         ERR("Out of memory\n");
4980         return;
4981     }
4982
4983     rec->ins = *ins;
4984     dst_param = HeapAlloc(GetProcessHeap(), 0, sizeof(*dst_param));
4985     if(!dst_param) goto free;
4986     *dst_param = *ins->dst;
4987     if(ins->dst->reg.rel_addr)
4988     {
4989         rel_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(*dst_param->reg.rel_addr));
4990         if(!rel_addr) goto free;
4991         *rel_addr = *ins->dst->reg.rel_addr;
4992         dst_param->reg.rel_addr = rel_addr;
4993     }
4994     rec->ins.dst = dst_param;
4995
4996     src_param = HeapAlloc(GetProcessHeap(), 0, sizeof(*src_param) * ins->src_count);
4997     if(!src_param) goto free;
4998     for(i = 0; i < ins->src_count; i++)
4999     {
5000         src_param[i] = ins->src[i];
5001         if(ins->src[i].reg.rel_addr)
5002         {
5003             rel_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(*rel_addr));
5004             if(!rel_addr) goto free;
5005             *rel_addr = *ins->src[i].reg.rel_addr;
5006             src_param[i].reg.rel_addr = rel_addr;
5007         }
5008     }
5009     rec->ins.src = src_param;
5010     list_add_tail(list, &rec->entry);
5011     return;
5012
5013 free:
5014     ERR("Out of memory\n");
5015     if(dst_param)
5016     {
5017         HeapFree(GetProcessHeap(), 0, (void *) dst_param->reg.rel_addr);
5018         HeapFree(GetProcessHeap(), 0, dst_param);
5019     }
5020     if(src_param)
5021     {
5022         for(i = 0; i < ins->src_count; i++)
5023         {
5024             HeapFree(GetProcessHeap(), 0, (void *) src_param[i].reg.rel_addr);
5025         }
5026         HeapFree(GetProcessHeap(), 0, src_param);
5027     }
5028     HeapFree(GetProcessHeap(), 0, rec);
5029 }
5030
5031 static void free_recorded_instruction(struct list *list)
5032 {
5033     struct recorded_instruction *rec_ins, *entry2;
5034     unsigned int i;
5035
5036     LIST_FOR_EACH_ENTRY_SAFE(rec_ins, entry2, list, struct recorded_instruction, entry)
5037     {
5038         list_remove(&rec_ins->entry);
5039         if(rec_ins->ins.dst)
5040         {
5041             HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.dst->reg.rel_addr);
5042             HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.dst);
5043         }
5044         if(rec_ins->ins.src)
5045         {
5046             for(i = 0; i < rec_ins->ins.src_count; i++)
5047             {
5048                 HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.src[i].reg.rel_addr);
5049             }
5050             HeapFree(GetProcessHeap(), 0, (void *) rec_ins->ins.src);
5051         }
5052         HeapFree(GetProcessHeap(), 0, rec_ins);
5053     }
5054 }
5055
5056 static void shader_arb_handle_instruction(const struct wined3d_shader_instruction *ins) {
5057     SHADER_HANDLER hw_fct;
5058     struct shader_arb_ctx_priv *priv = ins->ctx->backend_data;
5059     IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
5060     struct control_frame *control_frame;
5061     struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
5062     BOOL bool_const;
5063
5064     if(ins->handler_idx == WINED3DSIH_LOOP || ins->handler_idx == WINED3DSIH_REP)
5065     {
5066         control_frame = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*control_frame));
5067         list_add_head(&priv->control_frames, &control_frame->entry);
5068
5069         if(ins->handler_idx == WINED3DSIH_LOOP) control_frame->type = LOOP;
5070         if(ins->handler_idx == WINED3DSIH_REP) control_frame->type = REP;
5071
5072         if(priv->target_version >= NV2)
5073         {
5074             control_frame->no.loop = priv->num_loops++;
5075             priv->loop_depth++;
5076         }
5077         else
5078         {
5079             /* Don't bother recording when we're in a not used if branch */
5080             if(priv->muted)
5081             {
5082                 return;
5083             }
5084
5085             if(!priv->recording)
5086             {
5087                 list_init(&priv->record);
5088                 priv->recording = TRUE;
5089                 control_frame->outer_loop = TRUE;
5090                 get_loop_control_const(ins, This, ins->src[0].reg.idx, &control_frame->loop_control);
5091                 return; /* Instruction is handled */
5092             }
5093             /* Record this loop in the outer loop's recording */
5094         }
5095     }
5096     else if(ins->handler_idx == WINED3DSIH_ENDLOOP || ins->handler_idx == WINED3DSIH_ENDREP)
5097     {
5098         if(priv->target_version >= NV2)
5099         {
5100             /* Nothing to do. The control frame is popped after the HW instr handler */
5101         }
5102         else
5103         {
5104             struct list *e = list_head(&priv->control_frames);
5105             control_frame = LIST_ENTRY(e, struct control_frame, entry);
5106             list_remove(&control_frame->entry);
5107
5108             if(control_frame->outer_loop)
5109             {
5110                 int iteration, aL = 0;
5111                 struct list copy;
5112
5113                 /* Turn off recording before playback */
5114                 priv->recording = FALSE;
5115
5116                 /* Move the recorded instructions to a separate list and get them out of the private data
5117                  * structure. If there are nested loops, the shader_arb_handle_instruction below will
5118                  * be recorded again, thus priv->record might be overwritten
5119                  */
5120                 list_init(&copy);
5121                 list_move_tail(&copy, &priv->record);
5122                 list_init(&priv->record);
5123
5124                 if(ins->handler_idx == WINED3DSIH_ENDLOOP)
5125                 {
5126                     shader_addline(buffer, "#unrolling loop: %u iterations, aL=%u, inc %d\n",
5127                                    control_frame->loop_control.count, control_frame->loop_control.start,
5128                                    control_frame->loop_control.step);
5129                     aL = control_frame->loop_control.start;
5130                 }
5131                 else
5132                 {
5133                     shader_addline(buffer, "#unrolling rep: %u iterations\n", control_frame->loop_control.count);
5134                 }
5135
5136                 for (iteration = 0; iteration < control_frame->loop_control.count; ++iteration)
5137                 {
5138                     struct recorded_instruction *rec_ins;
5139                     if(ins->handler_idx == WINED3DSIH_ENDLOOP)
5140                     {
5141                         priv->aL = aL;
5142                         shader_addline(buffer, "#Iteration %d, aL=%d\n", iteration, aL);
5143                     }
5144                     else
5145                     {
5146                         shader_addline(buffer, "#Iteration %d\n", iteration);
5147                     }
5148
5149                     LIST_FOR_EACH_ENTRY(rec_ins, &copy, struct recorded_instruction, entry)
5150                     {
5151                         shader_arb_handle_instruction(&rec_ins->ins);
5152                     }
5153
5154                     if(ins->handler_idx == WINED3DSIH_ENDLOOP)
5155                     {
5156                         aL += control_frame->loop_control.step;
5157                     }
5158                 }
5159                 shader_addline(buffer, "#end loop/rep\n");
5160
5161                 free_recorded_instruction(&copy);
5162                 HeapFree(GetProcessHeap(), 0, control_frame);
5163                 return; /* Instruction is handled */
5164             }
5165             else
5166             {
5167                 /* This is a nested loop. Proceed to the normal recording function */
5168                 HeapFree(GetProcessHeap(), 0, control_frame);
5169             }
5170         }
5171     }
5172
5173     if(priv->recording)
5174     {
5175         record_instruction(&priv->record, ins);
5176         return;
5177     }
5178
5179     /* boolean if */
5180     if(ins->handler_idx == WINED3DSIH_IF)
5181     {
5182         control_frame = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*control_frame));
5183         list_add_head(&priv->control_frames, &control_frame->entry);
5184         control_frame->type = IF;
5185
5186         bool_const = get_bool_const(ins, This, ins->src[0].reg.idx);
5187         if(ins->src[0].modifiers == WINED3DSPSM_NOT) bool_const = !bool_const;
5188         if(!priv->muted && bool_const == FALSE)
5189         {
5190             shader_addline(buffer, "#if(FALSE){\n");
5191             priv->muted = TRUE;
5192             control_frame->muting = TRUE;
5193         }
5194         else shader_addline(buffer, "#if(TRUE) {\n");
5195
5196         return; /* Instruction is handled */
5197     }
5198     else if(ins->handler_idx == WINED3DSIH_IFC)
5199     {
5200         /* IF(bool) and if_cond(a, b) use the same ELSE and ENDIF tokens */
5201         control_frame = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*control_frame));
5202         control_frame->type = IFC;
5203         control_frame->no.ifc = priv->num_ifcs++;
5204         list_add_head(&priv->control_frames, &control_frame->entry);
5205     }
5206     else if(ins->handler_idx == WINED3DSIH_ELSE)
5207     {
5208         struct list *e = list_head(&priv->control_frames);
5209         control_frame = LIST_ENTRY(e, struct control_frame, entry);
5210
5211         if(control_frame->type == IF)
5212         {
5213             shader_addline(buffer, "#} else {\n");
5214             if(!priv->muted && !control_frame->muting)
5215             {
5216                 priv->muted = TRUE;
5217                 control_frame->muting = TRUE;
5218             }
5219             else if(control_frame->muting) priv->muted = FALSE;
5220             return; /* Instruction is handled. */
5221         }
5222         /* In case of an ifc, generate a HW shader instruction */
5223     }
5224     else if(ins->handler_idx == WINED3DSIH_ENDIF)
5225     {
5226         struct list *e = list_head(&priv->control_frames);
5227         control_frame = LIST_ENTRY(e, struct control_frame, entry);
5228
5229         if(control_frame->type == IF)
5230         {
5231             shader_addline(buffer, "#} endif\n");
5232             if(control_frame->muting) priv->muted = FALSE;
5233             list_remove(&control_frame->entry);
5234             HeapFree(GetProcessHeap(), 0, control_frame);
5235             return; /* Instruction is handled */
5236         }
5237     }
5238
5239     if(priv->muted) return;
5240
5241     /* Select handler */
5242     hw_fct = shader_arb_instruction_handler_table[ins->handler_idx];
5243
5244     /* Unhandled opcode */
5245     if (!hw_fct)
5246     {
5247         FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5248         return;
5249     }
5250     hw_fct(ins);
5251
5252     if(ins->handler_idx == WINED3DSIH_ENDLOOP || ins->handler_idx == WINED3DSIH_ENDREP)
5253     {
5254         struct list *e = list_head(&priv->control_frames);
5255         control_frame = LIST_ENTRY(e, struct control_frame, entry);
5256         list_remove(&control_frame->entry);
5257         HeapFree(GetProcessHeap(), 0, control_frame);
5258         priv->loop_depth--;
5259     }
5260     else if(ins->handler_idx == WINED3DSIH_ENDIF)
5261     {
5262         /* Non-ifc ENDIFs don't reach that place because of the return in the if block above */
5263         struct list *e = list_head(&priv->control_frames);
5264         control_frame = LIST_ENTRY(e, struct control_frame, entry);
5265         list_remove(&control_frame->entry);
5266         HeapFree(GetProcessHeap(), 0, control_frame);
5267     }
5268
5269
5270     shader_arb_add_instruction_modifiers(ins);
5271 }
5272
5273 const shader_backend_t arb_program_shader_backend = {
5274     shader_arb_handle_instruction,
5275     shader_arb_select,
5276     shader_arb_select_depth_blt,
5277     shader_arb_deselect_depth_blt,
5278     shader_arb_update_float_vertex_constants,
5279     shader_arb_update_float_pixel_constants,
5280     shader_arb_load_constants,
5281     shader_arb_load_np2fixup_constants,
5282     shader_arb_destroy,
5283     shader_arb_alloc,
5284     shader_arb_free,
5285     shader_arb_dirty_const,
5286     shader_arb_get_caps,
5287     shader_arb_color_fixup_supported,
5288 };
5289
5290 /* ARB_fragment_program fixed function pipeline replacement definitions */
5291 #define ARB_FFP_CONST_TFACTOR           0
5292 #define ARB_FFP_CONST_SPECULAR_ENABLE   ((ARB_FFP_CONST_TFACTOR) + 1)
5293 #define ARB_FFP_CONST_CONSTANT(i)       ((ARB_FFP_CONST_SPECULAR_ENABLE) + 1 + i)
5294 #define ARB_FFP_CONST_BUMPMAT(i)        ((ARB_FFP_CONST_CONSTANT(7)) + 1 + i)
5295 #define ARB_FFP_CONST_LUMINANCE(i)      ((ARB_FFP_CONST_BUMPMAT(7)) + 1 + i)
5296
5297 struct arbfp_ffp_desc
5298 {
5299     struct ffp_frag_desc parent;
5300     GLuint shader;
5301     unsigned int num_textures_used;
5302 };
5303
5304 /* Context activation is done by the caller. */
5305 static void arbfp_enable(IWineD3DDevice *iface, BOOL enable) {
5306     ENTER_GL();
5307     if(enable) {
5308         glEnable(GL_FRAGMENT_PROGRAM_ARB);
5309         checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
5310     } else {
5311         glDisable(GL_FRAGMENT_PROGRAM_ARB);
5312         checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
5313     }
5314     LEAVE_GL();
5315 }
5316
5317 static HRESULT arbfp_alloc(IWineD3DDevice *iface) {
5318     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
5319     struct shader_arb_priv *priv;
5320     /* Share private data between the shader backend and the pipeline replacement, if both
5321      * are the arb implementation. This is needed to figure out whether ARBfp should be disabled
5322      * if no pixel shader is bound or not
5323      */
5324     if(This->shader_backend == &arb_program_shader_backend) {
5325         This->fragment_priv = This->shader_priv;
5326     } else {
5327         This->fragment_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_arb_priv));
5328         if(!This->fragment_priv) return E_OUTOFMEMORY;
5329     }
5330     priv = This->fragment_priv;
5331     if (wine_rb_init(&priv->fragment_shaders, &wined3d_ffp_frag_program_rb_functions) == -1)
5332     {
5333         ERR("Failed to initialize rbtree.\n");
5334         HeapFree(GetProcessHeap(), 0, This->fragment_priv);
5335         return E_OUTOFMEMORY;
5336     }
5337     priv->use_arbfp_fixed_func = TRUE;
5338     return WINED3D_OK;
5339 }
5340
5341 /* Context activation is done by the caller. */
5342 static void arbfp_free_ffpshader(struct wine_rb_entry *entry, void *context)
5343 {
5344     const struct wined3d_gl_info *gl_info = context;
5345     struct arbfp_ffp_desc *entry_arb = WINE_RB_ENTRY_VALUE(entry, struct arbfp_ffp_desc, parent.entry);
5346
5347     ENTER_GL();
5348     GL_EXTCALL(glDeleteProgramsARB(1, &entry_arb->shader));
5349     checkGLcall("glDeleteProgramsARB(1, &entry_arb->shader)");
5350     HeapFree(GetProcessHeap(), 0, entry_arb);
5351     LEAVE_GL();
5352 }
5353
5354 /* Context activation is done by the caller. */
5355 static void arbfp_free(IWineD3DDevice *iface) {
5356     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *) iface;
5357     struct shader_arb_priv *priv = This->fragment_priv;
5358
5359     wine_rb_destroy(&priv->fragment_shaders, arbfp_free_ffpshader, &This->adapter->gl_info);
5360     priv->use_arbfp_fixed_func = FALSE;
5361
5362     if(This->shader_backend != &arb_program_shader_backend) {
5363         HeapFree(GetProcessHeap(), 0, This->fragment_priv);
5364     }
5365 }
5366
5367 static void arbfp_get_caps(const struct wined3d_gl_info *gl_info, struct fragment_caps *caps)
5368 {
5369     caps->PrimitiveMiscCaps = WINED3DPMISCCAPS_TSSARGTEMP;
5370     caps->TextureOpCaps =  WINED3DTEXOPCAPS_DISABLE                     |
5371                            WINED3DTEXOPCAPS_SELECTARG1                  |
5372                            WINED3DTEXOPCAPS_SELECTARG2                  |
5373                            WINED3DTEXOPCAPS_MODULATE4X                  |
5374                            WINED3DTEXOPCAPS_MODULATE2X                  |
5375                            WINED3DTEXOPCAPS_MODULATE                    |
5376                            WINED3DTEXOPCAPS_ADDSIGNED2X                 |
5377                            WINED3DTEXOPCAPS_ADDSIGNED                   |
5378                            WINED3DTEXOPCAPS_ADD                         |
5379                            WINED3DTEXOPCAPS_SUBTRACT                    |
5380                            WINED3DTEXOPCAPS_ADDSMOOTH                   |
5381                            WINED3DTEXOPCAPS_BLENDCURRENTALPHA           |
5382                            WINED3DTEXOPCAPS_BLENDFACTORALPHA            |
5383                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHA           |
5384                            WINED3DTEXOPCAPS_BLENDDIFFUSEALPHA           |
5385                            WINED3DTEXOPCAPS_BLENDTEXTUREALPHAPM         |
5386                            WINED3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR      |
5387                            WINED3DTEXOPCAPS_MODULATECOLOR_ADDALPHA      |
5388                            WINED3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA   |
5389                            WINED3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR   |
5390                            WINED3DTEXOPCAPS_DOTPRODUCT3                 |
5391                            WINED3DTEXOPCAPS_MULTIPLYADD                 |
5392                            WINED3DTEXOPCAPS_LERP                        |
5393                            WINED3DTEXOPCAPS_BUMPENVMAP                  |
5394                            WINED3DTEXOPCAPS_BUMPENVMAPLUMINANCE;
5395
5396     /* TODO: Implement WINED3DTEXOPCAPS_PREMODULATE */
5397
5398     caps->MaxTextureBlendStages   = 8;
5399     caps->MaxSimultaneousTextures = min(gl_info->limits.fragment_samplers, 8);
5400 }
5401 #undef GLINFO_LOCATION
5402
5403 #define GLINFO_LOCATION stateblock->device->adapter->gl_info
5404 static void state_texfactor_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5405 {
5406     IWineD3DDeviceImpl *device = stateblock->device;
5407     float col[4];
5408
5409     /* Don't load the parameter if we're using an arbfp pixel shader, otherwise we'll overwrite
5410      * application provided constants
5411      */
5412     if(device->shader_backend == &arb_program_shader_backend) {
5413         if (use_ps(stateblock)) return;
5414
5415         context->pshader_const_dirty[ARB_FFP_CONST_TFACTOR] = 1;
5416         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_TFACTOR + 1);
5417     }
5418
5419     D3DCOLORTOGLFLOAT4(stateblock->renderState[WINED3DRS_TEXTUREFACTOR], col);
5420     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col));
5421     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_TFACTOR, col)");
5422
5423 }
5424
5425 static void state_arb_specularenable(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5426 {
5427     IWineD3DDeviceImpl *device = stateblock->device;
5428     float col[4];
5429
5430     /* Don't load the parameter if we're using an arbfp pixel shader, otherwise we'll overwrite
5431      * application provided constants
5432      */
5433     if(device->shader_backend == &arb_program_shader_backend) {
5434         if (use_ps(stateblock)) return;
5435
5436         context->pshader_const_dirty[ARB_FFP_CONST_SPECULAR_ENABLE] = 1;
5437         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_SPECULAR_ENABLE + 1);
5438     }
5439
5440     if(stateblock->renderState[WINED3DRS_SPECULARENABLE]) {
5441         /* The specular color has no alpha */
5442         col[0] = 1.0f; col[1] = 1.0f;
5443         col[2] = 1.0f; col[3] = 0.0f;
5444     } else {
5445         col[0] = 0.0f; col[1] = 0.0f;
5446         col[2] = 0.0f; col[3] = 0.0f;
5447     }
5448     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_SPECULAR_ENABLE, col));
5449     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_SPECULAR_ENABLE, col)");
5450 }
5451
5452 static void set_bumpmat_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5453 {
5454     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
5455     IWineD3DDeviceImpl *device = stateblock->device;
5456     float mat[2][2];
5457
5458     if (use_ps(stateblock))
5459     {
5460         if (stage != 0
5461                 && (((IWineD3DPixelShaderImpl *)stateblock->pixelShader)->baseShader.reg_maps.bumpmat & (1 << stage)))
5462         {
5463             /* The pixel shader has to know the bump env matrix. Do a constants update if it isn't scheduled
5464              * anyway
5465              */
5466             if (!isStateDirty(context, STATE_PIXELSHADERCONSTANT))
5467                 stateblock_apply_state(STATE_PIXELSHADERCONSTANT, stateblock, context);
5468         }
5469
5470         if(device->shader_backend == &arb_program_shader_backend) {
5471             /* Exit now, don't set the bumpmat below, otherwise we may overwrite pixel shader constants */
5472             return;
5473         }
5474     } else if(device->shader_backend == &arb_program_shader_backend) {
5475         context->pshader_const_dirty[ARB_FFP_CONST_BUMPMAT(stage)] = 1;
5476         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_BUMPMAT(stage) + 1);
5477     }
5478
5479     mat[0][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT00]);
5480     mat[0][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT01]);
5481     mat[1][0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT10]);
5482     mat[1][1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVMAT11]);
5483
5484     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0]));
5485     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_BUMPMAT(stage), &mat[0][0])");
5486 }
5487
5488 static void tex_bumpenvlum_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
5489 {
5490     DWORD stage = (state - STATE_TEXTURESTAGE(0, 0)) / (WINED3D_HIGHEST_TEXTURE_STATE + 1);
5491     IWineD3DDeviceImpl *device = stateblock->device;
5492     float param[4];
5493
5494     if (use_ps(stateblock))
5495     {
5496         if (stage != 0
5497                 && (((IWineD3DPixelShaderImpl *)stateblock->pixelShader)->baseShader.reg_maps.luminanceparams & (1 << stage)))
5498         {
5499             /* The pixel shader has to know the luminance offset. Do a constants update if it
5500              * isn't scheduled anyway
5501              */
5502             if (!isStateDirty(context, STATE_PIXELSHADERCONSTANT))
5503                 stateblock_apply_state(STATE_PIXELSHADERCONSTANT, stateblock, context);
5504         }
5505
5506         if(device->shader_backend == &arb_program_shader_backend) {
5507             /* Exit now, don't set the bumpmat below, otherwise we may overwrite pixel shader constants */
5508             return;
5509         }
5510     } else if(device->shader_backend == &arb_program_shader_backend) {
5511         context->pshader_const_dirty[ARB_FFP_CONST_LUMINANCE(stage)] = 1;
5512         device->highest_dirty_ps_const = max(device->highest_dirty_ps_const, ARB_FFP_CONST_LUMINANCE(stage) + 1);
5513     }
5514
5515     param[0] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVLSCALE]);
5516     param[1] = *((float *) &stateblock->textureState[stage][WINED3DTSS_BUMPENVLOFFSET]);
5517     param[2] = 0.0f;
5518     param[3] = 0.0f;
5519
5520     GL_EXTCALL(glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_LUMINANCE(stage), param));
5521     checkGLcall("glProgramEnvParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, ARB_FFP_CONST_LUMINANCE(stage), param)");
5522 }
5523
5524 static const char *get_argreg(struct wined3d_shader_buffer *buffer, DWORD argnum, unsigned int stage, DWORD arg)
5525 {
5526     const char *ret;
5527
5528     if(arg == ARG_UNUSED) return "unused"; /* This is the marker for unused registers */
5529
5530     switch(arg & WINED3DTA_SELECTMASK) {
5531         case WINED3DTA_DIFFUSE:
5532             ret = "fragment.color.primary"; break;
5533
5534         case WINED3DTA_CURRENT:
5535             if(stage == 0) ret = "fragment.color.primary";
5536             else ret = "ret";
5537             break;
5538
5539         case WINED3DTA_TEXTURE:
5540             switch(stage) {
5541                 case 0: ret = "tex0"; break;
5542                 case 1: ret = "tex1"; break;
5543                 case 2: ret = "tex2"; break;
5544                 case 3: ret = "tex3"; break;
5545                 case 4: ret = "tex4"; break;
5546                 case 5: ret = "tex5"; break;
5547                 case 6: ret = "tex6"; break;
5548                 case 7: ret = "tex7"; break;
5549                 default: ret = "unknown texture";
5550             }
5551             break;
5552
5553         case WINED3DTA_TFACTOR:
5554             ret = "tfactor"; break;
5555
5556         case WINED3DTA_SPECULAR:
5557             ret = "fragment.color.secondary"; break;
5558
5559         case WINED3DTA_TEMP:
5560             ret = "tempreg"; break;
5561
5562         case WINED3DTA_CONSTANT:
5563             FIXME("Implement perstage constants\n");
5564             switch(stage) {
5565                 case 0: ret = "const0"; break;
5566                 case 1: ret = "const1"; break;
5567                 case 2: ret = "const2"; break;
5568                 case 3: ret = "const3"; break;
5569                 case 4: ret = "const4"; break;
5570                 case 5: ret = "const5"; break;
5571                 case 6: ret = "const6"; break;
5572                 case 7: ret = "const7"; break;
5573                 default: ret = "unknown constant";
5574             }
5575             break;
5576
5577         default:
5578             return "unknown";
5579     }
5580
5581     if(arg & WINED3DTA_COMPLEMENT) {
5582         shader_addline(buffer, "SUB arg%u, const.x, %s;\n", argnum, ret);
5583         if(argnum == 0) ret = "arg0";
5584         if(argnum == 1) ret = "arg1";
5585         if(argnum == 2) ret = "arg2";
5586     }
5587     if(arg & WINED3DTA_ALPHAREPLICATE) {
5588         shader_addline(buffer, "MOV arg%u, %s.w;\n", argnum, ret);
5589         if(argnum == 0) ret = "arg0";
5590         if(argnum == 1) ret = "arg1";
5591         if(argnum == 2) ret = "arg2";
5592     }
5593     return ret;
5594 }
5595
5596 static void gen_ffp_instr(struct wined3d_shader_buffer *buffer, unsigned int stage, BOOL color,
5597         BOOL alpha, DWORD dst, DWORD op, DWORD dw_arg0, DWORD dw_arg1, DWORD dw_arg2)
5598 {
5599     const char *dstmask, *dstreg, *arg0, *arg1, *arg2;
5600     unsigned int mul = 1;
5601     BOOL mul_final_dest = FALSE;
5602
5603     if(color && alpha) dstmask = "";
5604     else if(color) dstmask = ".xyz";
5605     else dstmask = ".w";
5606
5607     if(dst == tempreg) dstreg = "tempreg";
5608     else dstreg = "ret";
5609
5610     arg0 = get_argreg(buffer, 0, stage, dw_arg0);
5611     arg1 = get_argreg(buffer, 1, stage, dw_arg1);
5612     arg2 = get_argreg(buffer, 2, stage, dw_arg2);
5613
5614     switch(op) {
5615         case WINED3DTOP_DISABLE:
5616             if(stage == 0) shader_addline(buffer, "MOV %s%s, fragment.color.primary;\n", dstreg, dstmask);
5617             break;
5618
5619         case WINED3DTOP_SELECTARG2:
5620             arg1 = arg2;
5621         case WINED3DTOP_SELECTARG1:
5622             shader_addline(buffer, "MOV %s%s, %s;\n", dstreg, dstmask, arg1);
5623             break;
5624
5625         case WINED3DTOP_MODULATE4X:
5626             mul = 2;
5627         case WINED3DTOP_MODULATE2X:
5628             mul *= 2;
5629             if(strcmp(dstreg, "result.color") == 0) {
5630                 dstreg = "ret";
5631                 mul_final_dest = TRUE;
5632             }
5633         case WINED3DTOP_MODULATE:
5634             shader_addline(buffer, "MUL %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
5635             break;
5636
5637         case WINED3DTOP_ADDSIGNED2X:
5638             mul = 2;
5639             if(strcmp(dstreg, "result.color") == 0) {
5640                 dstreg = "ret";
5641                 mul_final_dest = TRUE;
5642             }
5643         case WINED3DTOP_ADDSIGNED:
5644             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
5645             arg2 = "arg2";
5646         case WINED3DTOP_ADD:
5647             shader_addline(buffer, "ADD_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
5648             break;
5649
5650         case WINED3DTOP_SUBTRACT:
5651             shader_addline(buffer, "SUB_SAT %s%s, %s, %s;\n", dstreg, dstmask, arg1, arg2);
5652             break;
5653
5654         case WINED3DTOP_ADDSMOOTH:
5655             shader_addline(buffer, "SUB arg1, const.x, %s;\n", arg1);
5656             shader_addline(buffer, "MAD_SAT %s%s, arg1, %s, %s;\n", dstreg, dstmask, arg2, arg1);
5657             break;
5658
5659         case WINED3DTOP_BLENDCURRENTALPHA:
5660             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_CURRENT);
5661             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5662             break;
5663         case WINED3DTOP_BLENDFACTORALPHA:
5664             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TFACTOR);
5665             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5666             break;
5667         case WINED3DTOP_BLENDTEXTUREALPHA:
5668             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TEXTURE);
5669             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5670             break;
5671         case WINED3DTOP_BLENDDIFFUSEALPHA:
5672             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_DIFFUSE);
5673             shader_addline(buffer, "LRP %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5674             break;
5675
5676         case WINED3DTOP_BLENDTEXTUREALPHAPM:
5677             arg0 = get_argreg(buffer, 0, stage, WINED3DTA_TEXTURE);
5678             shader_addline(buffer, "SUB arg0.w, const.x, %s.w;\n", arg0);
5679             shader_addline(buffer, "MAD_SAT %s%s, %s, arg0.w, %s;\n", dstreg, dstmask, arg2, arg1);
5680             break;
5681
5682         /* D3DTOP_PREMODULATE ???? */
5683
5684         case WINED3DTOP_MODULATEINVALPHA_ADDCOLOR:
5685             shader_addline(buffer, "SUB arg0.w, const.x, %s;\n", arg1);
5686             shader_addline(buffer, "MAD_SAT %s%s, arg0.w, %s, %s;\n", dstreg, dstmask, arg2, arg1);
5687             break;
5688         case WINED3DTOP_MODULATEALPHA_ADDCOLOR:
5689             shader_addline(buffer, "MAD_SAT %s%s, %s.w, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg1);
5690             break;
5691         case WINED3DTOP_MODULATEINVCOLOR_ADDALPHA:
5692             shader_addline(buffer, "SUB arg0, const.x, %s;\n", arg1);
5693             shader_addline(buffer, "MAD_SAT %s%s, arg0, %s, %s.w;\n", dstreg, dstmask, arg2, arg1);
5694             break;
5695         case WINED3DTOP_MODULATECOLOR_ADDALPHA:
5696             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s.w;\n", dstreg, dstmask, arg1, arg2, arg1);
5697             break;
5698
5699         case WINED3DTOP_DOTPRODUCT3:
5700             mul = 4;
5701             if(strcmp(dstreg, "result.color") == 0) {
5702                 dstreg = "ret";
5703                 mul_final_dest = TRUE;
5704             }
5705             shader_addline(buffer, "SUB arg1, %s, const.w;\n", arg1);
5706             shader_addline(buffer, "SUB arg2, %s, const.w;\n", arg2);
5707             shader_addline(buffer, "DP3_SAT %s%s, arg1, arg2;\n", dstreg, dstmask);
5708             break;
5709
5710         case WINED3DTOP_MULTIPLYADD:
5711             shader_addline(buffer, "MAD_SAT %s%s, %s, %s, %s;\n", dstreg, dstmask, arg1, arg2, arg0);
5712             break;
5713
5714         case WINED3DTOP_LERP:
5715             /* The msdn is not quite right here */
5716             shader_addline(buffer, "LRP %s%s, %s, %s, %s;\n", dstreg, dstmask, arg0, arg1, arg2);
5717             break;
5718
5719         case WINED3DTOP_BUMPENVMAP:
5720         case WINED3DTOP_BUMPENVMAPLUMINANCE:
5721             /* Those are handled in the first pass of the shader(generation pass 1 and 2) already */
5722             break;
5723
5724         default:
5725             FIXME("Unhandled texture op %08x\n", op);
5726     }
5727
5728     if(mul == 2) {
5729         shader_addline(buffer, "MUL_SAT %s%s, %s, const.y;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
5730     } else if(mul == 4) {
5731         shader_addline(buffer, "MUL_SAT %s%s, %s, const.z;\n", mul_final_dest ? "result.color" : dstreg, dstmask, dstreg);
5732     }
5733 }
5734
5735 /* The stateblock is passed for GLINFO_LOCATION */
5736 static GLuint gen_arbfp_ffp_shader(const struct ffp_frag_settings *settings, IWineD3DStateBlockImpl *stateblock)
5737 {
5738     unsigned int stage;
5739     struct wined3d_shader_buffer buffer;
5740     BOOL tex_read[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
5741     BOOL bump_used[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
5742     BOOL luminance_used[MAX_TEXTURES] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
5743     const char *textype;
5744     const char *instr, *sat;
5745     char colorcor_dst[8];
5746     GLuint ret;
5747     DWORD arg0, arg1, arg2;
5748     BOOL tempreg_used = FALSE, tfactor_used = FALSE;
5749     BOOL op_equal;
5750     const char *final_combiner_src = "ret";
5751     GLint pos;
5752
5753     /* Find out which textures are read */
5754     for(stage = 0; stage < MAX_TEXTURES; stage++) {
5755         if(settings->op[stage].cop == WINED3DTOP_DISABLE) break;
5756         arg0 = settings->op[stage].carg0 & WINED3DTA_SELECTMASK;
5757         arg1 = settings->op[stage].carg1 & WINED3DTA_SELECTMASK;
5758         arg2 = settings->op[stage].carg2 & WINED3DTA_SELECTMASK;
5759         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5760         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5761         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5762
5763         if(settings->op[stage].cop == WINED3DTOP_BLENDTEXTUREALPHA) tex_read[stage] = TRUE;
5764         if(settings->op[stage].cop == WINED3DTOP_BLENDTEXTUREALPHAPM) tex_read[stage] = TRUE;
5765         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP) {
5766             bump_used[stage] = TRUE;
5767             tex_read[stage] = TRUE;
5768         }
5769         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
5770             bump_used[stage] = TRUE;
5771             tex_read[stage] = TRUE;
5772             luminance_used[stage] = TRUE;
5773         } else if(settings->op[stage].cop == WINED3DTOP_BLENDFACTORALPHA) {
5774             tfactor_used = TRUE;
5775         }
5776
5777         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
5778             tfactor_used = TRUE;
5779         }
5780
5781         if(settings->op[stage].dst == tempreg) tempreg_used = TRUE;
5782         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
5783             tempreg_used = TRUE;
5784         }
5785
5786         if(settings->op[stage].aop == WINED3DTOP_DISABLE) continue;
5787         arg0 = settings->op[stage].aarg0 & WINED3DTA_SELECTMASK;
5788         arg1 = settings->op[stage].aarg1 & WINED3DTA_SELECTMASK;
5789         arg2 = settings->op[stage].aarg2 & WINED3DTA_SELECTMASK;
5790         if(arg0 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5791         if(arg1 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5792         if(arg2 == WINED3DTA_TEXTURE) tex_read[stage] = TRUE;
5793
5794         if(arg0 == WINED3DTA_TEMP || arg1 == WINED3DTA_TEMP || arg2 == WINED3DTA_TEMP) {
5795             tempreg_used = TRUE;
5796         }
5797         if(arg0 == WINED3DTA_TFACTOR || arg1 == WINED3DTA_TFACTOR || arg2 == WINED3DTA_TFACTOR) {
5798             tfactor_used = TRUE;
5799         }
5800     }
5801
5802     /* Shader header */
5803     if (!shader_buffer_init(&buffer))
5804     {
5805         ERR("Failed to initialize shader buffer.\n");
5806         return 0;
5807     }
5808
5809     shader_addline(&buffer, "!!ARBfp1.0\n");
5810
5811     switch(settings->fog) {
5812         case FOG_OFF:                                                         break;
5813         case FOG_LINEAR: shader_addline(&buffer, "OPTION ARB_fog_linear;\n"); break;
5814         case FOG_EXP:    shader_addline(&buffer, "OPTION ARB_fog_exp;\n");    break;
5815         case FOG_EXP2:   shader_addline(&buffer, "OPTION ARB_fog_exp2;\n");   break;
5816         default: FIXME("Unexpected fog setting %d\n", settings->fog);
5817     }
5818
5819     shader_addline(&buffer, "PARAM const = {1, 2, 4, 0.5};\n");
5820     shader_addline(&buffer, "TEMP TMP;\n");
5821     shader_addline(&buffer, "TEMP ret;\n");
5822     if(tempreg_used || settings->sRGB_write) shader_addline(&buffer, "TEMP tempreg;\n");
5823     shader_addline(&buffer, "TEMP arg0;\n");
5824     shader_addline(&buffer, "TEMP arg1;\n");
5825     shader_addline(&buffer, "TEMP arg2;\n");
5826     for(stage = 0; stage < MAX_TEXTURES; stage++) {
5827         if(!tex_read[stage]) continue;
5828         shader_addline(&buffer, "TEMP tex%u;\n", stage);
5829         if(!bump_used[stage]) continue;
5830         shader_addline(&buffer, "PARAM bumpmat%u = program.env[%u];\n", stage, ARB_FFP_CONST_BUMPMAT(stage));
5831         if(!luminance_used[stage]) continue;
5832         shader_addline(&buffer, "PARAM luminance%u = program.env[%u];\n", stage, ARB_FFP_CONST_LUMINANCE(stage));
5833     }
5834     if(tfactor_used) {
5835         shader_addline(&buffer, "PARAM tfactor = program.env[%u];\n", ARB_FFP_CONST_TFACTOR);
5836     }
5837         shader_addline(&buffer, "PARAM specular_enable = program.env[%u];\n", ARB_FFP_CONST_SPECULAR_ENABLE);
5838
5839     if(settings->sRGB_write) {
5840         shader_addline(&buffer, "PARAM srgb_consts1 = {%f, %f, %f, %f};\n",
5841                        srgb_mul_low, srgb_cmp, srgb_pow, srgb_mul_high);
5842         shader_addline(&buffer, "PARAM srgb_consts2 = {%f, %f, %f, %f};\n",
5843                        srgb_sub_high, 0.0, 0.0, 0.0);
5844     }
5845
5846     if(ffp_clip_emul(stateblock) && settings->emul_clipplanes) shader_addline(&buffer, "KIL fragment.texcoord[7];\n");
5847
5848     /* Generate texture sampling instructions) */
5849     for(stage = 0; stage < MAX_TEXTURES && settings->op[stage].cop != WINED3DTOP_DISABLE; stage++) {
5850         if(!tex_read[stage]) continue;
5851
5852         switch(settings->op[stage].tex_type) {
5853             case tex_1d:                    textype = "1D";     break;
5854             case tex_2d:                    textype = "2D";     break;
5855             case tex_3d:                    textype = "3D";     break;
5856             case tex_cube:                  textype = "CUBE";   break;
5857             case tex_rect:                  textype = "RECT";   break;
5858             default: textype = "unexpected_textype";   break;
5859         }
5860
5861         if(settings->op[stage].cop == WINED3DTOP_BUMPENVMAP ||
5862            settings->op[stage].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
5863             sat = "";
5864         } else {
5865             sat = "_SAT";
5866         }
5867
5868         if(settings->op[stage].projected == proj_none) {
5869             instr = "TEX";
5870         } else if(settings->op[stage].projected == proj_count4 ||
5871                   settings->op[stage].projected == proj_count3) {
5872             instr = "TXP";
5873         } else {
5874             FIXME("Unexpected projection mode %d\n", settings->op[stage].projected);
5875             instr = "TXP";
5876         }
5877
5878         if(stage > 0 &&
5879            (settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAP ||
5880             settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAPLUMINANCE)) {
5881             shader_addline(&buffer, "SWZ arg1, bumpmat%u, x, z, 0, 0;\n", stage - 1);
5882             shader_addline(&buffer, "DP3 ret.x, arg1, tex%u;\n", stage - 1);
5883             shader_addline(&buffer, "SWZ arg1, bumpmat%u, y, w, 0, 0;\n", stage - 1);
5884             shader_addline(&buffer, "DP3 ret.y, arg1, tex%u;\n", stage - 1);
5885
5886             /* with projective textures, texbem only divides the static texture coord, not the displacement,
5887              * so multiply the displacement with the dividing parameter before passing it to TXP
5888              */
5889             if (settings->op[stage].projected != proj_none) {
5890                 if(settings->op[stage].projected == proj_count4) {
5891                     shader_addline(&buffer, "MOV ret.w, fragment.texcoord[%u].w;\n", stage);
5892                     shader_addline(&buffer, "MUL ret.xyz, ret, fragment.texcoord[%u].w, fragment.texcoord[%u];\n", stage, stage);
5893                 } else {
5894                     shader_addline(&buffer, "MOV ret.w, fragment.texcoord[%u].z;\n", stage);
5895                     shader_addline(&buffer, "MAD ret.xyz, ret, fragment.texcoord[%u].z, fragment.texcoord[%u];\n", stage, stage);
5896                 }
5897             } else {
5898                 shader_addline(&buffer, "ADD ret, ret, fragment.texcoord[%u];\n", stage);
5899             }
5900
5901             shader_addline(&buffer, "%s%s tex%u, ret, texture[%u], %s;\n",
5902                            instr, sat, stage, stage, textype);
5903             if(settings->op[stage - 1].cop == WINED3DTOP_BUMPENVMAPLUMINANCE) {
5904                 shader_addline(&buffer, "MAD_SAT ret.x, tex%u.z, luminance%u.x, luminance%u.y;\n",
5905                                stage - 1, stage - 1, stage - 1);
5906                 shader_addline(&buffer, "MUL tex%u, tex%u, ret.x;\n", stage, stage);
5907             }
5908         } else if(settings->op[stage].projected == proj_count3) {
5909             shader_addline(&buffer, "MOV ret, fragment.texcoord[%u];\n", stage);
5910             shader_addline(&buffer, "MOV ret.w, ret.z;\n");
5911             shader_addline(&buffer, "%s%s tex%u, ret, texture[%u], %s;\n",
5912                             instr, sat, stage, stage, textype);
5913         } else {
5914             shader_addline(&buffer, "%s%s tex%u, fragment.texcoord[%u], texture[%u], %s;\n",
5915                             instr, sat, stage, stage, stage, textype);
5916         }
5917
5918         sprintf(colorcor_dst, "tex%u", stage);
5919         gen_color_correction(&buffer, colorcor_dst, WINED3DSP_WRITEMASK_ALL, "const.x", "const.y",
5920                 settings->op[stage].color_fixup);
5921     }
5922
5923     /* Generate the main shader */
5924     for(stage = 0; stage < MAX_TEXTURES; stage++) {
5925         if(settings->op[stage].cop == WINED3DTOP_DISABLE) {
5926             if(stage == 0) {
5927                 final_combiner_src = "fragment.color.primary";
5928             }
5929             break;
5930         }
5931
5932         if(settings->op[stage].cop == WINED3DTOP_SELECTARG1 &&
5933            settings->op[stage].aop == WINED3DTOP_SELECTARG1) {
5934             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg1;
5935         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG1 &&
5936                   settings->op[stage].aop == WINED3DTOP_SELECTARG2) {
5937             op_equal = settings->op[stage].carg1 == settings->op[stage].aarg2;
5938         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG2 &&
5939                   settings->op[stage].aop == WINED3DTOP_SELECTARG1) {
5940             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg1;
5941         } else if(settings->op[stage].cop == WINED3DTOP_SELECTARG2 &&
5942                   settings->op[stage].aop == WINED3DTOP_SELECTARG2) {
5943             op_equal = settings->op[stage].carg2 == settings->op[stage].aarg2;
5944         } else {
5945             op_equal = settings->op[stage].aop   == settings->op[stage].cop &&
5946                        settings->op[stage].carg0 == settings->op[stage].aarg0 &&
5947                        settings->op[stage].carg1 == settings->op[stage].aarg1 &&
5948                        settings->op[stage].carg2 == settings->op[stage].aarg2;
5949         }
5950
5951         if(settings->op[stage].aop == WINED3DTOP_DISABLE) {
5952             gen_ffp_instr(&buffer, stage, TRUE, FALSE, settings->op[stage].dst,
5953                           settings->op[stage].cop, settings->op[stage].carg0,
5954                           settings->op[stage].carg1, settings->op[stage].carg2);
5955             if(stage == 0) {
5956                 shader_addline(&buffer, "MOV ret.w, fragment.color.primary.w;\n");
5957             }
5958         } else if(op_equal) {
5959             gen_ffp_instr(&buffer, stage, TRUE, TRUE, settings->op[stage].dst,
5960                           settings->op[stage].cop, settings->op[stage].carg0,
5961                           settings->op[stage].carg1, settings->op[stage].carg2);
5962         } else {
5963             gen_ffp_instr(&buffer, stage, TRUE, FALSE, settings->op[stage].dst,
5964                           settings->op[stage].cop, settings->op[stage].carg0,
5965                           settings->op[stage].carg1, settings->op[stage].carg2);
5966             gen_ffp_instr(&buffer, stage, FALSE, TRUE, settings->op[stage].dst,
5967                           settings->op[stage].aop, settings->op[stage].aarg0,
5968                           settings->op[stage].aarg1, settings->op[stage].aarg2);
5969         }
5970     }
5971
5972     if(settings->sRGB_write) {
5973         shader_addline(&buffer, "MAD ret, fragment.color.secondary, specular_enable, %s;\n", final_combiner_src);
5974         arbfp_add_sRGB_correction(&buffer, "ret", "arg0", "arg1", "arg2", "tempreg", FALSE);
5975         shader_addline(&buffer, "MOV result.color, ret;\n");
5976     } else {
5977         shader_addline(&buffer, "MAD result.color, fragment.color.secondary, specular_enable, %s;\n", final_combiner_src);
5978     }
5979
5980     /* Footer */
5981     shader_addline(&buffer, "END\n");
5982
5983     /* Generate the shader */
5984     GL_EXTCALL(glGenProgramsARB(1, &ret));
5985     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret));
5986     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
5987             strlen(buffer.buffer), buffer.buffer));
5988     checkGLcall("glProgramStringARB()");
5989
5990     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
5991     if (pos != -1)
5992     {
5993         FIXME("Fragment program error at position %d: %s\n\n", pos,
5994               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
5995         shader_arb_dump_program_source(buffer.buffer);
5996     }
5997     else
5998     {
5999         GLint native;
6000
6001         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
6002         checkGLcall("glGetProgramivARB()");
6003         if (!native) WARN("Program exceeds native resource limits.\n");
6004     }
6005
6006     shader_buffer_free(&buffer);
6007     return ret;
6008 }
6009
6010 static void fragment_prog_arbfp(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
6011 {
6012     IWineD3DDeviceImpl *device = stateblock->device;
6013     struct shader_arb_priv *priv = device->fragment_priv;
6014     BOOL use_pshader = use_ps(stateblock);
6015     BOOL use_vshader = use_vs(stateblock);
6016     struct ffp_frag_settings settings;
6017     const struct arbfp_ffp_desc *desc;
6018     unsigned int i;
6019
6020     TRACE("state %#x, stateblock %p, context %p\n", state, stateblock, context);
6021
6022     if(isStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE))) {
6023         if(!use_pshader && device->shader_backend == &arb_program_shader_backend && context->last_was_pshader) {
6024             /* Reload fixed function constants since they collide with the pixel shader constants */
6025             for(i = 0; i < MAX_TEXTURES; i++) {
6026                 set_bumpmat_arbfp(STATE_TEXTURESTAGE(i, WINED3DTSS_BUMPENVMAT00), stateblock, context);
6027             }
6028             state_texfactor_arbfp(STATE_RENDER(WINED3DRS_TEXTUREFACTOR), stateblock, context);
6029             state_arb_specularenable(STATE_RENDER(WINED3DRS_SPECULARENABLE), stateblock, context);
6030         } else if(use_pshader && !isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
6031             device->shader_backend->shader_select(context, use_pshader, use_vshader);
6032         }
6033         return;
6034     }
6035
6036     if(!use_pshader) {
6037         /* Find or create a shader implementing the fixed function pipeline settings, then activate it */
6038         gen_ffp_frag_op(stateblock, &settings, FALSE);
6039         desc = (const struct arbfp_ffp_desc *)find_ffp_frag_shader(&priv->fragment_shaders, &settings);
6040         if(!desc) {
6041             struct arbfp_ffp_desc *new_desc = HeapAlloc(GetProcessHeap(), 0, sizeof(*new_desc));
6042             if (!new_desc)
6043             {
6044                 ERR("Out of memory\n");
6045                 return;
6046             }
6047             new_desc->num_textures_used = 0;
6048             for (i = 0; i < context->gl_info->limits.texture_stages; ++i)
6049             {
6050                 if(settings.op[i].cop == WINED3DTOP_DISABLE) break;
6051                 new_desc->num_textures_used = i;
6052             }
6053
6054             memcpy(&new_desc->parent.settings, &settings, sizeof(settings));
6055             new_desc->shader = gen_arbfp_ffp_shader(&settings, stateblock);
6056             add_ffp_frag_shader(&priv->fragment_shaders, &new_desc->parent);
6057             TRACE("Allocated fixed function replacement shader descriptor %p\n", new_desc);
6058             desc = new_desc;
6059         }
6060
6061         /* Now activate the replacement program. GL_FRAGMENT_PROGRAM_ARB is already active(however, note the
6062          * comment above the shader_select call below). If e.g. GLSL is active, the shader_select call will
6063          * deactivate it.
6064          */
6065         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader));
6066         checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, desc->shader)");
6067         priv->current_fprogram_id = desc->shader;
6068
6069         if(device->shader_backend == &arb_program_shader_backend && context->last_was_pshader) {
6070             /* Reload fixed function constants since they collide with the pixel shader constants */
6071             for(i = 0; i < MAX_TEXTURES; i++) {
6072                 set_bumpmat_arbfp(STATE_TEXTURESTAGE(i, WINED3DTSS_BUMPENVMAT00), stateblock, context);
6073             }
6074             state_texfactor_arbfp(STATE_RENDER(WINED3DRS_TEXTUREFACTOR), stateblock, context);
6075             state_arb_specularenable(STATE_RENDER(WINED3DRS_SPECULARENABLE), stateblock, context);
6076         }
6077         context->last_was_pshader = FALSE;
6078     } else {
6079         context->last_was_pshader = TRUE;
6080     }
6081
6082     /* Finally, select the shader. If a pixel shader is used, it will be set and enabled by the shader backend.
6083      * If this shader backend is arbfp(most likely), then it will simply overwrite the last fixed function replace-
6084      * ment shader. If the shader backend is not ARB, it currently is important that the opengl implementation
6085      * type overwrites GL_ARB_fragment_program. This is currently the case with GLSL. If we really want to use
6086      * atifs or nvrc pixel shaders with arb fragment programs we'd have to disable GL_FRAGMENT_PROGRAM_ARB here
6087      *
6088      * Don't call shader_select if the vertex shader is dirty, because it will be called later on by the vertex
6089      * shader handler
6090      */
6091     if(!isStateDirty(context, device->StateTable[STATE_VSHADER].representative)) {
6092         device->shader_backend->shader_select(context, use_pshader, use_vshader);
6093
6094         if (!isStateDirty(context, STATE_VERTEXSHADERCONSTANT) && (use_vshader || use_pshader))
6095             stateblock_apply_state(STATE_VERTEXSHADERCONSTANT, stateblock, context);
6096     }
6097     if (use_pshader) stateblock_apply_state(STATE_PIXELSHADERCONSTANT, stateblock, context);
6098 }
6099
6100 /* We can't link the fog states to the fragment state directly since the vertex pipeline links them
6101  * to FOGENABLE. A different linking in different pipeline parts can't be expressed in the combined
6102  * state table, so we need to handle that with a forwarding function. The other invisible side effect
6103  * is that changing the fog start and fog end(which links to FOGENABLE in vertex) results in the
6104  * fragment_prog_arbfp function being called because FOGENABLE is dirty, which calls this function here
6105  */
6106 static void state_arbfp_fog(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
6107 {
6108     enum fogsource new_source;
6109
6110     TRACE("state %#x, stateblock %p, context %p\n", state, stateblock, context);
6111
6112     if(!isStateDirty(context, STATE_PIXELSHADER)) {
6113         fragment_prog_arbfp(state, stateblock, context);
6114     }
6115
6116     if(!stateblock->renderState[WINED3DRS_FOGENABLE]) return;
6117
6118     if(stateblock->renderState[WINED3DRS_FOGTABLEMODE] == WINED3DFOG_NONE) {
6119         if(use_vs(stateblock)) {
6120             new_source = FOGSOURCE_VS;
6121         } else {
6122             if(stateblock->renderState[WINED3DRS_FOGVERTEXMODE] == WINED3DFOG_NONE || context->last_was_rhw) {
6123                 new_source = FOGSOURCE_COORD;
6124             } else {
6125                 new_source = FOGSOURCE_FFP;
6126             }
6127         }
6128     } else {
6129         new_source = FOGSOURCE_FFP;
6130     }
6131     if(new_source != context->fog_source) {
6132         context->fog_source = new_source;
6133         state_fogstartend(STATE_RENDER(WINED3DRS_FOGSTART), stateblock, context);
6134     }
6135 }
6136
6137 static void textransform(DWORD state, IWineD3DStateBlockImpl *stateblock, struct wined3d_context *context)
6138 {
6139     if(!isStateDirty(context, STATE_PIXELSHADER)) {
6140         fragment_prog_arbfp(state, stateblock, context);
6141     }
6142 }
6143
6144 #undef GLINFO_LOCATION
6145
6146 static const struct StateEntryTemplate arbfp_fragmentstate_template[] = {
6147     {STATE_RENDER(WINED3DRS_TEXTUREFACTOR),               { STATE_RENDER(WINED3DRS_TEXTUREFACTOR),              state_texfactor_arbfp   }, WINED3D_GL_EXT_NONE             },
6148     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6149     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6150     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6151     {STATE_TEXTURESTAGE(0, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6152     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6153     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6154     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6155     {STATE_TEXTURESTAGE(0, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6156     {STATE_TEXTURESTAGE(0, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6157     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6158     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6159     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6160     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6161     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6162     {STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(0, WINED3DTSS_BUMPENVLSCALE),    NULL                    }, WINED3D_GL_EXT_NONE             },
6163     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6164     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6165     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6166     {STATE_TEXTURESTAGE(1, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6167     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6168     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6169     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6170     {STATE_TEXTURESTAGE(1, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6171     {STATE_TEXTURESTAGE(1, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6172     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6173     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6174     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6175     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6176     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6177     {STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(1, WINED3DTSS_BUMPENVLSCALE),    NULL                    }, WINED3D_GL_EXT_NONE             },
6178     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6179     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6180     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6181     {STATE_TEXTURESTAGE(2, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6182     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6183     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6184     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6185     {STATE_TEXTURESTAGE(2, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6186     {STATE_TEXTURESTAGE(2, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6187     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6188     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6189     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6190     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6191     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6192     {STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(2, WINED3DTSS_BUMPENVLSCALE),    NULL                    }, WINED3D_GL_EXT_NONE             },
6193     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6194     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6195     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6196     {STATE_TEXTURESTAGE(3, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6197     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6198     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6199     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6200     {STATE_TEXTURESTAGE(3, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6201     {STATE_TEXTURESTAGE(3, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6202     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6203     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6204     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6205     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6206     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6207     {STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(3, WINED3DTSS_BUMPENVLSCALE),    NULL                    }, WINED3D_GL_EXT_NONE             },
6208     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6209     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6210     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6211     {STATE_TEXTURESTAGE(4, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6212     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6213     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6214     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6215     {STATE_TEXTURESTAGE(4, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6216     {STATE_TEXTURESTAGE(4, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6217     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6218     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6219     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6220     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6221     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6222     {STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(4, WINED3DTSS_BUMPENVLSCALE),    NULL                    }, WINED3D_GL_EXT_NONE             },
6223     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6224     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6225     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6226     {STATE_TEXTURESTAGE(5, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6227     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6228     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6229     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6230     {STATE_TEXTURESTAGE(5, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6231     {STATE_TEXTURESTAGE(5, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6232     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6233     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6234     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6235     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6236     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6237     {STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(5, WINED3DTSS_BUMPENVLSCALE),    NULL                    }, WINED3D_GL_EXT_NONE             },
6238     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6239     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6240     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6241     {STATE_TEXTURESTAGE(6, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6242     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6243     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6244     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6245     {STATE_TEXTURESTAGE(6, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6246     {STATE_TEXTURESTAGE(6, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6247     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6248     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6249     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6250     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6251     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6252     {STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(6, WINED3DTSS_BUMPENVLSCALE),    NULL                    }, WINED3D_GL_EXT_NONE             },
6253     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLOROP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6254     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6255     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6256     {STATE_TEXTURESTAGE(7, WINED3DTSS_COLORARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6257     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAOP),           { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6258     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG1),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6259     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG2),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6260     {STATE_TEXTURESTAGE(7, WINED3DTSS_ALPHAARG0),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6261     {STATE_TEXTURESTAGE(7, WINED3DTSS_RESULTARG),         { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6262     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     set_bumpmat_arbfp       }, WINED3D_GL_EXT_NONE             },
6263     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT01),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6264     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT10),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6265     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT11),      { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVMAT00),     NULL                    }, WINED3D_GL_EXT_NONE             },
6266     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),     { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),    tex_bumpenvlum_arbfp    }, WINED3D_GL_EXT_NONE             },
6267     {STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLOFFSET),    { STATE_TEXTURESTAGE(7, WINED3DTSS_BUMPENVLSCALE),    NULL                    }, WINED3D_GL_EXT_NONE             },
6268     {STATE_SAMPLER(0),                                    { STATE_SAMPLER(0),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6269     {STATE_SAMPLER(1),                                    { STATE_SAMPLER(1),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6270     {STATE_SAMPLER(2),                                    { STATE_SAMPLER(2),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6271     {STATE_SAMPLER(3),                                    { STATE_SAMPLER(3),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6272     {STATE_SAMPLER(4),                                    { STATE_SAMPLER(4),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6273     {STATE_SAMPLER(5),                                    { STATE_SAMPLER(5),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6274     {STATE_SAMPLER(6),                                    { STATE_SAMPLER(6),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6275     {STATE_SAMPLER(7),                                    { STATE_SAMPLER(7),                                   sampler_texdim          }, WINED3D_GL_EXT_NONE             },
6276     {STATE_PIXELSHADER,                                   { STATE_PIXELSHADER,                                  fragment_prog_arbfp     }, WINED3D_GL_EXT_NONE             },
6277     {STATE_RENDER(WINED3DRS_FOGENABLE),                   { STATE_RENDER(WINED3DRS_FOGENABLE),                  state_arbfp_fog         }, WINED3D_GL_EXT_NONE             },
6278     {STATE_RENDER(WINED3DRS_FOGTABLEMODE),                { STATE_RENDER(WINED3DRS_FOGENABLE),                  NULL                    }, WINED3D_GL_EXT_NONE             },
6279     {STATE_RENDER(WINED3DRS_FOGVERTEXMODE),               { STATE_RENDER(WINED3DRS_FOGENABLE),                  NULL                    }, WINED3D_GL_EXT_NONE             },
6280     {STATE_RENDER(WINED3DRS_FOGSTART),                    { STATE_RENDER(WINED3DRS_FOGSTART),                   state_fogstartend       }, WINED3D_GL_EXT_NONE             },
6281     {STATE_RENDER(WINED3DRS_FOGEND),                      { STATE_RENDER(WINED3DRS_FOGSTART),                   NULL                    }, WINED3D_GL_EXT_NONE             },
6282     {STATE_RENDER(WINED3DRS_SRGBWRITEENABLE),             { STATE_PIXELSHADER,                                  NULL                    }, WINED3D_GL_EXT_NONE             },
6283     {STATE_RENDER(WINED3DRS_FOGCOLOR),                    { STATE_RENDER(WINED3DRS_FOGCOLOR),                   state_fogcolor          }, WINED3D_GL_EXT_NONE             },
6284     {STATE_RENDER(WINED3DRS_FOGDENSITY),                  { STATE_RENDER(WINED3DRS_FOGDENSITY),                 state_fogdensity        }, WINED3D_GL_EXT_NONE             },
6285     {STATE_TEXTURESTAGE(0,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(0, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6286     {STATE_TEXTURESTAGE(1,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(1, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6287     {STATE_TEXTURESTAGE(2,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(2, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6288     {STATE_TEXTURESTAGE(3,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(3, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6289     {STATE_TEXTURESTAGE(4,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(4, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6290     {STATE_TEXTURESTAGE(5,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(5, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6291     {STATE_TEXTURESTAGE(6,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(6, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6292     {STATE_TEXTURESTAGE(7,WINED3DTSS_TEXTURETRANSFORMFLAGS),{STATE_TEXTURESTAGE(7, WINED3DTSS_TEXTURETRANSFORMFLAGS), textransform      }, WINED3D_GL_EXT_NONE             },
6293     {STATE_RENDER(WINED3DRS_SPECULARENABLE),              { STATE_RENDER(WINED3DRS_SPECULARENABLE),             state_arb_specularenable}, WINED3D_GL_EXT_NONE             },
6294     {0 /* Terminate */,                                   { 0,                                                  0                       }, WINED3D_GL_EXT_NONE             },
6295 };
6296
6297 const struct fragment_pipeline arbfp_fragment_pipeline = {
6298     arbfp_enable,
6299     arbfp_get_caps,
6300     arbfp_alloc,
6301     arbfp_free,
6302     shader_arb_color_fixup_supported,
6303     arbfp_fragmentstate_template,
6304     TRUE /* We can disable projected textures */
6305 };
6306
6307 #define GLINFO_LOCATION device->adapter->gl_info
6308
6309 struct arbfp_blit_priv {
6310     GLenum yuy2_rect_shader, yuy2_2d_shader;
6311     GLenum uyvy_rect_shader, uyvy_2d_shader;
6312     GLenum yv12_rect_shader, yv12_2d_shader;
6313     GLenum p8_rect_shader, p8_2d_shader;
6314     GLuint palette_texture;
6315 };
6316
6317 static HRESULT arbfp_blit_alloc(IWineD3DDevice *iface) {
6318     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
6319     device->blit_priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct arbfp_blit_priv));
6320     if(!device->blit_priv) {
6321         ERR("Out of memory\n");
6322         return E_OUTOFMEMORY;
6323     }
6324     return WINED3D_OK;
6325 }
6326
6327 /* Context activation is done by the caller. */
6328 static void arbfp_blit_free(IWineD3DDevice *iface) {
6329     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
6330     struct arbfp_blit_priv *priv = device->blit_priv;
6331
6332     ENTER_GL();
6333     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_rect_shader));
6334     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yuy2_2d_shader));
6335     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_rect_shader));
6336     GL_EXTCALL(glDeleteProgramsARB(1, &priv->uyvy_2d_shader));
6337     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yv12_rect_shader));
6338     GL_EXTCALL(glDeleteProgramsARB(1, &priv->yv12_2d_shader));
6339     GL_EXTCALL(glDeleteProgramsARB(1, &priv->p8_rect_shader));
6340     GL_EXTCALL(glDeleteProgramsARB(1, &priv->p8_2d_shader));
6341     checkGLcall("Delete yuv and p8 programs");
6342
6343     if(priv->palette_texture) glDeleteTextures(1, &priv->palette_texture);
6344     LEAVE_GL();
6345
6346     HeapFree(GetProcessHeap(), 0, device->blit_priv);
6347     device->blit_priv = NULL;
6348 }
6349
6350 static BOOL gen_planar_yuv_read(struct wined3d_shader_buffer *buffer, enum complex_fixup fixup,
6351         GLenum textype, char *luminance)
6352 {
6353     char chroma;
6354     const char *tex, *texinstr;
6355
6356     if (fixup == COMPLEX_FIXUP_UYVY) {
6357         chroma = 'x';
6358         *luminance = 'w';
6359     } else {
6360         chroma = 'w';
6361         *luminance = 'x';
6362     }
6363     switch(textype) {
6364         case GL_TEXTURE_2D:             tex = "2D";     texinstr = "TXP"; break;
6365         case GL_TEXTURE_RECTANGLE_ARB:  tex = "RECT";   texinstr = "TEX"; break;
6366         default:
6367             /* This is more tricky than just replacing the texture type - we have to navigate
6368              * properly in the texture to find the correct chroma values
6369              */
6370             FIXME("Implement yuv correction for non-2d, non-rect textures\n");
6371             return FALSE;
6372     }
6373
6374     /* First we have to read the chroma values. This means we need at least two pixels(no filtering),
6375      * or 4 pixels(with filtering). To get the unmodified chromas, we have to rid ourselves of the
6376      * filtering when we sample the texture.
6377      *
6378      * These are the rules for reading the chroma:
6379      *
6380      * Even pixel: Cr
6381      * Even pixel: U
6382      * Odd pixel: V
6383      *
6384      * So we have to get the sampling x position in non-normalized coordinates in integers
6385      */
6386     if(textype != GL_TEXTURE_RECTANGLE_ARB) {
6387         shader_addline(buffer, "MUL texcrd.xy, fragment.texcoord[0], size.x;\n");
6388         shader_addline(buffer, "MOV texcrd.w, size.x;\n");
6389     } else {
6390         shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
6391     }
6392     /* We must not allow filtering between pixel x and x+1, this would mix U and V
6393      * Vertical filtering is ok. However, bear in mind that the pixel center is at
6394      * 0.5, so add 0.5.
6395      */
6396     shader_addline(buffer, "FLR texcrd.x, texcrd.x;\n");
6397     shader_addline(buffer, "ADD texcrd.x, texcrd.x, coef.y;\n");
6398
6399     /* Divide the x coordinate by 0.5 and get the fraction. This gives 0.25 and 0.75 for the
6400      * even and odd pixels respectively
6401      */
6402     shader_addline(buffer, "MUL texcrd2, texcrd, coef.y;\n");
6403     shader_addline(buffer, "FRC texcrd2, texcrd2;\n");
6404
6405     /* Sample Pixel 1 */
6406     shader_addline(buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
6407
6408     /* Put the value into either of the chroma values */
6409     shader_addline(buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
6410     shader_addline(buffer, "MUL chroma.x, luminance.%c, temp.x;\n", chroma);
6411     shader_addline(buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
6412     shader_addline(buffer, "MUL chroma.y, luminance.%c, temp.x;\n", chroma);
6413
6414     /* Sample pixel 2. If we read an even pixel(SLT above returned 1), sample
6415      * the pixel right to the current one. Otherwise, sample the left pixel.
6416      * Bias and scale the SLT result to -1;1 and add it to the texcrd.x.
6417      */
6418     shader_addline(buffer, "MAD temp.x, temp.x, coef.z, -coef.x;\n");
6419     shader_addline(buffer, "ADD texcrd.x, texcrd, temp.x;\n");
6420     shader_addline(buffer, "%s luminance, texcrd, texture[0], %s;\n", texinstr, tex);
6421
6422     /* Put the value into the other chroma */
6423     shader_addline(buffer, "SGE temp.x, texcrd2.x, coef.y;\n");
6424     shader_addline(buffer, "MAD chroma.y, luminance.%c, temp.x, chroma.y;\n", chroma);
6425     shader_addline(buffer, "SLT temp.x, texcrd2.x, coef.y;\n");
6426     shader_addline(buffer, "MAD chroma.x, luminance.%c, temp.x, chroma.x;\n", chroma);
6427
6428     /* TODO: If filtering is enabled, sample a 2nd pair of pixels left or right of
6429      * the current one and lerp the two U and V values
6430      */
6431
6432     /* This gives the correctly filtered luminance value */
6433     shader_addline(buffer, "TEX luminance, fragment.texcoord[0], texture[0], %s;\n", tex);
6434
6435     return TRUE;
6436 }
6437
6438 static BOOL gen_yv12_read(struct wined3d_shader_buffer *buffer, GLenum textype, char *luminance)
6439 {
6440     const char *tex;
6441
6442     switch(textype) {
6443         case GL_TEXTURE_2D:             tex = "2D";     break;
6444         case GL_TEXTURE_RECTANGLE_ARB:  tex = "RECT";   break;
6445         default:
6446             FIXME("Implement yv12 correction for non-2d, non-rect textures\n");
6447             return FALSE;
6448     }
6449
6450     /* YV12 surfaces contain a WxH sized luminance plane, followed by a (W/2)x(H/2)
6451      * V and a (W/2)x(H/2) U plane, each with 8 bit per pixel. So the effective
6452      * bitdepth is 12 bits per pixel. Since the U and V planes have only half the
6453      * pitch of the luminance plane, the packing into the gl texture is a bit
6454      * unfortunate. If the whole texture is interpreted as luminance data it looks
6455      * approximately like this:
6456      *
6457      *        +----------------------------------+----
6458      *        |                                  |
6459      *        |                                  |
6460      *        |                                  |
6461      *        |                                  |
6462      *        |                                  |   2
6463      *        |            LUMINANCE             |   -
6464      *        |                                  |   3
6465      *        |                                  |
6466      *        |                                  |
6467      *        |                                  |
6468      *        |                                  |
6469      *        +----------------+-----------------+----
6470      *        |                |                 |
6471      *        |  U even rows   |  U odd rows     |
6472      *        |                |                 |   1
6473      *        +----------------+------------------   -
6474      *        |                |                 |   3
6475      *        |  V even rows   |  V odd rows     |
6476      *        |                |                 |
6477      *        +----------------+-----------------+----
6478      *        |                |                 |
6479      *        |     0.5        |       0.5       |
6480      *
6481      * So it appears as if there are 4 chroma images, but in fact the odd rows
6482      * in the chroma images are in the same row as the even ones. So its is
6483      * kinda tricky to read
6484      *
6485      * When reading from rectangle textures, keep in mind that the input y coordinates
6486      * go from 0 to d3d_height, whereas the opengl texture height is 1.5 * d3d_height
6487      */
6488     shader_addline(buffer, "PARAM yv12_coef = {%f, %f, %f, %f};\n",
6489             2.0f / 3.0f, 1.0f / 6.0f, (2.0f / 3.0f) + (1.0f / 6.0f), 1.0f / 3.0f);
6490
6491     shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
6492     /* the chroma planes have only half the width */
6493     shader_addline(buffer, "MUL texcrd.x, texcrd.x, coef.y;\n");
6494
6495     /* The first value is between 2/3 and 5/6th of the texture's height, so scale+bias
6496      * the coordinate. Also read the right side of the image when reading odd lines
6497      *
6498      * Don't forget to clamp the y values in into the range, otherwise we'll get filtering
6499      * bleeding
6500      */
6501     if(textype == GL_TEXTURE_2D) {
6502
6503         shader_addline(buffer, "RCP chroma.w, size.y;\n");
6504
6505         shader_addline(buffer, "MUL texcrd2.y, texcrd.y, size.y;\n");
6506
6507         shader_addline(buffer, "FLR texcrd2.y, texcrd2.y;\n");
6508         shader_addline(buffer, "MAD texcrd.y, texcrd.y, yv12_coef.y, yv12_coef.x;\n");
6509
6510         /* Read odd lines from the right side(add size * 0.5 to the x coordinate */
6511         shader_addline(buffer, "ADD texcrd2.x, texcrd2.y, yv12_coef.y;\n"); /* To avoid 0.5 == 0.5 comparisons */
6512         shader_addline(buffer, "FRC texcrd2.x, texcrd2.x;\n");
6513         shader_addline(buffer, "SGE texcrd2.x, texcrd2.x, coef.y;\n");
6514         shader_addline(buffer, "MAD texcrd.x, texcrd2.x, coef.y, texcrd.x;\n");
6515
6516         /* clamp, keep the half pixel origin in mind */
6517         shader_addline(buffer, "MAD temp.y, coef.y, chroma.w, yv12_coef.x;\n");
6518         shader_addline(buffer, "MAX texcrd.y, temp.y, texcrd.y;\n");
6519         shader_addline(buffer, "MAD temp.y, -coef.y, chroma.w, yv12_coef.z;\n");
6520         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
6521     } else {
6522         /* Read from [size - size+size/4] */
6523         shader_addline(buffer, "FLR texcrd.y, texcrd.y;\n");
6524         shader_addline(buffer, "MAD texcrd.y, texcrd.y, coef.w, size.y;\n");
6525
6526         /* Read odd lines from the right side(add size * 0.5 to the x coordinate */
6527         shader_addline(buffer, "ADD texcrd2.x, texcrd.y, yv12_coef.y;\n"); /* To avoid 0.5 == 0.5 comparisons */
6528         shader_addline(buffer, "FRC texcrd2.x, texcrd2.x;\n");
6529         shader_addline(buffer, "SGE texcrd2.x, texcrd2.x, coef.y;\n");
6530         shader_addline(buffer, "MUL texcrd2.x, texcrd2.x, size.x;\n");
6531         shader_addline(buffer, "MAD texcrd.x, texcrd2.x, coef.y, texcrd.x;\n");
6532
6533         /* Make sure to read exactly from the pixel center */
6534         shader_addline(buffer, "FLR texcrd.y, texcrd.y;\n");
6535         shader_addline(buffer, "ADD texcrd.y, texcrd.y, coef.y;\n");
6536
6537         /* Clamp */
6538         shader_addline(buffer, "MAD temp.y, size.y, coef.w, size.y;\n");
6539         shader_addline(buffer, "ADD temp.y, temp.y, -coef.y;\n");
6540         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
6541         shader_addline(buffer, "ADD temp.y, size.y, -coef.y;\n");
6542         shader_addline(buffer, "MAX texcrd.y, temp.y, texcrd.y;\n");
6543     }
6544     /* Read the texture, put the result into the output register */
6545     shader_addline(buffer, "TEX temp, texcrd, texture[0], %s;\n", tex);
6546     shader_addline(buffer, "MOV chroma.x, temp.w;\n");
6547
6548     /* The other chroma value is 1/6th of the texture lower, from 5/6th to 6/6th
6549      * No need to clamp because we're just reusing the already clamped value from above
6550      */
6551     if(textype == GL_TEXTURE_2D) {
6552         shader_addline(buffer, "ADD texcrd.y, texcrd.y, yv12_coef.y;\n");
6553     } else {
6554         shader_addline(buffer, "MAD texcrd.y, size.y, coef.w, texcrd.y;\n");
6555     }
6556     shader_addline(buffer, "TEX temp, texcrd, texture[0], %s;\n", tex);
6557     shader_addline(buffer, "MOV chroma.y, temp.w;\n");
6558
6559     /* Sample the luminance value. It is in the top 2/3rd of the texture, so scale the y coordinate.
6560      * Clamp the y coordinate to prevent the chroma values from bleeding into the sampled luminance
6561      * values due to filtering
6562      */
6563     shader_addline(buffer, "MOV texcrd, fragment.texcoord[0];\n");
6564     if(textype == GL_TEXTURE_2D) {
6565         /* Multiply the y coordinate by 2/3 and clamp it */
6566         shader_addline(buffer, "MUL texcrd.y, texcrd.y, yv12_coef.x;\n");
6567         shader_addline(buffer, "MAD temp.y, -coef.y, chroma.w, yv12_coef.x;\n");
6568         shader_addline(buffer, "MIN texcrd.y, temp.y, texcrd.y;\n");
6569         shader_addline(buffer, "TEX luminance, texcrd, texture[0], %s;\n", tex);
6570     } else {
6571         /* Reading from texture_rectangles is pretty straightforward, just use the unmodified
6572          * texture coordinate. It is still a good idea to clamp it though, since the opengl texture
6573          * is bigger
6574          */
6575         shader_addline(buffer, "ADD temp.x, size.y, -coef.y;\n");
6576         shader_addline(buffer, "MIN texcrd.y, texcrd.y, size.x;\n");
6577         shader_addline(buffer, "TEX luminance, texcrd, texture[0], %s;\n", tex);
6578     }
6579     *luminance = 'a';
6580
6581     return TRUE;
6582 }
6583
6584 static GLuint gen_p8_shader(IWineD3DDeviceImpl *device, GLenum textype)
6585 {
6586     GLenum shader;
6587     struct wined3d_shader_buffer buffer;
6588     struct arbfp_blit_priv *priv = device->blit_priv;
6589     GLint pos;
6590
6591     /* Shader header */
6592     if (!shader_buffer_init(&buffer))
6593     {
6594         ERR("Failed to initialize shader buffer.\n");
6595         return 0;
6596     }
6597
6598     ENTER_GL();
6599     GL_EXTCALL(glGenProgramsARB(1, &shader));
6600     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
6601     LEAVE_GL();
6602     if(!shader) {
6603         shader_buffer_free(&buffer);
6604         return 0;
6605     }
6606
6607     shader_addline(&buffer, "!!ARBfp1.0\n");
6608     shader_addline(&buffer, "TEMP index;\n");
6609
6610     /* { 255/256, 0.5/255*255/256, 0, 0 } */
6611     shader_addline(&buffer, "PARAM constants = { 0.996, 0.00195, 0, 0 };\n");
6612
6613     /* The alpha-component contains the palette index */
6614     if(textype == GL_TEXTURE_RECTANGLE_ARB)
6615         shader_addline(&buffer, "TXP index, fragment.texcoord[0], texture[0], RECT;\n");
6616     else
6617         shader_addline(&buffer, "TEX index, fragment.texcoord[0], texture[0], 2D;\n");
6618
6619     /* Scale the index by 255/256 and add a bias of '0.5' in order to sample in the middle */
6620     shader_addline(&buffer, "MAD index.a, index.a, constants.x, constants.y;\n");
6621
6622     /* Use the alpha-component as an index in the palette to get the final color */
6623     shader_addline(&buffer, "TEX result.color, index.a, texture[1], 1D;\n");
6624     shader_addline(&buffer, "END\n");
6625
6626     ENTER_GL();
6627     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
6628             strlen(buffer.buffer), buffer.buffer));
6629     checkGLcall("glProgramStringARB()");
6630
6631     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
6632     if (pos != -1)
6633     {
6634         FIXME("Fragment program error at position %d: %s\n\n", pos,
6635               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
6636         shader_arb_dump_program_source(buffer.buffer);
6637     }
6638
6639     if (textype == GL_TEXTURE_RECTANGLE_ARB)
6640         priv->p8_rect_shader = shader;
6641     else
6642         priv->p8_2d_shader = shader;
6643
6644     shader_buffer_free(&buffer);
6645     LEAVE_GL();
6646
6647     return shader;
6648 }
6649
6650 /* Context activation is done by the caller. */
6651 static void upload_palette(IWineD3DSurfaceImpl *surface)
6652 {
6653     BYTE table[256][4];
6654     IWineD3DDeviceImpl *device = surface->resource.device;
6655     struct arbfp_blit_priv *priv = device->blit_priv;
6656     BOOL colorkey = (surface->CKeyFlags & WINEDDSD_CKSRCBLT) ? TRUE : FALSE;
6657
6658     d3dfmt_p8_init_palette(surface, table, colorkey);
6659
6660     ENTER_GL();
6661     if (!priv->palette_texture)
6662         glGenTextures(1, &priv->palette_texture);
6663
6664     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE1));
6665     glBindTexture(GL_TEXTURE_1D, priv->palette_texture);
6666
6667     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
6668
6669     glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
6670     /* Make sure we have discrete color levels. */
6671     glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
6672     glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
6673     /* Upload the palette */
6674     /* TODO: avoid unneeed uploads in the future by adding some SFLAG_PALETTE_DIRTY mechanism */
6675     glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, table);
6676
6677     /* Switch back to unit 0 in which the 2D texture will be stored. */
6678     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0));
6679     LEAVE_GL();
6680 }
6681
6682 /* Context activation is done by the caller. */
6683 static GLuint gen_yuv_shader(IWineD3DDeviceImpl *device, enum complex_fixup yuv_fixup, GLenum textype)
6684 {
6685     GLenum shader;
6686     struct wined3d_shader_buffer buffer;
6687     char luminance_component;
6688     struct arbfp_blit_priv *priv = device->blit_priv;
6689     GLint pos;
6690
6691     /* Shader header */
6692     if (!shader_buffer_init(&buffer))
6693     {
6694         ERR("Failed to initialize shader buffer.\n");
6695         return 0;
6696     }
6697
6698     ENTER_GL();
6699     GL_EXTCALL(glGenProgramsARB(1, &shader));
6700     checkGLcall("GL_EXTCALL(glGenProgramsARB(1, &shader))");
6701     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
6702     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
6703     LEAVE_GL();
6704     if(!shader) {
6705         shader_buffer_free(&buffer);
6706         return 0;
6707     }
6708
6709     /* The YUY2 and UYVY formats contain two pixels packed into a 32 bit macropixel,
6710      * giving effectively 16 bit per pixel. The color consists of a luminance(Y) and
6711      * two chroma(U and V) values. Each macropixel has two luminance values, one for
6712      * each single pixel it contains, and one U and one V value shared between both
6713      * pixels.
6714      *
6715      * The data is loaded into an A8L8 texture. With YUY2, the luminance component
6716      * contains the luminance and alpha the chroma. With UYVY it is vice versa. Thus
6717      * take the format into account when generating the read swizzles
6718      *
6719      * Reading the Y value is straightforward - just sample the texture. The hardware
6720      * takes care of filtering in the horizontal and vertical direction.
6721      *
6722      * Reading the U and V values is harder. We have to avoid filtering horizontally,
6723      * because that would mix the U and V values of one pixel or two adjacent pixels.
6724      * Thus floor the texture coordinate and add 0.5 to get an unfiltered read,
6725      * regardless of the filtering setting. Vertical filtering works automatically
6726      * though - the U and V values of two rows are mixed nicely.
6727      *
6728      * Appart of avoiding filtering issues, the code has to know which value it just
6729      * read, and where it can find the other one. To determine this, it checks if
6730      * it sampled an even or odd pixel, and shifts the 2nd read accordingly.
6731      *
6732      * Handling horizontal filtering of U and V values requires reading a 2nd pair
6733      * of pixels, extracting U and V and mixing them. This is not implemented yet.
6734      *
6735      * An alternative implementation idea is to load the texture as A8R8G8B8 texture,
6736      * with width / 2. This way one read gives all 3 values, finding U and V is easy
6737      * in an unfiltered situation. Finding the luminance on the other hand requires
6738      * finding out if it is an odd or even pixel. The real drawback of this approach
6739      * is filtering. This would have to be emulated completely in the shader, reading
6740      * up two 2 packed pixels in up to 2 rows and interpolating both horizontally and
6741      * vertically. Beyond that it would require adjustments to the texture handling
6742      * code to deal with the width scaling
6743      */
6744     shader_addline(&buffer, "!!ARBfp1.0\n");
6745     shader_addline(&buffer, "TEMP luminance;\n");
6746     shader_addline(&buffer, "TEMP temp;\n");
6747     shader_addline(&buffer, "TEMP chroma;\n");
6748     shader_addline(&buffer, "TEMP texcrd;\n");
6749     shader_addline(&buffer, "TEMP texcrd2;\n");
6750     shader_addline(&buffer, "PARAM coef = {1.0, 0.5, 2.0, 0.25};\n");
6751     shader_addline(&buffer, "PARAM yuv_coef = {1.403, 0.344, 0.714, 1.770};\n");
6752     shader_addline(&buffer, "PARAM size = program.local[0];\n");
6753
6754     switch (yuv_fixup)
6755     {
6756         case COMPLEX_FIXUP_UYVY:
6757         case COMPLEX_FIXUP_YUY2:
6758             if (!gen_planar_yuv_read(&buffer, yuv_fixup, textype, &luminance_component))
6759             {
6760                 shader_buffer_free(&buffer);
6761                 return 0;
6762             }
6763             break;
6764
6765         case COMPLEX_FIXUP_YV12:
6766             if (!gen_yv12_read(&buffer, textype, &luminance_component))
6767             {
6768                 shader_buffer_free(&buffer);
6769                 return 0;
6770             }
6771             break;
6772
6773         default:
6774             FIXME("Unsupported YUV fixup %#x\n", yuv_fixup);
6775             shader_buffer_free(&buffer);
6776             return 0;
6777     }
6778
6779     /* Calculate the final result. Formula is taken from
6780      * http://www.fourcc.org/fccyvrgb.php. Note that the chroma
6781      * ranges from -0.5 to 0.5
6782      */
6783     shader_addline(&buffer, "SUB chroma.xy, chroma, coef.y;\n");
6784
6785     shader_addline(&buffer, "MAD result.color.x, chroma.x, yuv_coef.x, luminance.%c;\n", luminance_component);
6786     shader_addline(&buffer, "MAD temp.x, -chroma.y, yuv_coef.y, luminance.%c;\n", luminance_component);
6787     shader_addline(&buffer, "MAD result.color.y, -chroma.x, yuv_coef.z, temp.x;\n");
6788     shader_addline(&buffer, "MAD result.color.z, chroma.y, yuv_coef.w, luminance.%c;\n", luminance_component);
6789     shader_addline(&buffer, "END\n");
6790
6791     ENTER_GL();
6792     GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
6793             strlen(buffer.buffer), buffer.buffer));
6794     checkGLcall("glProgramStringARB()");
6795
6796     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
6797     if (pos != -1)
6798     {
6799         FIXME("Fragment program error at position %d: %s\n\n", pos,
6800               debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
6801         shader_arb_dump_program_source(buffer.buffer);
6802     }
6803     else
6804     {
6805         GLint native;
6806
6807         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native));
6808         checkGLcall("glGetProgramivARB()");
6809         if (!native) WARN("Program exceeds native resource limits.\n");
6810     }
6811
6812     shader_buffer_free(&buffer);
6813     LEAVE_GL();
6814
6815     switch (yuv_fixup)
6816     {
6817         case COMPLEX_FIXUP_YUY2:
6818             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->yuy2_rect_shader = shader;
6819             else priv->yuy2_2d_shader = shader;
6820             break;
6821
6822         case COMPLEX_FIXUP_UYVY:
6823             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->uyvy_rect_shader = shader;
6824             else priv->uyvy_2d_shader = shader;
6825             break;
6826
6827         case COMPLEX_FIXUP_YV12:
6828             if (textype == GL_TEXTURE_RECTANGLE_ARB) priv->yv12_rect_shader = shader;
6829             else priv->yv12_2d_shader = shader;
6830             break;
6831         default:
6832             ERR("Unsupported complex fixup: %d\n", yuv_fixup);
6833     }
6834
6835     return shader;
6836 }
6837
6838 /* Context activation is done by the caller. */
6839 static HRESULT arbfp_blit_set(IWineD3DDevice *iface, IWineD3DSurfaceImpl *surface)
6840 {
6841     GLenum shader;
6842     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
6843     float size[4] = {surface->pow2Width, surface->pow2Height, 1, 1};
6844     struct arbfp_blit_priv *priv = device->blit_priv;
6845     enum complex_fixup fixup;
6846     GLenum textype = surface->texture_target;
6847
6848     if (!is_complex_fixup(surface->resource.format_desc->color_fixup))
6849     {
6850         TRACE("Fixup:\n");
6851         dump_color_fixup_desc(surface->resource.format_desc->color_fixup);
6852         /* Don't bother setting up a shader for unconverted formats */
6853         ENTER_GL();
6854         glEnable(textype);
6855         checkGLcall("glEnable(textype)");
6856         LEAVE_GL();
6857         return WINED3D_OK;
6858     }
6859
6860     fixup = get_complex_fixup(surface->resource.format_desc->color_fixup);
6861
6862     switch(fixup)
6863     {
6864         case COMPLEX_FIXUP_YUY2:
6865             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->yuy2_rect_shader : priv->yuy2_2d_shader;
6866             break;
6867
6868         case COMPLEX_FIXUP_UYVY:
6869             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->uyvy_rect_shader : priv->uyvy_2d_shader;
6870             break;
6871
6872         case COMPLEX_FIXUP_YV12:
6873             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->yv12_rect_shader : priv->yv12_2d_shader;
6874             break;
6875
6876         case COMPLEX_FIXUP_P8:
6877             shader = textype == GL_TEXTURE_RECTANGLE_ARB ? priv->p8_rect_shader : priv->p8_2d_shader;
6878             if (!shader) shader = gen_p8_shader(device, textype);
6879
6880             upload_palette(surface);
6881             break;
6882
6883         default:
6884             FIXME("Unsupported complex fixup %#x, not setting a shader\n", fixup);
6885             ENTER_GL();
6886             glEnable(textype);
6887             checkGLcall("glEnable(textype)");
6888             LEAVE_GL();
6889             return E_NOTIMPL;
6890     }
6891
6892     if (!shader) shader = gen_yuv_shader(device, fixup, textype);
6893
6894     ENTER_GL();
6895     glEnable(GL_FRAGMENT_PROGRAM_ARB);
6896     checkGLcall("glEnable(GL_FRAGMENT_PROGRAM_ARB)");
6897     GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader));
6898     checkGLcall("glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader)");
6899     GL_EXTCALL(glProgramLocalParameter4fvARB(GL_FRAGMENT_PROGRAM_ARB, 0, size));
6900     checkGLcall("glProgramLocalParameter4fvARB");
6901     LEAVE_GL();
6902
6903     return WINED3D_OK;
6904 }
6905
6906 /* Context activation is done by the caller. */
6907 static void arbfp_blit_unset(IWineD3DDevice *iface) {
6908     IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) iface;
6909     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
6910
6911     ENTER_GL();
6912     glDisable(GL_FRAGMENT_PROGRAM_ARB);
6913     checkGLcall("glDisable(GL_FRAGMENT_PROGRAM_ARB)");
6914     glDisable(GL_TEXTURE_2D);
6915     checkGLcall("glDisable(GL_TEXTURE_2D)");
6916     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
6917     {
6918         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
6919         checkGLcall("glDisable(GL_TEXTURE_CUBE_MAP_ARB)");
6920     }
6921     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
6922     {
6923         glDisable(GL_TEXTURE_RECTANGLE_ARB);
6924         checkGLcall("glDisable(GL_TEXTURE_RECTANGLE_ARB)");
6925     }
6926     LEAVE_GL();
6927 }
6928
6929 static BOOL arbfp_blit_supported(const struct wined3d_gl_info *gl_info, enum blit_operation blit_op,
6930                                  const RECT *src_rect, DWORD src_usage, WINED3DPOOL src_pool,
6931                                  const struct wined3d_format_desc *src_format_desc,
6932                                  const RECT *dst_rect, DWORD dst_usage, WINED3DPOOL dst_pool,
6933                                  const struct wined3d_format_desc *dst_format_desc)
6934 {
6935     enum complex_fixup src_fixup;
6936
6937     if (blit_op != BLIT_OP_BLIT)
6938     {
6939         TRACE("Unsupported blit_op=%d\n", blit_op);
6940         return FALSE;
6941     }
6942
6943     src_fixup = get_complex_fixup(src_format_desc->color_fixup);
6944     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
6945     {
6946         TRACE("Checking support for fixup:\n");
6947         dump_color_fixup_desc(src_format_desc->color_fixup);
6948     }
6949
6950     if (!is_identity_fixup(dst_format_desc->color_fixup))
6951     {
6952         TRACE("Destination fixups are not supported\n");
6953         return FALSE;
6954     }
6955
6956     if (is_identity_fixup(src_format_desc->color_fixup))
6957     {
6958         TRACE("[OK]\n");
6959         return TRUE;
6960     }
6961
6962      /* We only support YUV conversions. */
6963     if (!is_complex_fixup(src_format_desc->color_fixup))
6964     {
6965         TRACE("[FAILED]\n");
6966         return FALSE;
6967     }
6968
6969     switch(src_fixup)
6970     {
6971         case COMPLEX_FIXUP_YUY2:
6972         case COMPLEX_FIXUP_UYVY:
6973         case COMPLEX_FIXUP_YV12:
6974         case COMPLEX_FIXUP_P8:
6975             TRACE("[OK]\n");
6976             return TRUE;
6977
6978         default:
6979             FIXME("Unsupported YUV fixup %#x\n", src_fixup);
6980             TRACE("[FAILED]\n");
6981             return FALSE;
6982     }
6983 }
6984
6985 HRESULT arbfp_blit_surface(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *src_surface, const RECT *src_rect,
6986                            IWineD3DSurfaceImpl *dst_surface, const RECT *dst_rect_in, enum blit_operation blit_op,
6987                            DWORD Filter)
6988 {
6989     IWineD3DSwapChainImpl *dst_swapchain;
6990     struct wined3d_context *context;
6991     RECT dst_rect = *dst_rect_in;
6992
6993     /* Now load the surface */
6994     surface_internal_preload(src_surface, SRGB_RGB);
6995
6996     /* Activate the destination context, set it up for blitting */
6997     context = context_acquire(device, dst_surface);
6998     context_apply_blit_state(context, device);
6999
7000     /* The coordinates of the ddraw front buffer are always fullscreen ('screen coordinates',
7001      * while OpenGL coordinates are window relative.
7002      * Also beware of the origin difference(top left vs bottom left).
7003      * Also beware that the front buffer's surface size is screen width x screen height,
7004      * whereas the real gl drawable size is the size of the window. */
7005     dst_swapchain = (dst_surface->Flags & SFLAG_SWAPCHAIN) ? (IWineD3DSwapChainImpl *)dst_surface->container : NULL;
7006     if (dst_swapchain && dst_surface == dst_swapchain->front_buffer)
7007         surface_translate_frontbuffer_coords(dst_surface, context->win_handle, &dst_rect);
7008
7009     arbfp_blit_set((IWineD3DDevice *)device, src_surface);
7010
7011     ENTER_GL();
7012
7013     /* Draw a textured quad */
7014     draw_textured_quad(src_surface, src_rect, &dst_rect, Filter);
7015
7016     LEAVE_GL();
7017
7018     /* Leave the opengl state valid for blitting */
7019     arbfp_blit_unset((IWineD3DDevice *)device);
7020
7021     if (wined3d_settings.strict_draw_ordering || (dst_swapchain
7022             && (dst_surface == dst_swapchain->front_buffer
7023             || dst_swapchain->num_contexts > 1)))
7024         wglFlush(); /* Flush to ensure ordering across contexts. */
7025
7026     context_release(context);
7027
7028     IWineD3DSurface_ModifyLocation((IWineD3DSurface *)dst_surface, SFLAG_INDRAWABLE, TRUE);
7029     return WINED3D_OK;
7030 }
7031
7032 static HRESULT arbfp_blit_color_fill(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *dst_surface, const RECT *dst_rect, DWORD fill_color)
7033 {
7034     FIXME("Color filling not implemented by arbfp_blit\n");
7035     return WINED3DERR_INVALIDCALL;
7036 }
7037
7038 const struct blit_shader arbfp_blit = {
7039     arbfp_blit_alloc,
7040     arbfp_blit_free,
7041     arbfp_blit_set,
7042     arbfp_blit_unset,
7043     arbfp_blit_supported,
7044     arbfp_blit_color_fill
7045 };
7046
7047 #undef GLINFO_LOCATION