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