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