Debian Codegraph @

mojoshader.c

raw symbols SCIP
1 /**
2 * MojoShader; generate shader programs from bytecode of compiled
3 * Direct3D shaders.
4 *
5 * Please see the file LICENSE.txt in the source's root directory.
6 *
7 * This file written by Ryan C. Gordon.
8 */
9
10 // !!! FIXME: this file really needs to be split up.
11 // !!! FIXME: I keep changing coding styles for symbols and typedefs.
12
13 // !!! FIXME: rules from MSDN about temp registers we probably don't check.
14 // - There are limited temporaries: vs_1_1 has 12 (ps_1_1 has _2_!).
15 // - SM2 apparently was variable, between 12 and 32. Shader Model 3 has 32.
16 // - A maximum of three temp registers can be used in a single instruction.
17
18 #define __MOJOSHADER_INTERNAL__ 1
19 #include "profiles/mojoshader_profile.h"
20
21 // Deal with register lists... !!! FIXME: I sort of hate this.
22
23 static void free_reglist(MOJOSHADER_free f, void *d, RegisterList *item)
24 {
25 while (item != NULL)
26 {
27 RegisterList *next = item->next;
28 f(item, d);
29 item = next;
30 } // while
31 } // free_reglist
32
33 static inline const RegisterList *reglist_exists(RegisterList *prev,
34 const RegisterType regtype,
35 const int regnum)
36 {
37 return (reglist_find(prev, regtype, regnum));
38 } // reglist_exists
39
40 static inline int register_was_written(Context *ctx, const RegisterType rtype,
41 const int regnum)
42 {
43 RegisterList *reg = reglist_find(&ctx->used_registers, rtype, regnum);
44 return (reg && reg->written);
45 } // register_was_written
46
47 static inline int get_defined_register(Context *ctx, const RegisterType rtype,
48 const int regnum)
49 {
50 return (reglist_exists(&ctx->defined_registers, rtype, regnum) != NULL);
51 } // get_defined_register
52
53 static void add_attribute_register(Context *ctx, const RegisterType rtype,
54 const int regnum, const MOJOSHADER_usage usage,
55 const int index, const int writemask, int flags)
56 {
57 RegisterList *item = reglist_insert(ctx, &ctx->attributes, rtype, regnum);
58 item->usage = usage;
59 item->index = index;
60 item->writemask = writemask;
61 item->misc = flags;
62
63 if ((rtype == REG_TYPE_OUTPUT) && (usage == MOJOSHADER_USAGE_POINTSIZE))
64 ctx->uses_pointsize = 1; // note that we have to check this later.
65 else if ((rtype == REG_TYPE_OUTPUT) && (usage == MOJOSHADER_USAGE_FOG))
66 ctx->uses_fog = 1; // note that we have to check this later.
67 } // add_attribute_register
68
69 static inline TextureType cvtMojoToD3DSamplerType(const MOJOSHADER_samplerType type)
70 {
71 return (TextureType) (((int) type) + 2);
72 } // cvtMojoToD3DSamplerType
73
74 static inline MOJOSHADER_samplerType cvtD3DToMojoSamplerType(const TextureType type)
75 {
76 return (MOJOSHADER_samplerType) (((int) type) - 2);
77 } // cvtD3DToMojoSamplerType
78
79 static inline void add_sampler(Context *ctx, const int regnum,
80 TextureType ttype, const int texbem)
81 {
82 const RegisterType rtype = REG_TYPE_SAMPLER;
83
84 // !!! FIXME: make sure it doesn't exist?
85 // !!! FIXME: (ps_1_1 assume we can add it multiple times...)
86 RegisterList *item = reglist_insert(ctx, &ctx->samplers, rtype, regnum);
87
88 if (ctx->samplermap != NULL)
89 {
90 unsigned int i;
91 for (i = 0; i < ctx->samplermap_count; i++)
92 {
93 if (ctx->samplermap[i].index == regnum)
94 {
95 ttype = cvtMojoToD3DSamplerType(ctx->samplermap[i].type);
96 break;
97 } // if
98 } // for
99 } // if
100
101 item->index = (int) ttype;
102 item->misc |= texbem;
103 } // add_sampler
104
105 static inline void adjust_token_position(Context *ctx, const int incr)
106 {
107 ctx->tokens += incr;
108 ctx->tokencount -= incr;
109 ctx->current_position += incr * sizeof (uint32);
110 } // adjust_token_position
111
112 // Generate emitter declarations for each profile with this macro...
113
114 #define PREDECLARE_PROFILE(prof) \
115 void emit_##prof##_start(Context *ctx, const char *profilestr); \
116 void emit_##prof##_end(Context *ctx); \
117 void emit_##prof##_phase(Context *ctx); \
118 void emit_##prof##_finalize(Context *ctx); \
119 void emit_##prof##_global(Context *ctx, RegisterType regtype, int regnum);\
120 void emit_##prof##_array(Context *ctx, VariableList *var); \
121 void emit_##prof##_const_array(Context *ctx, const ConstantsList *clist, \
122 int base, int size); \
123 void emit_##prof##_uniform(Context *ctx, RegisterType regtype, int regnum,\
124 const VariableList *var); \
125 void emit_##prof##_sampler(Context *ctx, int stage, TextureType ttype, \
126 int tb); \
127 void emit_##prof##_attribute(Context *ctx, RegisterType regtype, \
128 int regnum, MOJOSHADER_usage usage, \
129 int index, int wmask, int flags); \
130 void emit_##prof##_NOP(Context *ctx); \
131 void emit_##prof##_MOV(Context *ctx); \
132 void emit_##prof##_ADD(Context *ctx); \
133 void emit_##prof##_SUB(Context *ctx); \
134 void emit_##prof##_MAD(Context *ctx); \
135 void emit_##prof##_MUL(Context *ctx); \
136 void emit_##prof##_RCP(Context *ctx); \
137 void emit_##prof##_RSQ(Context *ctx); \
138 void emit_##prof##_DP3(Context *ctx); \
139 void emit_##prof##_DP4(Context *ctx); \
140 void emit_##prof##_MIN(Context *ctx); \
141 void emit_##prof##_MAX(Context *ctx); \
142 void emit_##prof##_SLT(Context *ctx); \
143 void emit_##prof##_SGE(Context *ctx); \
144 void emit_##prof##_EXP(Context *ctx); \
145 void emit_##prof##_LOG(Context *ctx); \
146 void emit_##prof##_LIT(Context *ctx); \
147 void emit_##prof##_DST(Context *ctx); \
148 void emit_##prof##_LRP(Context *ctx); \
149 void emit_##prof##_FRC(Context *ctx); \
150 void emit_##prof##_M4X4(Context *ctx); \
151 void emit_##prof##_M4X3(Context *ctx); \
152 void emit_##prof##_M3X4(Context *ctx); \
153 void emit_##prof##_M3X3(Context *ctx); \
154 void emit_##prof##_M3X2(Context *ctx); \
155 void emit_##prof##_CALL(Context *ctx); \
156 void emit_##prof##_CALLNZ(Context *ctx); \
157 void emit_##prof##_LOOP(Context *ctx); \
158 void emit_##prof##_ENDLOOP(Context *ctx); \
159 void emit_##prof##_LABEL(Context *ctx); \
160 void emit_##prof##_DCL(Context *ctx); \
161 void emit_##prof##_POW(Context *ctx); \
162 void emit_##prof##_CRS(Context *ctx); \
163 void emit_##prof##_SGN(Context *ctx); \
164 void emit_##prof##_ABS(Context *ctx); \
165 void emit_##prof##_NRM(Context *ctx); \
166 void emit_##prof##_SINCOS(Context *ctx); \
167 void emit_##prof##_REP(Context *ctx); \
168 void emit_##prof##_ENDREP(Context *ctx); \
169 void emit_##prof##_IF(Context *ctx); \
170 void emit_##prof##_IFC(Context *ctx); \
171 void emit_##prof##_ELSE(Context *ctx); \
172 void emit_##prof##_ENDIF(Context *ctx); \
173 void emit_##prof##_BREAK(Context *ctx); \
174 void emit_##prof##_BREAKC(Context *ctx); \
175 void emit_##prof##_MOVA(Context *ctx); \
176 void emit_##prof##_DEFB(Context *ctx); \
177 void emit_##prof##_DEFI(Context *ctx); \
178 void emit_##prof##_TEXCRD(Context *ctx); \
179 void emit_##prof##_TEXKILL(Context *ctx); \
180 void emit_##prof##_TEXLD(Context *ctx); \
181 void emit_##prof##_TEXBEM(Context *ctx); \
182 void emit_##prof##_TEXBEML(Context *ctx); \
183 void emit_##prof##_TEXREG2AR(Context *ctx); \
184 void emit_##prof##_TEXREG2GB(Context *ctx); \
185 void emit_##prof##_TEXM3X2PAD(Context *ctx); \
186 void emit_##prof##_TEXM3X2TEX(Context *ctx); \
187 void emit_##prof##_TEXM3X3PAD(Context *ctx); \
188 void emit_##prof##_TEXM3X3TEX(Context *ctx); \
189 void emit_##prof##_TEXM3X3SPEC(Context *ctx); \
190 void emit_##prof##_TEXM3X3VSPEC(Context *ctx); \
191 void emit_##prof##_EXPP(Context *ctx); \
192 void emit_##prof##_LOGP(Context *ctx); \
193 void emit_##prof##_CND(Context *ctx); \
194 void emit_##prof##_DEF(Context *ctx); \
195 void emit_##prof##_TEXREG2RGB(Context *ctx); \
196 void emit_##prof##_TEXDP3TEX(Context *ctx); \
197 void emit_##prof##_TEXM3X2DEPTH(Context *ctx); \
198 void emit_##prof##_TEXDP3(Context *ctx); \
199 void emit_##prof##_TEXM3X3(Context *ctx); \
200 void emit_##prof##_TEXDEPTH(Context *ctx); \
201 void emit_##prof##_CMP(Context *ctx); \
202 void emit_##prof##_BEM(Context *ctx); \
203 void emit_##prof##_DP2ADD(Context *ctx); \
204 void emit_##prof##_DSX(Context *ctx); \
205 void emit_##prof##_DSY(Context *ctx); \
206 void emit_##prof##_TEXLDD(Context *ctx); \
207 void emit_##prof##_SETP(Context *ctx); \
208 void emit_##prof##_TEXLDL(Context *ctx); \
209 void emit_##prof##_BREAKP(Context *ctx); \
210 void emit_##prof##_RESERVED(Context *ctx); \
211 void emit_##prof##_RET(Context *ctx); \
212 const char *get_##prof##_varname(Context *ctx, RegisterType rt, \
213 int regnum); \
214 const char *get_##prof##_const_array_varname(Context *ctx, \
215 int base, int size);
216
217 // Check for profile support...
218
219 #define AT_LEAST_ONE_PROFILE 0
220
221 #if !SUPPORT_PROFILE_BYTECODE
222 #define PROFILE_EMITTER_BYTECODE(op)
223 #else
224 #undef AT_LEAST_ONE_PROFILE
225 #define AT_LEAST_ONE_PROFILE 1
226 #define PROFILE_EMITTER_BYTECODE(op) emit_BYTECODE_##op,
227 PREDECLARE_PROFILE(BYTECODE)
228 #endif
229
230 #if !SUPPORT_PROFILE_D3D
231 #define PROFILE_EMITTER_D3D(op)
232 #else
233 #undef AT_LEAST_ONE_PROFILE
234 #define AT_LEAST_ONE_PROFILE 1
235 #define PROFILE_EMITTER_D3D(op) emit_D3D_##op,
236 PREDECLARE_PROFILE(D3D)
237 #endif
238
239 #if !SUPPORT_PROFILE_HLSL
240 #define PROFILE_EMITTER_HLSL(op)
241 #else
242 #undef AT_LEAST_ONE_PROFILE
243 #define AT_LEAST_ONE_PROFILE 1
244 #define PROFILE_EMITTER_HLSL(op) emit_HLSL_##op,
245 PREDECLARE_PROFILE(HLSL)
246 #endif
247
248 #if !SUPPORT_PROFILE_GLSL
249 #define PROFILE_EMITTER_GLSL(op)
250 #else
251 #undef AT_LEAST_ONE_PROFILE
252 #define AT_LEAST_ONE_PROFILE 1
253 #define PROFILE_EMITTER_GLSL(op) emit_GLSL_##op,
254 PREDECLARE_PROFILE(GLSL)
255 #endif
256
257 #if !SUPPORT_PROFILE_METAL
258 #define PROFILE_EMITTER_METAL(op)
259 #else
260 #undef AT_LEAST_ONE_PROFILE
261 #define AT_LEAST_ONE_PROFILE 1
262 #define PROFILE_EMITTER_METAL(op) emit_METAL_##op,
263 PREDECLARE_PROFILE(METAL)
264 #endif
265
266 #if !SUPPORT_PROFILE_ARB1
267 #define PROFILE_EMITTER_ARB1(op)
268 #else
269 #undef AT_LEAST_ONE_PROFILE
270 #define AT_LEAST_ONE_PROFILE 1
271 #define PROFILE_EMITTER_ARB1(op) emit_ARB1_##op,
272 PREDECLARE_PROFILE(ARB1)
273 #endif
274
275 #if !SUPPORT_PROFILE_SPIRV
276 #define PROFILE_EMITTER_SPIRV(op)
277 #else
278 #undef AT_LEAST_ONE_PROFILE
279 #define AT_LEAST_ONE_PROFILE 1
280 #define PROFILE_EMITTER_SPIRV(op) emit_SPIRV_##op,
281 PREDECLARE_PROFILE(SPIRV)
282 #endif
283
284 #if !AT_LEAST_ONE_PROFILE
285 #error No profiles are supported. Fix your build.
286 #endif
287
288 #define DEFINE_PROFILE(prof) { \
289 MOJOSHADER_PROFILE_##prof, \
290 emit_##prof##_start, \
291 emit_##prof##_end, \
292 emit_##prof##_phase, \
293 emit_##prof##_global, \
294 emit_##prof##_array, \
295 emit_##prof##_const_array, \
296 emit_##prof##_uniform, \
297 emit_##prof##_sampler, \
298 emit_##prof##_attribute, \
299 emit_##prof##_finalize, \
300 get_##prof##_varname, \
301 get_##prof##_const_array_varname, \
302 },
303
304 static const Profile profiles[] =
305 {
306 #if SUPPORT_PROFILE_D3D
307 DEFINE_PROFILE(D3D)
308 #endif
309 #if SUPPORT_PROFILE_BYTECODE
310 DEFINE_PROFILE(BYTECODE)
311 #endif
312 #if SUPPORT_PROFILE_HLSL
313 DEFINE_PROFILE(HLSL)
314 #endif
315 #if SUPPORT_PROFILE_GLSL
316 DEFINE_PROFILE(GLSL)
317 #endif
318 #if SUPPORT_PROFILE_ARB1
319 DEFINE_PROFILE(ARB1)
320 #endif
321 #if SUPPORT_PROFILE_METAL
322 DEFINE_PROFILE(METAL)
323 #endif
324 #if SUPPORT_PROFILE_SPIRV
325 DEFINE_PROFILE(SPIRV)
326 #endif
327 };
328
329 #undef DEFINE_PROFILE
330
331 // This is for profiles that extend other profiles...
332 static const struct { const char *from; const char *to; } profileMap[] =
333 {
334 { MOJOSHADER_PROFILE_GLSPIRV, MOJOSHADER_PROFILE_SPIRV },
335 { MOJOSHADER_PROFILE_GLSLES, MOJOSHADER_PROFILE_GLSL },
336 { MOJOSHADER_PROFILE_GLSLES3, MOJOSHADER_PROFILE_GLSL },
337 { MOJOSHADER_PROFILE_GLSL120, MOJOSHADER_PROFILE_GLSL },
338 { MOJOSHADER_PROFILE_NV2, MOJOSHADER_PROFILE_ARB1 },
339 { MOJOSHADER_PROFILE_NV3, MOJOSHADER_PROFILE_ARB1 },
340 { MOJOSHADER_PROFILE_NV4, MOJOSHADER_PROFILE_ARB1 },
341 };
342
343 // The PROFILE_EMITTER_* items MUST be in the same order as profiles[]!
344 #define PROFILE_EMITTERS(op) { \
345 PROFILE_EMITTER_D3D(op) \
346 PROFILE_EMITTER_BYTECODE(op) \
347 PROFILE_EMITTER_HLSL(op) \
348 PROFILE_EMITTER_GLSL(op) \
349 PROFILE_EMITTER_ARB1(op) \
350 PROFILE_EMITTER_METAL(op) \
351 PROFILE_EMITTER_SPIRV(op) \
352 }
353
354 static int parse_destination_token(Context *ctx, DestArgInfo *info)
355 {
356 // !!! FIXME: recheck against the spec for ranges (like RASTOUT values, etc).
357 if (ctx->tokencount == 0)
358 {
359 fail(ctx, "Out of tokens in destination parameter");
360 return 0;
361 } // if
362
363 const uint32 token = SWAP32(*(ctx->tokens));
364 const int reserved1 = (int) ((token >> 14) & 0x3); // bits 14 through 15
365 const int reserved2 = (int) ((token >> 31) & 0x1); // bit 31
366
367 info->token = ctx->tokens;
368 info->regnum = (int) (token & 0x7ff); // bits 0 through 10
369 info->relative = (int) ((token >> 13) & 0x1); // bit 13
370 info->orig_writemask = (int) ((token >> 16) & 0xF); // bits 16 through 19
371 info->result_mod = (int) ((token >> 20) & 0xF); // bits 20 through 23
372 info->result_shift = (int) ((token >> 24) & 0xF); // bits 24 through 27 abc
373 info->regtype = (RegisterType) (((token >> 28) & 0x7) | ((token >> 8) & 0x18)); // bits 28-30, 11-12
374
375 int writemask;
376 if (isscalar(ctx, ctx->shader_type, info->regtype, info->regnum))
377 writemask = 0x1; // just x.
378 else
379 writemask = info->orig_writemask;
380
381 set_dstarg_writemask(info, writemask); // bits 16 through 19.
382
383 // all the REG_TYPE_CONSTx types are the same register type, it's just
384 // split up so its regnum can be > 2047 in the bytecode. Clean it up.
385 if (info->regtype == REG_TYPE_CONST2)
386 {
387 info->regtype = REG_TYPE_CONST;
388 info->regnum += 2048;
389 } // else if
390 else if (info->regtype == REG_TYPE_CONST3)
391 {
392 info->regtype = REG_TYPE_CONST;
393 info->regnum += 4096;
394 } // else if
395 else if (info->regtype == REG_TYPE_CONST4)
396 {
397 info->regtype = REG_TYPE_CONST;
398 info->regnum += 6144;
399 } // else if
400
401 // swallow token for now, for multiple calls in a row.
402 adjust_token_position(ctx, 1);
403
404 if (reserved1 != 0x0)
405 fail(ctx, "Reserved bit #1 in destination token must be zero");
406
407 if (reserved2 != 0x1)
408 fail(ctx, "Reserved bit #2 in destination token must be one");
409
410 if (info->relative)
411 {
412 if (!shader_is_vertex(ctx))
413 fail(ctx, "Relative addressing in non-vertex shader");
414 if (!shader_version_atleast(ctx, 3, 0))
415 fail(ctx, "Relative addressing in vertex shader version < 3.0");
416 if ((!ctx->ctab.have_ctab) && (!ctx->ignores_ctab))
417 {
418 // it's hard to do this efficiently without!
419 fail(ctx, "relative addressing unsupported without a CTAB");
420 } // if
421
422 // !!! FIXME: I don't have a shader that has a relative dest currently.
423 fail(ctx, "Relative addressing of dest tokens is unsupported");
424 return 2;
425 } // if
426
427 const int s = info->result_shift;
428 if (s != 0)
429 {
430 if (!shader_is_pixel(ctx))
431 fail(ctx, "Result shift scale in non-pixel shader");
432 if (shader_version_atleast(ctx, 2, 0))
433 fail(ctx, "Result shift scale in pixel shader version >= 2.0");
434 if ( ! (((s >= 1) && (s <= 3)) || ((s >= 0xD) && (s <= 0xF))) )
435 fail(ctx, "Result shift scale isn't 1 to 3, or 13 to 15.");
436 } // if
437
438 if (info->result_mod & MOD_PP) // Partial precision (pixel shaders only)
439 {
440 if (!shader_is_pixel(ctx))
441 fail(ctx, "Partial precision result mod in non-pixel shader");
442 } // if
443
444 if (info->result_mod & MOD_CENTROID) // Centroid (pixel shaders only)
445 {
446 if (!shader_is_pixel(ctx))
447 fail(ctx, "Centroid result mod in non-pixel shader");
448 else if (!ctx->centroid_allowed) // only on DCL opcodes!
449 fail(ctx, "Centroid modifier not allowed here");
450 } // if
451
452 if (/*(info->regtype < 0) ||*/ (info->regtype > REG_TYPE_MAX))
453 fail(ctx, "Register type is out of range");
454
455 if (!isfail(ctx))
456 set_used_register(ctx, info->regtype, info->regnum, 1);
457
458 return 1;
459 } // parse_destination_token
460
461
462 static void determine_constants_arrays(Context *ctx)
463 {
464 // Only process this stuff once. This is called after all DEF* opcodes
465 // could have been parsed.
466 if (ctx->determined_constants_arrays)
467 return;
468
469 ctx->determined_constants_arrays = 1;
470
471 if (ctx->constant_count <= 1)
472 return; // nothing to sort or group.
473
474 // Sort the linked list into an array for easier tapdancing...
475 ConstantsList **array = (ConstantsList **) alloca(sizeof (ConstantsList *) * (ctx->constant_count + 1));
476 ConstantsList *item = ctx->constants;
477 int i;
478
479 for (i = 0; i < ctx->constant_count; i++)
480 {
481 if (item == NULL)
482 {
483 fail(ctx, "BUG: mismatched constant list and count");
484 return;
485 } // if
486
487 array[i] = item;
488 item = item->next;
489 } // for
490
491 array[ctx->constant_count] = NULL;
492
493 // bubble sort ftw.
494 int sorted;
495 do
496 {
497 sorted = 1;
498 for (i = 0; i < ctx->constant_count-1; i++)
499 {
500 if (array[i]->constant.index > array[i+1]->constant.index)
501 {
502 ConstantsList *tmp = array[i];
503 array[i] = array[i+1];
504 array[i+1] = tmp;
505 sorted = 0;
506 } // if
507 } // for
508 } while (!sorted);
509
510 // okay, sorted. While we're here, let's redo the linked list in order...
511 for (i = 0; i < ctx->constant_count; i++)
512 array[i]->next = array[i+1];
513 ctx->constants = array[0];
514
515 // now figure out the groupings of constants and add to ctx->variables...
516 int start = -1;
517 int prev = -1;
518 int count = 0;
519 const int hi = ctx->constant_count;
520 for (i = 0; i <= hi; i++)
521 {
522 if (array[i] && (array[i]->constant.type != MOJOSHADER_UNIFORM_FLOAT))
523 continue; // we only care about REG_TYPE_CONST for array groups.
524
525 if (start == -1)
526 {
527 prev = start = i; // first REG_TYPE_CONST we've seen. Mark it!
528 continue;
529 } // if
530
531 // not a match (or last item in the array)...see if we had a
532 // contiguous set before this point...
533 if ( (array[i]) && (array[i]->constant.index == (array[prev]->constant.index + 1)) )
534 count++;
535 else
536 {
537 if (count > 0) // multiple constants in the set?
538 {
539 VariableList *var;
540 var = (VariableList *) Malloc(ctx, sizeof (VariableList));
541 if (var == NULL)
542 break;
543
544 var->type = MOJOSHADER_UNIFORM_FLOAT;
545 var->index = array[start]->constant.index;
546 var->count = (array[prev]->constant.index - var->index) + 1;
547 var->constant = array[start];
548 var->used = 0;
549 var->emit_position = -1;
550 var->next = ctx->variables;
551 ctx->variables = var;
552 } // if
553
554 start = i; // set this as new start of sequence.
555 } // if
556
557 prev = i;
558 } // for
559 } // determine_constants_arrays
560
561 static void shader_model_1_input_usage(const int regnum, MOJOSHADER_usage *usage, int *index)
562 {
563 *index = 0;
564 switch (regnum) // these are hardcoded for Shader Model 1: v0 is POSITION, v1 is BLENDWEIGHT, etc.
565 {
566 case 0: *usage = MOJOSHADER_USAGE_POSITION; break;
567 case 1: *usage = MOJOSHADER_USAGE_BLENDWEIGHT; break;
568 case 2: *usage = MOJOSHADER_USAGE_BLENDINDICES; break;
569 case 3: *usage = MOJOSHADER_USAGE_NORMAL; break;
570 case 4: *usage = MOJOSHADER_USAGE_POINTSIZE; break;
571 case 5: *usage = MOJOSHADER_USAGE_COLOR; break; // diffuse
572 case 6: *usage = MOJOSHADER_USAGE_COLOR; *index = 1; break; // specular
573 case 7: *usage = MOJOSHADER_USAGE_TEXCOORD; break;
574 case 8: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 1; break;
575 case 9: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 2; break;
576 case 10: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 3; break;
577 case 11: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 4; break;
578 case 12: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 5; break;
579 case 13: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 6; break;
580 case 14: *usage = MOJOSHADER_USAGE_TEXCOORD; *index = 7; break;
581 case 15: *usage = MOJOSHADER_USAGE_POSITION; *index = 1; break;
582 case 16: *usage = MOJOSHADER_USAGE_NORMAL; *index = 1; break;
583 default: *usage = MOJOSHADER_USAGE_UNKNOWN; break;
584 } // switch
585 } // shader_model_1_input_usage
586
587 static int adjust_swizzle(const Context *ctx, const RegisterType regtype,
588 const int regnum, const int swizzle)
589 {
590 if (regtype != REG_TYPE_INPUT) // !!! FIXME: maybe lift this later?
591 return swizzle;
592 else if (ctx->swizzles_count == 0)
593 return swizzle;
594
595 MOJOSHADER_usage usage = MOJOSHADER_USAGE_UNKNOWN;
596 int index = 0;
597
598 // Shader Model 1 didn't have to predeclare attribute variables, so
599 // reglist_find won't be able to look them up at this point, but
600 // their usages don't change.
601 if (!shader_version_atleast(ctx, 2, 0))
602 shader_model_1_input_usage(regnum, &usage, &index);
603 else
604 {
605 const RegisterList *reg = reglist_find(&ctx->attributes, regtype, regnum);
606 if (reg == NULL)
607 return swizzle;
608 usage = reg->usage;
609 index = reg->index;
610 } // else
611
612 if (usage == MOJOSHADER_USAGE_UNKNOWN)
613 return swizzle;
614
615 size_t i;
616 for (i = 0; i < ctx->swizzles_count; i++)
617 {
618 const MOJOSHADER_swizzle *swiz = &ctx->swizzles[i];
619 if ((swiz->usage == usage) && (swiz->index == index))
620 {
621 return ( (((int)(swiz->swizzles[((swizzle >> 0) & 0x3)])) << 0) |
622 (((int)(swiz->swizzles[((swizzle >> 2) & 0x3)])) << 2) |
623 (((int)(swiz->swizzles[((swizzle >> 4) & 0x3)])) << 4) |
624 (((int)(swiz->swizzles[((swizzle >> 6) & 0x3)])) << 6) );
625 } // if
626 } // for
627
628 return swizzle;
629 } // adjust_swizzle
630
631
632 static int parse_source_token(Context *ctx, SourceArgInfo *info)
633 {
634 int retval = 1;
635
636 if (ctx->tokencount == 0)
637 {
638 fail(ctx, "Out of tokens in source parameter");
639 return 0;
640 } // if
641
642 const uint32 token = SWAP32(*(ctx->tokens));
643 const int reserved1 = (int) ((token >> 14) & 0x3); // bits 14 through 15
644 const int reserved2 = (int) ((token >> 31) & 0x1); // bit 31
645
646 info->token = ctx->tokens;
647 info->regnum = (int) (token & 0x7ff); // bits 0 through 10
648 info->relative = (int) ((token >> 13) & 0x1); // bit 13
649 const int swizzle = (int) ((token >> 16) & 0xFF); // bits 16 through 23
650 info->src_mod = (SourceMod) ((token >> 24) & 0xF); // bits 24 through 27
651 info->regtype = (RegisterType) (((token >> 28) & 0x7) | ((token >> 8) & 0x18)); // bits 28-30, 11-12
652
653 // all the REG_TYPE_CONSTx types are the same register type, it's just
654 // split up so its regnum can be > 2047 in the bytecode. Clean it up.
655 if (info->regtype == REG_TYPE_CONST2)
656 {
657 info->regtype = REG_TYPE_CONST;
658 info->regnum += 2048;
659 } // else if
660 else if (info->regtype == REG_TYPE_CONST3)
661 {
662 info->regtype = REG_TYPE_CONST;
663 info->regnum += 4096;
664 } // else if
665 else if (info->regtype == REG_TYPE_CONST4)
666 {
667 info->regtype = REG_TYPE_CONST;
668 info->regnum += 6144;
669 } // else if
670
671 info->swizzle = adjust_swizzle(ctx, info->regtype, info->regnum, swizzle);
672 info->swizzle_x = ((info->swizzle >> 0) & 0x3);
673 info->swizzle_y = ((info->swizzle >> 2) & 0x3);
674 info->swizzle_z = ((info->swizzle >> 4) & 0x3);
675 info->swizzle_w = ((info->swizzle >> 6) & 0x3);
676
677 // swallow token for now, for multiple calls in a row.
678 adjust_token_position(ctx, 1);
679
680 if (reserved1 != 0x0)
681 fail(ctx, "Reserved bits #1 in source token must be zero");
682
683 if (reserved2 != 0x1)
684 fail(ctx, "Reserved bit #2 in source token must be one");
685
686 if ((info->relative) && (ctx->tokencount == 0))
687 {
688 fail(ctx, "Out of tokens in relative source parameter");
689 info->relative = 0; // don't try to process it.
690 } // if
691
692 if (info->relative)
693 {
694 if ( (shader_is_pixel(ctx)) && (!shader_version_atleast(ctx, 3, 0)) )
695 fail(ctx, "Relative addressing in pixel shader version < 3.0");
696
697 // Shader Model 1 doesn't have an extra token to specify the
698 // relative register: it's always a0.x.
699 if (!shader_version_atleast(ctx, 2, 0))
700 {
701 info->relative_regnum = 0;
702 info->relative_regtype = REG_TYPE_ADDRESS;
703 info->relative_component = 0;
704 } // if
705
706 else // Shader Model 2 and later...
707 {
708 const uint32 reltoken = SWAP32(*(ctx->tokens));
709 // swallow token for now, for multiple calls in a row.
710 adjust_token_position(ctx, 1);
711
712 const int relswiz = (int) ((reltoken >> 16) & 0xFF);
713 info->relative_regnum = (int) (reltoken & 0x7ff);
714 info->relative_regtype = (RegisterType)
715 (((reltoken >> 28) & 0x7) |
716 ((reltoken >> 8) & 0x18));
717
718 if (((reltoken >> 31) & 0x1) == 0)
719 fail(ctx, "bit #31 in relative address must be set");
720
721 if ((reltoken & 0xF00E000) != 0) // usused bits.
722 fail(ctx, "relative address reserved bit must be zero");
723
724 switch (info->relative_regtype)
725 {
726 case REG_TYPE_LOOP:
727 case REG_TYPE_ADDRESS:
728 break;
729 default:
730 fail(ctx, "invalid register for relative address");
731 break;
732 } // switch
733
734 if (info->relative_regnum != 0) // true for now.
735 fail(ctx, "invalid register for relative address");
736
737 if ( (info->relative_regtype != REG_TYPE_LOOP) && !replicate_swizzle(relswiz) )
738 fail(ctx, "relative address needs replicate swizzle");
739
740 info->relative_component = (relswiz & 0x3);
741
742 retval++;
743 } // else
744
745 if (info->regtype == REG_TYPE_INPUT)
746 {
747 if ( (shader_is_pixel(ctx)) || (!shader_version_atleast(ctx, 3, 0)) )
748 fail(ctx, "relative addressing of input registers not supported in this shader model");
749 ctx->have_relative_input_registers = 1;
750 } // if
751 else if (info->regtype == REG_TYPE_CONST)
752 {
753 // figure out what array we're in...
754 if (!ctx->ignores_ctab)
755 {
756 if (!ctx->ctab.have_ctab) // hard to do efficiently without!
757 fail(ctx, "relative addressing unsupported without a CTAB");
758 else
759 {
760 determine_constants_arrays(ctx);
761
762 VariableList *var;
763 const int reltarget = info->regnum;
764 for (var = ctx->variables; var != NULL; var = var->next)
765 {
766 const int lo = var->index;
767 if ( (reltarget >= lo) && (reltarget < (lo + var->count)) )
768 break; // match!
769 } // for
770
771 if (var == NULL)
772 fail(ctx, "relative addressing of indeterminate array");
773 else
774 {
775 var->used = 1;
776 info->relative_array = var;
777 set_used_register(ctx, info->relative_regtype, info->relative_regnum, 0);
778 } // else
779 } // else
780 } // if
781 } // else if
782 else
783 {
784 fail(ctx, "relative addressing of invalid register");
785 } // else
786 } // if
787
788 switch (info->src_mod)
789 {
790 case SRCMOD_NONE:
791 case SRCMOD_ABSNEGATE:
792 case SRCMOD_ABS:
793 case SRCMOD_NEGATE:
794 break; // okay in any shader model.
795
796 // apparently these are only legal in Shader Model 1.x ...
797 case SRCMOD_BIASNEGATE:
798 case SRCMOD_BIAS:
799 case SRCMOD_SIGNNEGATE:
800 case SRCMOD_SIGN:
801 case SRCMOD_COMPLEMENT:
802 case SRCMOD_X2NEGATE:
803 case SRCMOD_X2:
804 case SRCMOD_DZ:
805 case SRCMOD_DW:
806 if (shader_version_atleast(ctx, 2, 0))
807 fail(ctx, "illegal source mod for this Shader Model.");
808 break;
809
810 case SRCMOD_NOT: // !!! FIXME: I _think_ this is right...
811 if (shader_version_atleast(ctx, 2, 0))
812 {
813 if (info->regtype != REG_TYPE_PREDICATE
814 && info->regtype != REG_TYPE_CONSTBOOL)
815 fail(ctx, "NOT only allowed on bool registers.");
816 } // if
817 break;
818
819 default:
820 fail(ctx, "Unknown source modifier");
821 } // switch
822
823 // !!! FIXME: docs say this for sm3 ... check these!
824 // "The negate modifier cannot be used on second source register of these
825 // instructions: m3x2 - ps, m3x3 - ps, m3x4 - ps, m4x3 - ps, and
826 // m4x4 - ps."
827 // "If any version 3 shader reads from one or more constant float
828 // registers (c#), one of the following must be true.
829 // All of the constant floating-point registers must use the abs modifier.
830 // None of the constant floating-point registers can use the abs modifier.
831
832 if (!isfail(ctx))
833 {
834 RegisterList *reg;
835 reg = set_used_register(ctx, info->regtype, info->regnum, 0);
836 // !!! FIXME: this test passes if you write to the register
837 // !!! FIXME: in this same instruction, because we parse the
838 // !!! FIXME: destination token first.
839 // !!! FIXME: Microsoft's shader validation explicitly checks temp
840 // !!! FIXME: registers for this...do they check other writable ones?
841 if ((info->regtype == REG_TYPE_TEMP) && (reg) && (!reg->written))
842 failf(ctx, "Temp register r%d used uninitialized", info->regnum);
843 } // if
844
845 return retval;
846 } // parse_source_token
847
848
849 static int parse_predicated_token(Context *ctx)
850 {
851 SourceArgInfo *arg = &ctx->predicate_arg;
852 parse_source_token(ctx, arg);
853 if (arg->regtype != REG_TYPE_PREDICATE)
854 fail(ctx, "Predicated instruction but not predicate register!");
855 if ((arg->src_mod != SRCMOD_NONE) && (arg->src_mod != SRCMOD_NOT))
856 fail(ctx, "Predicated instruction register is not NONE or NOT");
857 if ( !no_swizzle(arg->swizzle) && !replicate_swizzle(arg->swizzle) )
858 fail(ctx, "Predicated instruction register has wrong swizzle");
859 if (arg->relative) // I'm pretty sure this is illegal...?
860 fail(ctx, "relative addressing in predicated token");
861
862 return 1;
863 } // parse_predicated_token
864
865
866 static int parse_args_NULL(Context *ctx)
867 {
868 return 1;
869 } // parse_args_NULL
870
871
872 static int parse_args_DEF(Context *ctx)
873 {
874 parse_destination_token(ctx, &ctx->dest_arg);
875 if (ctx->dest_arg.regtype != REG_TYPE_CONST)
876 fail(ctx, "DEF using non-CONST register");
877 if (ctx->dest_arg.relative) // I'm pretty sure this is illegal...?
878 fail(ctx, "relative addressing in DEF");
879
880 ctx->dwords[0] = SWAP32(ctx->tokens[0]);
881 ctx->dwords[1] = SWAP32(ctx->tokens[1]);
882 ctx->dwords[2] = SWAP32(ctx->tokens[2]);
883 ctx->dwords[3] = SWAP32(ctx->tokens[3]);
884
885 return 6;
886 } // parse_args_DEF
887
888
889 static int parse_args_DEFI(Context *ctx)
890 {
891 parse_destination_token(ctx, &ctx->dest_arg);
892 if (ctx->dest_arg.regtype != REG_TYPE_CONSTINT)
893 fail(ctx, "DEFI using non-CONSTING register");
894 if (ctx->dest_arg.relative) // I'm pretty sure this is illegal...?
895 fail(ctx, "relative addressing in DEFI");
896
897 ctx->dwords[0] = SWAP32(ctx->tokens[0]);
898 ctx->dwords[1] = SWAP32(ctx->tokens[1]);
899 ctx->dwords[2] = SWAP32(ctx->tokens[2]);
900 ctx->dwords[3] = SWAP32(ctx->tokens[3]);
901
902 return 6;
903 } // parse_args_DEFI
904
905
906 static int parse_args_DEFB(Context *ctx)
907 {
908 parse_destination_token(ctx, &ctx->dest_arg);
909 if (ctx->dest_arg.regtype != REG_TYPE_CONSTBOOL)
910 fail(ctx, "DEFB using non-CONSTBOOL register");
911 if (ctx->dest_arg.relative) // I'm pretty sure this is illegal...?
912 fail(ctx, "relative addressing in DEFB");
913
914 ctx->dwords[0] = *(ctx->tokens) ? 1 : 0;
915
916 return 3;
917 } // parse_args_DEFB
918
919
920 static int valid_texture_type(const uint32 ttype)
921 {
922 switch ((const TextureType) ttype)
923 {
924 case TEXTURE_TYPE_2D:
925 case TEXTURE_TYPE_CUBE:
926 case TEXTURE_TYPE_VOLUME:
927 return 1; // it's okay.
928 } // switch
929
930 return 0;
931 } // valid_texture_type
932
933
934 // !!! FIXME: this function is kind of a mess.
935 static int parse_args_DCL(Context *ctx)
936 {
937 int unsupported = 0;
938 const uint32 token = SWAP32(*(ctx->tokens));
939 const int reserved1 = (int) ((token >> 31) & 0x1); // bit 31
940 uint32 reserved_mask = 0x00000000;
941
942 if (reserved1 != 0x1)
943 fail(ctx, "Bit #31 in DCL token must be one");
944
945 ctx->centroid_allowed = 1;
946 adjust_token_position(ctx, 1);
947 parse_destination_token(ctx, &ctx->dest_arg);
948 ctx->centroid_allowed = 0;
949
950 if (ctx->dest_arg.result_shift != 0) // I'm pretty sure this is illegal...?
951 fail(ctx, "shift scale in DCL");
952 if (ctx->dest_arg.relative) // I'm pretty sure this is illegal...?
953 fail(ctx, "relative addressing in DCL");
954
955 const RegisterType regtype = ctx->dest_arg.regtype;
956 const int regnum = ctx->dest_arg.regnum;
957 if ( (shader_is_pixel(ctx)) && (shader_version_atleast(ctx, 3, 0)) )
958 {
959 if (regtype == REG_TYPE_INPUT)
960 {
961 const uint32 usage = (token & 0xF);
962 const uint32 index = ((token >> 16) & 0xF);
963 reserved_mask = 0x7FF0FFE0;
964 ctx->dwords[0] = usage;
965 ctx->dwords[1] = index;
966 } // if
967
968 else if (regtype == REG_TYPE_MISCTYPE)
969 {
970 const MiscTypeType mt = (MiscTypeType) regnum;
971 if (mt == MISCTYPE_TYPE_POSITION)
972 reserved_mask = 0x7FFFFFFF;
973 else if (mt == MISCTYPE_TYPE_FACE)
974 {
975 reserved_mask = 0x7FFFFFFF;
976 if (!writemask_xyzw(ctx->dest_arg.orig_writemask))
977 fail(ctx, "DCL face writemask must be full");
978 if (ctx->dest_arg.result_mod != 0)
979 fail(ctx, "DCL face result modifier must be zero");
980 if (ctx->dest_arg.result_shift != 0)
981 fail(ctx, "DCL face shift scale must be zero");
982 } // else if
983 else
984 {
985 unsupported = 1;
986 } // else
987
988 ctx->dwords[0] = (uint32) MOJOSHADER_USAGE_UNKNOWN;
989 ctx->dwords[1] = 0;
990 } // else if
991
992 else if (regtype == REG_TYPE_TEXTURE)
993 {
994 const uint32 usage = (token & 0xF);
995 const uint32 index = ((token >> 16) & 0xF);
996 if (usage == MOJOSHADER_USAGE_TEXCOORD)
997 {
998 if (index > 7)
999 fail(ctx, "DCL texcoord usage must have 0-7 index");
1000 } // if
1001 else if (usage == MOJOSHADER_USAGE_COLOR)
1002 {
1003 if (index != 0)
1004 fail(ctx, "DCL color usage must have 0 index");
1005 } // else if
1006 else
1007 {
1008 fail(ctx, "Invalid DCL texture usage");
1009 } // else
1010
1011 reserved_mask = 0x7FF0FFE0;
1012 ctx->dwords[0] = usage;
1013 ctx->dwords[1] = index;
1014 } // else if
1015
1016 else if (regtype == REG_TYPE_SAMPLER)
1017 {
1018 const uint32 ttype = ((token >> 27) & 0xF);
1019 if (!valid_texture_type(ttype))
1020 fail(ctx, "unknown sampler texture type");
1021 reserved_mask = 0x7FFFFFF;
1022 ctx->dwords[0] = ttype;
1023 } // else if
1024
1025 else
1026 {
1027 unsupported = 1;
1028 } // else
1029 } // if
1030
1031 else if ( (shader_is_pixel(ctx)) && (shader_version_atleast(ctx, 2, 0)) )
1032 {
1033 if (regtype == REG_TYPE_INPUT)
1034 {
1035 ctx->dwords[0] = (uint32) MOJOSHADER_USAGE_COLOR;
1036 ctx->dwords[1] = regnum;
1037 reserved_mask = 0x7FFFFFFF;
1038 } // if
1039 else if (regtype == REG_TYPE_TEXTURE)
1040 {
1041 ctx->dwords[0] = (uint32) MOJOSHADER_USAGE_TEXCOORD;
1042 ctx->dwords[1] = regnum;
1043 reserved_mask = 0x7FFFFFFF;
1044 } // else if
1045 else if (regtype == REG_TYPE_SAMPLER)
1046 {
1047 const uint32 ttype = ((token >> 27) & 0xF);
1048 if (!valid_texture_type(ttype))
1049 fail(ctx, "unknown sampler texture type");
1050 reserved_mask = 0x7FFFFFF;
1051 ctx->dwords[0] = ttype;
1052 } // else if
1053 else
1054 {
1055 unsupported = 1;
1056 } // else
1057 } // if
1058
1059 else if ( (shader_is_vertex(ctx)) && (shader_version_atleast(ctx, 3, 0)) )
1060 {
1061 if ((regtype == REG_TYPE_INPUT) || (regtype == REG_TYPE_OUTPUT))
1062 {
1063 const uint32 usage = (token & 0xF);
1064 const uint32 index = ((token >> 16) & 0xF);
1065 reserved_mask = 0x7FF0FFE0;
1066 ctx->dwords[0] = usage;
1067 ctx->dwords[1] = index;
1068 } // if
1069 else if (regtype == REG_TYPE_TEXTURE)
1070 {
1071 const uint32 usage = (token & 0xF);
1072 const uint32 index = ((token >> 16) & 0xF);
1073 if (usage == MOJOSHADER_USAGE_TEXCOORD)
1074 {
1075 if (index > 7)
1076 fail(ctx, "DCL texcoord usage must have 0-7 index");
1077 } // if
1078 else if (usage == MOJOSHADER_USAGE_COLOR)
1079 {
1080 if (index != 0)
1081 fail(ctx, "DCL texcoord usage must have 0 index");
1082 } // else if
1083 else
1084 fail(ctx, "Invalid DCL texture usage");
1085
1086 reserved_mask = 0x7FF0FFE0;
1087 ctx->dwords[0] = usage;
1088 ctx->dwords[1] = index;
1089 } // else if
1090 else if (regtype == REG_TYPE_SAMPLER)
1091 {
1092 const uint32 ttype = ((token >> 27) & 0xF);
1093 if (!valid_texture_type(ttype))
1094 fail(ctx, "Unknown sampler texture type");
1095 reserved_mask = 0x0FFFFFFF;
1096 ctx->dwords[0] = ttype;
1097 } // else if
1098 else
1099 {
1100 unsupported = 1;
1101 } // else
1102 } // else if
1103
1104 else if ( (shader_is_vertex(ctx)) && (shader_version_atleast(ctx, 1, 1)) )
1105 {
1106 if (regtype == REG_TYPE_INPUT)
1107 {
1108 const uint32 usage = (token & 0xF);
1109 const uint32 index = ((token >> 16) & 0xF);
1110 reserved_mask = 0x7FF0FFE0;
1111 ctx->dwords[0] = usage;
1112 ctx->dwords[1] = index;
1113 } // if
1114 else
1115 {
1116 unsupported = 1;
1117 } // else
1118 } // else if
1119
1120 else
1121 {
1122 unsupported = 1;
1123 } // else
1124
1125 if (unsupported)
1126 fail(ctx, "invalid DCL register type for this shader model");
1127
1128 if ((token & reserved_mask) != 0)
1129 fail(ctx, "reserved bits in DCL dword aren't zero");
1130
1131 return 3;
1132 } // parse_args_DCL
1133
1134
1135 static int parse_args_D(Context *ctx)
1136 {
1137 int retval = 1;
1138 retval += parse_destination_token(ctx, &ctx->dest_arg);
1139 return retval;
1140 } // parse_args_D
1141
1142
1143 static int parse_args_S(Context *ctx)
1144 {
1145 int retval = 1;
1146 retval += parse_source_token(ctx, &ctx->source_args[0]);
1147 return retval;
1148 } // parse_args_S
1149
1150
1151 static int parse_args_SS(Context *ctx)
1152 {
1153 int retval = 1;
1154 retval += parse_source_token(ctx, &ctx->source_args[0]);
1155 retval += parse_source_token(ctx, &ctx->source_args[1]);
1156 return retval;
1157 } // parse_args_SS
1158
1159
1160 static int parse_args_DS(Context *ctx)
1161 {
1162 int retval = 1;
1163 retval += parse_destination_token(ctx, &ctx->dest_arg);
1164 retval += parse_source_token(ctx, &ctx->source_args[0]);
1165 return retval;
1166 } // parse_args_DS
1167
1168
1169 static int parse_args_DSS(Context *ctx)
1170 {
1171 int retval = 1;
1172 retval += parse_destination_token(ctx, &ctx->dest_arg);
1173 retval += parse_source_token(ctx, &ctx->source_args[0]);
1174 retval += parse_source_token(ctx, &ctx->source_args[1]);
1175 return retval;
1176 } // parse_args_DSS
1177
1178
1179 static int parse_args_DSSS(Context *ctx)
1180 {
1181 int retval = 1;
1182 retval += parse_destination_token(ctx, &ctx->dest_arg);
1183 retval += parse_source_token(ctx, &ctx->source_args[0]);
1184 retval += parse_source_token(ctx, &ctx->source_args[1]);
1185 retval += parse_source_token(ctx, &ctx->source_args[2]);
1186 return retval;
1187 } // parse_args_DSSS
1188
1189
1190 static int parse_args_DSSSS(Context *ctx)
1191 {
1192 int retval = 1;
1193 retval += parse_destination_token(ctx, &ctx->dest_arg);
1194 retval += parse_source_token(ctx, &ctx->source_args[0]);
1195 retval += parse_source_token(ctx, &ctx->source_args[1]);
1196 retval += parse_source_token(ctx, &ctx->source_args[2]);
1197 retval += parse_source_token(ctx, &ctx->source_args[3]);
1198 return retval;
1199 } // parse_args_DSSSS
1200
1201
1202 static int parse_args_SINCOS(Context *ctx)
1203 {
1204 // this opcode needs extra registers for sm2 and lower.
1205 if (!shader_version_atleast(ctx, 3, 0))
1206 return parse_args_DSSS(ctx);
1207 return parse_args_DS(ctx);
1208 } // parse_args_SINCOS
1209
1210
1211 static int parse_args_TEXCRD(Context *ctx)
1212 {
1213 // added extra register in ps_1_4.
1214 if (shader_version_atleast(ctx, 1, 4))
1215 return parse_args_DS(ctx);
1216 return parse_args_D(ctx);
1217 } // parse_args_TEXCRD
1218
1219
1220 static int parse_args_TEXLD(Context *ctx)
1221 {
1222 // different registers in px_1_3, ps_1_4, and ps_2_0!
1223 if (shader_version_atleast(ctx, 2, 0))
1224 return parse_args_DSS(ctx);
1225 else if (shader_version_atleast(ctx, 1, 4))
1226 return parse_args_DS(ctx);
1227 return parse_args_D(ctx);
1228 } // parse_args_TEXLD
1229
1230
1231 // State machine functions...
1232
1233 static ConstantsList *alloc_constant_listitem(Context *ctx)
1234 {
1235 ConstantsList *item = (ConstantsList *) Malloc(ctx, sizeof (ConstantsList));
1236 if (item == NULL)
1237 return NULL;
1238
1239 memset(&item->constant, '\0', sizeof (MOJOSHADER_constant));
1240 item->next = ctx->constants;
1241 ctx->constants = item;
1242 ctx->constant_count++;
1243
1244 return item;
1245 } // alloc_constant_listitem
1246
1247
1248 static void state_DEF(Context *ctx)
1249 {
1250 const RegisterType regtype = ctx->dest_arg.regtype;
1251 const int regnum = ctx->dest_arg.regnum;
1252
1253 // !!! FIXME: fail if same register is defined twice.
1254
1255 if (ctx->instruction_count != 0)
1256 fail(ctx, "DEF token must come before any instructions");
1257 else if (regtype != REG_TYPE_CONST)
1258 fail(ctx, "DEF token using invalid register");
1259 else
1260 {
1261 ConstantsList *item = alloc_constant_listitem(ctx);
1262 if (item != NULL)
1263 {
1264 item->constant.index = regnum;
1265 item->constant.type = MOJOSHADER_UNIFORM_FLOAT;
1266 memcpy(item->constant.value.f, ctx->dwords,
1267 sizeof (item->constant.value.f));
1268 set_defined_register(ctx, regtype, regnum);
1269 } // if
1270 } // else
1271 } // state_DEF
1272
1273 static void state_DEFI(Context *ctx)
1274 {
1275 const RegisterType regtype = ctx->dest_arg.regtype;
1276 const int regnum = ctx->dest_arg.regnum;
1277
1278 // !!! FIXME: fail if same register is defined twice.
1279
1280 if (ctx->instruction_count != 0)
1281 fail(ctx, "DEFI token must come before any instructions");
1282 else if (regtype != REG_TYPE_CONSTINT)
1283 fail(ctx, "DEFI token using invalid register");
1284 else
1285 {
1286 ConstantsList *item = alloc_constant_listitem(ctx);
1287 if (item != NULL)
1288 {
1289 item->constant.index = regnum;
1290 item->constant.type = MOJOSHADER_UNIFORM_INT;
1291 memcpy(item->constant.value.i, ctx->dwords,
1292 sizeof (item->constant.value.i));
1293
1294 set_defined_register(ctx, regtype, regnum);
1295 } // if
1296 } // else
1297 } // state_DEFI
1298
1299 static void state_DEFB(Context *ctx)
1300 {
1301 const RegisterType regtype = ctx->dest_arg.regtype;
1302 const int regnum = ctx->dest_arg.regnum;
1303
1304 // !!! FIXME: fail if same register is defined twice.
1305
1306 if (ctx->instruction_count != 0)
1307 fail(ctx, "DEFB token must come before any instructions");
1308 else if (regtype != REG_TYPE_CONSTBOOL)
1309 fail(ctx, "DEFB token using invalid register");
1310 else
1311 {
1312 ConstantsList *item = alloc_constant_listitem(ctx);
1313 if (item != NULL)
1314 {
1315 item->constant.index = regnum;
1316 item->constant.type = MOJOSHADER_UNIFORM_BOOL;
1317 item->constant.value.b = ctx->dwords[0] ? 1 : 0;
1318 set_defined_register(ctx, regtype, regnum);
1319 } // if
1320 } // else
1321 } // state_DEFB
1322
1323 static void state_DCL(Context *ctx)
1324 {
1325 const DestArgInfo *arg = &ctx->dest_arg;
1326 const RegisterType regtype = arg->regtype;
1327 const int regnum = arg->regnum;
1328 const int wmask = arg->writemask;
1329 const int mods = arg->result_mod;
1330
1331 // parse_args_DCL() does a lot of state checking before we get here.
1332
1333 // !!! FIXME: apparently vs_3_0 can use sampler registers now.
1334 // !!! FIXME: (but only s0 through s3, not all 16 of them.)
1335
1336 if (ctx->instruction_count != 0)
1337 fail(ctx, "DCL token must come before any instructions");
1338
1339 else if (shader_is_vertex(ctx) || shader_is_pixel(ctx))
1340 {
1341 if (regtype == REG_TYPE_SAMPLER)
1342 add_sampler(ctx, regnum, (TextureType) ctx->dwords[0], 0);
1343 else
1344 {
1345 const MOJOSHADER_usage usage = (const MOJOSHADER_usage) ctx->dwords[0];
1346 const int index = ctx->dwords[1];
1347 if (usage >= MOJOSHADER_USAGE_TOTAL)
1348 {
1349 fail(ctx, "unknown DCL usage");
1350 return;
1351 } // if
1352 add_attribute_register(ctx, regtype, regnum, usage, index, wmask, mods);
1353 } // else
1354 } // if
1355
1356 else
1357 {
1358 fail(ctx, "unsupported shader type."); // should be caught elsewhere.
1359 return;
1360 } // else
1361
1362 set_defined_register(ctx, regtype, regnum);
1363 } // state_DCL
1364
1365 static void state_TEXCRD(Context *ctx)
1366 {
1367 if (shader_version_atleast(ctx, 2, 0))
1368 fail(ctx, "TEXCRD in Shader Model >= 2.0"); // apparently removed.
1369 } // state_TEXCRD
1370
1371 static void state_FRC(Context *ctx)
1372 {
1373 const DestArgInfo *dst = &ctx->dest_arg;
1374
1375 if (dst->result_mod & MOD_SATURATE) // according to msdn...
1376 fail(ctx, "FRC destination can't use saturate modifier");
1377
1378 else if (!shader_version_atleast(ctx, 2, 0))
1379 {
1380 if (!writemask_y(dst->writemask) && !writemask_xy(dst->writemask))
1381 fail(ctx, "FRC writemask must be .y or .xy for shader model 1.x");
1382 } // else if
1383 } // state_FRC
1384
1385
1386 // replicate the matrix registers to source args. The D3D profile will
1387 // only use the one legitimate argument, but this saves other profiles
1388 // from having to build this.
1389 static void srcarg_matrix_replicate(Context *ctx, const int idx,
1390 const int rows)
1391 {
1392 int i;
1393 SourceArgInfo *src = &ctx->source_args[idx];
1394 SourceArgInfo *dst = &ctx->source_args[idx+1];
1395 for (i = 0; i < (rows-1); i++, dst++)
1396 {
1397 memcpy(dst, src, sizeof (SourceArgInfo));
1398 dst->regnum += (i + 1);
1399 set_used_register(ctx, dst->regtype, dst->regnum, 0);
1400 } // for
1401 } // srcarg_matrix_replicate
1402
1403 static void state_M4X4(Context *ctx)
1404 {
1405 const DestArgInfo *info = &ctx->dest_arg;
1406 if (!writemask_xyzw(info->writemask))
1407 fail(ctx, "M4X4 writemask must be full");
1408
1409 // !!! FIXME: MSDN:
1410 //The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.
1411 //Swizzle and negate modifiers are invalid for the src0 register. The dest and src0 registers cannot be the same.
1412
1413 srcarg_matrix_replicate(ctx, 1, 4);
1414 } // state_M4X4
1415
1416 static void state_M4X3(Context *ctx)
1417 {
1418 const DestArgInfo *info = &ctx->dest_arg;
1419 if (!writemask_xyz(info->writemask))
1420 fail(ctx, "M4X3 writemask must be .xyz");
1421
1422 // !!! FIXME: MSDN stuff
1423
1424 srcarg_matrix_replicate(ctx, 1, 3);
1425 } // state_M4X3
1426
1427 static void state_M3X4(Context *ctx)
1428 {
1429 const DestArgInfo *info = &ctx->dest_arg;
1430 if (!writemask_xyzw(info->writemask))
1431 fail(ctx, "M3X4 writemask must be .xyzw");
1432
1433 // !!! FIXME: MSDN stuff
1434
1435 srcarg_matrix_replicate(ctx, 1, 4);
1436 } // state_M3X4
1437
1438 static void state_M3X3(Context *ctx)
1439 {
1440 const DestArgInfo *info = &ctx->dest_arg;
1441 if (!writemask_xyz(info->writemask))
1442 fail(ctx, "M3X3 writemask must be .xyz");
1443
1444 // !!! FIXME: MSDN stuff
1445
1446 srcarg_matrix_replicate(ctx, 1, 3);
1447 } // state_M3X3
1448
1449 static void state_M3X2(Context *ctx)
1450 {
1451 const DestArgInfo *info = &ctx->dest_arg;
1452 if (!writemask_xy(info->writemask))
1453 fail(ctx, "M3X2 writemask must be .xy");
1454
1455 // !!! FIXME: MSDN stuff
1456
1457 srcarg_matrix_replicate(ctx, 1, 2);
1458 } // state_M3X2
1459
1460 static void state_RET(Context *ctx)
1461 {
1462 // MSDN all but says that assembly shaders are more or less serialized
1463 // HLSL functions, and a RET means you're at the end of one, unlike how
1464 // most CPUs would behave. This is actually really helpful,
1465 // since we can use high-level constructs and not a mess of GOTOs,
1466 // which is a godsend for GLSL...this also means we can consider things
1467 // like a LOOP without a matching ENDLOOP within a label's section as
1468 // an error.
1469 if (ctx->loops > 0)
1470 fail(ctx, "LOOP without ENDLOOP");
1471 if (ctx->reps > 0)
1472 fail(ctx, "REP without ENDREP");
1473 } // state_RET
1474
1475 static void check_label_register(Context *ctx, int arg, const char *opcode)
1476 {
1477 const SourceArgInfo *info = &ctx->source_args[arg];
1478 const RegisterType regtype = info->regtype;
1479 const int regnum = info->regnum;
1480
1481 if (regtype != REG_TYPE_LABEL)
1482 failf(ctx, "%s with a non-label register specified", opcode);
1483 if (!shader_version_atleast(ctx, 2, 0))
1484 failf(ctx, "%s not supported in Shader Model 1", opcode);
1485 if ((shader_version_atleast(ctx, 2, 255)) && (regnum > 2047))
1486 fail(ctx, "label register number must be <= 2047");
1487 if (regnum > 15)
1488 fail(ctx, "label register number must be <= 15");
1489 } // check_label_register
1490
1491 static void state_LABEL(Context *ctx)
1492 {
1493 if (ctx->previous_opcode != OPCODE_RET)
1494 fail(ctx, "LABEL not followed by a RET");
1495 check_label_register(ctx, 0, "LABEL");
1496 set_defined_register(ctx, REG_TYPE_LABEL, ctx->source_args[0].regnum);
1497 } // state_LABEL
1498
1499 static void check_call_loop_wrappage(Context *ctx, const int regnum)
1500 {
1501 // msdn says subroutines inherit aL register if you're in a loop when
1502 // you call, and further more _if you ever call this function in a loop,
1503 // it must always be called in a loop_. So we'll just pass our loop
1504 // variable as a function parameter in those cases.
1505
1506 const int current_usage = (ctx->loops > 0) ? 1 : -1;
1507 RegisterList *reg = reglist_find(&ctx->used_registers, REG_TYPE_LABEL, regnum);
1508
1509 if (reg == NULL)
1510 fail(ctx, "Invalid label for CALL");
1511 else if (reg->misc == 0)
1512 reg->misc = current_usage;
1513 else if (reg->misc != current_usage)
1514 {
1515 if (current_usage == 1)
1516 fail(ctx, "CALL to this label must be wrapped in LOOP/ENDLOOP");
1517 else
1518 fail(ctx, "CALL to this label must not be wrapped in LOOP/ENDLOOP");
1519 } // else if
1520 } // check_call_loop_wrappage
1521
1522 static void state_CALL(Context *ctx)
1523 {
1524 check_label_register(ctx, 0, "CALL");
1525 check_call_loop_wrappage(ctx, ctx->source_args[0].regnum);
1526 } // state_CALL
1527
1528 static void state_CALLNZ(Context *ctx)
1529 {
1530 const RegisterType regtype = ctx->source_args[1].regtype;
1531 if ((regtype != REG_TYPE_CONSTBOOL) && (regtype != REG_TYPE_PREDICATE))
1532 fail(ctx, "CALLNZ argument isn't constbool or predicate register");
1533 check_label_register(ctx, 0, "CALLNZ");
1534 check_call_loop_wrappage(ctx, ctx->source_args[0].regnum);
1535 } // state_CALLNZ
1536
1537 static void state_MOVA(Context *ctx)
1538 {
1539 if (ctx->dest_arg.regtype != REG_TYPE_ADDRESS)
1540 fail(ctx, "MOVA argument isn't address register");
1541 } // state_MOVA
1542
1543 static void state_RCP(Context *ctx)
1544 {
1545 if (!replicate_swizzle(ctx->source_args[0].swizzle))
1546 fail(ctx, "RCP without replicate swizzle");
1547 } // state_RCP
1548
1549 static void state_RSQ(Context *ctx)
1550 {
1551 if (!replicate_swizzle(ctx->source_args[0].swizzle))
1552 fail(ctx, "RSQ without replicate swizzle");
1553 } // state_RSQ
1554
1555 static void state_LOOP(Context *ctx)
1556 {
1557 if (ctx->source_args[0].regtype != REG_TYPE_LOOP)
1558 fail(ctx, "LOOP argument isn't loop register");
1559 else if (ctx->source_args[1].regtype != REG_TYPE_CONSTINT)
1560 fail(ctx, "LOOP argument isn't constint register");
1561 else
1562 ctx->loops++;
1563 } // state_LOOP
1564
1565 static void state_ENDLOOP(Context *ctx)
1566 {
1567 // !!! FIXME: check that we aren't straddling an IF block.
1568 if (ctx->loops <= 0)
1569 fail(ctx, "ENDLOOP without LOOP");
1570 ctx->loops--;
1571 } // state_ENDLOOP
1572
1573 static void state_BREAKP(Context *ctx)
1574 {
1575 const RegisterType regtype = ctx->source_args[0].regtype;
1576 if (regtype != REG_TYPE_PREDICATE)
1577 fail(ctx, "BREAKP argument isn't predicate register");
1578 else if (!replicate_swizzle(ctx->source_args[0].swizzle))
1579 fail(ctx, "BREAKP without replicate swizzle");
1580 else if ((ctx->loops == 0) && (ctx->reps == 0))
1581 fail(ctx, "BREAKP outside LOOP/ENDLOOP or REP/ENDREP");
1582 } // state_BREAKP
1583
1584 static void state_BREAK(Context *ctx)
1585 {
1586 if ((ctx->loops == 0) && (ctx->reps == 0))
1587 fail(ctx, "BREAK outside LOOP/ENDLOOP or REP/ENDREP");
1588 } // state_BREAK
1589
1590 static void state_SETP(Context *ctx)
1591 {
1592 const RegisterType regtype = ctx->dest_arg.regtype;
1593 if (regtype != REG_TYPE_PREDICATE)
1594 fail(ctx, "SETP argument isn't predicate register");
1595 } // state_SETP
1596
1597 static void state_REP(Context *ctx)
1598 {
1599 const RegisterType regtype = ctx->source_args[0].regtype;
1600 if (regtype != REG_TYPE_CONSTINT)
1601 fail(ctx, "REP argument isn't constint register");
1602
1603 ctx->reps++;
1604 if (ctx->reps > ctx->max_reps)
1605 ctx->max_reps = ctx->reps;
1606 } // state_REP
1607
1608 static void state_ENDREP(Context *ctx)
1609 {
1610 // !!! FIXME: check that we aren't straddling an IF block.
1611 if (ctx->reps <= 0)
1612 fail(ctx, "ENDREP without REP");
1613 ctx->reps--;
1614 } // state_ENDREP
1615
1616 static void state_CMP(Context *ctx)
1617 {
1618 ctx->cmps++;
1619
1620 // extra limitations for ps <= 1.4 ...
1621 if (!shader_version_atleast(ctx, 1, 4))
1622 {
1623 int i;
1624 const DestArgInfo *dst = &ctx->dest_arg;
1625 const RegisterType dregtype = dst->regtype;
1626 const int dregnum = dst->regnum;
1627
1628 if (ctx->cmps > 3)
1629 fail(ctx, "only 3 CMP instructions allowed in this shader model");
1630
1631 for (i = 0; i < 3; i++)
1632 {
1633 const SourceArgInfo *src = &ctx->source_args[i];
1634 const RegisterType sregtype = src->regtype;
1635 const int sregnum = src->regnum;
1636 if ((dregtype == sregtype) && (dregnum == sregnum))
1637 fail(ctx, "CMP dest can't match sources in this shader model");
1638 } // for
1639
1640 ctx->instruction_count++; // takes an extra slot in ps_1_2 and _3.
1641 } // if
1642 } // state_CMP
1643
1644 static void state_DP4(Context *ctx)
1645 {
1646 // extra limitations for ps <= 1.4 ...
1647 if (!shader_version_atleast(ctx, 1, 4))
1648 ctx->instruction_count++; // takes an extra slot in ps_1_2 and _3.
1649 } // state_DP4
1650
1651 static void state_CND(Context *ctx)
1652 {
1653 // apparently it was removed...it's not in the docs past ps_1_4 ...
1654 if (shader_version_atleast(ctx, 2, 0))
1655 fail(ctx, "CND not allowed in this shader model");
1656
1657 // extra limitations for ps <= 1.4 ...
1658 else if (!shader_version_atleast(ctx, 1, 4))
1659 {
1660 const SourceArgInfo *src = &ctx->source_args[0];
1661 if ((src->regtype != REG_TYPE_TEMP) || (src->regnum != 0) ||
1662 (src->swizzle != 0xFF))
1663 {
1664 fail(ctx, "CND src must be r0.a in this shader model");
1665 } // if
1666 } // if
1667 } // state_CND
1668
1669 static void state_POW(Context *ctx)
1670 {
1671 if (!replicate_swizzle(ctx->source_args[0].swizzle))
1672 fail(ctx, "POW src0 must have replicate swizzle");
1673 else if (!replicate_swizzle(ctx->source_args[1].swizzle))
1674 fail(ctx, "POW src1 must have replicate swizzle");
1675 } // state_POW
1676
1677 static void state_LOG(Context *ctx)
1678 {
1679 if (!replicate_swizzle(ctx->source_args[0].swizzle))
1680 fail(ctx, "LOG src0 must have replicate swizzle");
1681 } // state_LOG
1682
1683 static void state_LOGP(Context *ctx)
1684 {
1685 if (!replicate_swizzle(ctx->source_args[0].swizzle))
1686 fail(ctx, "LOGP src0 must have replicate swizzle");
1687 } // state_LOGP
1688
1689 static void state_SINCOS(Context *ctx)
1690 {
1691 const DestArgInfo *dst = &ctx->dest_arg;
1692 const int mask = dst->writemask;
1693 if (!writemask_x(mask) && !writemask_y(mask) && !writemask_xy(mask))
1694 fail(ctx, "SINCOS write mask must be .x or .y or .xy");
1695
1696 else if (!replicate_swizzle(ctx->source_args[0].swizzle))
1697 fail(ctx, "SINCOS src0 must have replicate swizzle");
1698
1699 else if (dst->result_mod & MOD_SATURATE) // according to msdn...
1700 fail(ctx, "SINCOS destination can't use saturate modifier");
1701
1702 // this opcode needs extra registers, with extra limitations, for <= sm2.
1703 else if (!shader_version_atleast(ctx, 3, 0))
1704 {
1705 int i;
1706 for (i = 1; i < 3; i++)
1707 {
1708 if (ctx->source_args[i].regtype != REG_TYPE_CONST)
1709 {
1710 failf(ctx, "SINCOS src%d must be constfloat", i);
1711 return;
1712 } // if
1713 } // for
1714
1715 if (ctx->source_args[1].regnum == ctx->source_args[2].regnum)
1716 fail(ctx, "SINCOS src1 and src2 must be different registers");
1717 } // if
1718 } // state_SINCOS
1719
1720 static void state_IF(Context *ctx)
1721 {
1722 const RegisterType regtype = ctx->source_args[0].regtype;
1723 if ((regtype != REG_TYPE_PREDICATE) && (regtype != REG_TYPE_CONSTBOOL))
1724 fail(ctx, "IF src0 must be CONSTBOOL or PREDICATE");
1725 // !!! FIXME: track if nesting depth.
1726 } // state_IF
1727
1728 static void state_IFC(Context *ctx)
1729 {
1730 if (!replicate_swizzle(ctx->source_args[0].swizzle))
1731 fail(ctx, "IFC src0 must have replicate swizzle");
1732 else if (!replicate_swizzle(ctx->source_args[1].swizzle))
1733 fail(ctx, "IFC src1 must have replicate swizzle");
1734 // !!! FIXME: track if nesting depth.
1735 } // state_IFC
1736
1737 static void state_BREAKC(Context *ctx)
1738 {
1739 if (!replicate_swizzle(ctx->source_args[0].swizzle))
1740 fail(ctx, "BREAKC src1 must have replicate swizzle");
1741 else if (!replicate_swizzle(ctx->source_args[1].swizzle))
1742 fail(ctx, "BREAKC src2 must have replicate swizzle");
1743 else if ((ctx->loops == 0) && (ctx->reps == 0))
1744 fail(ctx, "BREAKC outside LOOP/ENDLOOP or REP/ENDREP");
1745 } // state_BREAKC
1746
1747 static void state_TEXKILL(Context *ctx)
1748 {
1749 // The MSDN docs say this should be a source arg, but the driver docs
1750 // say it's a dest arg. That's annoying.
1751 const DestArgInfo *info = &ctx->dest_arg;
1752 const RegisterType regtype = info->regtype;
1753 if (!writemask_xyzw(info->writemask))
1754 fail(ctx, "TEXKILL writemask must be .xyzw");
1755 else if ((regtype != REG_TYPE_TEMP) && (regtype != REG_TYPE_TEXTURE))
1756 fail(ctx, "TEXKILL must use a temp or texture register");
1757
1758 // !!! FIXME: "If a temporary register is used, all components must have been previously written."
1759 // !!! FIXME: "If a texture register is used, all components that are read must have been declared."
1760 // !!! FIXME: there are further limitations in ps_1_3 and earlier.
1761 } // state_TEXKILL
1762
1763 // Some rules that apply to some of the fruity ps_1_1 texture opcodes...
1764 static void state_texops(Context *ctx, const char *opcode,
1765 const int dims, const int texbem)
1766 {
1767 const DestArgInfo *dst = &ctx->dest_arg;
1768 const SourceArgInfo *src = &ctx->source_args[0];
1769 if (dst->regtype != REG_TYPE_TEXTURE)
1770 failf(ctx, "%s destination must be a texture register", opcode);
1771 if (src->regtype != REG_TYPE_TEXTURE)
1772 failf(ctx, "%s source must be a texture register", opcode);
1773 if (src->regnum >= dst->regnum) // so says MSDN.
1774 failf(ctx, "%s dest must be a higher register than source", opcode);
1775
1776 if (dims)
1777 {
1778 TextureType ttyp = (dims == 2) ? TEXTURE_TYPE_2D : TEXTURE_TYPE_CUBE;
1779 add_sampler(ctx, dst->regnum, ttyp, texbem);
1780 } // if
1781
1782 add_attribute_register(ctx, REG_TYPE_TEXTURE, dst->regnum,
1783 MOJOSHADER_USAGE_TEXCOORD, dst->regnum, 0xF, 0);
1784
1785 // Strictly speaking, there should be a TEX opcode prior to this call that
1786 // should fill in this metadata, but I'm not sure that's required for the
1787 // shader to assemble in D3D, so we'll do this so we don't fail with a
1788 // cryptic error message even if the developer didn't do the TEX.
1789 add_attribute_register(ctx, REG_TYPE_TEXTURE, src->regnum,
1790 MOJOSHADER_USAGE_TEXCOORD, src->regnum, 0xF, 0);
1791 } // state_texops
1792
1793 static void state_texbem(Context *ctx, const char *opcode)
1794 {
1795 // The TEXBEM equasion, according to MSDN:
1796 //u' = TextureCoordinates(stage m)u + D3DTSS_BUMPENVMAT00(stage m)*t(n)R
1797 // + D3DTSS_BUMPENVMAT10(stage m)*t(n)G
1798 //v' = TextureCoordinates(stage m)v + D3DTSS_BUMPENVMAT01(stage m)*t(n)R
1799 // + D3DTSS_BUMPENVMAT11(stage m)*t(n)G
1800 //t(m)RGBA = TextureSample(stage m)
1801 //
1802 // ...TEXBEML adds this at the end:
1803 //t(m)RGBA = t(m)RGBA * [(t(n)B * D3DTSS_BUMPENVLSCALE(stage m)) +
1804 // D3DTSS_BUMPENVLOFFSET(stage m)]
1805
1806 if (shader_version_atleast(ctx, 1, 4))
1807 failf(ctx, "%s opcode not available after Shader Model 1.3", opcode);
1808
1809 if (!shader_version_atleast(ctx, 1, 2))
1810 {
1811 if (ctx->source_args[0].src_mod == SRCMOD_SIGN)
1812 failf(ctx, "%s forbids _bx2 on source reg before ps_1_2", opcode);
1813 } // if
1814
1815 // !!! FIXME: MSDN:
1816 // !!! FIXME: Register data that has been read by a texbem
1817 // !!! FIXME: or texbeml instruction cannot be read later,
1818 // !!! FIXME: except by another texbem or texbeml.
1819
1820 state_texops(ctx, opcode, 2, 1);
1821 } // state_texbem
1822
1823 static void state_TEXBEM(Context *ctx)
1824 {
1825 state_texbem(ctx, "TEXBEM");
1826 } // state_TEXBEM
1827
1828 static void state_TEXBEML(Context *ctx)
1829 {
1830 state_texbem(ctx, "TEXBEML");
1831 } // state_TEXBEML
1832
1833 static void state_TEXM3X2PAD(Context *ctx)
1834 {
1835 if (shader_version_atleast(ctx, 1, 4))
1836 fail(ctx, "TEXM3X2PAD opcode not available after Shader Model 1.3");
1837 state_texops(ctx, "TEXM3X2PAD", 0, 0);
1838 // !!! FIXME: check for correct opcode existance and order more rigorously?
1839 ctx->texm3x2pad_src0 = ctx->source_args[0].regnum;
1840 ctx->texm3x2pad_dst0 = ctx->dest_arg.regnum;
1841 } // state_TEXM3X2PAD
1842
1843 static void state_TEXM3X2TEX(Context *ctx)
1844 {
1845 if (shader_version_atleast(ctx, 1, 4))
1846 fail(ctx, "TEXM3X2TEX opcode not available after Shader Model 1.3");
1847 if (ctx->texm3x2pad_dst0 == -1)
1848 fail(ctx, "TEXM3X2TEX opcode without matching TEXM3X2PAD");
1849 // !!! FIXME: check for correct opcode existance and order more rigorously?
1850 state_texops(ctx, "TEXM3X2TEX", 2, 0);
1851 ctx->reset_texmpad = 1;
1852
1853 RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER,
1854 ctx->dest_arg.regnum);
1855 const TextureType ttype = (TextureType) (sreg ? sreg->index : 0);
1856
1857 // A samplermap might change this to something nonsensical.
1858 if (ttype != TEXTURE_TYPE_2D)
1859 fail(ctx, "TEXM3X2TEX needs a 2D sampler");
1860 } // state_TEXM3X2TEX
1861
1862 static void state_TEXM3X3PAD(Context *ctx)
1863 {
1864 if (shader_version_atleast(ctx, 1, 4))
1865 fail(ctx, "TEXM3X2TEX opcode not available after Shader Model 1.3");
1866 state_texops(ctx, "TEXM3X3PAD", 0, 0);
1867
1868 // !!! FIXME: check for correct opcode existance and order more rigorously?
1869 if (ctx->texm3x3pad_dst0 == -1)
1870 {
1871 ctx->texm3x3pad_src0 = ctx->source_args[0].regnum;
1872 ctx->texm3x3pad_dst0 = ctx->dest_arg.regnum;
1873 } // if
1874 else if (ctx->texm3x3pad_dst1 == -1)
1875 {
1876 ctx->texm3x3pad_src1 = ctx->source_args[0].regnum;
1877 ctx->texm3x3pad_dst1 = ctx->dest_arg.regnum;
1878 } // else
1879 } // state_TEXM3X3PAD
1880
1881 static void state_texm3x3(Context *ctx, const char *opcode, const int dims)
1882 {
1883 // !!! FIXME: check for correct opcode existance and order more rigorously?
1884 if (shader_version_atleast(ctx, 1, 4))
1885 failf(ctx, "%s opcode not available after Shader Model 1.3", opcode);
1886 if (ctx->texm3x3pad_dst1 == -1)
1887 failf(ctx, "%s opcode without matching TEXM3X3PADs", opcode);
1888 state_texops(ctx, opcode, dims, 0);
1889 ctx->reset_texmpad = 1;
1890
1891 RegisterList *sreg = reglist_find(&ctx->samplers, REG_TYPE_SAMPLER,
1892 ctx->dest_arg.regnum);
1893 const TextureType ttype = (TextureType) (sreg ? sreg->index : 0);
1894
1895 // A samplermap might change this to something nonsensical.
1896 if ((ttype != TEXTURE_TYPE_VOLUME) && (ttype != TEXTURE_TYPE_CUBE))
1897 failf(ctx, "%s needs a 3D or Cubemap sampler", opcode);
1898 } // state_texm3x3
1899
1900 static void state_TEXM3X3(Context *ctx)
1901 {
1902 if (!shader_version_atleast(ctx, 1, 2))
1903 fail(ctx, "TEXM3X3 opcode not available in Shader Model 1.1");
1904 state_texm3x3(ctx, "TEXM3X3", 0);
1905 } // state_TEXM3X3
1906
1907 static void state_TEXM3X3TEX(Context *ctx)
1908 {
1909 state_texm3x3(ctx, "TEXM3X3TEX", 3);
1910 } // state_TEXM3X3TEX
1911
1912 static void state_TEXM3X3SPEC(Context *ctx)
1913 {
1914 state_texm3x3(ctx, "TEXM3X3SPEC", 3);
1915 if (ctx->source_args[1].regtype != REG_TYPE_CONST)
1916 fail(ctx, "TEXM3X3SPEC final arg must be a constant register");
1917 } // state_TEXM3X3SPEC
1918
1919 static void state_TEXM3X3VSPEC(Context *ctx)
1920 {
1921 state_texm3x3(ctx, "TEXM3X3VSPEC", 3);
1922 } // state_TEXM3X3VSPEC
1923
1924
1925 static void state_TEXLD(Context *ctx)
1926 {
1927 if (shader_version_atleast(ctx, 2, 0))
1928 {
1929 const SourceArgInfo *src0 = &ctx->source_args[0];
1930 const SourceArgInfo *src1 = &ctx->source_args[1];
1931
1932 // !!! FIXME: verify texldp restrictions:
1933 //http://msdn.microsoft.com/en-us/library/bb206221(VS.85).aspx
1934 // !!! FIXME: ...and texldb, too.
1935 //http://msdn.microsoft.com/en-us/library/bb206217(VS.85).aspx
1936
1937 //const RegisterType rt0 = src0->regtype;
1938
1939 // !!! FIXME: msdn says it has to be temp, but Microsoft's HLSL
1940 // !!! FIXME: compiler is generating code that uses oC0 for a dest.
1941 //if (ctx->dest_arg.regtype != REG_TYPE_TEMP)
1942 // fail(ctx, "TEXLD dest must be a temp register");
1943
1944 // !!! FIXME: this can be an REG_TYPE_INPUT, DCL'd to TEXCOORD.
1945 //else if ((rt0 != REG_TYPE_TEXTURE) && (rt0 != REG_TYPE_TEMP))
1946 // fail(ctx, "TEXLD src0 must be texture or temp register");
1947 //else
1948
1949 if (src0->src_mod != SRCMOD_NONE)
1950 fail(ctx, "TEXLD src0 must have no modifiers");
1951 else if (src1->regtype != REG_TYPE_SAMPLER)
1952 fail(ctx, "TEXLD src1 must be sampler register");
1953 else if (src1->src_mod != SRCMOD_NONE)
1954 fail(ctx, "TEXLD src1 must have no modifiers");
1955 else if ( (ctx->instruction_controls != CONTROL_TEXLD) &&
1956 (ctx->instruction_controls != CONTROL_TEXLDP) &&
1957 (ctx->instruction_controls != CONTROL_TEXLDB) )
1958 {
1959 fail(ctx, "TEXLD has unknown control bits");
1960 } // else if
1961
1962 // Shader Model 3 added swizzle support to this opcode.
1963 if (!shader_version_atleast(ctx, 3, 0))
1964 {
1965 if (!no_swizzle(src0->swizzle))
1966 fail(ctx, "TEXLD src0 must not swizzle");
1967 else if (!no_swizzle(src1->swizzle))
1968 fail(ctx, "TEXLD src1 must not swizzle");
1969 } // if
1970
1971 if ( ((TextureType) ctx->source_args[1].regnum) == TEXTURE_TYPE_CUBE )
1972 ctx->instruction_count += 3;
1973 } // if
1974
1975 else if (shader_version_atleast(ctx, 1, 4))
1976 {
1977 // !!! FIXME: checks for ps_1_4 version here...
1978 } // else if
1979
1980 else
1981 {
1982 // !!! FIXME: add (other?) checks for ps_1_1 version here...
1983 const DestArgInfo *info = &ctx->dest_arg;
1984 const int sampler = info->regnum;
1985 if (info->regtype != REG_TYPE_TEXTURE)
1986 fail(ctx, "TEX param must be a texture register");
1987 add_sampler(ctx, sampler, TEXTURE_TYPE_2D, 0);
1988 } // else
1989 } // state_TEXLD
1990
1991 static void state_TEXLDL(Context *ctx)
1992 {
1993 if (!shader_version_atleast(ctx, 3, 0))
1994 fail(ctx, "TEXLDL in version < Shader Model 3.0");
1995 else if (ctx->source_args[1].regtype != REG_TYPE_SAMPLER)
1996 fail(ctx, "TEXLDL src1 must be sampler register");
1997 else
1998 {
1999 if ( ((TextureType) ctx->source_args[1].regnum) == TEXTURE_TYPE_CUBE )
2000 ctx->instruction_count += 3;
2001 } // else
2002 } // state_TEXLDL
2003
2004 static void state_DP2ADD(Context *ctx)
2005 {
2006 if (!replicate_swizzle(ctx->source_args[2].swizzle))
2007 fail(ctx, "DP2ADD src2 must have replicate swizzle");
2008 } // state_DP2ADD
2009
2010
2011 // Lookup table for instruction opcodes...
2012 typedef struct
2013 {
2014 const char *opcode_string;
2015 int slots; // number of instruction slots this opcode eats.
2016 MOJOSHADER_shaderType shader_types; // mask of types that can use opcode.
2017 args_function parse_args;
2018 state_function state;
2019 emit_function emitter[STATICARRAYLEN(profiles)];
2020 } Instruction;
2021
2022 // These have to be in the right order! This array is indexed by the value
2023 // of the instruction token.
2024 static const Instruction instructions[] =
2025 {
2026 #define INSTRUCTION_STATE(op, opstr, slots, a, t, w) { \
2027 opstr, slots, t, parse_args_##a, state_##op, PROFILE_EMITTERS(op) \
2028 },
2029
2030 #define INSTRUCTION(op, opstr, slots, a, t, w) { \
2031 opstr, slots, t, parse_args_##a, NULL, PROFILE_EMITTERS(op) \
2032 },
2033
2034 #define MOJOSHADER_DO_INSTRUCTION_TABLE 1
2035 #include "mojoshader_internal.h"
2036 };
2037
2038
2039 // parse various token types...
2040
2041 static int parse_instruction_token(Context *ctx)
2042 {
2043 int retval = 0;
2044 const int start_position = ctx->current_position;
2045 const uint32 *start_tokens = ctx->tokens;
2046 const uint32 start_tokencount = ctx->tokencount;
2047 const uint32 token = SWAP32(*(ctx->tokens));
2048 const uint32 opcode = (token & 0xFFFF);
2049 const uint32 controls = ((token >> 16) & 0xFF);
2050 const uint32 insttoks = ((token >> 24) & 0x0F);
2051 const int coissue = (token & 0x40000000) ? 1 : 0;
2052 const int predicated = (token & 0x10000000) ? 1 : 0;
2053
2054 if ( opcode >= (sizeof (instructions) / sizeof (instructions[0])) )
2055 return 0; // not an instruction token, or just not handled here.
2056
2057 const Instruction *instruction = &instructions[opcode];
2058 const emit_function emitter = instruction->emitter[ctx->profileid];
2059
2060 if ((token & 0x80000000) != 0)
2061 fail(ctx, "instruction token high bit must be zero."); // so says msdn.
2062
2063 if (instruction->opcode_string == NULL)
2064 {
2065 fail(ctx, "Unknown opcode.");
2066 return insttoks + 1; // pray that you resync later.
2067 } // if
2068
2069 ctx->coissue = coissue;
2070 if (coissue)
2071 {
2072 if (!shader_is_pixel(ctx))
2073 fail(ctx, "coissue instruction on non-pixel shader");
2074 if (shader_version_atleast(ctx, 2, 0))
2075 fail(ctx, "coissue instruction in Shader Model >= 2.0");
2076 } // if
2077
2078 if ((ctx->shader_type & instruction->shader_types) == 0)
2079 {
2080 failf(ctx, "opcode '%s' not available in this shader type.",
2081 instruction->opcode_string);
2082 } // if
2083
2084 memset(ctx->dwords, '\0', sizeof (ctx->dwords));
2085 ctx->instruction_controls = controls;
2086 ctx->predicated = predicated;
2087
2088 // Update the context with instruction's arguments.
2089 adjust_token_position(ctx, 1);
2090 retval = instruction->parse_args(ctx);
2091
2092 if (predicated)
2093 retval += parse_predicated_token(ctx);
2094
2095 // parse_args() moves these forward for convenience...reset them.
2096 ctx->tokens = start_tokens;
2097 ctx->tokencount = start_tokencount;
2098 ctx->current_position = start_position;
2099
2100 if (instruction->state != NULL)
2101 instruction->state(ctx);
2102
2103 ctx->instruction_count += instruction->slots;
2104
2105 if (!isfail(ctx))
2106 emitter(ctx); // call the profile's emitter.
2107
2108 if (ctx->reset_texmpad)
2109 {
2110 ctx->texm3x2pad_dst0 = -1;
2111 ctx->texm3x2pad_src0 = -1;
2112 ctx->texm3x3pad_dst0 = -1;
2113 ctx->texm3x3pad_src0 = -1;
2114 ctx->texm3x3pad_dst1 = -1;
2115 ctx->texm3x3pad_src1 = -1;
2116 ctx->reset_texmpad = 0;
2117 } // if
2118
2119 ctx->previous_opcode = opcode;
2120 ctx->scratch_registers = 0; // reset after every instruction.
2121
2122 if (!shader_version_atleast(ctx, 2, 0))
2123 {
2124 if (insttoks != 0) // reserved field in shaders < 2.0 ...
2125 fail(ctx, "instruction token count must be zero");
2126 } // if
2127 else
2128 {
2129 if (((uint32)retval) != (insttoks+1))
2130 {
2131 failf(ctx, "wrong token count (%u, not %u) for opcode '%s'.",
2132 (uint) retval, (uint) (insttoks+1),
2133 instruction->opcode_string);
2134 retval = insttoks + 1; // try to keep sync.
2135 } // if
2136 } // else
2137
2138 return retval;
2139 } // parse_instruction_token
2140
2141
2142 static int parse_version_token(Context *ctx, const char *profilestr)
2143 {
2144 if (ctx->tokencount == 0)
2145 {
2146 fail(ctx, "Expected version token, got none at all.");
2147 return 0;
2148 } // if
2149
2150 const uint32 token = SWAP32(*(ctx->tokens));
2151 const uint32 shadertype = ((token >> 16) & 0xFFFF);
2152 const uint8 major = (uint8) ((token >> 8) & 0xFF);
2153 const uint8 minor = (uint8) (token & 0xFF);
2154
2155 ctx->version_token = token;
2156
2157 // 0xFFFF == pixel shader, 0xFFFE == vertex shader
2158 if (shadertype == 0xFFFF)
2159 {
2160 ctx->shader_type = MOJOSHADER_TYPE_PIXEL;
2161 ctx->shader_type_str = "ps";
2162 } // if
2163 else if (shadertype == 0xFFFE)
2164 {
2165 ctx->shader_type = MOJOSHADER_TYPE_VERTEX;
2166 ctx->shader_type_str = "vs";
2167 } // else if
2168 else // geometry shader? Bogus data?
2169 {
2170 fail(ctx, "Unsupported shader type or not a shader at all");
2171 return -1;
2172 } // else
2173
2174 ctx->major_ver = major;
2175 ctx->minor_ver = minor;
2176
2177 if (!shader_version_supported(major, minor))
2178 {
2179 failf(ctx, "Shader Model %u.%u is currently unsupported.",
2180 (uint) major, (uint) minor);
2181 } // if
2182
2183 if (!isfail(ctx))
2184 ctx->profile->start_emitter(ctx, profilestr);
2185
2186 return 1; // ate one token.
2187 } // parse_version_token
2188
2189
2190 static int parse_ctab_string(const uint8 *start, const uint32 bytes,
2191 const uint32 name)
2192 {
2193 // Make sure strings don't overflow the CTAB buffer...
2194 if (name < bytes)
2195 {
2196 int i;
2197 const int slenmax = bytes - name;
2198 const char *namestr = (const char *) (start + name);
2199 for (i = 0; i < slenmax; i++)
2200 {
2201 if (namestr[i] == '\0')
2202 return 1; // it's okay.
2203 } // for
2204 } // if
2205
2206 return 0; // overflowed.
2207 } // parse_ctab_string
2208
2209
2210 static int parse_ctab_typeinfo(Context *ctx, const uint8 *start,
2211 const uint32 bytes, const uint32 pos,
2212 MOJOSHADER_symbolTypeInfo *info,
2213 const int depth)
2214 {
2215 if ((bytes <= pos) || ((bytes - pos) < 16))
2216 return 0; // corrupt CTAB.
2217
2218 const uint16 *typeptr = (const uint16 *) (start + pos);
2219
2220 info->parameter_class = (MOJOSHADER_symbolClass) SWAP16(typeptr[0]);
2221 info->parameter_type = (MOJOSHADER_symbolType) SWAP16(typeptr[1]);
2222 info->rows = (unsigned int) SWAP16(typeptr[2]);
2223 info->columns = (unsigned int) SWAP16(typeptr[3]);
2224 info->elements = (unsigned int) SWAP16(typeptr[4]);
2225
2226 if (info->parameter_class >= MOJOSHADER_SYMCLASS_TOTAL)
2227 {
2228 failf(ctx, "Unknown parameter class (0x%X)", info->parameter_class);
2229 info->parameter_class = MOJOSHADER_SYMCLASS_SCALAR;
2230 } // if
2231
2232 if (info->parameter_type >= MOJOSHADER_SYMTYPE_TOTAL)
2233 {
2234 failf(ctx, "Unknown parameter type (0x%X)", info->parameter_type);
2235 info->parameter_type = MOJOSHADER_SYMTYPE_INT;
2236 } // if
2237
2238 const unsigned int member_count = (unsigned int) SWAP16(typeptr[5]);
2239 info->member_count = 0;
2240 info->members = NULL;
2241
2242 if ((pos + 16 + (member_count * 8)) >= bytes)
2243 return 0; // corrupt CTAB.
2244
2245 if (member_count > 0)
2246 {
2247 if (depth > 300) // make sure we aren't in an infinite loop here.
2248 {
2249 fail(ctx, "Possible infinite loop in CTAB structure.");
2250 return 0;
2251 } // if
2252
2253 const size_t len = sizeof (MOJOSHADER_symbolStructMember) * member_count;
2254 info->members = (MOJOSHADER_symbolStructMember *) Malloc(ctx, len);
2255 if (info->members == NULL)
2256 return 1; // we'll check ctx->out_of_memory later.
2257 memset(info->members, '\0', len);
2258 info->member_count = member_count;
2259 } // else
2260
2261 unsigned int i;
2262 const uint32 *member = (const uint32 *) (start + typeptr[6]);
2263 for (i = 0; i < member_count; i++)
2264 {
2265 MOJOSHADER_symbolStructMember *mbr = &info->members[i];
2266 const uint32 name = SWAP32(member[0]);
2267 const uint32 memberinfopos = SWAP32(member[1]);
2268 member += 2;
2269
2270 if (!parse_ctab_string(start, bytes, name))
2271 return 0; // info->members will be free()'d elsewhere.
2272
2273 mbr->name = StrDup(ctx, (const char *) (start + name));
2274 if (mbr->name == NULL)
2275 return 1; // we'll check ctx->out_of_memory later.
2276 if (!parse_ctab_typeinfo(ctx, start, bytes, memberinfopos, &mbr->info, depth + 1))
2277 return 0;
2278 if (ctx->out_of_memory)
2279 return 1; // drop out now.
2280 } // for
2281
2282 return 1;
2283 } // parse_ctab_typeinfo
2284
2285
2286 // Microsoft's tools add a CTAB comment to all shaders. This is the
2287 // "constant table," or specifically: D3DXSHADER_CONSTANTTABLE:
2288 // http://msdn.microsoft.com/en-us/library/bb205440(VS.85).aspx
2289 // This may tell us high-level truths about an otherwise generic low-level
2290 // registers, for instance, how large an array actually is, etc.
2291 static void parse_constant_table(Context *ctx, const uint32 *tokens,
2292 const uint32 bytes, const uint32 okay_version,
2293 const int setvariables, CtabData *ctab)
2294 {
2295 const uint32 id = SWAP32(tokens[1]);
2296 if (id != CTAB_ID)
2297 return; // not the constant table.
2298
2299 if (ctab->have_ctab) // !!! FIXME: can you have more than one?
2300 {
2301 fail(ctx, "Shader has multiple CTAB sections");
2302 return;
2303 } // if
2304
2305 ctab->have_ctab = 1;
2306
2307 const uint8 *start = (uint8 *) &tokens[2];
2308
2309 if (bytes < 32)
2310 {
2311 fail(ctx, "Truncated CTAB data");
2312 return;
2313 } // if
2314
2315 const uint32 size = SWAP32(tokens[2]);
2316 const uint32 creator = SWAP32(tokens[3]);
2317 const uint32 version = SWAP32(tokens[4]);
2318 const uint32 constants = SWAP32(tokens[5]);
2319 const uint32 constantinfo = SWAP32(tokens[6]);
2320 const uint32 target = SWAP32(tokens[8]);
2321
2322 if (size != CTAB_SIZE)
2323 goto corrupt_ctab;
2324 else if (constants > 1000000) // sanity check.
2325 goto corrupt_ctab;
2326
2327 if (version != okay_version) goto corrupt_ctab;
2328 if (creator >= bytes) goto corrupt_ctab;
2329 if (constantinfo >= bytes) goto corrupt_ctab;
2330 if ((bytes - constantinfo) < (constants * CINFO_SIZE)) goto corrupt_ctab;
2331 if (target >= bytes) goto corrupt_ctab;
2332 if (!parse_ctab_string(start, bytes, target)) goto corrupt_ctab;
2333 // !!! FIXME: check that (start+target) points to "ps_3_0", etc.
2334
2335 ctab->symbols = NULL;
2336 if (constants > 0)
2337 {
2338 ctab->symbols = (MOJOSHADER_symbol *) Malloc(ctx, sizeof (MOJOSHADER_symbol) * constants);
2339 if (ctab->symbols == NULL)
2340 return;
2341 memset(ctab->symbols, '\0', sizeof (MOJOSHADER_symbol) * constants);
2342 } // if
2343 ctab->symbol_count = constants;
2344
2345 uint32 i = 0;
2346 for (i = 0; i < constants; i++)
2347 {
2348 const uint8 *ptr = start + constantinfo + (i * CINFO_SIZE);
2349 const uint32 name = SWAP32(*((uint32 *) (ptr + 0)));
2350 const uint16 regset = SWAP16(*((uint16 *) (ptr + 4)));
2351 const uint16 regidx = SWAP16(*((uint16 *) (ptr + 6)));
2352 const uint16 regcnt = SWAP16(*((uint16 *) (ptr + 8)));
2353 const uint32 typeinf = SWAP32(*((uint32 *) (ptr + 12)));
2354 const uint32 defval = SWAP32(*((uint32 *) (ptr + 16)));
2355 MOJOSHADER_uniformType mojotype = MOJOSHADER_UNIFORM_UNKNOWN;
2356
2357 if (!parse_ctab_string(start, bytes, name)) goto corrupt_ctab;
2358 if (defval >= bytes) goto corrupt_ctab;
2359
2360 switch (regset)
2361 {
2362 case 0: mojotype = MOJOSHADER_UNIFORM_BOOL; break;
2363 case 1: mojotype = MOJOSHADER_UNIFORM_INT; break;
2364 case 2: mojotype = MOJOSHADER_UNIFORM_FLOAT; break;
2365 case 3: /* SAMPLER */ break;
2366 default: goto corrupt_ctab;
2367 } // switch
2368
2369 if ((setvariables) && (mojotype != MOJOSHADER_UNIFORM_UNKNOWN))
2370 {
2371 VariableList *item;
2372 item = (VariableList *) Malloc(ctx, sizeof (VariableList));
2373 if (item != NULL)
2374 {
2375 item->type = mojotype;
2376 item->index = regidx;
2377 item->count = regcnt;
2378 item->constant = NULL;
2379 item->used = 0;
2380 item->emit_position = -1;
2381 item->next = ctx->variables;
2382 ctx->variables = item;
2383 } // if
2384 } // if
2385
2386 // Add the symbol.
2387 const char *namecpy = StrDup(ctx, (const char *) (start + name));
2388 if (namecpy == NULL)
2389 return;
2390
2391 MOJOSHADER_symbol *sym = &ctab->symbols[i];
2392 sym->name = namecpy;
2393 sym->register_set = (MOJOSHADER_symbolRegisterSet) regset;
2394 sym->register_index = (unsigned int) regidx;
2395 sym->register_count = (unsigned int) regcnt;
2396 if (!parse_ctab_typeinfo(ctx, start, bytes, typeinf, &sym->info, 0))
2397 goto corrupt_ctab; // sym->name will get free()'d later.
2398 else if (ctx->out_of_memory)
2399 return; // just bail now.
2400 } // for
2401
2402 return;
2403
2404 corrupt_ctab:
2405 fail(ctx, "Shader has corrupt CTAB data");
2406 } // parse_constant_table
2407
2408
2409 static void free_symbols(MOJOSHADER_free f, void *d, MOJOSHADER_symbol *syms,
2410 const int symcount);
2411
2412
2413 static int is_comment_token(Context *ctx, const uint32 tok, uint32 *tokcount)
2414 {
2415 const uint32 token = SWAP32(tok);
2416 if ((token & 0xFFFF) == 0xFFFE) // actually a comment token?
2417 {
2418 if ((token & 0x80000000) != 0)
2419 fail(ctx, "comment token high bit must be zero."); // so says msdn.
2420 *tokcount = ((token >> 16) & 0xFFFF);
2421 return 1;
2422 } // if
2423
2424 return 0;
2425 } // is_comment_token
2426
2427
2428 typedef struct PreshaderBlockInfo
2429 {
2430 const uint32 *tokens;
2431 uint32 tokcount;
2432 int seen;
2433 } PreshaderBlockInfo;
2434
2435 // Preshaders only show up in compiled Effect files. The format is
2436 // undocumented, and even the instructions aren't the same opcodes as you
2437 // would find in a regular shader. These things show up because the HLSL
2438 // compiler can detect work that sets up constant registers that could
2439 // be moved out of the shader itself. Preshaders run once, then the shader
2440 // itself runs many times, using the constant registers the preshader has set
2441 // up. There are cases where the preshaders are 3+ times as many instructions
2442 // as the shader itself, so this can be a big performance win.
2443 // My presumption is that Microsoft's Effects framework runs the preshaders on
2444 // the CPU, then loads the constant register file appropriately before handing
2445 // off to the GPU. As such, we do the same.
2446 static void parse_preshader(Context *ctx, const uint32 *tokens, uint32 tokcount)
2447 {
2448 #ifndef MOJOSHADER_EFFECT_SUPPORT
2449 fail(ctx, "Preshader found, but effect support is disabled!");
2450 #else
2451 uint32 i;
2452
2453 assert(ctx->have_preshader == 0); // !!! FIXME: can you have more than one?
2454 ctx->have_preshader = 1;
2455
2456 // !!! FIXME: I don't know what specific versions signify, but we need to
2457 // !!! FIXME: save this to test against the CTAB version field, if
2458 // !!! FIXME: nothing else.
2459 // !!! FIXME: 0x02 0x0? is probably the version (fx_2_?),
2460 // !!! FIXME: and 0x4658 is the magic, like a real shader's version token.
2461 const uint32 version_magic = 0x46580000;
2462 const uint32 min_version = 0x00000200 | version_magic;
2463 const uint32 max_version = 0x00000201 | version_magic;
2464 const uint32 version = SWAP32(tokens[0]);
2465 if (version < min_version || version > max_version)
2466 {
2467 fail(ctx, "Unsupported preshader version.");
2468 return; // fail because the shader will malfunction w/o this.
2469 } // if
2470
2471 tokens++;
2472 tokcount--;
2473
2474 // All sections of a preshader are packed into separate comment tokens,
2475 // inside the containing comment token block. Find them all before
2476 // we start, so we don't care about the order they appear in the file.
2477 PreshaderBlockInfo ctab = { 0, 0, 0 };
2478 PreshaderBlockInfo prsi = { 0, 0, 0 };
2479 PreshaderBlockInfo fxlc = { 0, 0, 0 };
2480 PreshaderBlockInfo clit = { 0, 0, 0 };
2481
2482 while (tokcount > 0)
2483 {
2484 uint32 subtokcount = 0;
2485 if ( (!is_comment_token(ctx, *tokens, &subtokcount)) ||
2486 (subtokcount > tokcount) )
2487 {
2488 // !!! FIXME: Standalone preshaders have this EOS-looking token,
2489 // !!! FIXME: sometimes followed by tokens that don't appear to
2490 // !!! FIXME: have anything to do with the rest of the blob.
2491 // !!! FIXME: So for now, treat this as a special "EOS" comment.
2492 if (SWAP32(*tokens) == 0xFFFF)
2493 break;
2494
2495 fail(ctx, "Bogus preshader data.");
2496 return;
2497 } // if
2498
2499 tokens++;
2500 tokcount--;
2501
2502 const uint32 *nexttokens = tokens + subtokcount;
2503 const uint32 nexttokcount = tokcount - subtokcount;
2504
2505 if (subtokcount > 0)
2506 {
2507 switch (SWAP32(*tokens))
2508 {
2509 #define PRESHADER_BLOCK_CASE(id, var) \
2510 case id##_ID: { \
2511 if (var.seen) { \
2512 fail(ctx, "Multiple " #id " preshader blocks."); \
2513 return; \
2514 } \
2515 var.tokens = tokens; \
2516 var.tokcount = subtokcount; \
2517 var.seen = 1; \
2518 break; \
2519 }
2520 PRESHADER_BLOCK_CASE(CTAB, ctab);
2521 PRESHADER_BLOCK_CASE(PRSI, prsi);
2522 PRESHADER_BLOCK_CASE(FXLC, fxlc);
2523 PRESHADER_BLOCK_CASE(CLIT, clit);
2524 default: fail(ctx, "Bogus preshader section."); return;
2525 #undef PRESHADER_BLOCK_CASE
2526 } // switch
2527 } // if
2528
2529 tokens = nexttokens;
2530 tokcount = nexttokcount;
2531 } // while
2532
2533 if (!ctab.seen) { fail(ctx, "No CTAB block in preshader."); return; }
2534 if (!fxlc.seen) { fail(ctx, "No FXLC block in preshader."); return; }
2535 if (!clit.seen) { fail(ctx, "No CLIT block in preshader."); return; }
2536 // prsi.seen is optional, apparently.
2537
2538 MOJOSHADER_preshader *preshader = (MOJOSHADER_preshader *)
2539 Malloc(ctx, sizeof (MOJOSHADER_preshader));
2540 if (preshader == NULL)
2541 return;
2542
2543 memset(preshader, '\0', sizeof (MOJOSHADER_preshader));
2544 preshader->malloc = ctx->malloc;
2545 preshader->free = ctx->free;
2546 preshader->malloc_data = ctx->malloc_data;
2547
2548 ctx->preshader = preshader;
2549
2550 // Let's set up the constant literals first...
2551 if (clit.tokcount == 0)
2552 fail(ctx, "Bogus CLIT block in preshader.");
2553 else
2554 {
2555 const uint32 lit_count = SWAP32(clit.tokens[1]);
2556 if (lit_count > ((clit.tokcount - 2) / 2))
2557 {
2558 fail(ctx, "Bogus CLIT block in preshader.");
2559 return;
2560 } // if
2561 else if (lit_count > 0)
2562 {
2563 preshader->literal_count = (unsigned int) lit_count;
2564 assert(sizeof (double) == 8); // just in case.
2565 const size_t len = sizeof (double) * lit_count;
2566 preshader->literals = (double *) Malloc(ctx, len);
2567 if (preshader->literals == NULL)
2568 return; // oh well.
2569 const double *litptr = (const double *) (clit.tokens + 2);
2570 // !!! FIXME: This should be a SWAPDBL loop, but in addition to
2571 // !!! FIXME: never having an implementation, it turns out some
2572 // !!! FIXME: MinGW versions do not optimize this correctly, which
2573 // !!! FIXME: can cause random crashes on Win64. -flibit
2574 //for (i = 0; i < lit_count; i++)
2575 // preshader->literals[i] = SWAPDBL(litptr[i]);
2576 memcpy(preshader->literals, litptr, len);
2577 } // else if
2578 } // else
2579
2580 // Parse out the PRSI block. This is used to map the output registers.
2581 uint32 output_map_count = 0;
2582 const uint32 *output_map = NULL;
2583 if (prsi.seen)
2584 {
2585 if (prsi.tokcount < 8)
2586 {
2587 fail(ctx, "Bogus preshader PRSI data");
2588 return;
2589 } // if
2590
2591 //const uint32 first_output_reg = SWAP32(prsi.tokens[1]);
2592 // !!! FIXME: there are a lot of fields here I don't know about.
2593 // !!! FIXME: maybe [2] and [3] are for int4 and bool registers?
2594 //const uint32 output_reg_count = SWAP32(prsi.tokens[4]);
2595 // !!! FIXME: maybe [5] and [6] are for int4 and bool registers?
2596 output_map_count = SWAP32(prsi.tokens[7]);
2597
2598 prsi.tokcount -= 8;
2599 prsi.tokens += 8;
2600
2601 if (prsi.tokcount < ((output_map_count + 1) * 2))
2602 {
2603 fail(ctx, "Bogus preshader PRSI data");
2604 return;
2605 } // if
2606
2607 output_map = prsi.tokens;
2608 } // if
2609
2610 // Now we'll figure out the CTAB...
2611 CtabData ctabdata = { 0, 0, 0 };
2612 parse_constant_table(ctx, ctab.tokens - 1, ctab.tokcount * 4,
2613 version, 0, &ctabdata);
2614
2615 // preshader owns this now. Don't free it in this function.
2616 preshader->symbol_count = ctabdata.symbol_count;
2617 preshader->symbols = ctabdata.symbols;
2618
2619 if (!ctabdata.have_ctab)
2620 {
2621 fail(ctx, "Bogus preshader CTAB data");
2622 return;
2623 } // if
2624
2625 // The FXLC block has the actual instructions...
2626 uint32 opcode_count = SWAP32(fxlc.tokens[1]);
2627
2628 const size_t len = sizeof (MOJOSHADER_preshaderInstruction) * opcode_count;
2629 preshader->instruction_count = (unsigned int) opcode_count;
2630 preshader->instructions = (MOJOSHADER_preshaderInstruction *) Malloc(ctx, len);
2631 if (preshader->instructions == NULL)
2632 return;
2633 memset(preshader->instructions, '\0', len);
2634
2635 fxlc.tokens += 2;
2636 fxlc.tokcount -= 2;
2637 if (opcode_count > (fxlc.tokcount / 2))
2638 {
2639 fail(ctx, "Bogus preshader FXLC block.");
2640 return;
2641 } // if
2642
2643 MOJOSHADER_preshaderInstruction *inst = preshader->instructions;
2644 while (opcode_count--)
2645 {
2646 const uint32 opcodetok = SWAP32(fxlc.tokens[0]);
2647 MOJOSHADER_preshaderOpcode opcode = MOJOSHADER_PRESHADEROP_NOP;
2648 switch ((opcodetok >> 16) & 0xFFFF)
2649 {
2650 case 0x1000: opcode = MOJOSHADER_PRESHADEROP_MOV; break;
2651 case 0x1010: opcode = MOJOSHADER_PRESHADEROP_NEG; break;
2652 case 0x1030: opcode = MOJOSHADER_PRESHADEROP_RCP; break;
2653 case 0x1040: opcode = MOJOSHADER_PRESHADEROP_FRC; break;
2654 case 0x1050: opcode = MOJOSHADER_PRESHADEROP_EXP; break;
2655 case 0x1060: opcode = MOJOSHADER_PRESHADEROP_LOG; break;
2656 case 0x1070: opcode = MOJOSHADER_PRESHADEROP_RSQ; break;
2657 case 0x1080: opcode = MOJOSHADER_PRESHADEROP_SIN; break;
2658 case 0x1090: opcode = MOJOSHADER_PRESHADEROP_COS; break;
2659 case 0x10A0: opcode = MOJOSHADER_PRESHADEROP_ASIN; break;
2660 case 0x10B0: opcode = MOJOSHADER_PRESHADEROP_ACOS; break;
2661 case 0x10C0: opcode = MOJOSHADER_PRESHADEROP_ATAN; break;
2662 case 0x2000: opcode = MOJOSHADER_PRESHADEROP_MIN; break;
2663 case 0x2010: opcode = MOJOSHADER_PRESHADEROP_MAX; break;
2664 case 0x2020: opcode = MOJOSHADER_PRESHADEROP_LT; break;
2665 case 0x2030: opcode = MOJOSHADER_PRESHADEROP_GE; break;
2666 case 0x2040: opcode = MOJOSHADER_PRESHADEROP_ADD; break;
2667 case 0x2050: opcode = MOJOSHADER_PRESHADEROP_MUL; break;
2668 case 0x2060: opcode = MOJOSHADER_PRESHADEROP_ATAN2; break;
2669 case 0x2080: opcode = MOJOSHADER_PRESHADEROP_DIV; break;
2670 case 0x3000: opcode = MOJOSHADER_PRESHADEROP_CMP; break;
2671 case 0x3010: opcode = MOJOSHADER_PRESHADEROP_MOVC; break;
2672 case 0x5000: opcode = MOJOSHADER_PRESHADEROP_DOT; break;
2673 case 0x5020: opcode = MOJOSHADER_PRESHADEROP_NOISE; break;
2674 case 0xA000: opcode = MOJOSHADER_PRESHADEROP_MIN_SCALAR; break;
2675 case 0xA010: opcode = MOJOSHADER_PRESHADEROP_MAX_SCALAR; break;
2676 case 0xA020: opcode = MOJOSHADER_PRESHADEROP_LT_SCALAR; break;
2677 case 0xA030: opcode = MOJOSHADER_PRESHADEROP_GE_SCALAR; break;
2678 case 0xA040: opcode = MOJOSHADER_PRESHADEROP_ADD_SCALAR; break;
2679 case 0xA050: opcode = MOJOSHADER_PRESHADEROP_MUL_SCALAR; break;
2680 case 0xA060: opcode = MOJOSHADER_PRESHADEROP_ATAN2_SCALAR; break;
2681 case 0xA080: opcode = MOJOSHADER_PRESHADEROP_DIV_SCALAR; break;
2682 case 0xD000: opcode = MOJOSHADER_PRESHADEROP_DOT_SCALAR; break;
2683 case 0xD020: opcode = MOJOSHADER_PRESHADEROP_NOISE_SCALAR; break;
2684 default: fail(ctx, "Unknown preshader opcode."); break;
2685 } // switch
2686
2687 uint32 operand_count = SWAP32(fxlc.tokens[1]) + 1; // +1 for dest.
2688
2689 inst->opcode = opcode;
2690 inst->element_count = (unsigned int) (opcodetok & 0xFF);
2691 inst->operand_count = (unsigned int) operand_count;
2692
2693 fxlc.tokens += 2;
2694 fxlc.tokcount -= 2;
2695 if ((operand_count * 3) > fxlc.tokcount)
2696 {
2697 fail(ctx, "Bogus preshader FXLC block.");
2698 return;
2699 } // if
2700
2701 MOJOSHADER_preshaderOperand *operand = inst->operands;
2702 while (operand_count--)
2703 {
2704 const unsigned int item = (unsigned int) SWAP32(fxlc.tokens[2]);
2705
2706 // !!! FIXME: Is this used anywhere other than INPUT? -flibit
2707 const uint32 numarrays = SWAP32(fxlc.tokens[0]);
2708 switch (SWAP32(fxlc.tokens[1]))
2709 {
2710 case 1: // literal from CLIT block.
2711 {
2712 if (item > preshader->literal_count)
2713 {
2714 fail(ctx, "Bogus preshader literal index.");
2715 break;
2716 } // if
2717 operand->type = MOJOSHADER_PRESHADEROPERAND_LITERAL;
2718 break;
2719 } // case
2720
2721 case 2: // item from ctabdata.
2722 {
2723 MOJOSHADER_symbol *sym = ctabdata.symbols;
2724 const uint32 symcount = (uint32) ctabdata.symbol_count;
2725 for (i = 0; i < symcount; i++, sym++)
2726 {
2727 const uint32 base = sym->register_index * 4;
2728 const uint32 count = sym->register_count * 4;
2729 assert(sym->register_set==MOJOSHADER_SYMREGSET_FLOAT4);
2730 if ( (base <= item) && ((base + count) > item) )
2731 break;
2732 } // for
2733 if (i == ctabdata.symbol_count)
2734 {
2735 fail(ctx, "Bogus preshader input index.");
2736 break;
2737 } // if
2738 operand->type = MOJOSHADER_PRESHADEROPERAND_INPUT;
2739 if (numarrays > 0)
2740 {
2741 // malloc the array symbol name array
2742 const uint32 siz = numarrays * sizeof (uint32);
2743 operand->array_register_count = numarrays;
2744 operand->array_registers = (uint32 *) Malloc(ctx, siz);
2745 memset(operand->array_registers, '\0', siz);
2746 // Get each register base, indicating the arrays used.
2747 // !!! FIXME: fail if fxlc.tokcount*2 > numarrays ?
2748 for (i = 0; i < numarrays; i++)
2749 {
2750 const uint32 jmp = SWAP32(fxlc.tokens[4]);
2751 const uint32 bigjmp = (jmp >> 4) * 4;
2752 const uint32 ltljmp = (jmp >> 2) & 3;
2753 operand->array_registers[i] = bigjmp + ltljmp;
2754 fxlc.tokens += 2;
2755 fxlc.tokcount -= 2;
2756 } // for
2757 } // if
2758 break;
2759 } // case
2760
2761 case 4:
2762 {
2763 operand->type = MOJOSHADER_PRESHADEROPERAND_OUTPUT;
2764
2765 for (i = 0; i < output_map_count; i++)
2766 {
2767 const uint32 base = output_map[(i*2)] * 4;
2768 const uint32 count = output_map[(i*2)+1] * 4;
2769 if ( (base <= item) && ((base + count) > item) )
2770 break;
2771 } // for
2772
2773 if (i == output_map_count)
2774 {
2775 if (prsi.seen) // No PRSI tokens, no output map.
2776 fail(ctx, "Bogus preshader output index.");
2777 } // if
2778
2779 break;
2780 } // case
2781
2782 case 7:
2783 {
2784 operand->type = MOJOSHADER_PRESHADEROPERAND_TEMP;
2785 if (item >= preshader->temp_count)
2786 preshader->temp_count = item + 1;
2787 break;
2788 } // case
2789
2790 default:
2791 assert(0 && "Unhandled fxlc.tokens[1] in parse_preshader!");
2792 break;
2793 } // switch
2794
2795 operand->index = item;
2796
2797 fxlc.tokens += 3;
2798 fxlc.tokcount -= 3;
2799 operand++;
2800 } // while
2801
2802 inst++;
2803 } // while
2804
2805 // Registers need to be vec4, round up to nearest 4
2806 preshader->temp_count = (preshader->temp_count + 3) & ~3;
2807
2808 unsigned int largest = 0;
2809 const MOJOSHADER_symbol *sym = preshader->symbols;
2810 const uint32 symcount = (uint32) preshader->symbol_count;
2811 for (i = 0; i < symcount; i++, sym++)
2812 {
2813 const unsigned int val = sym->register_index + sym->register_count;
2814 if (val > largest)
2815 largest = val;
2816 } // for
2817
2818 if (largest > 0)
2819 {
2820 const size_t len = largest * sizeof (float) * 4;
2821 preshader->registers = (float *) Malloc(ctx, len);
2822 memset(preshader->registers, '\0', len);
2823 preshader->register_count = largest;
2824 } // if
2825 #endif
2826 } // parse_preshader
2827
2828 static int parse_comment_token(Context *ctx)
2829 {
2830 uint32 commenttoks = 0;
2831 if (is_comment_token(ctx, *ctx->tokens, &commenttoks))
2832 {
2833 if ((commenttoks >= 2) && (commenttoks < ctx->tokencount))
2834 {
2835 const uint32 id = SWAP32(ctx->tokens[1]);
2836 if (id == PRES_ID)
2837 parse_preshader(ctx, ctx->tokens + 2, commenttoks - 2);
2838 else if (id == CTAB_ID)
2839 {
2840 parse_constant_table(ctx, ctx->tokens, commenttoks * 4,
2841 ctx->version_token, 1, &ctx->ctab);
2842 } // else if
2843 } // if
2844 return commenttoks + 1; // comment data plus the initial token.
2845 } // if
2846
2847 return 0; // not a comment token.
2848 } // parse_comment_token
2849
2850
2851 static int parse_end_token(Context *ctx)
2852 {
2853 if (SWAP32(*(ctx->tokens)) != 0x0000FFFF) // end token always 0x0000FFFF.
2854 return 0; // not us, eat no tokens.
2855
2856 if (!ctx->know_shader_size) // this is the end of stream!
2857 ctx->tokencount = 1;
2858 else if (ctx->tokencount != 1) // we _must_ be last. If not: fail.
2859 fail(ctx, "end token before end of stream");
2860
2861 if (!isfail(ctx))
2862 ctx->profile->end_emitter(ctx);
2863
2864 return 1;
2865 } // parse_end_token
2866
2867
2868 static int parse_phase_token(Context *ctx)
2869 {
2870 // !!! FIXME: needs state; allow only one phase token per shader, I think?
2871 if (SWAP32(*(ctx->tokens)) != 0x0000FFFD) // phase token always 0x0000FFFD.
2872 return 0; // not us, eat no tokens.
2873
2874 if ( (!shader_is_pixel(ctx)) || (!shader_version_exactly(ctx, 1, 4)) )
2875 fail(ctx, "phase token only available in 1.4 pixel shaders");
2876
2877 if (!isfail(ctx))
2878 ctx->profile->phase_emitter(ctx);
2879
2880 return 1;
2881 } // parse_phase_token
2882
2883
2884 static int parse_token(Context *ctx)
2885 {
2886 int rc = 0;
2887
2888 assert(ctx->output_stack_len == 0);
2889
2890 if (ctx->tokencount == 0)
2891 fail(ctx, "unexpected end of shader.");
2892
2893 else if ((rc = parse_comment_token(ctx)) != 0)
2894 return rc;
2895
2896 else if ((rc = parse_end_token(ctx)) != 0)
2897 return rc;
2898
2899 else if ((rc = parse_phase_token(ctx)) != 0)
2900 return rc;
2901
2902 else if ((rc = parse_instruction_token(ctx)) != 0)
2903 return rc;
2904
2905 failf(ctx, "unknown token (0x%x)", (uint) *ctx->tokens);
2906 return 1; // good luck!
2907 } // parse_token
2908
2909
2910 static int find_profile_id(const char *profile)
2911 {
2912 size_t i;
2913 for (i = 0; i < STATICARRAYLEN(profileMap); i++)
2914 {
2915 const char *name = profileMap[i].from;
2916 if (strcmp(name, profile) == 0)
2917 {
2918 profile = profileMap[i].to;
2919 break;
2920 } // if
2921 } // for
2922
2923 for (i = 0; i < STATICARRAYLEN(profiles); i++)
2924 {
2925 const char *name = profiles[i].name;
2926 if (strcmp(name, profile) == 0)
2927 return i;
2928 } // for
2929
2930 return -1; // no match.
2931 } // find_profile_id
2932
2933
2934 static Context *build_context(const char *profile,
2935 const char *mainfn,
2936 const unsigned char *tokenbuf,
2937 const unsigned int bufsize,
2938 const MOJOSHADER_swizzle *swiz,
2939 const unsigned int swizcount,
2940 const MOJOSHADER_samplerMap *smap,
2941 const unsigned int smapcount,
2942 MOJOSHADER_malloc m, MOJOSHADER_free f, void *d)
2943 {
2944 if (m == NULL) m = MOJOSHADER_internal_malloc;
2945 if (f == NULL) f = MOJOSHADER_internal_free;
2946
2947 Context *ctx = (Context *) m(sizeof (Context), d);
2948 if (ctx == NULL)
2949 return NULL;
2950
2951 memset(ctx, '\0', sizeof (Context));
2952 ctx->malloc = m;
2953 ctx->free = f;
2954 ctx->malloc_data = d;
2955 ctx->tokens = (const uint32 *) tokenbuf;
2956 ctx->orig_tokens = (const uint32 *) tokenbuf;
2957 ctx->know_shader_size = (bufsize != 0);
2958 ctx->tokencount = ctx->know_shader_size ? (bufsize / sizeof (uint32)) : 0xFFFFFFFF;
2959 ctx->swizzles = swiz;
2960 ctx->swizzles_count = swizcount;
2961 ctx->samplermap = smap;
2962 ctx->samplermap_count = smapcount;
2963 ctx->endline = ENDLINE_STR;
2964 ctx->endline_len = strlen(ctx->endline);
2965 ctx->last_address_reg_component = -1;
2966 ctx->current_position = MOJOSHADER_POSITION_BEFORE;
2967 ctx->texm3x2pad_dst0 = -1;
2968 ctx->texm3x2pad_src0 = -1;
2969 ctx->texm3x3pad_dst0 = -1;
2970 ctx->texm3x3pad_src0 = -1;
2971 ctx->texm3x3pad_dst1 = -1;
2972 ctx->texm3x3pad_src1 = -1;
2973
2974 ctx->errors = errorlist_create(MallocBridge, FreeBridge, ctx);
2975 if (ctx->errors == NULL)
2976 {
2977 f(ctx, d);
2978 return NULL;
2979 } // if
2980
2981 if (!set_output(ctx, &ctx->mainline))
2982 {
2983 errorlist_destroy(ctx->errors);
2984 f(ctx, d);
2985 return NULL;
2986 } // if
2987
2988 if (mainfn != NULL)
2989 {
2990 if (strlen(mainfn) > 55) // !!! FIXME: just to keep things sane. Lots of hardcoded stack arrays...
2991 failf(ctx, "Main function name '%s' is too big", mainfn);
2992 else
2993 ctx->mainfn = StrDup(ctx, mainfn);
2994 } // if
2995
2996 if (profile != NULL)
2997 {
2998 const int profileid = find_profile_id(profile);
2999 ctx->profileid = profileid;
3000 if (profileid >= 0)
3001 ctx->profile = &profiles[profileid];
3002 else
3003 failf(ctx, "Profile '%s' is unknown or unsupported", profile);
3004 } // if
3005
3006 return ctx;
3007 } // build_context
3008
3009
3010 static void free_constants_list(MOJOSHADER_free f, void *d, ConstantsList *item)
3011 {
3012 while (item != NULL)
3013 {
3014 ConstantsList *next = item->next;
3015 f(item, d);
3016 item = next;
3017 } // while
3018 } // free_constants_list
3019
3020
3021 static void free_variable_list(MOJOSHADER_free f, void *d, VariableList *item)
3022 {
3023 while (item != NULL)
3024 {
3025 VariableList *next = item->next;
3026 f(item, d);
3027 item = next;
3028 } // while
3029 } // free_variable_list
3030
3031
3032 static void free_sym_typeinfo(MOJOSHADER_free f, void *d,
3033 MOJOSHADER_symbolTypeInfo *typeinfo)
3034 {
3035 unsigned int i;
3036 for (i = 0; i < typeinfo->member_count; i++)
3037 {
3038 f((void *) typeinfo->members[i].name, d);
3039 free_sym_typeinfo(f, d, &typeinfo->members[i].info);
3040 } // for
3041 f((void *) typeinfo->members, d);
3042 } // free_sym_members
3043
3044
3045 static void free_symbols(MOJOSHADER_free f, void *d, MOJOSHADER_symbol *syms,
3046 const int symcount)
3047 {
3048 int i;
3049 for (i = 0; i < symcount; i++)
3050 {
3051 f((void *) syms[i].name, d);
3052 free_sym_typeinfo(f, d, &syms[i].info);
3053 } // for
3054 f((void *) syms, d);
3055 } // free_symbols
3056
3057
3058 static void destroy_context(Context *ctx)
3059 {
3060 if (ctx != NULL)
3061 {
3062 MOJOSHADER_free f = ((ctx->free != NULL) ? ctx->free : MOJOSHADER_internal_free);
3063 void *d = ctx->malloc_data;
3064 buffer_destroy(ctx->preflight);
3065 buffer_destroy(ctx->globals);
3066 buffer_destroy(ctx->inputs);
3067 buffer_destroy(ctx->outputs);
3068 buffer_destroy(ctx->helpers);
3069 buffer_destroy(ctx->subroutines);
3070 buffer_destroy(ctx->mainline_intro);
3071 buffer_destroy(ctx->mainline_arguments);
3072 buffer_destroy(ctx->mainline_top);
3073 buffer_destroy(ctx->mainline);
3074 buffer_destroy(ctx->postflight);
3075 buffer_destroy(ctx->ignore);
3076 free_constants_list(f, d, ctx->constants);
3077 free_reglist(f, d, ctx->used_registers.next);
3078 free_reglist(f, d, ctx->defined_registers.next);
3079 free_reglist(f, d, ctx->uniforms.next);
3080 free_reglist(f, d, ctx->attributes.next);
3081 free_reglist(f, d, ctx->samplers.next);
3082 free_variable_list(f, d, ctx->variables);
3083 errorlist_destroy(ctx->errors);
3084 free_symbols(f, d, ctx->ctab.symbols, ctx->ctab.symbol_count);
3085 MOJOSHADER_freePreshader(ctx->preshader);
3086 f((void *) ctx->mainfn, d);
3087 f(ctx, d);
3088 } // if
3089 } // destroy_context
3090
3091
3092 static char *build_output(Context *ctx, size_t *len)
3093 {
3094 // add a byte for a null terminator.
3095 Buffer *buffers[] = {
3096 ctx->preflight, ctx->globals, ctx->inputs, ctx->outputs, ctx->helpers,
3097 ctx->subroutines, ctx->mainline_intro, ctx->mainline_arguments,
3098 ctx->mainline_top, ctx->mainline, ctx->postflight
3099 // don't append ctx->ignore ... that's why it's called "ignore"
3100 };
3101 char *retval = buffer_merge(buffers, STATICARRAYLEN(buffers), len);
3102 return retval;
3103 } // build_output
3104
3105
3106 static inline const char *alloc_varname(Context *ctx, const RegisterList *reg)
3107 {
3108 return ctx->profile->get_varname(ctx, reg->regtype, reg->regnum);
3109 } // alloc_varname
3110
3111
3112 // !!! FIXME: this code is sort of hard to follow:
3113 // !!! FIXME: "var->used" only applies to arrays (at the moment, at least,
3114 // !!! FIXME: but this might be buggy at a later time?), and this code
3115 // !!! FIXME: relies on that.
3116 // !!! FIXME: "variables" means "things we found in a CTAB" but it's not
3117 // !!! FIXME: all registers, etc.
3118 // !!! FIXME: "const_array" means an array for d3d "const" registers (c0, c1,
3119 // !!! FIXME: etc), but not a constant array, although they _can_ be.
3120 // !!! FIXME: It's just a mess. :/
3121 static MOJOSHADER_uniform *build_uniforms(Context *ctx)
3122 {
3123 const size_t len = sizeof (MOJOSHADER_uniform) * ctx->uniform_count;
3124 MOJOSHADER_uniform *retval = (MOJOSHADER_uniform *) Malloc(ctx, len);
3125
3126 if (retval != NULL)
3127 {
3128 MOJOSHADER_uniform *wptr = retval;
3129 memset(wptr, '\0', len);
3130
3131 VariableList *var;
3132 int written = 0;
3133 for (var = ctx->variables; var != NULL; var = var->next)
3134 {
3135 if (var->used)
3136 {
3137 const char *name = ctx->profile->get_const_array_varname(ctx,
3138 var->index, var->count);
3139 if (name != NULL)
3140 {
3141 wptr->type = MOJOSHADER_UNIFORM_FLOAT;
3142 wptr->index = var->index;
3143 wptr->array_count = var->count;
3144 wptr->constant = (var->constant != NULL) ? 1 : 0;
3145 wptr->name = name;
3146 wptr++;
3147 written++;
3148 } // if
3149 } // if
3150 } // for
3151
3152 RegisterList *item = ctx->uniforms.next;
3153 MOJOSHADER_uniformType type = MOJOSHADER_UNIFORM_FLOAT;
3154 while (written < ctx->uniform_count)
3155 {
3156 int skip = 0;
3157
3158 // !!! FIXME: does this fail if written > ctx->uniform_count?
3159 if (item == NULL)
3160 {
3161 fail(ctx, "BUG: mismatched uniform list and count");
3162 break;
3163 } // if
3164
3165 int index = item->regnum;
3166 switch (item->regtype)
3167 {
3168 case REG_TYPE_CONST:
3169 skip = (item->array != NULL);
3170 type = MOJOSHADER_UNIFORM_FLOAT;
3171 break;
3172
3173 case REG_TYPE_CONSTINT:
3174 type = MOJOSHADER_UNIFORM_INT;
3175 break;
3176
3177 case REG_TYPE_CONSTBOOL:
3178 type = MOJOSHADER_UNIFORM_BOOL;
3179 break;
3180
3181 default:
3182 fail(ctx, "unknown uniform datatype");
3183 break;
3184 } // switch
3185
3186 if (!skip)
3187 {
3188 wptr->type = type;
3189 wptr->index = index;
3190 wptr->array_count = 0;
3191 wptr->name = alloc_varname(ctx, item);
3192 wptr++;
3193 written++;
3194 } // if
3195
3196 item = item->next;
3197 } // for
3198 } // if
3199
3200 return retval;
3201 } // build_uniforms
3202
3203
3204 static MOJOSHADER_constant *build_constants(Context *ctx)
3205 {
3206 const size_t len = sizeof (MOJOSHADER_constant) * ctx->constant_count;
3207 MOJOSHADER_constant *retval = (MOJOSHADER_constant *) Malloc(ctx, len);
3208
3209 if (retval != NULL)
3210 {
3211 ConstantsList *item = ctx->constants;
3212 int i;
3213
3214 for (i = 0; i < ctx->constant_count; i++)
3215 {
3216 if (item == NULL)
3217 {
3218 fail(ctx, "BUG: mismatched constant list and count");
3219 break;
3220 } // if
3221
3222 memcpy(&retval[i], &item->constant, sizeof (MOJOSHADER_constant));
3223 item = item->next;
3224 } // for
3225 } // if
3226
3227 return retval;
3228 } // build_constants
3229
3230
3231 static MOJOSHADER_sampler *build_samplers(Context *ctx)
3232 {
3233 const size_t len = sizeof (MOJOSHADER_sampler) * ctx->sampler_count;
3234 MOJOSHADER_sampler *retval = (MOJOSHADER_sampler *) Malloc(ctx, len);
3235
3236 if (retval != NULL)
3237 {
3238 RegisterList *item = ctx->samplers.next;
3239 int i;
3240
3241 memset(retval, '\0', len);
3242
3243 for (i = 0; i < ctx->sampler_count; i++)
3244 {
3245 if (item == NULL)
3246 {
3247 fail(ctx, "BUG: mismatched sampler list and count");
3248 break;
3249 } // if
3250
3251 assert(item->regtype == REG_TYPE_SAMPLER);
3252 retval[i].type = cvtD3DToMojoSamplerType((TextureType) item->index);
3253 retval[i].index = item->regnum;
3254 retval[i].name = alloc_varname(ctx, item);
3255 retval[i].texbem = (item->misc != 0) ? 1 : 0;
3256 item = item->next;
3257 } // for
3258 } // if
3259
3260 return retval;
3261 } // build_samplers
3262
3263
3264 static MOJOSHADER_attribute *build_attributes(Context *ctx, int *_count)
3265 {
3266 int count = 0;
3267
3268 if (ctx->attribute_count == 0)
3269 {
3270 *_count = 0;
3271 return NULL; // nothing to do.
3272 } // if
3273
3274 const size_t len = sizeof (MOJOSHADER_attribute) * ctx->attribute_count;
3275 MOJOSHADER_attribute *retval = (MOJOSHADER_attribute *) Malloc(ctx, len);
3276
3277 if (retval != NULL)
3278 {
3279 RegisterList *item = ctx->attributes.next;
3280 MOJOSHADER_attribute *wptr = retval;
3281 int ignore = 0;
3282 int i;
3283
3284 memset(retval, '\0', len);
3285
3286 for (i = 0; i < ctx->attribute_count; i++)
3287 {
3288 if (item == NULL)
3289 {
3290 fail(ctx, "BUG: mismatched attribute list and count");
3291 break;
3292 } // if
3293
3294 switch (item->regtype)
3295 {
3296 case REG_TYPE_RASTOUT:
3297 case REG_TYPE_ATTROUT:
3298 case REG_TYPE_TEXCRDOUT:
3299 case REG_TYPE_COLOROUT:
3300 case REG_TYPE_DEPTHOUT:
3301 ignore = 1;
3302 break;
3303 default:
3304 ignore = 0;
3305 break;
3306 } // switch
3307
3308 if (!ignore)
3309 {
3310 wptr->usage = item->usage;
3311 wptr->index = item->index;
3312 wptr->name = alloc_varname(ctx, item);
3313 wptr++;
3314 count++;
3315 } // if
3316
3317 item = item->next;
3318 } // for
3319 } // if
3320
3321 *_count = count;
3322 return retval;
3323 } // build_attributes
3324
3325 static MOJOSHADER_attribute *build_outputs(Context *ctx, int *_count)
3326 {
3327 int count = 0;
3328
3329 if (ctx->attribute_count == 0)
3330 {
3331 *_count = 0;
3332 return NULL; // nothing to do.
3333 } // if
3334
3335 const size_t len = sizeof (MOJOSHADER_attribute) * ctx->attribute_count;
3336 MOJOSHADER_attribute *retval = (MOJOSHADER_attribute *) Malloc(ctx, len);
3337
3338 if (retval != NULL)
3339 {
3340 RegisterList *item = ctx->attributes.next;
3341 MOJOSHADER_attribute *wptr = retval;
3342 int i;
3343
3344 memset(retval, '\0', len);
3345
3346 for (i = 0; i < ctx->attribute_count; i++)
3347 {
3348 if (item == NULL)
3349 {
3350 fail(ctx, "BUG: mismatched attribute list and count");
3351 break;
3352 } // if
3353
3354 switch (item->regtype)
3355 {
3356 case REG_TYPE_RASTOUT:
3357 case REG_TYPE_ATTROUT:
3358 case REG_TYPE_TEXCRDOUT:
3359 case REG_TYPE_COLOROUT:
3360 case REG_TYPE_DEPTHOUT:
3361 wptr->usage = item->usage;
3362 wptr->index = item->index;
3363 wptr->name = alloc_varname(ctx, item);
3364 wptr++;
3365 count++;
3366 break;
3367 default:
3368 break;
3369 } // switch
3370
3371
3372 item = item->next;
3373 } // for
3374 } // if
3375
3376 *_count = count;
3377 return retval;
3378 } // build_outputs
3379
3380
3381 static MOJOSHADER_parseData *build_parsedata(Context *ctx)
3382 {
3383 char *output = NULL;
3384 MOJOSHADER_constant *constants = NULL;
3385 MOJOSHADER_uniform *uniforms = NULL;
3386 MOJOSHADER_attribute *attributes = NULL;
3387 MOJOSHADER_attribute *outputs = NULL;
3388 MOJOSHADER_sampler *samplers = NULL;
3389 MOJOSHADER_swizzle *swizzles = NULL;
3390 MOJOSHADER_error *errors = NULL;
3391 MOJOSHADER_parseData *retval = NULL;
3392 size_t output_len = 0;
3393 int attribute_count = 0;
3394 int output_count = 0;
3395
3396 if (ctx->out_of_memory)
3397 return &MOJOSHADER_out_of_mem_data;
3398
3399 retval = (MOJOSHADER_parseData*) Malloc(ctx, sizeof(MOJOSHADER_parseData));
3400 if (retval == NULL)
3401 return &MOJOSHADER_out_of_mem_data;
3402
3403 memset(retval, '\0', sizeof (MOJOSHADER_parseData));
3404
3405 if (!isfail(ctx))
3406 output = build_output(ctx, &output_len);
3407
3408 if (!isfail(ctx))
3409 constants = build_constants(ctx);
3410
3411 if (!isfail(ctx))
3412 uniforms = build_uniforms(ctx);
3413
3414 if (!isfail(ctx))
3415 attributes = build_attributes(ctx, &attribute_count);
3416
3417 if (!isfail(ctx))
3418 outputs = build_outputs(ctx, &output_count);
3419
3420 if (!isfail(ctx))
3421 samplers = build_samplers(ctx);
3422
3423 const int error_count = errorlist_count(ctx->errors);
3424 errors = errorlist_flatten(ctx->errors);
3425
3426 if (!isfail(ctx))
3427 {
3428 if (ctx->swizzles_count > 0)
3429 {
3430 const int len = ctx->swizzles_count * sizeof (MOJOSHADER_swizzle);
3431 swizzles = (MOJOSHADER_swizzle *) Malloc(ctx, len);
3432 if (swizzles != NULL)
3433 memcpy(swizzles, ctx->swizzles, len);
3434 } // if
3435 } // if
3436
3437 // check again, in case build_output, etc, ran out of memory.
3438 if (isfail(ctx))
3439 {
3440 int i;
3441
3442 Free(ctx, output);
3443 Free(ctx, constants);
3444 Free(ctx, swizzles);
3445
3446 if (uniforms != NULL)
3447 {
3448 for (i = 0; i < ctx->uniform_count; i++)
3449 Free(ctx, (void *) uniforms[i].name);
3450 Free(ctx, uniforms);
3451 } // if
3452
3453 if (attributes != NULL)
3454 {
3455 for (i = 0; i < attribute_count; i++)
3456 Free(ctx, (void *) attributes[i].name);
3457 Free(ctx, attributes);
3458 } // if
3459
3460 if (outputs != NULL)
3461 {
3462 for (i = 0; i < output_count; i++)
3463 Free(ctx, (void *) outputs[i].name);
3464 Free(ctx, outputs);
3465 } // if
3466
3467 if (samplers != NULL)
3468 {
3469 for (i = 0; i < ctx->sampler_count; i++)
3470 Free(ctx, (void *) samplers[i].name);
3471 Free(ctx, samplers);
3472 } // if
3473
3474 if (ctx->out_of_memory)
3475 {
3476 for (i = 0; i < error_count; i++)
3477 {
3478 Free(ctx, (void *) errors[i].filename);
3479 Free(ctx, (void *) errors[i].error);
3480 } // for
3481 Free(ctx, errors);
3482 Free(ctx, retval);
3483 return &MOJOSHADER_out_of_mem_data;
3484 } // if
3485 } // if
3486 else
3487 {
3488 retval->profile = ctx->profile->name;
3489 retval->output = output;
3490 retval->output_len = (int) output_len;
3491 retval->instruction_count = ctx->instruction_count;
3492 retval->shader_type = ctx->shader_type;
3493 retval->major_ver = (int) ctx->major_ver;
3494 retval->minor_ver = (int) ctx->minor_ver;
3495 retval->uniform_count = ctx->uniform_count;
3496 retval->uniforms = uniforms;
3497 retval->constant_count = ctx->constant_count;
3498 retval->constants = constants;
3499 retval->sampler_count = ctx->sampler_count;
3500 retval->samplers = samplers;
3501 retval->attribute_count = attribute_count;
3502 retval->attributes = attributes;
3503 retval->output_count = output_count;
3504 retval->outputs = outputs;
3505 retval->swizzle_count = ctx->swizzles_count;
3506 retval->swizzles = swizzles;
3507 retval->symbol_count = ctx->ctab.symbol_count;
3508 retval->symbols = ctx->ctab.symbols;
3509 retval->preshader = ctx->preshader;
3510 retval->mainfn = ctx->mainfn;
3511
3512 #if SUPPORT_PROFILE_SPIRV
3513 if (strcmp(retval->profile, MOJOSHADER_PROFILE_SPIRV) == 0
3514 || strcmp(retval->profile, MOJOSHADER_PROFILE_GLSPIRV) == 0)
3515 {
3516 size_t i, max;
3517 int binary_size = retval->output_len - sizeof(SpirvPatchTable);
3518 uint32 *binary = (uint32 *) retval->output;
3519 SpirvPatchTable *table = (SpirvPatchTable *) &retval->output[binary_size];
3520
3521 if (table->vpflip.offset) binary[table->vpflip.offset] = table->vpflip.location;
3522 if (table->array_vec4.offset) binary[table->array_vec4.offset] = table->array_vec4.location;
3523 if (table->array_ivec4.offset) binary[table->array_ivec4.offset] = table->array_ivec4.location;
3524 if (table->array_bool.offset) binary[table->array_bool.offset] = table->array_bool.location;
3525
3526 for (i = 0, max = STATICARRAYLEN(table->samplers); i < max; i++)
3527 {
3528 SpirvPatchEntry entry = table->samplers[i];
3529 if (entry.offset)
3530 binary[entry.offset] = entry.location;
3531 } // for
3532 } // if
3533 #endif // SUPPORT_PROFILE_SPIRV
3534
3535 // we don't own these now, retval does.
3536 ctx->ctab.symbols = NULL;
3537 ctx->preshader = NULL;
3538 ctx->ctab.symbol_count = 0;
3539 ctx->mainfn = NULL;
3540 } // else
3541
3542 retval->error_count = error_count;
3543 retval->errors = errors;
3544 retval->malloc = (ctx->malloc == MOJOSHADER_internal_malloc) ? NULL : ctx->malloc;
3545 retval->free = (ctx->free == MOJOSHADER_internal_free) ? NULL : ctx->free;
3546 retval->malloc_data = ctx->malloc_data;
3547
3548 return retval;
3549 } // build_parsedata
3550
3551 static void process_definitions(Context *ctx)
3552 {
3553 // !!! FIXME: apparently, pre ps_3_0, sampler registers don't need to be
3554 // !!! FIXME: DCL'd before use (default to 2d?). We aren't checking
3555 // !!! FIXME: this at the moment, though.
3556
3557 determine_constants_arrays(ctx); // in case this hasn't been called yet.
3558
3559 RegisterList *uitem = &ctx->uniforms;
3560 RegisterList *prev = &ctx->used_registers;
3561 RegisterList *item = prev->next;
3562
3563 while (item != NULL)
3564 {
3565 RegisterList *next = item->next;
3566 const RegisterType regtype = item->regtype;
3567 const int regnum = item->regnum;
3568 MOJOSHADER_usage usage;
3569
3570 if (!get_defined_register(ctx, regtype, regnum))
3571 {
3572 // haven't already dealt with this one.
3573 switch (regtype)
3574 {
3575 // !!! FIXME: I'm not entirely sure this is right...
3576 case REG_TYPE_RASTOUT:
3577 case REG_TYPE_ATTROUT:
3578 case REG_TYPE_TEXCRDOUT:
3579 case REG_TYPE_COLOROUT:
3580 case REG_TYPE_DEPTHOUT:
3581 if (shader_is_vertex(ctx)&&shader_version_atleast(ctx,3,0))
3582 {
3583 fail(ctx, "vs_3 can't use output registers"
3584 " without declaring them first.");
3585 return;
3586 } // if
3587
3588 // Apparently this is an attribute that wasn't DCL'd.
3589 // Add it to the attribute list; deal with it later.
3590 if (regtype == REG_TYPE_RASTOUT)
3591 {
3592 if ((RastOutType) regnum == RASTOUT_TYPE_POSITION)
3593 usage = MOJOSHADER_USAGE_POSITION;
3594 else if ((RastOutType) regnum == RASTOUT_TYPE_FOG)
3595 usage = MOJOSHADER_USAGE_FOG;
3596 else if ((RastOutType) regnum==RASTOUT_TYPE_POINT_SIZE)
3597 usage = MOJOSHADER_USAGE_POINTSIZE;
3598 } // if
3599 else if (regtype == REG_TYPE_ATTROUT ||
3600 regtype == REG_TYPE_COLOROUT)
3601 {
3602 usage = MOJOSHADER_USAGE_COLOR;
3603 } // else if
3604 else if (regtype == REG_TYPE_TEXCRDOUT)
3605 usage = MOJOSHADER_USAGE_TEXCOORD;
3606 else if (regtype == REG_TYPE_DEPTHOUT)
3607 usage = MOJOSHADER_USAGE_DEPTH;
3608
3609 add_attribute_register(ctx, regtype, regnum, usage,
3610 regnum, 0xF, 0);
3611 break;
3612
3613 case REG_TYPE_ADDRESS:
3614 case REG_TYPE_PREDICATE:
3615 case REG_TYPE_TEMP:
3616 case REG_TYPE_LOOP:
3617 case REG_TYPE_LABEL:
3618 ctx->profile->global_emitter(ctx, regtype, regnum);
3619 break;
3620
3621 case REG_TYPE_CONST:
3622 case REG_TYPE_CONSTINT:
3623 case REG_TYPE_CONSTBOOL:
3624 // separate uniforms into a different list for now.
3625 prev->next = next;
3626 item->next = NULL;
3627 uitem->next = item;
3628 uitem = item;
3629 item = prev;
3630 break;
3631
3632 case REG_TYPE_INPUT:
3633 // You don't have to dcl_ your inputs in Shader Model 1.
3634 if (!shader_version_atleast(ctx,2,0))
3635 {
3636 if (shader_is_pixel(ctx))
3637 {
3638 add_attribute_register(ctx, regtype, regnum,
3639 MOJOSHADER_USAGE_COLOR, regnum,
3640 0xF, 0);
3641 break;
3642 } // if
3643 else if (shader_is_vertex(ctx))
3644 {
3645 int index = 0;
3646 shader_model_1_input_usage(regnum, &usage, &index);
3647 if (usage != MOJOSHADER_USAGE_UNKNOWN)
3648 {
3649 add_attribute_register(ctx, regtype, regnum, usage, index, 0xF, 0);
3650 break;
3651 } // if
3652 } // else if
3653 } // if
3654
3655 // fall through...
3656
3657 default:
3658 fail(ctx, "BUG: we used a register we don't know how to define.");
3659 } // switch
3660 } // if
3661
3662 prev = item;
3663 item = next;
3664 } // while
3665
3666 // okay, now deal with uniform/constant arrays...
3667 for (VariableList *var = ctx->variables; var != NULL; var = var->next)
3668 {
3669 if (var->used)
3670 {
3671 if (var->constant)
3672 {
3673 ctx->profile->const_array_emitter(ctx, var->constant,
3674 var->index, var->count);
3675 } // if
3676 else
3677 {
3678 ctx->profile->array_emitter(ctx, var);
3679 ctx->uniform_float4_count += var->count;
3680 } // else
3681 ctx->uniform_count++;
3682 } // if
3683 } // for
3684
3685 // ...and uniforms...
3686 for (item = ctx->uniforms.next; item != NULL; item = item->next)
3687 {
3688 int arraysize = -1;
3689 VariableList *var = NULL;
3690
3691 // check if this is a register contained in an array...
3692 if (item->regtype == REG_TYPE_CONST)
3693 {
3694 for (var = ctx->variables; var != NULL; var = var->next)
3695 {
3696 if (!var->used)
3697 continue;
3698
3699 const int regnum = item->regnum;
3700 const int lo = var->index;
3701 if ( (regnum >= lo) && (regnum < (lo + var->count)) )
3702 {
3703 assert(!var->constant);
3704 item->array = var; // used when building parseData.
3705 arraysize = var->count;
3706 break;
3707 } // if
3708 } // for
3709 } // if
3710
3711 ctx->profile->uniform_emitter(ctx, item->regtype, item->regnum, var);
3712
3713 if (arraysize < 0) // not part of an array?
3714 {
3715 ctx->uniform_count++;
3716 switch (item->regtype)
3717 {
3718 case REG_TYPE_CONST: ctx->uniform_float4_count++; break;
3719 case REG_TYPE_CONSTINT: ctx->uniform_int4_count++; break;
3720 case REG_TYPE_CONSTBOOL: ctx->uniform_bool_count++; break;
3721 default: break;
3722 } // switch
3723 } // if
3724 } // for
3725
3726 // ...and samplers...
3727 for (item = ctx->samplers.next; item != NULL; item = item->next)
3728 {
3729 ctx->sampler_count++;
3730 ctx->profile->sampler_emitter(ctx, item->regnum,
3731 (TextureType) item->index,
3732 item->misc != 0);
3733 } // for
3734
3735 // ...and attributes...
3736 for (item = ctx->attributes.next; item != NULL; item = item->next)
3737 {
3738 ctx->attribute_count++;
3739 ctx->profile->attribute_emitter(ctx, item->regtype, item->regnum,
3740 item->usage, item->index,
3741 item->writemask, item->misc);
3742 } // for
3743 } // process_definitions
3744
3745
3746 static void verify_swizzles(Context *ctx)
3747 {
3748 size_t i;
3749 const char *failmsg = "invalid swizzle";
3750 for (i = 0; i < ctx->swizzles_count; i++)
3751 {
3752 const MOJOSHADER_swizzle *swiz = &ctx->swizzles[i];
3753 if (swiz->swizzles[0] > 3) { fail(ctx, failmsg); return; }
3754 if (swiz->swizzles[1] > 3) { fail(ctx, failmsg); return; }
3755 if (swiz->swizzles[2] > 3) { fail(ctx, failmsg); return; }
3756 if (swiz->swizzles[3] > 3) { fail(ctx, failmsg); return; }
3757 } // for
3758 } // verify_swizzles
3759
3760
3761 // API entry point...
3762
3763 // !!! FIXME:
3764 // MSDN: "Shader validation will fail CreatePixelShader on any shader that
3765 // attempts to read from a temporary register that has not been written by a
3766 // previous instruction." (true for ps_1_*, maybe others). Check this.
3767
3768 const MOJOSHADER_parseData *MOJOSHADER_parse(const char *profile,
3769 const char *mainfn,
3770 const unsigned char *tokenbuf,
3771 const unsigned int bufsize,
3772 const MOJOSHADER_swizzle *swiz,
3773 const unsigned int swizcount,
3774 const MOJOSHADER_samplerMap *smap,
3775 const unsigned int smapcount,
3776 MOJOSHADER_malloc m,
3777 MOJOSHADER_free f, void *d)
3778 {
3779 MOJOSHADER_parseData *retval = NULL;
3780 Context *ctx = NULL;
3781 int rc = 0;
3782 int failed = 0;
3783
3784 if ( ((m == NULL) && (f != NULL)) || ((m != NULL) && (f == NULL)) )
3785 return &MOJOSHADER_out_of_mem_data; // supply both or neither.
3786
3787 ctx = build_context(profile, mainfn, tokenbuf, bufsize, swiz, swizcount,
3788 smap, smapcount, m, f, d);
3789 if (ctx == NULL)
3790 return &MOJOSHADER_out_of_mem_data;
3791
3792 if (profile == NULL) // build_context allows NULL; check this ourselves.
3793 fail(ctx, "Profile name is NULL");
3794
3795 if (isfail(ctx))
3796 {
3797 retval = build_parsedata(ctx);
3798 destroy_context(ctx);
3799 return retval;
3800 } // if
3801
3802 verify_swizzles(ctx);
3803
3804 if (!ctx->mainfn)
3805 ctx->mainfn = StrDup(ctx, "main");
3806
3807 // Version token always comes first.
3808 ctx->current_position = 0;
3809 rc = parse_version_token(ctx, profile);
3810
3811 // drop out now if this definitely isn't bytecode. Saves lots of
3812 // meaningless errors flooding through.
3813 if (rc < 0)
3814 {
3815 retval = build_parsedata(ctx);
3816 destroy_context(ctx);
3817 return retval;
3818 } // if
3819
3820 if ( ((uint32) rc) > ctx->tokencount )
3821 {
3822 fail(ctx, "Corrupted or truncated shader");
3823 ctx->tokencount = rc;
3824 } // if
3825
3826 adjust_token_position(ctx, rc);
3827
3828 // parse out the rest of the tokens after the version token...
3829 while (ctx->tokencount > 0)
3830 {
3831 if (!ctx->know_shader_size)
3832 ctx->tokencount = 0xFFFFFFFF; // keep this value obscenely large.
3833
3834 // reset for each token.
3835 if (isfail(ctx))
3836 {
3837 failed = 1;
3838 ctx->isfail = 0;
3839 } // if
3840
3841 rc = parse_token(ctx);
3842 if ( ((uint32) rc) > ctx->tokencount )
3843 {
3844 fail(ctx, "Corrupted or truncated shader");
3845 break;
3846 } // if
3847
3848 adjust_token_position(ctx, rc);
3849 } // while
3850
3851 ctx->current_position = MOJOSHADER_POSITION_AFTER;
3852
3853 // for ps_1_*, the output color is written to r0...throw an
3854 // error if this register was never written. This isn't
3855 // important for vertex shaders, or shader model 2+.
3856 if (shader_is_pixel(ctx) && !shader_version_atleast(ctx, 2, 0))
3857 {
3858 if (!register_was_written(ctx, REG_TYPE_TEMP, 0))
3859 fail(ctx, "r0 (pixel shader 1.x color output) never written to");
3860 } // if
3861
3862 if (!failed)
3863 {
3864 process_definitions(ctx);
3865 failed = isfail(ctx);
3866 } // if
3867
3868 if (!failed)
3869 ctx->profile->finalize_emitter(ctx);
3870
3871 ctx->isfail = failed;
3872 retval = build_parsedata(ctx);
3873 destroy_context(ctx);
3874 return retval;
3875 } // MOJOSHADER_parse
3876
3877
3878 void MOJOSHADER_freeParseData(const MOJOSHADER_parseData *_data)
3879 {
3880 MOJOSHADER_parseData *data = (MOJOSHADER_parseData *) _data;
3881 if ((data == NULL) || (data == &MOJOSHADER_out_of_mem_data))
3882 return; // no-op.
3883
3884 MOJOSHADER_free f = (data->free == NULL) ? MOJOSHADER_internal_free : data->free;
3885 void *d = data->malloc_data;
3886 int i;
3887
3888 // we don't f(data->profile), because that's internal static data.
3889
3890 f((void *) data->mainfn, d);
3891 f((void *) data->output, d);
3892 f((void *) data->constants, d);
3893 f((void *) data->swizzles, d);
3894
3895 for (i = 0; i < data->error_count; i++)
3896 {
3897 f((void *) data->errors[i].error, d);
3898 f((void *) data->errors[i].filename, d);
3899 } // for
3900 f((void *) data->errors, d);
3901
3902 for (i = 0; i < data->uniform_count; i++)
3903 f((void *) data->uniforms[i].name, d);
3904 f((void *) data->uniforms, d);
3905
3906 for (i = 0; i < data->attribute_count; i++)
3907 f((void *) data->attributes[i].name, d);
3908 f((void *) data->attributes, d);
3909
3910 for (i = 0; i < data->output_count; i++)
3911 f((void *) data->outputs[i].name, d);
3912 f((void *) data->outputs, d);
3913
3914 for (i = 0; i < data->sampler_count; i++)
3915 f((void *) data->samplers[i].name, d);
3916 f((void *) data->samplers, d);
3917
3918 free_symbols(f, d, data->symbols, data->symbol_count);
3919 MOJOSHADER_freePreshader(data->preshader);
3920
3921 f(data, d);
3922 } // MOJOSHADER_freeParseData
3923
3924
3925 int MOJOSHADER_version(void)
3926 {
3927 return MOJOSHADER_VERSION;
3928 } // MOJOSHADER_version
3929
3930
3931 const char *MOJOSHADER_changeset(void)
3932 {
3933 return MOJOSHADER_CHANGESET;
3934 } // MOJOSHADER_changeset
3935
3936
3937 int MOJOSHADER_maxShaderModel(const char *profile)
3938 {
3939 #define PROFILE_SHADER_MODEL(p,v) if (strcmp(profile, p) == 0) return v;
3940 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_D3D, 3);
3941 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_BYTECODE, 3);
3942 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_HLSL, 3);
3943 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_GLSL, 3);
3944 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_GLSL120, 3);
3945 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_GLSLES, 3);
3946 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_ARB1, 2);
3947 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_NV2, 2);
3948 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_NV3, 2);
3949 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_NV4, 3);
3950 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_METAL, 3);
3951 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_SPIRV, 3);
3952 PROFILE_SHADER_MODEL(MOJOSHADER_PROFILE_GLSPIRV, 3);
3953 #undef PROFILE_SHADER_MODEL
3954 return -1; // unknown profile?
3955 } // MOJOSHADER_maxShaderModel
3956
3957
3958 const MOJOSHADER_preshader *MOJOSHADER_parsePreshader(const unsigned char *buf,
3959 const unsigned int buflen,
3960 MOJOSHADER_malloc m,
3961 MOJOSHADER_free f,
3962 void *d)
3963 {
3964 MOJOSHADER_preshader *retval = NULL;
3965
3966 // We need just enough Context for allocators and error state.
3967 Context *ctx = build_context(NULL, NULL, buf, buflen, NULL, 0, NULL, 0, m, f, d);
3968 if (ctx == NULL)
3969 {
3970 return retval; // !!! FIXME: Out of memory struct for MOJOSHADER_preshader
3971 }
3972 parse_preshader(ctx, ctx->tokens, ctx->tokencount);
3973 if (!isfail(ctx))
3974 {
3975 retval = ctx->preshader;
3976 ctx->preshader = NULL; // don't let destroy_context() eat the retval.
3977 } // if
3978
3979 destroy_context(ctx);
3980 return retval;
3981 } // MOJOSHADER_parsePreshader
3982
3983 void MOJOSHADER_freePreshader(const MOJOSHADER_preshader *preshader)
3984 {
3985 if (preshader != NULL)
3986 {
3987 unsigned int i, j;
3988 void *d = preshader->malloc_data;
3989 MOJOSHADER_free f = preshader->free;
3990 if (f == NULL) f = MOJOSHADER_internal_free;
3991
3992 f((void *) preshader->literals, d);
3993 for (i = 0; i < preshader->instruction_count; i++)
3994 {
3995 for (j = 0; j < preshader->instructions[i].operand_count; j++)
3996 f((void *) preshader->instructions[i].operands[j].array_registers, d);
3997 } // for
3998 f((void *) preshader->instructions, d);
3999 f((void *) preshader->registers, d);
4000 free_symbols(f, d, preshader->symbols, preshader->symbol_count);
4001 f((void *) preshader, d);
4002 } // if
4003 } // MOJOSHADER_freePreshader
4004
4005 #if SUPPORT_PROFILE_SPIRV
4006 #include <spirv/spirv.h> /* SpvOp, SpvOpConvertUToF, SpvOpConvertSToF, SpvOpCopyObject */
4007 #endif
4008
4009 int MOJOSHADER_linkSPIRVShaders(const MOJOSHADER_parseData *vertex_spirv,
4010 const MOJOSHADER_parseData *pixel_spirv,
4011 const MOJOSHADER_vertexAttribute *vertexAttributes,
4012 const int vertexAttributeCount)
4013 {
4014 #if SUPPORT_PROFILE_SPIRV
4015 // We have to patch the SPIR-V output to ensure type consistency. The non-float types are:
4016 // BYTE4 - 5
4017 // SHORT2 - 6
4018 // SHORT4 - 7
4019 int vDataLen = vertex_spirv->output_len - sizeof(SpirvPatchTable);
4020 SpirvPatchTable *vTable = (SpirvPatchTable *) &vertex_spirv->output[vDataLen];
4021
4022 for (int i = 0; i < vertexAttributeCount; i += 1)
4023 {
4024 const MOJOSHADER_vertexAttribute *element = &vertexAttributes[i];
4025 uint32 typeDecl, typeLoad;
4026 SpvOp opcodeLoad;
4027
4028 if (element->vertexElementFormat >= MOJOSHADER_VERTEXELEMENTFORMAT_BYTE4 && element->vertexElementFormat <= MOJOSHADER_VERTEXELEMENTFORMAT_SHORT4)
4029 {
4030 const int isByte = (element->vertexElementFormat == MOJOSHADER_VERTEXELEMENTFORMAT_BYTE4);
4031 typeDecl = isByte ? vTable->tid_uvec4_p : vTable->tid_ivec4_p;
4032 typeLoad = isByte ? vTable->tid_uvec4 : vTable->tid_ivec4;
4033 opcodeLoad = isByte ? SpvOpConvertUToF : SpvOpConvertSToF;
4034 }
4035 else
4036 {
4037 typeDecl = vTable->tid_vec4_p;
4038 typeLoad = vTable->tid_vec4;
4039 opcodeLoad = SpvOpCopyObject;
4040 }
4041
4042 uint32 typeDeclOffset = vTable->attrib_type_offsets[element->usage][element->usageIndex];
4043 if (typeDeclOffset > 0) // Vertex attribs passed may not exist in the vertex shader
4044 {
4045 ((uint32*)vertex_spirv->output)[typeDeclOffset] = typeDecl;
4046 for (uint32 j = 0; j < vTable->attrib_type_load_offsets[element->usage][element->usageIndex].num_loads; j += 1)
4047 {
4048
4049 uint32 typeLoadOffset = vTable->attrib_type_load_offsets[element->usage][element->usageIndex].load_types[j];
4050 uint32 opcodeLoadOffset = vTable->attrib_type_load_offsets[element->usage][element->usageIndex].load_opcodes[j];
4051 if (typeLoadOffset > 0)
4052 ((uint32*)vertex_spirv->output)[typeLoadOffset] = typeLoad;
4053 if (opcodeLoadOffset > 0)
4054 {
4055 uint32* ptr_to_opcode_u32 = &((uint32*)vertex_spirv->output)[opcodeLoadOffset];
4056 *ptr_to_opcode_u32 = (*ptr_to_opcode_u32 & 0xFFFF0000) | opcodeLoad;
4057 } // if
4058 } // for
4059 } // if
4060 } // if
4061
4062 MOJOSHADER_spirv_link_attributes(vertex_spirv, pixel_spirv, 0);
4063 return sizeof(SpirvPatchTable);
4064 #else
4065 return 0;
4066 #endif
4067 }
4068
4069 // end of mojoshader.c ...
4070