d3d8: Check for D3DPOOL_DEFAULT resources before doing a Reset().
[wine] / dlls / wined3d / shader.c
1 /*
2  * Copyright 2002-2003 Jason Edmeades
3  * Copyright 2002-2003 Raphael Junqueira
4  * Copyright 2004 Christian Costa
5  * Copyright 2005 Oliver Stieber
6  * Copyright 2006 Ivan Gyurdiev
7  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
8  * Copyright 2009-2011 Henri Verbeet for CodeWeavers
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26
27 #include <math.h>
28 #include <stdio.h>
29 #include <string.h>
30
31 #include "wined3d_private.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
34 WINE_DECLARE_DEBUG_CHANNEL(d3d);
35
36 static const char * const shader_opcode_names[] =
37 {
38     /* WINED3DSIH_ABS           */ "abs",
39     /* WINED3DSIH_ADD           */ "add",
40     /* WINED3DSIH_AND           */ "and",
41     /* WINED3DSIH_BEM           */ "bem",
42     /* WINED3DSIH_BREAK         */ "break",
43     /* WINED3DSIH_BREAKC        */ "breakc",
44     /* WINED3DSIH_BREAKP        */ "breakp",
45     /* WINED3DSIH_CALL          */ "call",
46     /* WINED3DSIH_CALLNZ        */ "callnz",
47     /* WINED3DSIH_CMP           */ "cmp",
48     /* WINED3DSIH_CND           */ "cnd",
49     /* WINED3DSIH_CRS           */ "crs",
50     /* WINED3DSIH_CUT           */ "cut",
51     /* WINED3DSIH_DCL           */ "dcl",
52     /* WINED3DSIH_DEF           */ "def",
53     /* WINED3DSIH_DEFB          */ "defb",
54     /* WINED3DSIH_DEFI          */ "defi",
55     /* WINED3DSIH_DIV           */ "div",
56     /* WINED3DSIH_DP2ADD        */ "dp2add",
57     /* WINED3DSIH_DP3           */ "dp3",
58     /* WINED3DSIH_DP4           */ "dp4",
59     /* WINED3DSIH_DST           */ "dst",
60     /* WINED3DSIH_DSX           */ "dsx",
61     /* WINED3DSIH_DSY           */ "dsy",
62     /* WINED3DSIH_ELSE          */ "else",
63     /* WINED3DSIH_EMIT          */ "emit",
64     /* WINED3DSIH_ENDIF         */ "endif",
65     /* WINED3DSIH_ENDLOOP       */ "endloop",
66     /* WINED3DSIH_ENDREP        */ "endrep",
67     /* WINED3DSIH_EXP           */ "exp",
68     /* WINED3DSIH_EXPP          */ "expp",
69     /* WINED3DSIH_FRC           */ "frc",
70     /* WINED3DSIH_FTOI          */ "ftoi",
71     /* WINED3DSIH_IADD          */ "iadd",
72     /* WINED3DSIH_IEQ           */ "ieq",
73     /* WINED3DSIH_IF            */ "if",
74     /* WINED3DSIH_IFC           */ "ifc",
75     /* WINED3DSIH_IGE           */ "ige",
76     /* WINED3DSIH_IMUL          */ "imul",
77     /* WINED3DSIH_ITOF          */ "itof",
78     /* WINED3DSIH_LABEL         */ "label",
79     /* WINED3DSIH_LD            */ "ld",
80     /* WINED3DSIH_LIT           */ "lit",
81     /* WINED3DSIH_LOG           */ "log",
82     /* WINED3DSIH_LOGP          */ "logp",
83     /* WINED3DSIH_LOOP          */ "loop",
84     /* WINED3DSIH_LRP           */ "lrp",
85     /* WINED3DSIH_LT            */ "lt",
86     /* WINED3DSIH_M3x2          */ "m3x2",
87     /* WINED3DSIH_M3x3          */ "m3x3",
88     /* WINED3DSIH_M3x4          */ "m3x4",
89     /* WINED3DSIH_M4x3          */ "m4x3",
90     /* WINED3DSIH_M4x4          */ "m4x4",
91     /* WINED3DSIH_MAD           */ "mad",
92     /* WINED3DSIH_MAX           */ "max",
93     /* WINED3DSIH_MIN           */ "min",
94     /* WINED3DSIH_MOV           */ "mov",
95     /* WINED3DSIH_MOVA          */ "mova",
96     /* WINED3DSIH_MOVC          */ "movc",
97     /* WINED3DSIH_MUL           */ "mul",
98     /* WINED3DSIH_NOP           */ "nop",
99     /* WINED3DSIH_NRM           */ "nrm",
100     /* WINED3DSIH_PHASE         */ "phase",
101     /* WINED3DSIH_POW           */ "pow",
102     /* WINED3DSIH_RCP           */ "rcp",
103     /* WINED3DSIH_REP           */ "rep",
104     /* WINED3DSIH_RET           */ "ret",
105     /* WINED3DSIH_RSQ           */ "rsq",
106     /* WINED3DSIH_SAMPLE        */ "sample",
107     /* WINED3DSIH_SAMPLE_GRAD   */ "sample_d",
108     /* WINED3DSIH_SAMPLE_LOD    */ "sample_l",
109     /* WINED3DSIH_SETP          */ "setp",
110     /* WINED3DSIH_SGE           */ "sge",
111     /* WINED3DSIH_SGN           */ "sgn",
112     /* WINED3DSIH_SINCOS        */ "sincos",
113     /* WINED3DSIH_SLT           */ "slt",
114     /* WINED3DSIH_SQRT          */ "sqrt",
115     /* WINED3DSIH_SUB           */ "sub",
116     /* WINED3DSIH_TEX           */ "texld",
117     /* WINED3DSIH_TEXBEM        */ "texbem",
118     /* WINED3DSIH_TEXBEML       */ "texbeml",
119     /* WINED3DSIH_TEXCOORD      */ "texcrd",
120     /* WINED3DSIH_TEXDEPTH      */ "texdepth",
121     /* WINED3DSIH_TEXDP3        */ "texdp3",
122     /* WINED3DSIH_TEXDP3TEX     */ "texdp3tex",
123     /* WINED3DSIH_TEXKILL       */ "texkill",
124     /* WINED3DSIH_TEXLDD        */ "texldd",
125     /* WINED3DSIH_TEXLDL        */ "texldl",
126     /* WINED3DSIH_TEXM3x2DEPTH  */ "texm3x2depth",
127     /* WINED3DSIH_TEXM3x2PAD    */ "texm3x2pad",
128     /* WINED3DSIH_TEXM3x2TEX    */ "texm3x2tex",
129     /* WINED3DSIH_TEXM3x3       */ "texm3x3",
130     /* WINED3DSIH_TEXM3x3DIFF   */ "texm3x3diff",
131     /* WINED3DSIH_TEXM3x3PAD    */ "texm3x3pad",
132     /* WINED3DSIH_TEXM3x3SPEC   */ "texm3x3spec",
133     /* WINED3DSIH_TEXM3x3TEX    */ "texm3x3tex",
134     /* WINED3DSIH_TEXM3x3VSPEC  */ "texm3x3vspec",
135     /* WINED3DSIH_TEXREG2AR     */ "texreg2ar",
136     /* WINED3DSIH_TEXREG2GB     */ "texreg2gb",
137     /* WINED3DSIH_TEXREG2RGB    */ "texreg2rgb",
138     /* WINED3DSIH_UTOF          */ "utof",
139 };
140
141 static const char * const semantic_names[] =
142 {
143     /* WINED3DDECLUSAGE_POSITION        */ "SV_POSITION",
144     /* WINED3DDECLUSAGE_BLENDWEIGHT     */ "BLENDWEIGHT",
145     /* WINED3DDECLUSAGE_BLENDINDICES    */ "BLENDINDICES",
146     /* WINED3DDECLUSAGE_NORMAL          */ "NORMAL",
147     /* WINED3DDECLUSAGE_PSIZE           */ "PSIZE",
148     /* WINED3DDECLUSAGE_TEXCOORD        */ "TEXCOORD",
149     /* WINED3DDECLUSAGE_TANGENT         */ "TANGENT",
150     /* WINED3DDECLUSAGE_BINORMAL        */ "BINORMAL",
151     /* WINED3DDECLUSAGE_TESSFACTOR      */ "TESSFACTOR",
152     /* WINED3DDECLUSAGE_POSITIONT       */ "POSITIONT",
153     /* WINED3DDECLUSAGE_COLOR           */ "COLOR",
154     /* WINED3DDECLUSAGE_FOG             */ "FOG",
155     /* WINED3DDECLUSAGE_DEPTH           */ "DEPTH",
156     /* WINED3DDECLUSAGE_SAMPLE          */ "SAMPLE",
157 };
158
159 static const char *shader_semantic_name_from_usage(WINED3DDECLUSAGE usage)
160 {
161     if (usage >= sizeof(semantic_names) / sizeof(*semantic_names))
162     {
163         FIXME("Unrecognized usage %#x.\n", usage);
164         return "UNRECOGNIZED";
165     }
166
167     return semantic_names[usage];
168 }
169
170 static WINED3DDECLUSAGE shader_usage_from_semantic_name(const char *name)
171 {
172     unsigned int i;
173
174     for (i = 0; i < sizeof(semantic_names) / sizeof(*semantic_names); ++i)
175     {
176         if (!strcmp(name, semantic_names[i])) return i;
177     }
178
179     return ~0U;
180 }
181
182 BOOL shader_match_semantic(const char *semantic_name, WINED3DDECLUSAGE usage)
183 {
184     return !strcmp(semantic_name, shader_semantic_name_from_usage(usage));
185 }
186
187 static void shader_signature_from_semantic(struct wined3d_shader_signature_element *e,
188         const struct wined3d_shader_semantic *s)
189 {
190     e->semantic_name = shader_semantic_name_from_usage(s->usage);
191     e->semantic_idx = s->usage_idx;
192     e->sysval_semantic = 0;
193     e->component_type = 0;
194     e->register_idx = s->reg.reg.idx;
195     e->mask = s->reg.write_mask;
196 }
197
198 static void shader_signature_from_usage(struct wined3d_shader_signature_element *e,
199         WINED3DDECLUSAGE usage, UINT usage_idx, UINT reg_idx, DWORD write_mask)
200 {
201     e->semantic_name = shader_semantic_name_from_usage(usage);
202     e->semantic_idx = usage_idx;
203     e->sysval_semantic = 0;
204     e->component_type = 0;
205     e->register_idx = reg_idx;
206     e->mask = write_mask;
207 }
208
209 static const struct wined3d_shader_frontend *shader_select_frontend(DWORD version_token)
210 {
211     switch (version_token >> 16)
212     {
213         case WINED3D_SM1_VS:
214         case WINED3D_SM1_PS:
215             return &sm1_shader_frontend;
216
217         case WINED3D_SM4_PS:
218         case WINED3D_SM4_VS:
219         case WINED3D_SM4_GS:
220             return &sm4_shader_frontend;
221
222         default:
223             FIXME("Unrecognised version token %#x\n", version_token);
224             return NULL;
225     }
226 }
227
228 void shader_buffer_clear(struct wined3d_shader_buffer *buffer)
229 {
230     buffer->buffer[0] = '\0';
231     buffer->bsize = 0;
232     buffer->lineNo = 0;
233     buffer->newline = TRUE;
234 }
235
236 BOOL shader_buffer_init(struct wined3d_shader_buffer *buffer)
237 {
238     buffer->buffer = HeapAlloc(GetProcessHeap(), 0, SHADER_PGMSIZE);
239     if (!buffer->buffer)
240     {
241         ERR("Failed to allocate shader buffer memory.\n");
242         return FALSE;
243     }
244
245     shader_buffer_clear(buffer);
246     return TRUE;
247 }
248
249 void shader_buffer_free(struct wined3d_shader_buffer *buffer)
250 {
251     HeapFree(GetProcessHeap(), 0, buffer->buffer);
252 }
253
254 int shader_vaddline(struct wined3d_shader_buffer *buffer, const char *format, va_list args)
255 {
256     char *base = buffer->buffer + buffer->bsize;
257     int rc;
258
259     rc = vsnprintf(base, SHADER_PGMSIZE - 1 - buffer->bsize, format, args);
260
261     if (rc < 0 /* C89 */ || (unsigned int)rc > SHADER_PGMSIZE - 1 - buffer->bsize /* C99 */)
262     {
263         ERR("The buffer allocated for the shader program string "
264             "is too small at %d bytes.\n", SHADER_PGMSIZE);
265         buffer->bsize = SHADER_PGMSIZE - 1;
266         return -1;
267     }
268
269     if (buffer->newline)
270     {
271         TRACE("GL HW (%u, %u) : %s", buffer->lineNo + 1, buffer->bsize, base);
272         buffer->newline = FALSE;
273     }
274     else
275     {
276         TRACE("%s", base);
277     }
278
279     buffer->bsize += rc;
280     if (buffer->buffer[buffer->bsize-1] == '\n')
281     {
282         ++buffer->lineNo;
283         buffer->newline = TRUE;
284     }
285
286     return 0;
287 }
288
289 int shader_addline(struct wined3d_shader_buffer *buffer, const char *format, ...)
290 {
291     va_list args;
292     int ret;
293
294     va_start(args, format);
295     ret = shader_vaddline(buffer, format, args);
296     va_end(args);
297
298     return ret;
299 }
300
301 static void shader_init(struct wined3d_shader *shader, IWineD3DDeviceImpl *device,
302         void *parent, const struct wined3d_parent_ops *parent_ops)
303 {
304     shader->ref = 1;
305     shader->device = device;
306     shader->parent = parent;
307     shader->parent_ops = parent_ops;
308     list_init(&shader->linked_programs);
309     list_add_head(&device->shaders, &shader->shader_list_entry);
310 }
311
312 /* Convert floating point offset relative to a register file to an absolute
313  * offset for float constants. */
314 static unsigned int shader_get_float_offset(WINED3DSHADER_PARAM_REGISTER_TYPE register_type, UINT register_idx)
315 {
316     switch (register_type)
317     {
318         case WINED3DSPR_CONST: return register_idx;
319         case WINED3DSPR_CONST2: return 2048 + register_idx;
320         case WINED3DSPR_CONST3: return 4096 + register_idx;
321         case WINED3DSPR_CONST4: return 6144 + register_idx;
322         default:
323             FIXME("Unsupported register type: %u.\n", register_type);
324             return register_idx;
325     }
326 }
327
328 static void shader_delete_constant_list(struct list *clist)
329 {
330     struct local_constant *constant;
331     struct list *ptr;
332
333     ptr = list_head(clist);
334     while (ptr)
335     {
336         constant = LIST_ENTRY(ptr, struct local_constant, entry);
337         ptr = list_next(clist, ptr);
338         HeapFree(GetProcessHeap(), 0, constant);
339     }
340     list_init(clist);
341 }
342
343 static inline void set_bitmap_bit(DWORD *bitmap, DWORD bit)
344 {
345     DWORD idx, shift;
346     idx = bit >> 5;
347     shift = bit & 0x1f;
348     bitmap[idx] |= (1 << shift);
349 }
350
351 static void shader_record_register_usage(struct wined3d_shader *shader, struct wined3d_shader_reg_maps *reg_maps,
352         const struct wined3d_shader_register *reg, enum wined3d_shader_type shader_type)
353 {
354     switch (reg->type)
355     {
356         case WINED3DSPR_TEXTURE: /* WINED3DSPR_ADDR */
357             if (shader_type == WINED3D_SHADER_TYPE_PIXEL) reg_maps->texcoord |= 1 << reg->idx;
358             else reg_maps->address |= 1 << reg->idx;
359             break;
360
361         case WINED3DSPR_TEMP:
362             reg_maps->temporary |= 1 << reg->idx;
363             break;
364
365         case WINED3DSPR_INPUT:
366             if (shader_type == WINED3D_SHADER_TYPE_PIXEL)
367             {
368                 if (reg->rel_addr)
369                 {
370                     /* If relative addressing is used, we must assume that all registers
371                      * are used. Even if it is a construct like v3[aL], we can't assume
372                      * that v0, v1 and v2 aren't read because aL can be negative */
373                     unsigned int i;
374                     for (i = 0; i < MAX_REG_INPUT; ++i)
375                     {
376                         shader->u.ps.input_reg_used[i] = TRUE;
377                     }
378                 }
379                 else
380                 {
381                     shader->u.ps.input_reg_used[reg->idx] = TRUE;
382                 }
383             }
384             else reg_maps->input_registers |= 1 << reg->idx;
385             break;
386
387         case WINED3DSPR_RASTOUT:
388             if (reg->idx == 1) reg_maps->fog = 1;
389             break;
390
391         case WINED3DSPR_MISCTYPE:
392             if (shader_type == WINED3D_SHADER_TYPE_PIXEL)
393             {
394                 if (!reg->idx) reg_maps->vpos = 1;
395                 else if (reg->idx == 1) reg_maps->usesfacing = 1;
396             }
397             break;
398
399         case WINED3DSPR_CONST:
400             if (reg->rel_addr)
401             {
402                 if (reg->idx < reg_maps->min_rel_offset) reg_maps->min_rel_offset = reg->idx;
403                 if (reg->idx > reg_maps->max_rel_offset) reg_maps->max_rel_offset = reg->idx;
404                 reg_maps->usesrelconstF = TRUE;
405             }
406             else
407             {
408                 set_bitmap_bit(reg_maps->constf, reg->idx);
409             }
410             break;
411
412         case WINED3DSPR_CONSTINT:
413             reg_maps->integer_constants |= (1 << reg->idx);
414             break;
415
416         case WINED3DSPR_CONSTBOOL:
417             reg_maps->boolean_constants |= (1 << reg->idx);
418             break;
419
420         case WINED3DSPR_COLOROUT:
421             reg_maps->highest_render_target = max(reg_maps->highest_render_target, reg->idx);
422             break;
423
424         default:
425             TRACE("Not recording register of type %#x and idx %u\n", reg->type, reg->idx);
426             break;
427     }
428 }
429
430 static unsigned int get_instr_extra_regcount(enum WINED3D_SHADER_INSTRUCTION_HANDLER instr, unsigned int param)
431 {
432     switch (instr)
433     {
434         case WINED3DSIH_M4x4:
435         case WINED3DSIH_M3x4:
436             return param == 1 ? 3 : 0;
437
438         case WINED3DSIH_M4x3:
439         case WINED3DSIH_M3x3:
440             return param == 1 ? 2 : 0;
441
442         case WINED3DSIH_M3x2:
443             return param == 1 ? 1 : 0;
444
445         default:
446             return 0;
447     }
448 }
449
450 /* Note that this does not count the loop register as an address register. */
451 static HRESULT shader_get_registers_used(struct wined3d_shader *shader, const struct wined3d_shader_frontend *fe,
452         struct wined3d_shader_reg_maps *reg_maps, struct wined3d_shader_signature_element *input_signature,
453         struct wined3d_shader_signature_element *output_signature, const DWORD *byte_code, DWORD constf_size)
454 {
455     unsigned int cur_loop_depth = 0, max_loop_depth = 0;
456     void *fe_data = shader->frontend_data;
457     struct wined3d_shader_version shader_version;
458     const DWORD *ptr = byte_code;
459
460     memset(reg_maps, 0, sizeof(*reg_maps));
461     reg_maps->min_rel_offset = ~0U;
462
463     fe->shader_read_header(fe_data, &ptr, &shader_version);
464     reg_maps->shader_version = shader_version;
465
466     reg_maps->constf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
467             sizeof(*reg_maps->constf) * ((constf_size + 31) / 32));
468     if (!reg_maps->constf)
469     {
470         ERR("Failed to allocate constant map memory.\n");
471         return E_OUTOFMEMORY;
472     }
473
474     while (!fe->shader_is_end(fe_data, &ptr))
475     {
476         struct wined3d_shader_instruction ins;
477         const char *comment;
478         UINT comment_size;
479         UINT param_size;
480
481         /* Skip comments. */
482         fe->shader_read_comment(&ptr, &comment, &comment_size);
483         if (comment) continue;
484
485         /* Fetch opcode. */
486         fe->shader_read_opcode(fe_data, &ptr, &ins, &param_size);
487
488         /* Unhandled opcode, and its parameters. */
489         if (ins.handler_idx == WINED3DSIH_TABLE_SIZE)
490         {
491             TRACE("Skipping unrecognized instruction.\n");
492             ptr += param_size;
493             continue;
494         }
495
496         /* Handle declarations. */
497         if (ins.handler_idx == WINED3DSIH_DCL)
498         {
499             struct wined3d_shader_semantic semantic;
500
501             fe->shader_read_semantic(&ptr, &semantic);
502
503             switch (semantic.reg.reg.type)
504             {
505                 /* Mark input registers used. */
506                 case WINED3DSPR_INPUT:
507                     reg_maps->input_registers |= 1 << semantic.reg.reg.idx;
508                     shader_signature_from_semantic(&input_signature[semantic.reg.reg.idx], &semantic);
509                     break;
510
511                 /* Vertex shader: mark 3.0 output registers used, save token. */
512                 case WINED3DSPR_OUTPUT:
513                     reg_maps->output_registers |= 1 << semantic.reg.reg.idx;
514                     shader_signature_from_semantic(&output_signature[semantic.reg.reg.idx], &semantic);
515                     if (semantic.usage == WINED3DDECLUSAGE_FOG) reg_maps->fog = 1;
516                     break;
517
518                 /* Save sampler usage token. */
519                 case WINED3DSPR_SAMPLER:
520                     reg_maps->sampler_type[semantic.reg.reg.idx] = semantic.sampler_type;
521                     break;
522
523                 default:
524                     TRACE("Not recording DCL register type %#x.\n", semantic.reg.reg.type);
525                     break;
526             }
527         }
528         else if (ins.handler_idx == WINED3DSIH_DEF)
529         {
530             struct wined3d_shader_src_param rel_addr;
531             struct wined3d_shader_dst_param dst;
532
533             local_constant *lconst = HeapAlloc(GetProcessHeap(), 0, sizeof(local_constant));
534             if (!lconst) return E_OUTOFMEMORY;
535
536             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
537             lconst->idx = dst.reg.idx;
538
539             memcpy(lconst->value, ptr, 4 * sizeof(DWORD));
540             ptr += 4;
541
542             /* In pixel shader 1.X shaders, the constants are clamped between [-1;1] */
543             if (shader_version.major == 1 && shader_version.type == WINED3D_SHADER_TYPE_PIXEL)
544             {
545                 float *value = (float *)lconst->value;
546                 if (value[0] < -1.0f) value[0] = -1.0f;
547                 else if (value[0] > 1.0f) value[0] = 1.0f;
548                 if (value[1] < -1.0f) value[1] = -1.0f;
549                 else if (value[1] > 1.0f) value[1] = 1.0f;
550                 if (value[2] < -1.0f) value[2] = -1.0f;
551                 else if (value[2] > 1.0f) value[2] = 1.0f;
552                 if (value[3] < -1.0f) value[3] = -1.0f;
553                 else if (value[3] > 1.0f) value[3] = 1.0f;
554             }
555
556             list_add_head(&shader->constantsF, &lconst->entry);
557         }
558         else if (ins.handler_idx == WINED3DSIH_DEFI)
559         {
560             struct wined3d_shader_src_param rel_addr;
561             struct wined3d_shader_dst_param dst;
562
563             local_constant *lconst = HeapAlloc(GetProcessHeap(), 0, sizeof(local_constant));
564             if (!lconst) return E_OUTOFMEMORY;
565
566             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
567             lconst->idx = dst.reg.idx;
568
569             memcpy(lconst->value, ptr, 4 * sizeof(DWORD));
570             ptr += 4;
571
572             list_add_head(&shader->constantsI, &lconst->entry);
573             reg_maps->local_int_consts |= (1 << dst.reg.idx);
574         }
575         else if (ins.handler_idx == WINED3DSIH_DEFB)
576         {
577             struct wined3d_shader_src_param rel_addr;
578             struct wined3d_shader_dst_param dst;
579
580             local_constant *lconst = HeapAlloc(GetProcessHeap(), 0, sizeof(local_constant));
581             if (!lconst) return E_OUTOFMEMORY;
582
583             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
584             lconst->idx = dst.reg.idx;
585
586             memcpy(lconst->value, ptr, sizeof(DWORD));
587             ++ptr;
588
589             list_add_head(&shader->constantsB, &lconst->entry);
590             reg_maps->local_bool_consts |= (1 << dst.reg.idx);
591         }
592         /* If there's a loop in the shader. */
593         else if (ins.handler_idx == WINED3DSIH_LOOP
594                 || ins.handler_idx == WINED3DSIH_REP)
595         {
596             struct wined3d_shader_src_param src, rel_addr;
597
598             fe->shader_read_src_param(fe_data, &ptr, &src, &rel_addr);
599
600             /* Rep and Loop always use an integer constant for the control parameters. */
601             if (ins.handler_idx == WINED3DSIH_REP)
602             {
603                 reg_maps->integer_constants |= 1 << src.reg.idx;
604             }
605             else
606             {
607                 fe->shader_read_src_param(fe_data, &ptr, &src, &rel_addr);
608                 reg_maps->integer_constants |= 1 << src.reg.idx;
609             }
610
611             cur_loop_depth++;
612             if (cur_loop_depth > max_loop_depth) max_loop_depth = cur_loop_depth;
613         }
614         else if (ins.handler_idx == WINED3DSIH_ENDLOOP
615                 || ins.handler_idx == WINED3DSIH_ENDREP)
616         {
617             cur_loop_depth--;
618         }
619         /* For subroutine prototypes. */
620         else if (ins.handler_idx == WINED3DSIH_LABEL)
621         {
622             struct wined3d_shader_src_param src, rel_addr;
623
624             fe->shader_read_src_param(fe_data, &ptr, &src, &rel_addr);
625             reg_maps->labels |= 1 << src.reg.idx;
626         }
627         /* Set texture, address, temporary registers. */
628         else
629         {
630             BOOL color0_mov = FALSE;
631             int i, limit;
632
633             /* This will loop over all the registers and try to
634              * make a bitmask of the ones we're interested in.
635              *
636              * Relative addressing tokens are ignored, but that's
637              * okay, since we'll catch any address registers when
638              * they are initialized (required by spec). */
639             for (i = 0; i < ins.dst_count; ++i)
640             {
641                 struct wined3d_shader_src_param dst_rel_addr;
642                 struct wined3d_shader_dst_param dst_param;
643
644                 fe->shader_read_dst_param(fe_data, &ptr, &dst_param, &dst_rel_addr);
645
646                 shader_record_register_usage(shader, reg_maps, &dst_param.reg, shader_version.type);
647
648                 /* WINED3DSPR_TEXCRDOUT is the same as WINED3DSPR_OUTPUT. _OUTPUT can be > MAX_REG_TEXCRD and
649                  * is used in >= 3.0 shaders. Filter 3.0 shaders to prevent overflows, and also filter pixel
650                  * shaders because TECRDOUT isn't used in them, but future register types might cause issues */
651                 if (shader_version.type == WINED3D_SHADER_TYPE_VERTEX && shader_version.major < 3)
652                 {
653                     UINT idx = dst_param.reg.idx;
654
655                     switch (dst_param.reg.type)
656                     {
657                         case WINED3DSPR_RASTOUT:
658                             switch (idx)
659                             {
660                                 case 0: /* oPos */
661                                     reg_maps->output_registers |= 1 << 10;
662                                     shader_signature_from_usage(&output_signature[10],
663                                             WINED3DDECLUSAGE_POSITION, 0, 10, WINED3DSP_WRITEMASK_ALL);
664                                     break;
665
666                                 case 1: /* oFog */
667                                     reg_maps->output_registers |= 1 << 11;
668                                     shader_signature_from_usage(&output_signature[11],
669                                             WINED3DDECLUSAGE_FOG, 0, 11, WINED3DSP_WRITEMASK_0);
670                                     break;
671
672                                 case 2: /* oPts */
673                                     reg_maps->output_registers |= 1 << 11;
674                                     shader_signature_from_usage(&output_signature[11],
675                                             WINED3DDECLUSAGE_PSIZE, 0, 11, WINED3DSP_WRITEMASK_1);
676                                     break;
677                             }
678                             break;
679
680                         case WINED3DSPR_ATTROUT:
681                             if (idx < 2)
682                             {
683                                 idx += 8;
684                                 if (reg_maps->output_registers & (1 << idx))
685                                 {
686                                     output_signature[idx].mask |= dst_param.write_mask;
687                                 }
688                                 else
689                                 {
690                                     reg_maps->output_registers |= 1 << idx;
691                                     shader_signature_from_usage(&output_signature[idx],
692                                             WINED3DDECLUSAGE_COLOR, idx - 8, idx, dst_param.write_mask);
693                                 }
694                             }
695                             break;
696
697                         case WINED3DSPR_TEXCRDOUT:
698
699                             reg_maps->texcoord_mask[idx] |= dst_param.write_mask;
700                             if (reg_maps->output_registers & (1 << idx))
701                             {
702                                 output_signature[idx].mask |= dst_param.write_mask;
703                             }
704                             else
705                             {
706                                 reg_maps->output_registers |= 1 << idx;
707                                 shader_signature_from_usage(&output_signature[idx],
708                                         WINED3DDECLUSAGE_TEXCOORD, idx, idx, dst_param.write_mask);
709                             }
710                             break;
711
712                         default:
713                             break;
714                     }
715                 }
716
717                 if (shader_version.type == WINED3D_SHADER_TYPE_PIXEL)
718                 {
719                     if (dst_param.reg.type == WINED3DSPR_COLOROUT && !dst_param.reg.idx)
720                     {
721                         /* Many 2.0 and 3.0 pixel shaders end with a MOV from a temp register to
722                          * COLOROUT 0. If we know this in advance, the ARB shader backend can skip
723                          * the mov and perform the sRGB write correction from the source register.
724                          *
725                          * However, if the mov is only partial, we can't do this, and if the write
726                          * comes from an instruction other than MOV it is hard to do as well. If
727                          * COLOROUT 0 is overwritten partially later, the marker is dropped again. */
728                         shader->u.ps.color0_mov = FALSE;
729                         if (ins.handler_idx == WINED3DSIH_MOV
730                                 && dst_param.write_mask == WINED3DSP_WRITEMASK_ALL)
731                         {
732                             /* Used later when the source register is read. */
733                             color0_mov = TRUE;
734                         }
735                     }
736                     /* Also drop the MOV marker if the source register is overwritten prior to the shader
737                      * end
738                      */
739                     else if (dst_param.reg.type == WINED3DSPR_TEMP
740                             && dst_param.reg.idx == shader->u.ps.color0_reg)
741                     {
742                         shader->u.ps.color0_mov = FALSE;
743                     }
744                 }
745
746                 /* Declare 1.x samplers implicitly, based on the destination reg. number. */
747                 if (shader_version.major == 1
748                         && (ins.handler_idx == WINED3DSIH_TEX
749                             || ins.handler_idx == WINED3DSIH_TEXBEM
750                             || ins.handler_idx == WINED3DSIH_TEXBEML
751                             || ins.handler_idx == WINED3DSIH_TEXDP3TEX
752                             || ins.handler_idx == WINED3DSIH_TEXM3x2TEX
753                             || ins.handler_idx == WINED3DSIH_TEXM3x3SPEC
754                             || ins.handler_idx == WINED3DSIH_TEXM3x3TEX
755                             || ins.handler_idx == WINED3DSIH_TEXM3x3VSPEC
756                             || ins.handler_idx == WINED3DSIH_TEXREG2AR
757                             || ins.handler_idx == WINED3DSIH_TEXREG2GB
758                             || ins.handler_idx == WINED3DSIH_TEXREG2RGB))
759                 {
760                     /* Fake sampler usage, only set reserved bit and type. */
761                     DWORD sampler_code = dst_param.reg.idx;
762
763                     TRACE("Setting fake 2D sampler for 1.x pixelshader.\n");
764                     reg_maps->sampler_type[sampler_code] = WINED3DSTT_2D;
765
766                     /* texbem is only valid with < 1.4 pixel shaders */
767                     if (ins.handler_idx == WINED3DSIH_TEXBEM
768                             || ins.handler_idx == WINED3DSIH_TEXBEML)
769                     {
770                         reg_maps->bumpmat |= 1 << dst_param.reg.idx;
771                         if (ins.handler_idx == WINED3DSIH_TEXBEML)
772                         {
773                             reg_maps->luminanceparams |= 1 << dst_param.reg.idx;
774                         }
775                     }
776                 }
777                 else if (ins.handler_idx == WINED3DSIH_BEM)
778                 {
779                     reg_maps->bumpmat |= 1 << dst_param.reg.idx;
780                 }
781             }
782
783             if (ins.handler_idx == WINED3DSIH_NRM) reg_maps->usesnrm = 1;
784             else if (ins.handler_idx == WINED3DSIH_DSY) reg_maps->usesdsy = 1;
785             else if (ins.handler_idx == WINED3DSIH_DSX) reg_maps->usesdsx = 1;
786             else if (ins.handler_idx == WINED3DSIH_TEXLDD) reg_maps->usestexldd = 1;
787             else if (ins.handler_idx == WINED3DSIH_TEXLDL) reg_maps->usestexldl = 1;
788             else if (ins.handler_idx == WINED3DSIH_MOVA) reg_maps->usesmova = 1;
789             else if (ins.handler_idx == WINED3DSIH_IFC) reg_maps->usesifc = 1;
790             else if (ins.handler_idx == WINED3DSIH_CALL) reg_maps->usescall = 1;
791
792             limit = ins.src_count + (ins.predicate ? 1 : 0);
793             for (i = 0; i < limit; ++i)
794             {
795                 struct wined3d_shader_src_param src_param, src_rel_addr;
796                 unsigned int count;
797
798                 fe->shader_read_src_param(fe_data, &ptr, &src_param, &src_rel_addr);
799                 count = get_instr_extra_regcount(ins.handler_idx, i);
800
801                 shader_record_register_usage(shader, reg_maps, &src_param.reg, shader_version.type);
802                 while (count)
803                 {
804                     ++src_param.reg.idx;
805                     shader_record_register_usage(shader, reg_maps, &src_param.reg, shader_version.type);
806                     --count;
807                 }
808
809                 if (color0_mov)
810                 {
811                     if (src_param.reg.type == WINED3DSPR_TEMP
812                             && src_param.swizzle == WINED3DSP_NOSWIZZLE)
813                     {
814                         shader->u.ps.color0_mov = TRUE;
815                         shader->u.ps.color0_reg = src_param.reg.idx;
816                     }
817                 }
818             }
819         }
820     }
821     reg_maps->loop_depth = max_loop_depth;
822
823     shader->functionLength = ((const char *)ptr - (const char *)byte_code);
824
825     return WINED3D_OK;
826 }
827
828 unsigned int shader_find_free_input_register(const struct wined3d_shader_reg_maps *reg_maps, unsigned int max)
829 {
830     DWORD map = 1 << max;
831     map |= map - 1;
832     map &= reg_maps->shader_version.major < 3 ? ~reg_maps->texcoord : ~reg_maps->input_registers;
833
834     return wined3d_log2i(map);
835 }
836
837 static void shader_dump_decl_usage(const struct wined3d_shader_semantic *semantic,
838         const struct wined3d_shader_version *shader_version)
839 {
840     TRACE("dcl");
841
842     if (semantic->reg.reg.type == WINED3DSPR_SAMPLER)
843     {
844         switch (semantic->sampler_type)
845         {
846             case WINED3DSTT_2D: TRACE("_2d"); break;
847             case WINED3DSTT_CUBE: TRACE("_cube"); break;
848             case WINED3DSTT_VOLUME: TRACE("_volume"); break;
849             default: TRACE("_unknown_ttype(0x%08x)", semantic->sampler_type);
850         }
851     }
852     else
853     {
854         /* Pixel shaders 3.0 don't have usage semantics. */
855         if (shader_version->major < 3 && shader_version->type == WINED3D_SHADER_TYPE_PIXEL) return;
856         else TRACE("_");
857
858         switch (semantic->usage)
859         {
860             case WINED3DDECLUSAGE_POSITION:
861                 TRACE("position%u", semantic->usage_idx);
862                 break;
863
864             case WINED3DDECLUSAGE_BLENDINDICES:
865                 TRACE("blend");
866                 break;
867
868             case WINED3DDECLUSAGE_BLENDWEIGHT:
869                 TRACE("weight");
870                 break;
871
872             case WINED3DDECLUSAGE_NORMAL:
873                 TRACE("normal%u", semantic->usage_idx);
874                 break;
875
876             case WINED3DDECLUSAGE_PSIZE:
877                 TRACE("psize");
878                 break;
879
880             case WINED3DDECLUSAGE_COLOR:
881                 if (!semantic->usage_idx) TRACE("color");
882                 else TRACE("specular%u", (semantic->usage_idx - 1));
883                 break;
884
885             case WINED3DDECLUSAGE_TEXCOORD:
886                 TRACE("texture%u", semantic->usage_idx);
887                 break;
888
889             case WINED3DDECLUSAGE_TANGENT:
890                 TRACE("tangent");
891                 break;
892
893             case WINED3DDECLUSAGE_BINORMAL:
894                 TRACE("binormal");
895                 break;
896
897             case WINED3DDECLUSAGE_TESSFACTOR:
898                 TRACE("tessfactor");
899                 break;
900
901             case WINED3DDECLUSAGE_POSITIONT:
902                 TRACE("positionT%u", semantic->usage_idx);
903                 break;
904
905             case WINED3DDECLUSAGE_FOG:
906                 TRACE("fog");
907                 break;
908
909             case WINED3DDECLUSAGE_DEPTH:
910                 TRACE("depth");
911                 break;
912
913             case WINED3DDECLUSAGE_SAMPLE:
914                 TRACE("sample");
915                 break;
916
917             default:
918                 FIXME("unknown_semantics(0x%08x)", semantic->usage);
919         }
920     }
921 }
922
923 static void shader_dump_register(const struct wined3d_shader_register *reg,
924         const struct wined3d_shader_version *shader_version)
925 {
926     static const char * const rastout_reg_names[] = {"oPos", "oFog", "oPts"};
927     static const char * const misctype_reg_names[] = {"vPos", "vFace"};
928     UINT offset = reg->idx;
929
930     switch (reg->type)
931     {
932         case WINED3DSPR_TEMP:
933             TRACE("r");
934             break;
935
936         case WINED3DSPR_INPUT:
937             TRACE("v");
938             break;
939
940         case WINED3DSPR_CONST:
941         case WINED3DSPR_CONST2:
942         case WINED3DSPR_CONST3:
943         case WINED3DSPR_CONST4:
944             TRACE("c");
945             offset = shader_get_float_offset(reg->type, reg->idx);
946             break;
947
948         case WINED3DSPR_TEXTURE: /* vs: case WINED3DSPR_ADDR */
949             TRACE("%c", shader_version->type == WINED3D_SHADER_TYPE_PIXEL ? 't' : 'a');
950             break;
951
952         case WINED3DSPR_RASTOUT:
953             TRACE("%s", rastout_reg_names[reg->idx]);
954             break;
955
956         case WINED3DSPR_COLOROUT:
957             TRACE("oC");
958             break;
959
960         case WINED3DSPR_DEPTHOUT:
961             TRACE("oDepth");
962             break;
963
964         case WINED3DSPR_ATTROUT:
965             TRACE("oD");
966             break;
967
968         case WINED3DSPR_TEXCRDOUT:
969             /* Vertex shaders >= 3.0 use general purpose output registers
970              * (WINED3DSPR_OUTPUT), which can include an address token. */
971             if (shader_version->major >= 3) TRACE("o");
972             else TRACE("oT");
973             break;
974
975         case WINED3DSPR_CONSTINT:
976             TRACE("i");
977             break;
978
979         case WINED3DSPR_CONSTBOOL:
980             TRACE("b");
981             break;
982
983         case WINED3DSPR_LABEL:
984             TRACE("l");
985             break;
986
987         case WINED3DSPR_LOOP:
988             TRACE("aL");
989             break;
990
991         case WINED3DSPR_SAMPLER:
992             TRACE("s");
993             break;
994
995         case WINED3DSPR_MISCTYPE:
996             if (reg->idx > 1) FIXME("Unhandled misctype register %u.\n", reg->idx);
997             else TRACE("%s", misctype_reg_names[reg->idx]);
998             break;
999
1000         case WINED3DSPR_PREDICATE:
1001             TRACE("p");
1002             break;
1003
1004         case WINED3DSPR_IMMCONST:
1005             TRACE("l");
1006             break;
1007
1008         case WINED3DSPR_CONSTBUFFER:
1009             TRACE("cb");
1010             break;
1011
1012         case WINED3DSPR_NULL:
1013             TRACE("null");
1014             break;
1015
1016         case WINED3DSPR_RESOURCE:
1017             TRACE("t");
1018             break;
1019
1020         default:
1021             TRACE("unhandled_rtype(%#x)", reg->type);
1022             break;
1023     }
1024
1025     if (reg->type == WINED3DSPR_IMMCONST)
1026     {
1027         TRACE("(");
1028         switch (reg->immconst_type)
1029         {
1030             case WINED3D_IMMCONST_SCALAR:
1031                 TRACE("%.8e", *(const float *)reg->immconst_data);
1032                 break;
1033
1034             case WINED3D_IMMCONST_VEC4:
1035                 TRACE("%.8e, %.8e, %.8e, %.8e",
1036                         *(const float *)&reg->immconst_data[0], *(const float *)&reg->immconst_data[1],
1037                         *(const float *)&reg->immconst_data[2], *(const float *)&reg->immconst_data[3]);
1038                 break;
1039
1040             default:
1041                 TRACE("<unhandled immconst_type %#x>", reg->immconst_type);
1042                 break;
1043         }
1044         TRACE(")");
1045     }
1046     else if (reg->type != WINED3DSPR_RASTOUT
1047             && reg->type != WINED3DSPR_MISCTYPE
1048             && reg->type != WINED3DSPR_NULL)
1049     {
1050         if (reg->array_idx != ~0U)
1051         {
1052             TRACE("%u[%u", offset, reg->array_idx);
1053             if (reg->rel_addr)
1054             {
1055                 TRACE(" + ");
1056                 shader_dump_src_param(reg->rel_addr, shader_version);
1057             }
1058             TRACE("]");
1059         }
1060         else
1061         {
1062             if (reg->rel_addr)
1063             {
1064                 TRACE("[");
1065                 shader_dump_src_param(reg->rel_addr, shader_version);
1066                 TRACE(" + ");
1067             }
1068             TRACE("%u", offset);
1069             if (reg->rel_addr) TRACE("]");
1070         }
1071     }
1072 }
1073
1074 void shader_dump_dst_param(const struct wined3d_shader_dst_param *param,
1075         const struct wined3d_shader_version *shader_version)
1076 {
1077     DWORD write_mask = param->write_mask;
1078
1079     shader_dump_register(&param->reg, shader_version);
1080
1081     if (write_mask && write_mask != WINED3DSP_WRITEMASK_ALL)
1082     {
1083         static const char *write_mask_chars = "xyzw";
1084
1085         TRACE(".");
1086         if (write_mask & WINED3DSP_WRITEMASK_0) TRACE("%c", write_mask_chars[0]);
1087         if (write_mask & WINED3DSP_WRITEMASK_1) TRACE("%c", write_mask_chars[1]);
1088         if (write_mask & WINED3DSP_WRITEMASK_2) TRACE("%c", write_mask_chars[2]);
1089         if (write_mask & WINED3DSP_WRITEMASK_3) TRACE("%c", write_mask_chars[3]);
1090     }
1091 }
1092
1093 void shader_dump_src_param(const struct wined3d_shader_src_param *param,
1094         const struct wined3d_shader_version *shader_version)
1095 {
1096     DWORD src_modifier = param->modifiers;
1097     DWORD swizzle = param->swizzle;
1098
1099     if (src_modifier == WINED3DSPSM_NEG
1100             || src_modifier == WINED3DSPSM_BIASNEG
1101             || src_modifier == WINED3DSPSM_SIGNNEG
1102             || src_modifier == WINED3DSPSM_X2NEG
1103             || src_modifier == WINED3DSPSM_ABSNEG)
1104         TRACE("-");
1105     else if (src_modifier == WINED3DSPSM_COMP)
1106         TRACE("1-");
1107     else if (src_modifier == WINED3DSPSM_NOT)
1108         TRACE("!");
1109
1110     if (src_modifier == WINED3DSPSM_ABS || src_modifier == WINED3DSPSM_ABSNEG)
1111         TRACE("abs(");
1112
1113     shader_dump_register(&param->reg, shader_version);
1114
1115     if (src_modifier)
1116     {
1117         switch (src_modifier)
1118         {
1119             case WINED3DSPSM_NONE:    break;
1120             case WINED3DSPSM_NEG:     break;
1121             case WINED3DSPSM_NOT:     break;
1122             case WINED3DSPSM_BIAS:    TRACE("_bias"); break;
1123             case WINED3DSPSM_BIASNEG: TRACE("_bias"); break;
1124             case WINED3DSPSM_SIGN:    TRACE("_bx2"); break;
1125             case WINED3DSPSM_SIGNNEG: TRACE("_bx2"); break;
1126             case WINED3DSPSM_COMP:    break;
1127             case WINED3DSPSM_X2:      TRACE("_x2"); break;
1128             case WINED3DSPSM_X2NEG:   TRACE("_x2"); break;
1129             case WINED3DSPSM_DZ:      TRACE("_dz"); break;
1130             case WINED3DSPSM_DW:      TRACE("_dw"); break;
1131             case WINED3DSPSM_ABSNEG:  TRACE(")"); break;
1132             case WINED3DSPSM_ABS:     TRACE(")"); break;
1133             default:                  TRACE("_unknown_modifier(%#x)", src_modifier);
1134         }
1135     }
1136
1137     if (swizzle != WINED3DSP_NOSWIZZLE)
1138     {
1139         static const char *swizzle_chars = "xyzw";
1140         DWORD swizzle_x = swizzle & 0x03;
1141         DWORD swizzle_y = (swizzle >> 2) & 0x03;
1142         DWORD swizzle_z = (swizzle >> 4) & 0x03;
1143         DWORD swizzle_w = (swizzle >> 6) & 0x03;
1144
1145         if (swizzle_x == swizzle_y
1146                 && swizzle_x == swizzle_z
1147                 && swizzle_x == swizzle_w)
1148         {
1149             TRACE(".%c", swizzle_chars[swizzle_x]);
1150         }
1151         else
1152         {
1153             TRACE(".%c%c%c%c", swizzle_chars[swizzle_x], swizzle_chars[swizzle_y],
1154                     swizzle_chars[swizzle_z], swizzle_chars[swizzle_w]);
1155         }
1156     }
1157 }
1158
1159 /* Shared code in order to generate the bulk of the shader string.
1160  * NOTE: A description of how to parse tokens can be found on MSDN. */
1161 void shader_generate_main(struct wined3d_shader *shader, struct wined3d_shader_buffer *buffer,
1162         const struct wined3d_shader_reg_maps *reg_maps, const DWORD *byte_code, void *backend_ctx)
1163 {
1164     IWineD3DDeviceImpl *device = shader->device;
1165     const struct wined3d_shader_frontend *fe = shader->frontend;
1166     void *fe_data = shader->frontend_data;
1167     struct wined3d_shader_src_param dst_rel_addr[2];
1168     struct wined3d_shader_src_param src_rel_addr[4];
1169     struct wined3d_shader_dst_param dst_param[2];
1170     struct wined3d_shader_src_param src_param[4];
1171     struct wined3d_shader_version shader_version;
1172     struct wined3d_shader_loop_state loop_state;
1173     struct wined3d_shader_instruction ins;
1174     struct wined3d_shader_tex_mx tex_mx;
1175     struct wined3d_shader_context ctx;
1176     const DWORD *ptr = byte_code;
1177     DWORD i;
1178
1179     /* Initialize current parsing state. */
1180     tex_mx.current_row = 0;
1181     loop_state.current_depth = 0;
1182     loop_state.current_reg = 0;
1183
1184     ctx.shader = shader;
1185     ctx.gl_info = &device->adapter->gl_info;
1186     ctx.reg_maps = reg_maps;
1187     ctx.buffer = buffer;
1188     ctx.tex_mx = &tex_mx;
1189     ctx.loop_state = &loop_state;
1190     ctx.backend_data = backend_ctx;
1191
1192     ins.ctx = &ctx;
1193     ins.dst = dst_param;
1194     ins.src = src_param;
1195
1196     fe->shader_read_header(fe_data, &ptr, &shader_version);
1197
1198     while (!fe->shader_is_end(fe_data, &ptr))
1199     {
1200         const char *comment;
1201         UINT comment_size;
1202         UINT param_size;
1203
1204         /* Skip comment tokens. */
1205         fe->shader_read_comment(&ptr, &comment, &comment_size);
1206         if (comment) continue;
1207
1208         /* Read opcode. */
1209         fe->shader_read_opcode(fe_data, &ptr, &ins, &param_size);
1210
1211         /* Unknown opcode and its parameters. */
1212         if (ins.handler_idx == WINED3DSIH_TABLE_SIZE)
1213         {
1214             TRACE("Skipping unrecognized instruction.\n");
1215             ptr += param_size;
1216             continue;
1217         }
1218
1219         /* Nothing to do. */
1220         if (ins.handler_idx == WINED3DSIH_DCL
1221                 || ins.handler_idx == WINED3DSIH_NOP
1222                 || ins.handler_idx == WINED3DSIH_DEF
1223                 || ins.handler_idx == WINED3DSIH_DEFI
1224                 || ins.handler_idx == WINED3DSIH_DEFB
1225                 || ins.handler_idx == WINED3DSIH_PHASE)
1226         {
1227             ptr += param_size;
1228             continue;
1229         }
1230
1231         /* Destination tokens */
1232         for (i = 0; i < ins.dst_count; ++i)
1233         {
1234             fe->shader_read_dst_param(fe_data, &ptr, &dst_param[i], &dst_rel_addr[i]);
1235         }
1236
1237         /* Predication token */
1238         if (ins.predicate)
1239         {
1240             FIXME("Predicates not implemented.\n");
1241             ins.predicate = *ptr++;
1242         }
1243
1244         /* Other source tokens */
1245         for (i = 0; i < ins.src_count; ++i)
1246         {
1247             fe->shader_read_src_param(fe_data, &ptr, &src_param[i], &src_rel_addr[i]);
1248         }
1249
1250         /* Call appropriate function for output target */
1251         device->shader_backend->shader_handle_instruction(&ins);
1252     }
1253 }
1254
1255 static void shader_dump_ins_modifiers(const struct wined3d_shader_dst_param *dst)
1256 {
1257     DWORD mmask = dst->modifiers;
1258
1259     switch (dst->shift)
1260     {
1261         case 0: break;
1262         case 13: TRACE("_d8"); break;
1263         case 14: TRACE("_d4"); break;
1264         case 15: TRACE("_d2"); break;
1265         case 1: TRACE("_x2"); break;
1266         case 2: TRACE("_x4"); break;
1267         case 3: TRACE("_x8"); break;
1268         default: TRACE("_unhandled_shift(%d)", dst->shift); break;
1269     }
1270
1271     if (mmask & WINED3DSPDM_SATURATE)         TRACE("_sat");
1272     if (mmask & WINED3DSPDM_PARTIALPRECISION) TRACE("_pp");
1273     if (mmask & WINED3DSPDM_MSAMPCENTROID)    TRACE("_centroid");
1274
1275     mmask &= ~(WINED3DSPDM_SATURATE | WINED3DSPDM_PARTIALPRECISION | WINED3DSPDM_MSAMPCENTROID);
1276     if (mmask) FIXME("_unrecognized_modifier(%#x)", mmask);
1277 }
1278
1279 static void shader_trace_init(const struct wined3d_shader_frontend *fe, void *fe_data, const DWORD *byte_code)
1280 {
1281     struct wined3d_shader_version shader_version;
1282     const DWORD *ptr = byte_code;
1283     const char *type_prefix;
1284     DWORD i;
1285
1286     TRACE("Parsing %p.\n", byte_code);
1287
1288     fe->shader_read_header(fe_data, &ptr, &shader_version);
1289
1290     switch (shader_version.type)
1291     {
1292         case WINED3D_SHADER_TYPE_VERTEX:
1293             type_prefix = "vs";
1294             break;
1295
1296         case WINED3D_SHADER_TYPE_GEOMETRY:
1297             type_prefix = "gs";
1298             break;
1299
1300         case WINED3D_SHADER_TYPE_PIXEL:
1301             type_prefix = "ps";
1302             break;
1303
1304         default:
1305             FIXME("Unhandled shader type %#x.\n", shader_version.type);
1306             type_prefix = "unknown";
1307             break;
1308     }
1309
1310     TRACE("%s_%u_%u\n", type_prefix, shader_version.major, shader_version.minor);
1311
1312     while (!fe->shader_is_end(fe_data, &ptr))
1313     {
1314         struct wined3d_shader_instruction ins;
1315         const char *comment;
1316         UINT comment_size;
1317         UINT param_size;
1318
1319         /* comment */
1320         fe->shader_read_comment(&ptr, &comment, &comment_size);
1321         if (comment)
1322         {
1323             if (comment_size > 4 && *(const DWORD *)comment == WINEMAKEFOURCC('T', 'E', 'X', 'T'))
1324             {
1325                 const char *end = comment + comment_size;
1326                 const char *ptr = comment + 4;
1327                 const char *line = ptr;
1328
1329                 TRACE("// TEXT\n");
1330                 while (ptr != end)
1331                 {
1332                     if (*ptr == '\n')
1333                     {
1334                         UINT len = ptr - line;
1335                         if (len && *(ptr - 1) == '\r') --len;
1336                         TRACE("// %s\n", debugstr_an(line, len));
1337                         line = ++ptr;
1338                     }
1339                     else ++ptr;
1340                 }
1341                 if (line != ptr) TRACE("// %s\n", debugstr_an(line, ptr - line));
1342             }
1343             else TRACE("// %s\n", debugstr_an(comment, comment_size));
1344             continue;
1345         }
1346
1347         fe->shader_read_opcode(fe_data, &ptr, &ins, &param_size);
1348         if (ins.handler_idx == WINED3DSIH_TABLE_SIZE)
1349         {
1350             TRACE("Skipping unrecognized instruction.\n");
1351             ptr += param_size;
1352             continue;
1353         }
1354
1355         if (ins.handler_idx == WINED3DSIH_DCL)
1356         {
1357             struct wined3d_shader_semantic semantic;
1358
1359             fe->shader_read_semantic(&ptr, &semantic);
1360
1361             shader_dump_decl_usage(&semantic, &shader_version);
1362             shader_dump_ins_modifiers(&semantic.reg);
1363             TRACE(" ");
1364             shader_dump_dst_param(&semantic.reg, &shader_version);
1365         }
1366         else if (ins.handler_idx == WINED3DSIH_DEF)
1367         {
1368             struct wined3d_shader_src_param rel_addr;
1369             struct wined3d_shader_dst_param dst;
1370
1371             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
1372
1373             TRACE("def c%u = %f, %f, %f, %f", shader_get_float_offset(dst.reg.type, dst.reg.idx),
1374                     *(const float *)(ptr),
1375                     *(const float *)(ptr + 1),
1376                     *(const float *)(ptr + 2),
1377                     *(const float *)(ptr + 3));
1378             ptr += 4;
1379         }
1380         else if (ins.handler_idx == WINED3DSIH_DEFI)
1381         {
1382             struct wined3d_shader_src_param rel_addr;
1383             struct wined3d_shader_dst_param dst;
1384
1385             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
1386
1387             TRACE("defi i%u = %d, %d, %d, %d", dst.reg.idx,
1388                     *(ptr),
1389                     *(ptr + 1),
1390                     *(ptr + 2),
1391                     *(ptr + 3));
1392             ptr += 4;
1393         }
1394         else if (ins.handler_idx == WINED3DSIH_DEFB)
1395         {
1396             struct wined3d_shader_src_param rel_addr;
1397             struct wined3d_shader_dst_param dst;
1398
1399             fe->shader_read_dst_param(fe_data, &ptr, &dst, &rel_addr);
1400
1401             TRACE("defb b%u = %s", dst.reg.idx, *ptr ? "true" : "false");
1402             ++ptr;
1403         }
1404         else
1405         {
1406             struct wined3d_shader_src_param dst_rel_addr[2];
1407             struct wined3d_shader_src_param src_rel_addr;
1408             struct wined3d_shader_dst_param dst_param[2];
1409             struct wined3d_shader_src_param src_param;
1410
1411             for (i = 0; i < ins.dst_count; ++i)
1412             {
1413                 fe->shader_read_dst_param(fe_data, &ptr, &dst_param[i], &dst_rel_addr[i]);
1414             }
1415
1416             /* Print out predication source token first - it follows
1417              * the destination token. */
1418             if (ins.predicate)
1419             {
1420                 fe->shader_read_src_param(fe_data, &ptr, &src_param, &src_rel_addr);
1421                 TRACE("(");
1422                 shader_dump_src_param(&src_param, &shader_version);
1423                 TRACE(") ");
1424             }
1425
1426             /* PixWin marks instructions with the coissue flag with a '+' */
1427             if (ins.coissue) TRACE("+");
1428
1429             TRACE("%s", shader_opcode_names[ins.handler_idx]);
1430
1431             if (ins.handler_idx == WINED3DSIH_IFC
1432                     || ins.handler_idx == WINED3DSIH_BREAKC)
1433             {
1434                 switch (ins.flags)
1435                 {
1436                     case COMPARISON_GT: TRACE("_gt"); break;
1437                     case COMPARISON_EQ: TRACE("_eq"); break;
1438                     case COMPARISON_GE: TRACE("_ge"); break;
1439                     case COMPARISON_LT: TRACE("_lt"); break;
1440                     case COMPARISON_NE: TRACE("_ne"); break;
1441                     case COMPARISON_LE: TRACE("_le"); break;
1442                     default: TRACE("_(%u)", ins.flags);
1443                 }
1444             }
1445             else if (ins.handler_idx == WINED3DSIH_TEX
1446                     && shader_version.major >= 2
1447                     && (ins.flags & WINED3DSI_TEXLD_PROJECT))
1448             {
1449                 TRACE("p");
1450             }
1451
1452             /* We already read the destination tokens, print them. */
1453             for (i = 0; i < ins.dst_count; ++i)
1454             {
1455                 shader_dump_ins_modifiers(&dst_param[i]);
1456                 TRACE(!i ? " " : ", ");
1457                 shader_dump_dst_param(&dst_param[i], &shader_version);
1458             }
1459
1460             /* Other source tokens */
1461             for (i = ins.dst_count; i < (ins.dst_count + ins.src_count); ++i)
1462             {
1463                 fe->shader_read_src_param(fe_data, &ptr, &src_param, &src_rel_addr);
1464                 TRACE(!i ? " " : ", ");
1465                 shader_dump_src_param(&src_param, &shader_version);
1466             }
1467         }
1468         TRACE("\n");
1469     }
1470 }
1471
1472 static void shader_cleanup(struct wined3d_shader *shader)
1473 {
1474     shader->device->shader_backend->shader_destroy(shader);
1475     HeapFree(GetProcessHeap(), 0, shader->reg_maps.constf);
1476     HeapFree(GetProcessHeap(), 0, shader->function);
1477     shader_delete_constant_list(&shader->constantsF);
1478     shader_delete_constant_list(&shader->constantsB);
1479     shader_delete_constant_list(&shader->constantsI);
1480     list_remove(&shader->shader_list_entry);
1481
1482     if (shader->frontend && shader->frontend_data)
1483         shader->frontend->shader_free(shader->frontend_data);
1484 }
1485
1486 static void shader_none_handle_instruction(const struct wined3d_shader_instruction *ins) {}
1487 static void shader_none_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS) {}
1488 static void shader_none_select_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info,
1489         enum tex_types tex_type, const SIZE *ds_mask_size) {}
1490 static void shader_none_deselect_depth_blt(void *shader_priv, const struct wined3d_gl_info *gl_info) {}
1491 static void shader_none_update_float_vertex_constants(IWineD3DDeviceImpl *device, UINT start, UINT count) {}
1492 static void shader_none_update_float_pixel_constants(IWineD3DDeviceImpl *device, UINT start, UINT count) {}
1493 static void shader_none_load_constants(const struct wined3d_context *context, char usePS, char useVS) {}
1494 static void shader_none_load_np2fixup_constants(void *shader_priv,
1495         const struct wined3d_gl_info *gl_info, const struct wined3d_state *state) {}
1496 static void shader_none_destroy(struct wined3d_shader *shader) {}
1497 static HRESULT shader_none_alloc(IWineD3DDeviceImpl *device) {return WINED3D_OK;}
1498 static void shader_none_free(IWineD3DDeviceImpl *device) {}
1499 static BOOL shader_none_dirty_const(void) {return FALSE;}
1500
1501 static void shader_none_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *caps)
1502 {
1503     /* Set the shader caps to 0 for the none shader backend */
1504     caps->VertexShaderVersion = 0;
1505     caps->MaxVertexShaderConst = 0;
1506     caps->PixelShaderVersion = 0;
1507     caps->PixelShader1xMaxValue = 0.0f;
1508     caps->MaxPixelShaderConst = 0;
1509     caps->VSClipping = FALSE;
1510 }
1511
1512 static BOOL shader_none_color_fixup_supported(struct color_fixup_desc fixup)
1513 {
1514     if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
1515     {
1516         TRACE("Checking support for fixup:\n");
1517         dump_color_fixup_desc(fixup);
1518     }
1519
1520     /* Faked to make some apps happy. */
1521     if (!is_complex_fixup(fixup))
1522     {
1523         TRACE("[OK]\n");
1524         return TRUE;
1525     }
1526
1527     TRACE("[FAILED]\n");
1528     return FALSE;
1529 }
1530
1531 const shader_backend_t none_shader_backend = {
1532     shader_none_handle_instruction,
1533     shader_none_select,
1534     shader_none_select_depth_blt,
1535     shader_none_deselect_depth_blt,
1536     shader_none_update_float_vertex_constants,
1537     shader_none_update_float_pixel_constants,
1538     shader_none_load_constants,
1539     shader_none_load_np2fixup_constants,
1540     shader_none_destroy,
1541     shader_none_alloc,
1542     shader_none_free,
1543     shader_none_dirty_const,
1544     shader_none_get_caps,
1545     shader_none_color_fixup_supported,
1546 };
1547
1548 static HRESULT shader_set_function(struct wined3d_shader *shader, const DWORD *byte_code,
1549         const struct wined3d_shader_signature *output_signature, DWORD float_const_count)
1550 {
1551     struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
1552     const struct wined3d_shader_frontend *fe;
1553     HRESULT hr;
1554
1555     TRACE("shader %p, byte_code %p, output_signature %p, float_const_count %u.\n",
1556             shader, byte_code, output_signature, float_const_count);
1557
1558     fe = shader_select_frontend(*byte_code);
1559     if (!fe)
1560     {
1561         FIXME("Unable to find frontend for shader.\n");
1562         return WINED3DERR_INVALIDCALL;
1563     }
1564     shader->frontend = fe;
1565     shader->frontend_data = fe->shader_init(byte_code, output_signature);
1566     if (!shader->frontend_data)
1567     {
1568         FIXME("Failed to initialize frontend.\n");
1569         return WINED3DERR_INVALIDCALL;
1570     }
1571
1572     /* First pass: trace shader. */
1573     if (TRACE_ON(d3d_shader))
1574         shader_trace_init(fe, shader->frontend_data, byte_code);
1575
1576     /* Initialize immediate constant lists. */
1577     list_init(&shader->constantsF);
1578     list_init(&shader->constantsB);
1579     list_init(&shader->constantsI);
1580
1581     /* Second pass: figure out which registers are used, what the semantics are, etc. */
1582     hr = shader_get_registers_used(shader, fe,
1583             reg_maps, shader->input_signature, shader->output_signature,
1584             byte_code, float_const_count);
1585     if (FAILED(hr)) return hr;
1586
1587     shader->function = HeapAlloc(GetProcessHeap(), 0, shader->functionLength);
1588     if (!shader->function)
1589         return E_OUTOFMEMORY;
1590     memcpy(shader->function, byte_code, shader->functionLength);
1591
1592     return WINED3D_OK;
1593 }
1594
1595 ULONG CDECL wined3d_shader_incref(struct wined3d_shader *shader)
1596 {
1597     ULONG refcount = InterlockedIncrement(&shader->ref);
1598
1599     TRACE("%p increasing refcount to %u.\n", shader, refcount);
1600
1601     return refcount;
1602 }
1603
1604 /* Do not call while under the GL lock. */
1605 ULONG CDECL wined3d_shader_decref(struct wined3d_shader *shader)
1606 {
1607     ULONG refcount = InterlockedDecrement(&shader->ref);
1608
1609     TRACE("%p decreasing refcount to %u.\n", shader, refcount);
1610
1611     if (!refcount)
1612     {
1613         shader_cleanup(shader);
1614         shader->parent_ops->wined3d_object_destroyed(shader->parent);
1615         HeapFree(GetProcessHeap(), 0, shader);
1616     }
1617
1618     return refcount;
1619 }
1620
1621 void * CDECL wined3d_shader_get_parent(const struct wined3d_shader *shader)
1622 {
1623     TRACE("shader %p.\n", shader);
1624
1625     return shader->parent;
1626 }
1627
1628 HRESULT CDECL wined3d_shader_get_byte_code(const struct wined3d_shader *shader,
1629         void *byte_code, UINT *byte_code_size)
1630 {
1631     TRACE("shader %p, byte_code %p, byte_code_size %p.\n", shader, byte_code, byte_code_size);
1632
1633     if (!byte_code)
1634     {
1635         *byte_code_size = shader->functionLength;
1636         return WINED3D_OK;
1637     }
1638
1639     if (*byte_code_size < shader->functionLength)
1640     {
1641         /* MSDN claims (for d3d8 at least) that if *byte_code_size is smaller
1642          * than the required size we should write the required size and
1643          * return D3DERR_MOREDATA. That's not actually true. */
1644         return WINED3DERR_INVALIDCALL;
1645     }
1646
1647     memcpy(byte_code, shader->function, shader->functionLength);
1648
1649     return WINED3D_OK;
1650 }
1651
1652 /* Set local constants for d3d8 shaders. */
1653 HRESULT CDECL wined3d_shader_set_local_constants_float(struct wined3d_shader *shader,
1654         UINT start_idx, const float *src_data, UINT count)
1655 {
1656     UINT end_idx = start_idx + count;
1657     UINT i;
1658
1659     TRACE("shader %p, start_idx %u, src_data %p, count %u.\n", shader, start_idx, src_data, count);
1660
1661     if (end_idx > shader->limits.constant_float)
1662     {
1663         WARN("end_idx %u > float constants limit %u.\n",
1664                 end_idx, shader->limits.constant_float);
1665         end_idx = shader->limits.constant_float;
1666     }
1667
1668     for (i = start_idx; i < end_idx; ++i)
1669     {
1670         struct local_constant *lconst = HeapAlloc(GetProcessHeap(), 0, sizeof(local_constant));
1671         if (!lconst)
1672             return E_OUTOFMEMORY;
1673
1674         lconst->idx = i;
1675         memcpy(lconst->value, src_data + (i - start_idx) * 4 /* 4 components */, 4 * sizeof(float));
1676         list_add_head(&shader->constantsF, &lconst->entry);
1677     }
1678
1679     return WINED3D_OK;
1680 }
1681
1682 void find_vs_compile_args(const struct wined3d_state *state,
1683         const struct wined3d_shader *shader, struct vs_compile_args *args)
1684 {
1685     args->fog_src = state->render_states[WINED3DRS_FOGTABLEMODE]
1686             == WINED3DFOG_NONE ? VS_FOG_COORD : VS_FOG_Z;
1687     args->clip_enabled = state->render_states[WINED3DRS_CLIPPING]
1688             && state->render_states[WINED3DRS_CLIPPLANEENABLE];
1689     args->swizzle_map = shader->device->strided_streams.swizzle_map;
1690 }
1691
1692 static BOOL match_usage(BYTE usage1, BYTE usage_idx1, BYTE usage2, BYTE usage_idx2)
1693 {
1694     if (usage_idx1 != usage_idx2) return FALSE;
1695     if (usage1 == usage2) return TRUE;
1696     if (usage1 == WINED3DDECLUSAGE_POSITION && usage2 == WINED3DDECLUSAGE_POSITIONT) return TRUE;
1697     if (usage2 == WINED3DDECLUSAGE_POSITION && usage1 == WINED3DDECLUSAGE_POSITIONT) return TRUE;
1698
1699     return FALSE;
1700 }
1701
1702 BOOL vshader_get_input(struct wined3d_shader *shader,
1703         BYTE usage_req, BYTE usage_idx_req, unsigned int *regnum)
1704 {
1705     WORD map = shader->reg_maps.input_registers;
1706     unsigned int i;
1707
1708     for (i = 0; map; map >>= 1, ++i)
1709     {
1710         if (!(map & 1)) continue;
1711
1712         if (match_usage(shader->u.vs.attributes[i].usage,
1713                 shader->u.vs.attributes[i].usage_idx, usage_req, usage_idx_req))
1714         {
1715             *regnum = i;
1716             return TRUE;
1717         }
1718     }
1719     return FALSE;
1720 }
1721
1722 static void vertexshader_set_limits(struct wined3d_shader *shader)
1723 {
1724     DWORD shader_version = WINED3D_SHADER_VERSION(shader->reg_maps.shader_version.major,
1725             shader->reg_maps.shader_version.minor);
1726     IWineD3DDeviceImpl *device = shader->device;
1727
1728     shader->limits.texcoord = 0;
1729     shader->limits.attributes = 16;
1730     shader->limits.packed_input = 0;
1731
1732     switch (shader_version)
1733     {
1734         case WINED3D_SHADER_VERSION(1, 0):
1735         case WINED3D_SHADER_VERSION(1, 1):
1736             shader->limits.temporary = 12;
1737             shader->limits.constant_bool = 0;
1738             shader->limits.constant_int = 0;
1739             shader->limits.address = 1;
1740             shader->limits.packed_output = 12;
1741             shader->limits.sampler = 0;
1742             shader->limits.label = 0;
1743             /* TODO: vs_1_1 has a minimum of 96 constants. What happens when
1744              * a vs_1_1 shader is used on a vs_3_0 capable card that has 256
1745              * constants? */
1746             shader->limits.constant_float = min(256, device->d3d_vshader_constantF);
1747             break;
1748
1749         case WINED3D_SHADER_VERSION(2, 0):
1750         case WINED3D_SHADER_VERSION(2, 1):
1751             shader->limits.temporary = 12;
1752             shader->limits.constant_bool = 16;
1753             shader->limits.constant_int = 16;
1754             shader->limits.address = 1;
1755             shader->limits.packed_output = 12;
1756             shader->limits.sampler = 0;
1757             shader->limits.label = 16;
1758             shader->limits.constant_float = min(256, device->d3d_vshader_constantF);
1759             break;
1760
1761         case WINED3D_SHADER_VERSION(4, 0):
1762             FIXME("Using 3.0 limits for 4.0 shader.\n");
1763             /* Fall through. */
1764
1765         case WINED3D_SHADER_VERSION(3, 0):
1766             shader->limits.temporary = 32;
1767             shader->limits.constant_bool = 32;
1768             shader->limits.constant_int = 32;
1769             shader->limits.address = 1;
1770             shader->limits.packed_output = 12;
1771             shader->limits.sampler = 4;
1772             shader->limits.label = 16; /* FIXME: 2048 */
1773             /* DX10 cards on Windows advertise a d3d9 constant limit of 256
1774              * even though they are capable of supporting much more (GL
1775              * drivers advertise 1024). d3d9.dll and d3d8.dll clamp the
1776              * wined3d-advertised maximum. Clamp the constant limit for <= 3.0
1777              * shaders to 256. */
1778             shader->limits.constant_float = min(256, device->d3d_vshader_constantF);
1779             break;
1780
1781         default:
1782             shader->limits.temporary = 12;
1783             shader->limits.constant_bool = 16;
1784             shader->limits.constant_int = 16;
1785             shader->limits.address = 1;
1786             shader->limits.packed_output = 12;
1787             shader->limits.sampler = 0;
1788             shader->limits.label = 16;
1789             shader->limits.constant_float = min(256, device->d3d_vshader_constantF);
1790             FIXME("Unrecognized vertex shader version \"%u.%u\".\n",
1791                     shader->reg_maps.shader_version.major,
1792                     shader->reg_maps.shader_version.minor);
1793     }
1794 }
1795
1796 HRESULT vertexshader_init(struct wined3d_shader *shader, IWineD3DDeviceImpl *device,
1797         const DWORD *byte_code, const struct wined3d_shader_signature *output_signature,
1798         void *parent, const struct wined3d_parent_ops *parent_ops)
1799 {
1800     struct wined3d_shader_reg_maps *reg_maps = &shader->reg_maps;
1801     unsigned int i;
1802     HRESULT hr;
1803     WORD map;
1804
1805     if (!byte_code) return WINED3DERR_INVALIDCALL;
1806
1807     shader_init(shader, device, parent, parent_ops);
1808     hr = shader_set_function(shader, byte_code, output_signature, device->d3d_vshader_constantF);
1809     if (FAILED(hr))
1810     {
1811         WARN("Failed to set function, hr %#x.\n", hr);
1812         shader_cleanup(shader);
1813         return hr;
1814     }
1815
1816     map = reg_maps->input_registers;
1817     for (i = 0; map; map >>= 1, ++i)
1818     {
1819         if (!(map & 1) || !shader->input_signature[i].semantic_name)
1820             continue;
1821
1822         shader->u.vs.attributes[i].usage =
1823                 shader_usage_from_semantic_name(shader->input_signature[i].semantic_name);
1824         shader->u.vs.attributes[i].usage_idx = shader->input_signature[i].semantic_idx;
1825     }
1826
1827     if (output_signature)
1828     {
1829         for (i = 0; i < output_signature->element_count; ++i)
1830         {
1831             struct wined3d_shader_signature_element *e = &output_signature->elements[i];
1832             reg_maps->output_registers |= 1 << e->register_idx;
1833             shader->output_signature[e->register_idx] = *e;
1834         }
1835     }
1836
1837     vertexshader_set_limits(shader);
1838
1839     shader->load_local_constsF = reg_maps->usesrelconstF
1840             && !list_empty(&shader->constantsF);
1841
1842     return WINED3D_OK;
1843 }
1844
1845 HRESULT geometryshader_init(struct wined3d_shader *shader, IWineD3DDeviceImpl *device,
1846         const DWORD *byte_code, const struct wined3d_shader_signature *output_signature,
1847         void *parent, const struct wined3d_parent_ops *parent_ops)
1848 {
1849     HRESULT hr;
1850
1851     shader_init(shader, device, parent, parent_ops);
1852     hr = shader_set_function(shader, byte_code, output_signature, 0);
1853     if (FAILED(hr))
1854     {
1855         WARN("Failed to set function, hr %#x.\n", hr);
1856         shader_cleanup(shader);
1857         return hr;
1858     }
1859
1860     shader->load_local_constsF = FALSE;
1861
1862     return WINED3D_OK;
1863 }
1864
1865 void find_ps_compile_args(const struct wined3d_state *state,
1866         const struct wined3d_shader *shader, struct ps_compile_args *args)
1867 {
1868     IWineD3DDeviceImpl *device = shader->device;
1869     const struct wined3d_texture *texture;
1870     UINT i;
1871
1872     memset(args, 0, sizeof(*args)); /* FIXME: Make sure all bits are set. */
1873     if (state->render_states[WINED3DRS_SRGBWRITEENABLE])
1874     {
1875         struct wined3d_surface *rt = device->render_targets[0];
1876         if (rt->resource.format->flags & WINED3DFMT_FLAG_SRGB_WRITE) args->srgb_correction = 1;
1877     }
1878
1879     if (shader->reg_maps.shader_version.major == 1
1880             && shader->reg_maps.shader_version.minor <= 3)
1881     {
1882         for (i = 0; i < 4; ++i)
1883         {
1884             DWORD flags = state->texture_states[i][WINED3DTSS_TEXTURETRANSFORMFLAGS];
1885             DWORD tex_transform = flags & ~WINED3DTTFF_PROJECTED;
1886             if (flags & WINED3DTTFF_PROJECTED)
1887                 tex_transform |= WINED3D_PSARGS_PROJECTED;
1888             args->tex_transform |= tex_transform << i * WINED3D_PSARGS_TEXTRANSFORM_SHIFT;
1889         }
1890     }
1891
1892     for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
1893     {
1894         if (!shader->reg_maps.sampler_type[i])
1895             continue;
1896
1897         texture = state->textures[i];
1898         if (!texture)
1899         {
1900             args->color_fixup[i] = COLOR_FIXUP_IDENTITY;
1901             continue;
1902         }
1903         args->color_fixup[i] = texture->resource.format->color_fixup;
1904
1905         if (texture->resource.format->flags & WINED3DFMT_FLAG_SHADOW)
1906             args->shadow |= 1 << i;
1907
1908         /* Flag samplers that need NP2 texcoord fixup. */
1909         if (!(texture->flags & WINED3D_TEXTURE_POW2_MAT_IDENT))
1910             args->np2_fixup |= (1 << i);
1911     }
1912     if (shader->reg_maps.shader_version.major >= 3)
1913     {
1914         if (device->strided_streams.position_transformed)
1915         {
1916             args->vp_mode = pretransformed;
1917         }
1918         else if (use_vs(state))
1919         {
1920             args->vp_mode = vertexshader;
1921         }
1922         else
1923         {
1924             args->vp_mode = fixedfunction;
1925         }
1926         args->fog = FOG_OFF;
1927     }
1928     else
1929     {
1930         args->vp_mode = vertexshader;
1931         if (state->render_states[WINED3DRS_FOGENABLE])
1932         {
1933             switch (state->render_states[WINED3DRS_FOGTABLEMODE])
1934             {
1935                 case WINED3DFOG_NONE:
1936                     if (device->strided_streams.position_transformed || use_vs(state))
1937                     {
1938                         args->fog = FOG_LINEAR;
1939                         break;
1940                     }
1941
1942                     switch (state->render_states[WINED3DRS_FOGVERTEXMODE])
1943                     {
1944                         case WINED3DFOG_NONE: /* Fall through. */
1945                         case WINED3DFOG_LINEAR: args->fog = FOG_LINEAR; break;
1946                         case WINED3DFOG_EXP:    args->fog = FOG_EXP;    break;
1947                         case WINED3DFOG_EXP2:   args->fog = FOG_EXP2;   break;
1948                     }
1949                     break;
1950
1951                 case WINED3DFOG_LINEAR: args->fog = FOG_LINEAR; break;
1952                 case WINED3DFOG_EXP:    args->fog = FOG_EXP;    break;
1953                 case WINED3DFOG_EXP2:   args->fog = FOG_EXP2;   break;
1954             }
1955         }
1956         else
1957         {
1958             args->fog = FOG_OFF;
1959         }
1960     }
1961 }
1962
1963 static void pixelshader_set_limits(struct wined3d_shader *shader)
1964 {
1965     DWORD shader_version = WINED3D_SHADER_VERSION(shader->reg_maps.shader_version.major,
1966             shader->reg_maps.shader_version.minor);
1967
1968     shader->limits.attributes = 0;
1969     shader->limits.address = 0;
1970     shader->limits.packed_output = 0;
1971
1972     switch (shader_version)
1973     {
1974         case WINED3D_SHADER_VERSION(1, 0):
1975         case WINED3D_SHADER_VERSION(1, 1):
1976         case WINED3D_SHADER_VERSION(1, 2):
1977         case WINED3D_SHADER_VERSION(1, 3):
1978             shader->limits.temporary = 2;
1979             shader->limits.constant_float = 8;
1980             shader->limits.constant_int = 0;
1981             shader->limits.constant_bool = 0;
1982             shader->limits.texcoord = 4;
1983             shader->limits.sampler = 4;
1984             shader->limits.packed_input = 0;
1985             shader->limits.label = 0;
1986             break;
1987
1988         case WINED3D_SHADER_VERSION(1, 4):
1989             shader->limits.temporary = 6;
1990             shader->limits.constant_float = 8;
1991             shader->limits.constant_int = 0;
1992             shader->limits.constant_bool = 0;
1993             shader->limits.texcoord = 6;
1994             shader->limits.sampler = 6;
1995             shader->limits.packed_input = 0;
1996             shader->limits.label = 0;
1997             break;
1998
1999         /* FIXME: Temporaries must match D3DPSHADERCAPS2_0.NumTemps. */
2000         case WINED3D_SHADER_VERSION(2, 0):
2001             shader->limits.temporary = 32;
2002             shader->limits.constant_float = 32;
2003             shader->limits.constant_int = 16;
2004             shader->limits.constant_bool = 16;
2005             shader->limits.texcoord = 8;
2006             shader->limits.sampler = 16;
2007             shader->limits.packed_input = 0;
2008             break;
2009
2010         case WINED3D_SHADER_VERSION(2, 1):
2011             shader->limits.temporary = 32;
2012             shader->limits.constant_float = 32;
2013             shader->limits.constant_int = 16;
2014             shader->limits.constant_bool = 16;
2015             shader->limits.texcoord = 8;
2016             shader->limits.sampler = 16;
2017             shader->limits.packed_input = 0;
2018             shader->limits.label = 16;
2019             break;
2020
2021         case WINED3D_SHADER_VERSION(4, 0):
2022             FIXME("Using 3.0 limits for 4.0 shader.\n");
2023             /* Fall through. */
2024
2025         case WINED3D_SHADER_VERSION(3, 0):
2026             shader->limits.temporary = 32;
2027             shader->limits.constant_float = 224;
2028             shader->limits.constant_int = 16;
2029             shader->limits.constant_bool = 16;
2030             shader->limits.texcoord = 0;
2031             shader->limits.sampler = 16;
2032             shader->limits.packed_input = 12;
2033             shader->limits.label = 16; /* FIXME: 2048 */
2034             break;
2035
2036         default:
2037             shader->limits.temporary = 32;
2038             shader->limits.constant_float = 32;
2039             shader->limits.constant_int = 16;
2040             shader->limits.constant_bool = 16;
2041             shader->limits.texcoord = 8;
2042             shader->limits.sampler = 16;
2043             shader->limits.packed_input = 0;
2044             shader->limits.label = 0;
2045             FIXME("Unrecognized pixel shader version %u.%u\n",
2046                     shader->reg_maps.shader_version.major,
2047                     shader->reg_maps.shader_version.minor);
2048     }
2049 }
2050
2051 HRESULT pixelshader_init(struct wined3d_shader *shader, IWineD3DDeviceImpl *device,
2052         const DWORD *byte_code, const struct wined3d_shader_signature *output_signature,
2053         void *parent, const struct wined3d_parent_ops *parent_ops)
2054 {
2055     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
2056     unsigned int i, highest_reg_used = 0, num_regs_used = 0;
2057     HRESULT hr;
2058
2059     if (!byte_code) return WINED3DERR_INVALIDCALL;
2060
2061     shader_init(shader, device, parent, parent_ops);
2062     hr = shader_set_function(shader, byte_code, output_signature, device->d3d_pshader_constantF);
2063     if (FAILED(hr))
2064     {
2065         WARN("Failed to set function, hr %#x.\n", hr);
2066         shader_cleanup(shader);
2067         return hr;
2068     }
2069
2070     pixelshader_set_limits(shader);
2071
2072     for (i = 0; i < MAX_REG_INPUT; ++i)
2073     {
2074         if (shader->u.ps.input_reg_used[i])
2075         {
2076             ++num_regs_used;
2077             highest_reg_used = i;
2078         }
2079     }
2080
2081     /* Don't do any register mapping magic if it is not needed, or if we can't
2082      * achieve anything anyway */
2083     if (highest_reg_used < (gl_info->limits.glsl_varyings / 4)
2084             || num_regs_used > (gl_info->limits.glsl_varyings / 4))
2085     {
2086         if (num_regs_used > (gl_info->limits.glsl_varyings / 4))
2087         {
2088             /* This happens with relative addressing. The input mapper function
2089              * warns about this if the higher registers are declared too, so
2090              * don't write a FIXME here */
2091             WARN("More varying registers used than supported\n");
2092         }
2093
2094         for (i = 0; i < MAX_REG_INPUT; ++i)
2095         {
2096             shader->u.ps.input_reg_map[i] = i;
2097         }
2098
2099         shader->u.ps.declared_in_count = highest_reg_used + 1;
2100     }
2101     else
2102     {
2103         shader->u.ps.declared_in_count = 0;
2104         for (i = 0; i < MAX_REG_INPUT; ++i)
2105         {
2106             if (shader->u.ps.input_reg_used[i])
2107                 shader->u.ps.input_reg_map[i] = shader->u.ps.declared_in_count++;
2108             else shader->u.ps.input_reg_map[i] = ~0U;
2109         }
2110     }
2111
2112     shader->load_local_constsF = FALSE;
2113
2114     return WINED3D_OK;
2115 }
2116
2117 void pixelshader_update_samplers(struct wined3d_shader_reg_maps *reg_maps, struct wined3d_texture * const *textures)
2118 {
2119     WINED3DSAMPLER_TEXTURE_TYPE *sampler_type = reg_maps->sampler_type;
2120     unsigned int i;
2121
2122     if (reg_maps->shader_version.major != 1) return;
2123
2124     for (i = 0; i < max(MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS); ++i)
2125     {
2126         /* We don't sample from this sampler. */
2127         if (!sampler_type[i]) continue;
2128
2129         if (!textures[i])
2130         {
2131             WARN("No texture bound to sampler %u, using 2D.\n", i);
2132             sampler_type[i] = WINED3DSTT_2D;
2133             continue;
2134         }
2135
2136         switch (textures[i]->target)
2137         {
2138             case GL_TEXTURE_RECTANGLE_ARB:
2139             case GL_TEXTURE_2D:
2140                 /* We have to select between texture rectangles and 2D
2141                  * textures later because 2.0 and 3.0 shaders only have
2142                  * WINED3DSTT_2D as well. */
2143                 sampler_type[i] = WINED3DSTT_2D;
2144                 break;
2145
2146             case GL_TEXTURE_3D:
2147                 sampler_type[i] = WINED3DSTT_VOLUME;
2148                 break;
2149
2150             case GL_TEXTURE_CUBE_MAP_ARB:
2151                 sampler_type[i] = WINED3DSTT_CUBE;
2152                 break;
2153
2154             default:
2155                 FIXME("Unrecognized texture type %#x, using 2D.\n", textures[i]->target);
2156                 sampler_type[i] = WINED3DSTT_2D;
2157         }
2158     }
2159 }