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