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