Debian Codegraph @

mojoshader_d3d11.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 #ifdef _WIN32
11 #define WIN32_LEAN_AND_MEAN 1
12 #include <windows.h> // Include this early to avoid SDL conflicts
13 #endif
14
15 #define __MOJOSHADER_INTERNAL__ 1
16 #include "mojoshader_internal.h"
17
18 #if SUPPORT_PROFILE_HLSL
19
20 #define D3D11_NO_HELPERS
21 #define CINTERFACE
22 #define COBJMACROS
23 #include <d3d11.h>
24
25 /* d3dcompiler DLL */
26
27 #ifndef WINAPI_FAMILY_WINRT
28 #define WINAPI_FAMILY_WINRT 0
29 #endif
30 #if WINAPI_FAMILY_WINRT
31 #include <d3dcompiler.h>
32 #elif defined(_WIN32)
33 #define LOAD_D3DCOMPILER LoadLibrary("d3dcompiler_47.dll")
34 #define UNLOAD_D3DCOMPILER(d) FreeLibrary(d)
35 #define LOAD_D3DCOMPILE(d) GetProcAddress(d, "D3DCompile")
36 #else
37 #define USING_VKD3D
38 #if defined(__APPLE__)
39 #define LOAD_D3DCOMPILER dlopen("libvkd3d-utils.1.dylib", RTLD_NOW|RTLD_LOCAL)
40 #else
41 #define LOAD_D3DCOMPILER dlopen("libvkd3d-utils.so.1", RTLD_NOW|RTLD_LOCAL)
42 #endif
43 #define UNLOAD_D3DCOMPILER(d) dlclose(d)
44 #define LOAD_D3DCOMPILE(d) dlsym(d, "D3DCompile")
45 #endif
46
47 /* __stdcall declaration, largely taken from vkd3d_windows.h */
48
49 #ifdef _WIN32
50 #define D3DCOMPILER_API WINAPI
51 #else
52 # ifdef __stdcall
53 # undef __stdcall
54 # endif
55 # ifdef __x86_64__
56 # define __stdcall __attribute__((ms_abi))
57 # else
58 # if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) || defined(__APPLE__)
59 # define __stdcall __attribute__((__stdcall__)) __attribute__((__force_align_arg_pointer__))
60 # else
61 # define __stdcall __attribute__((__stdcall__))
62 # endif
63 # endif
64 # define D3DCOMPILER_API __stdcall
65 #endif
66
67 /* vkd3d uses stdcall for its ID3D10Blob implementation */
68
69 #ifdef USING_VKD3D
70 typedef struct VKD3DBlob VKD3DBlob;
71 typedef struct VKD3DBlobVtbl
72 {
73 HRESULT (__stdcall *QueryInterface)(
74 VKD3DBlob *This,
75 REFIID riid,
76 void **ppvObject);
77 ULONG (__stdcall *AddRef)(VKD3DBlob *This);
78 ULONG (__stdcall *Release)(VKD3DBlob *This);
79 void * (__stdcall *GetBufferPointer)(VKD3DBlob *This);
80 SIZE_T (__stdcall *GetBufferSize)(VKD3DBlob *This);
81 } VKD3DBlobVtbl;
82 struct VKD3DBlob
83 {
84 const VKD3DBlobVtbl *lpVtbl;
85 };
86 #define ID3D10Blob VKD3DBlob
87 #define ID3DBlob VKD3DBlob
88 #endif // USING_VKD3D
89
90 /* D3DCompile signature */
91
92 typedef HRESULT(D3DCOMPILER_API *PFN_D3DCOMPILE)(
93 LPCVOID pSrcData,
94 SIZE_T SrcDataSize,
95 LPCSTR pSourceName,
96 const D3D_SHADER_MACRO *pDefines,
97 ID3DInclude *pInclude,
98 LPCSTR pEntrypoint,
99 LPCSTR pTarget,
100 UINT Flags1,
101 UINT Flags2,
102 ID3DBlob **ppCode,
103 ID3DBlob **ppErrorMsgs
104 );
105
106 // D3DCompile optimization can be overzealous and cause very visible bugs,
107 // so we disable it when compiling shaders to preserve correctness.
108 #define D3D_SKIP_OPT (1 << 2)
109
110 /* Error state */
111
112 static char error_buffer[1024] = { '\0' };
113
114 static void set_error(const char *str)
115 {
116 snprintf(error_buffer, sizeof (error_buffer), "%s", str);
117 } // set_error
118
119 static inline void out_of_memory(void)
120 {
121 set_error("out of memory");
122 } // out_of_memory
123
124 /* Structs */
125
126 typedef struct d3d11ShaderMap
127 {
128 void *val;
129 union
130 {
131 struct
132 {
133 uint64 layoutHash;
134 ID3D10Blob *blob;
135 } vertex;
136 struct
137 {
138 MOJOSHADER_d3d11Shader *vshader;
139 } pixel;
140 };
141 } d3d11ShaderMap;
142
143 typedef struct MOJOSHADER_d3d11Shader
144 {
145 const MOJOSHADER_parseData *parseData;
146 uint32 refcount;
147 ID3D11Buffer *ubo;
148 size_t buflen;
149 unsigned char *constantData;
150 unsigned int mapCapacity;
151 unsigned int numMaps;
152 d3d11ShaderMap *shaderMaps;
153 } MOJOSHADER_d3d11Shader;
154
155 // Max entries for each register file type...
156 #define MAX_REG_FILE_F 8192
157 #define MAX_REG_FILE_I 2047
158 #define MAX_REG_FILE_B 2047
159
160 typedef struct MOJOSHADER_d3d11Context
161 {
162 // Allocators...
163 MOJOSHADER_malloc malloc_fn;
164 MOJOSHADER_free free_fn;
165 void *malloc_data;
166
167 // The constant register files...
168 // !!! FIXME: Man, it kills me how much memory this takes...
169 // !!! FIXME: ... make this dynamically allocated on demand.
170 float vs_reg_file_f[MAX_REG_FILE_F * 4];
171 int vs_reg_file_i[MAX_REG_FILE_I * 4];
172 uint8 vs_reg_file_b[MAX_REG_FILE_B];
173 float ps_reg_file_f[MAX_REG_FILE_F * 4];
174 int ps_reg_file_i[MAX_REG_FILE_I * 4];
175 uint8 ps_reg_file_b[MAX_REG_FILE_B];
176
177 // Pointer to the active ID3D11Device.
178 ID3D11Device *device;
179
180 // Pointer to the ID3D11DeviceContext.
181 ID3D11DeviceContext *deviceContext;
182
183 // Currently bound vertex and pixel shaders.
184 MOJOSHADER_d3d11Shader *vertexShader;
185 MOJOSHADER_d3d11Shader *pixelShader;
186 int vertexNeedsBound;
187 int pixelNeedsBound;
188
189 // D3DCompile function pointer.
190 PFN_D3DCOMPILE D3DCompileFunc;
191 #if !WINAPI_FAMILY_WINRT
192 HMODULE d3dcompilerDLL;
193 #endif
194 } MOJOSHADER_d3d11Context;
195
196 /* Uniform buffer utilities */
197
198 static inline int next_highest_alignment(int n)
199 {
200 const int align = 16;
201 return align * ((n + align - 1) / align);
202 } // next_highest_alignment
203
204 static inline void *get_uniform_buffer(MOJOSHADER_d3d11Shader *shader)
205 {
206 return (shader == NULL || shader->ubo == NULL) ? NULL : shader->ubo;
207 } // get_uniform_buffer
208
209 static void update_uniform_buffer(
210 MOJOSHADER_d3d11Context *ctx,
211 MOJOSHADER_d3d11Shader *shader
212 ) {
213 int i, j;
214 float *regF; int *regI; uint8 *regB;
215 int needsUpdate;
216 size_t offset;
217 int idx;
218 int arrayCount;
219 void *src, *dst;
220 size_t size;
221 int *vecDst;
222
223 if (shader == NULL || shader->ubo == NULL)
224 return;
225
226 if (shader->parseData->shader_type == MOJOSHADER_TYPE_VERTEX)
227 {
228 regF = ctx->vs_reg_file_f;
229 regI = ctx->vs_reg_file_i;
230 regB = ctx->vs_reg_file_b;
231 } // if
232 else
233 {
234 regF = ctx->ps_reg_file_f;
235 regI = ctx->ps_reg_file_i;
236 regB = ctx->ps_reg_file_b;
237 } // else
238
239 // Update the buffer contents
240 needsUpdate = 0;
241 offset = 0;
242 for (i = 0; i < shader->parseData->uniform_count; i++)
243 {
244 if (shader->parseData->uniforms[i].constant)
245 continue;
246
247 idx = shader->parseData->uniforms[i].index;
248 arrayCount = shader->parseData->uniforms[i].array_count;
249
250 src = NULL;
251 dst = NULL;
252 size = arrayCount ? (arrayCount * 16) : 16;
253
254 switch (shader->parseData->uniforms[i].type)
255 {
256 case MOJOSHADER_UNIFORM_FLOAT:
257 src = &regF[4 * idx];
258 dst = shader->constantData + offset;
259 break;
260
261 case MOJOSHADER_UNIFORM_INT:
262 src = &regI[4 * idx];
263 dst = shader->constantData + offset;
264 break;
265
266 case MOJOSHADER_UNIFORM_BOOL:
267 // bool registers are a whole other mess, thanks to alignment.
268 // The bool field is an int4 in HLSL 4+, so we have to cast the
269 // bool to an int, then skip 3 ints. Super efficient, right?
270 vecDst = (int*) (shader->constantData + offset);
271 j = 0;
272 do
273 {
274 if (vecDst[j * 4] != regB[idx + j])
275 {
276 needsUpdate = 1;
277 vecDst[j * 4] = regB[idx + j];
278 } // if
279 } while (++j < arrayCount);
280
281 offset += size;
282 continue; // Skip the rest, do NOT break!
283
284 default:
285 assert(0); // This should never happen.
286 break;
287 } // switch
288
289 if (memcmp(dst, src, size) != 0)
290 {
291 memcpy(dst, src, size);
292 needsUpdate = 1;
293 } // if
294
295 offset += size;
296 } // for
297
298 if (needsUpdate)
299 {
300 // Map the buffer
301 D3D11_MAPPED_SUBRESOURCE res;
302 ID3D11DeviceContext_Map((ID3D11DeviceContext*) ctx->deviceContext,
303 (ID3D11Resource*) shader->ubo, 0,
304 D3D11_MAP_WRITE_DISCARD, 0, &res);
305
306 // Copy the contents
307 memcpy(res.pData, shader->constantData, shader->buflen);
308
309 // Unmap the buffer
310 ID3D11DeviceContext_Unmap(
311 (ID3D11DeviceContext*) ctx->deviceContext,
312 (ID3D11Resource*) shader->ubo,
313 0
314 );
315 } // if
316 } // update_uniform_buffer
317
318 static inline void expand_map(
319 MOJOSHADER_d3d11Context *ctx,
320 MOJOSHADER_d3d11Shader *shader
321 ) {
322 if (shader->numMaps == shader->mapCapacity)
323 {
324 d3d11ShaderMap *newMap = (d3d11ShaderMap *) ctx->malloc_fn(
325 sizeof(d3d11ShaderMap) * shader->mapCapacity * 2,
326 ctx->malloc_data
327 );
328 memcpy(newMap, shader->shaderMaps,
329 sizeof(d3d11ShaderMap) * shader->mapCapacity);
330 shader->mapCapacity *= 2;
331 ctx->free_fn(shader->shaderMaps, ctx->malloc_data);
332 shader->shaderMaps = newMap;
333 newMap = NULL;
334 } // if
335 } // expand_map
336
337 static inline int element_is_uint(DXGI_FORMAT format)
338 {
339 return format == DXGI_FORMAT_R32G32B32A32_UINT ||
340 format == DXGI_FORMAT_R32G32B32_UINT ||
341 format == DXGI_FORMAT_R16G16B16A16_UINT ||
342 format == DXGI_FORMAT_R32G32_UINT ||
343 format == DXGI_FORMAT_R10G10B10A2_UINT ||
344 format == DXGI_FORMAT_R8G8B8A8_UINT ||
345 format == DXGI_FORMAT_R16G16_UINT ||
346 format == DXGI_FORMAT_R32_UINT ||
347 format == DXGI_FORMAT_R8G8_UINT ||
348 format == DXGI_FORMAT_R16_UINT ||
349 format == DXGI_FORMAT_R8_UINT;
350 } // element_is_uint
351
352 static inline int element_is_int(DXGI_FORMAT format)
353 {
354 return format == DXGI_FORMAT_R32G32B32A32_SINT ||
355 format == DXGI_FORMAT_R32G32B32_SINT ||
356 format == DXGI_FORMAT_R16G16B16A16_SINT ||
357 format == DXGI_FORMAT_R32G32_SINT ||
358 format == DXGI_FORMAT_R8G8B8A8_SINT ||
359 format == DXGI_FORMAT_R16G16_SINT ||
360 format == DXGI_FORMAT_R32_SINT ||
361 format == DXGI_FORMAT_R8G8_SINT ||
362 format == DXGI_FORMAT_R16_SINT ||
363 format == DXGI_FORMAT_R8_SINT;
364 } // element_is_int
365
366 /* Shader Compilation Utilities */
367
368 static ID3D11VertexShader *compileVertexShader(
369 MOJOSHADER_d3d11Context *ctx,
370 MOJOSHADER_d3d11Shader *shader,
371 const char *src,
372 int src_len,
373 ID3D10Blob **blob
374 ) {
375 const MOJOSHADER_parseData *pd = shader->parseData;
376 HRESULT result = ctx->D3DCompileFunc(src, src_len, pd->mainfn,
377 NULL, NULL, pd->mainfn, "vs_4_0",
378 D3D_SKIP_OPT, 0, blob, blob);
379
380 if (result < 0)
381 {
382 set_error((const char *) ID3D10Blob_GetBufferPointer(*blob));
383 ID3D10Blob_Release(*blob);
384 return NULL;
385 } // if
386
387 void *bytecode = ID3D10Blob_GetBufferPointer(*blob);
388 int bytecodeLength = ID3D10Blob_GetBufferSize(*blob);
389 ID3D11VertexShader *ret = NULL;
390 ID3D11Device_CreateVertexShader(ctx->device, bytecode, bytecodeLength,
391 NULL, &ret);
392 return ret;
393 } // compileVertexShader
394
395 static void replaceVarname(
396 MOJOSHADER_d3d11Context *ctx,
397 const char *find,
398 const char *replace,
399 const char **source
400 ) {
401 const char *srcbuf = *source;
402 size_t find_len = strlen(find);
403 size_t replace_len = strlen(replace);
404
405 #define IS_PARTIAL_TOKEN(token) \
406 (isalnum(*(token + find_len)) || isalnum(*(token-1)))
407
408 // How many times does `find` occur in the source buffer?
409 int count = 0;
410 char *ptr = (char *) strstr(srcbuf, find);
411 while (ptr != NULL)
412 {
413 if (!IS_PARTIAL_TOKEN(ptr))
414 count++;
415 ptr = strstr(ptr + find_len, find);
416 } // while
417
418 // How big should we make the new text buffer?
419 size_t oldlen = strlen(srcbuf) + 1;
420 size_t newlen = oldlen + (count * (replace_len - find_len));
421
422 // Easy case; just find/replace in the original buffer
423 if (newlen == oldlen)
424 {
425 ptr = (char *) strstr(srcbuf, find);
426 while (ptr != NULL)
427 {
428 if (!IS_PARTIAL_TOKEN(ptr))
429 memcpy(ptr, replace, replace_len);
430 ptr = strstr(ptr + find_len, find);
431 } // while
432 return;
433 } // if
434
435 // Allocate a new buffer
436 char *newbuf = (char *) ctx->malloc_fn(newlen, ctx->malloc_data);
437 memset(newbuf, '\0', newlen);
438
439 // Find + replace
440 char *prev_ptr = (char *) srcbuf;
441 char *curr_ptr = (char *) newbuf;
442 ptr = (char*) strstr(srcbuf, find);
443 while (ptr != NULL)
444 {
445 memcpy(curr_ptr, prev_ptr, ptr - prev_ptr);
446 curr_ptr += ptr - prev_ptr;
447
448 if (!IS_PARTIAL_TOKEN(ptr))
449 {
450 memcpy(curr_ptr, replace, replace_len);
451 curr_ptr += replace_len;
452 } // if
453 else
454 {
455 // Don't accidentally eat partial tokens...
456 memcpy(curr_ptr, find, find_len);
457 curr_ptr += find_len;
458 } // else
459
460 prev_ptr = ptr + find_len;
461 ptr = strstr(prev_ptr, find);
462 } // while
463
464 #undef IS_PARTIAL_TOKEN
465
466 // Copy the remaining part of the source buffer
467 memcpy(curr_ptr, prev_ptr, (srcbuf + oldlen) - prev_ptr);
468
469 // Free the source buffer
470 ctx->free_fn((void *) srcbuf, ctx->malloc_data);
471
472 // Point the source parameter to the new buffer
473 *source = newbuf;
474 } // replaceVarname
475
476 static char *rewritePixelShader(
477 MOJOSHADER_d3d11Context *ctx,
478 MOJOSHADER_d3d11Shader *vshader,
479 MOJOSHADER_d3d11Shader *pshader
480 ) {
481 const MOJOSHADER_parseData *vpd = vshader->parseData;
482 const MOJOSHADER_parseData *ppd = pshader->parseData;
483 const char *_Output = "_Output" ENDLINE_STR "{" ENDLINE_STR;
484 const char *_Input = "_Input" ENDLINE_STR "{" ENDLINE_STR;
485 const char *vsrc = vpd->output;
486 const char *psrc = ppd->output;
487 const char *a, *b, *vout, *pstart, *vface, *pend;
488 size_t substr_len;
489 char *pfinal;
490
491 #define MAKE_STRBUF(buf) \
492 substr_len = b - a; \
493 buf = (const char *) ctx->malloc_fn(substr_len + 1, ctx->malloc_data); \
494 memset((void *) buf, '\0', substr_len + 1); \
495 memcpy((void *) buf, a, substr_len);
496
497 // Copy the vertex function's output struct into a buffer
498 a = strstr(vsrc, _Output) + strlen(_Output);
499 b = a;
500 while (*(b++) != '}');
501 b--;
502 MAKE_STRBUF(vout)
503
504 // Split up the pixel shader text...
505
506 // ...everything up to the input contents...
507 a = psrc;
508 b = strstr(psrc, _Input) + strlen(_Input);
509 MAKE_STRBUF(pstart)
510
511 // ...everything after the input contents.
512 a = b;
513 while (*(a++) != '}');
514 a--;
515 while (*(b++) != '\0');
516 MAKE_STRBUF(pend)
517
518 // Find matching semantics
519 int i, j;
520 int vfaceidx = -1;
521 const char *pvarname, *vvarname;
522 for (i = 0; i < ppd->attribute_count; i++)
523 {
524 int found_matching_vs_output_for_ps_input = 0;
525 for (j = 0; j < vpd->output_count; j++)
526 {
527 if (ppd->attributes[i].usage == vpd->outputs[j].usage &&
528 ppd->attributes[i].index == vpd->outputs[j].index)
529 {
530 found_matching_vs_output_for_ps_input = 1;
531 pvarname = ppd->attributes[i].name;
532 vvarname = vpd->outputs[j].name;
533 if (strcmp(pvarname, vvarname) != 0)
534 replaceVarname(ctx, pvarname, vvarname, &pend);
535 } // if
536 else if (strcmp(ppd->attributes[i].name, "vPos") == 0 &&
537 vpd->outputs[j].usage == MOJOSHADER_USAGE_POSITION &&
538 vpd->outputs[j].index == 0)
539 {
540 found_matching_vs_output_for_ps_input = 1;
541 pvarname = ppd->attributes[i].name;
542 vvarname = vpd->outputs[j].name;
543 if (strcmp(pvarname, vvarname) != 0)
544 replaceVarname(ctx, pvarname, vvarname, &pend);
545 } // else if
546 } // for
547
548 if (strcmp(ppd->attributes[i].name, "vFace") == 0)
549 vfaceidx = i;
550
551 // A vertex shader that doesn't properly initialize all its outputs
552 // can produce a situation where vpd->outputs is missing a matching
553 // entry for the PS's inputs, even though fxc will happily compile
554 // both shaders together as a technique in FX mode
555 // I don't know how to fix this yet, but a workaround is to
556 // correct your shader to zero-initialize all its outputs -kg
557 assert(found_matching_vs_output_for_ps_input);
558 } // for
559
560 // Special handling for VFACE
561 vface = (vfaceidx != -1) ? "\tbool m_vFace : SV_IsFrontFace;\n" : "";
562
563 // Concatenate the shader pieces together
564 substr_len = strlen(pstart) + strlen(vout) + strlen(vface) + strlen(pend);
565 pfinal = (char *) ctx->malloc_fn(substr_len + 1, ctx->malloc_data);
566 memset((void *) pfinal, '\0', substr_len + 1);
567 memcpy(pfinal, pstart, strlen(pstart));
568 memcpy(pfinal + strlen(pstart), vout, strlen(vout));
569 memcpy(pfinal + strlen(pstart) + strlen(vout), vface, strlen(vface));
570 memcpy(pfinal + strlen(pstart) + strlen(vout) + strlen(vface), pend, strlen(pend));
571
572 // Free the temporary buffers
573 ctx->free_fn((void *) vout, ctx->malloc_data);
574 ctx->free_fn((void *) pstart, ctx->malloc_data);
575 ctx->free_fn((void *) pend, ctx->malloc_data);
576
577 #undef MAKE_STRBUF
578
579 return pfinal;
580 } // spliceVertexShaderInput
581
582 static ID3D11PixelShader *compilePixelShader(
583 MOJOSHADER_d3d11Context *ctx,
584 MOJOSHADER_d3d11Shader *vshader,
585 MOJOSHADER_d3d11Shader *pshader
586 ) {
587 ID3D11PixelShader *retval = NULL;
588 const char *source;
589 ID3DBlob *blob;
590 HRESULT result;
591 int needs_free;
592
593 if (pshader->parseData->attribute_count > 0)
594 {
595 source = rewritePixelShader(ctx, vshader, pshader);
596 needs_free = 1;
597 } // if
598 else
599 {
600 source = pshader->parseData->output;
601 needs_free = 0;
602 } // else
603
604 result = ctx->D3DCompileFunc(source, strlen(source),
605 pshader->parseData->mainfn, NULL, NULL,
606 pshader->parseData->mainfn, "ps_4_0",
607 D3D_SKIP_OPT, 0, &blob, &blob);
608
609 if (needs_free)
610 ctx->free_fn((void *) source, ctx->malloc_data);
611
612 if (result < 0)
613 {
614 set_error((const char *) ID3D10Blob_GetBufferPointer(blob));
615 return NULL;
616 } // if
617
618 ID3D11Device_CreatePixelShader(ctx->device,
619 ID3D10Blob_GetBufferPointer(blob),
620 ID3D10Blob_GetBufferSize(blob),
621 NULL, &retval);
622
623 ID3D10Blob_Release(blob);
624 return retval;
625 } // compilePixelShader
626
627 /* Public API */
628
629 MOJOSHADER_d3d11Context* MOJOSHADER_d3d11CreateContext(
630 void *device,
631 void *deviceContext,
632 MOJOSHADER_malloc m,
633 MOJOSHADER_free f,
634 void *malloc_d
635 ) {
636 MOJOSHADER_d3d11Context *ctx;
637 PFN_D3DCOMPILE compileFunc;
638
639 #if WINAPI_FAMILY_WINRT
640 compileFunc = D3DCompile;
641 #else
642 HMODULE compileDLL;
643 compileDLL = LOAD_D3DCOMPILER;
644 if (compileDLL == NULL)
645 return NULL;
646 compileFunc = (PFN_D3DCOMPILE) LOAD_D3DCOMPILE(compileDLL);
647 if (compileFunc == NULL)
648 {
649 UNLOAD_D3DCOMPILER(compileDLL);
650 return NULL;
651 } // if
652 #ifdef USING_VKD3D
653 unsigned int major, minor;
654 const char *(*vkd3d_shader_get_version)(unsigned int *, unsigned int *);
655 vkd3d_shader_get_version = (const char *(*)(unsigned int *, unsigned int *)) dlsym(compileDLL, "vkd3d_shader_get_version");
656 if (vkd3d_shader_get_version == NULL)
657 {
658 UNLOAD_D3DCOMPILER(compileDLL);
659 return NULL;
660 }
661 vkd3d_shader_get_version(&major, &minor);
662 if (!((major > 1) || (major == 1 && minor >= 10)))
663 {
664 UNLOAD_D3DCOMPILER(compileDLL);
665 return NULL;
666 }
667 #endif
668 #endif
669
670 if (m == NULL) m = MOJOSHADER_internal_malloc;
671 if (f == NULL) f = MOJOSHADER_internal_free;
672
673 ctx = (MOJOSHADER_d3d11Context *) m(sizeof(MOJOSHADER_d3d11Context), malloc_d);
674 if (ctx == NULL)
675 {
676 out_of_memory();
677 goto init_fail;
678 } // if
679
680 memset(ctx, '\0', sizeof (MOJOSHADER_d3d11Context));
681 ctx->malloc_fn = m;
682 ctx->free_fn = f;
683 ctx->malloc_data = malloc_d;
684
685 // Store references to the D3D device and immediate context
686 ctx->device = (ID3D11Device*) device;
687 ctx->deviceContext = (ID3D11DeviceContext*) deviceContext;
688
689 // Store the d3dcompiler info
690 ctx->D3DCompileFunc = compileFunc;
691 #if !WINAPI_FAMILY_WINRT
692 ctx->d3dcompilerDLL = compileDLL;
693 #endif
694
695 return ctx;
696
697 init_fail:
698 if (ctx != NULL)
699 f(ctx, malloc_d);
700 return NULL;
701 } // MOJOSHADER_d3d11CreateContext
702
703 void MOJOSHADER_d3d11DestroyContext(MOJOSHADER_d3d11Context *ctx)
704 {
705 #if !WINAPI_FAMILY_WINRT
706 UNLOAD_D3DCOMPILER(ctx->d3dcompilerDLL);
707 #endif
708 ctx->free_fn(ctx, ctx->malloc_data);
709 } // MOJOSHADER_d3d11DestroyContext
710
711 MOJOSHADER_d3d11Shader *MOJOSHADER_d3d11CompileShader(MOJOSHADER_d3d11Context *ctx,
712 const char *mainfn,
713 const unsigned char *tokenbuf,
714 const unsigned int bufsize,
715 const MOJOSHADER_swizzle *swiz,
716 const unsigned int swizcount,
717 const MOJOSHADER_samplerMap *smap,
718 const unsigned int smapcount)
719 {
720 MOJOSHADER_malloc m = ctx->malloc_fn;
721 MOJOSHADER_free f = ctx->free_fn;
722 void *d = ctx->malloc_data;
723 int i;
724
725 const MOJOSHADER_parseData *pd = MOJOSHADER_parse("hlsl", mainfn, tokenbuf,
726 bufsize, swiz, swizcount,
727 smap, smapcount, m, f, d);
728
729 if (pd->error_count > 0)
730 {
731 // !!! FIXME: put multiple errors in the buffer? Don't use
732 // !!! FIXME: MOJOSHADER_d3d11GetError() for this?
733 set_error(pd->errors[0].error);
734 goto compile_shader_fail;
735 } // if
736
737 MOJOSHADER_d3d11Shader *retval = (MOJOSHADER_d3d11Shader *) m(sizeof(MOJOSHADER_d3d11Shader), d);
738 if (retval == NULL)
739 goto compile_shader_fail;
740
741 retval->parseData = pd;
742 retval->refcount = 1;
743 retval->ubo = NULL;
744 retval->constantData = NULL;
745 retval->buflen = 0;
746 retval->numMaps = 0;
747
748 // Allocate shader maps
749 retval->mapCapacity = 4; // arbitrary!
750 retval->shaderMaps = (d3d11ShaderMap *) m(retval->mapCapacity * sizeof(d3d11ShaderMap), d);
751 if (retval->shaderMaps == NULL)
752 goto compile_shader_fail;
753
754 memset(retval->shaderMaps, '\0', retval->mapCapacity * sizeof(d3d11ShaderMap));
755
756 // Create the uniform buffer, if needed
757 if (pd->uniform_count > 0)
758 {
759 // Calculate how big we need to make the buffer
760 for (i = 0; i < pd->uniform_count; i++)
761 {
762 const int arrayCount = pd->uniforms[i].array_count;
763 retval->buflen += (arrayCount ? arrayCount : 1) * 16;
764 } // for
765
766 D3D11_BUFFER_DESC bdesc;
767 bdesc.ByteWidth = next_highest_alignment(retval->buflen);
768 bdesc.Usage = D3D11_USAGE_DYNAMIC;
769 bdesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
770 bdesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
771 bdesc.MiscFlags = 0;
772 bdesc.StructureByteStride = 0;
773 ID3D11Device_CreateBuffer((ID3D11Device*) ctx->device, &bdesc, NULL,
774 (ID3D11Buffer**) &retval->ubo);
775
776 // Additionally allocate a CPU-side staging buffer
777 retval->constantData = (unsigned char *) m(retval->buflen, d);
778 memset(retval->constantData, '\0', retval->buflen);
779 } // if
780
781 return retval;
782
783 compile_shader_fail:
784 MOJOSHADER_freeParseData(pd);
785 return NULL;
786 } // MOJOSHADER_d3d11CompileShader
787
788 void MOJOSHADER_d3d11ShaderAddRef(MOJOSHADER_d3d11Shader *shader)
789 {
790 if (shader != NULL)
791 shader->refcount++;
792 } // MOJOSHADER_d3d11ShaderAddRef
793
794 void MOJOSHADER_d3d11DeleteShader(
795 MOJOSHADER_d3d11Context *ctx,
796 MOJOSHADER_d3d11Shader *shader
797 ) {
798 if (shader != NULL)
799 {
800 if (shader->refcount > 1)
801 shader->refcount--;
802 else
803 {
804 if (shader->ubo != NULL)
805 {
806 ID3D11Buffer_Release((ID3D11Buffer*) shader->ubo);
807 ctx->free_fn(shader->constantData, ctx->malloc_data);
808 } // if
809
810 if (shader->parseData->shader_type == MOJOSHADER_TYPE_VERTEX)
811 {
812 for (int i = 0; i < shader->numMaps; i++)
813 {
814 ID3D11VertexShader_Release((ID3D11VertexShader *) shader->shaderMaps[i].val);
815 ID3D10Blob_Release(shader->shaderMaps[i].vertex.blob);
816 } // for
817 } // if
818 else if (shader->parseData->shader_type == MOJOSHADER_TYPE_PIXEL)
819 {
820 for (int i = 0; i < shader->numMaps; i++)
821 ID3D11PixelShader_Release((ID3D11PixelShader *) shader->shaderMaps[i].val);
822 } // else if
823
824 ctx->free_fn(shader->shaderMaps, ctx->malloc_data);
825 shader->shaderMaps = NULL;
826 MOJOSHADER_freeParseData(shader->parseData);
827 ctx->free_fn(shader, ctx->malloc_data);
828 } // else
829 } // if
830 } // MOJOSHADER_d3d11DeleteShader
831
832 const MOJOSHADER_parseData *MOJOSHADER_d3d11GetShaderParseData(
833 MOJOSHADER_d3d11Shader *shader)
834 {
835 return (shader != NULL) ? shader->parseData : NULL;
836 } // MOJOSHADER_d3d11GetParseData
837
838 void MOJOSHADER_d3d11BindShaders(
839 MOJOSHADER_d3d11Context *ctx,
840 MOJOSHADER_d3d11Shader *vshader,
841 MOJOSHADER_d3d11Shader *pshader
842 ) {
843 // Use the last bound shaders in case of NULL
844 if (vshader != NULL)
845 {
846 ctx->vertexShader = vshader;
847 ctx->vertexNeedsBound = 1;
848 } // if
849
850 if (pshader != NULL)
851 {
852 ctx->pixelShader = pshader;
853 ctx->pixelNeedsBound = 1;
854 } // if
855 } // MOJOSHADER_d3d11BindShaders
856
857 void MOJOSHADER_d3d11GetBoundShaders(
858 MOJOSHADER_d3d11Context *ctx,
859 MOJOSHADER_d3d11Shader **vshader,
860 MOJOSHADER_d3d11Shader **pshader
861 ) {
862 *vshader = ctx->vertexShader;
863 *pshader = ctx->pixelShader;
864 } // MOJOSHADER_d3d11GetBoundShaders
865
866 void MOJOSHADER_d3d11MapUniformBufferMemory(
867 MOJOSHADER_d3d11Context *ctx,
868 float **vsf, int **vsi, unsigned char **vsb,
869 float **psf, int **psi, unsigned char **psb
870 ) {
871 *vsf = ctx->vs_reg_file_f;
872 *vsi = ctx->vs_reg_file_i;
873 *vsb = ctx->vs_reg_file_b;
874 *psf = ctx->ps_reg_file_f;
875 *psi = ctx->ps_reg_file_i;
876 *psb = ctx->ps_reg_file_b;
877 } // MOJOSHADER_d3d11MapUniformBufferMemory
878
879 void MOJOSHADER_d3d11UnmapUniformBufferMemory(MOJOSHADER_d3d11Context *ctx)
880 {
881 /* This has nothing to do with unmapping memory
882 * and everything to do with updating uniform
883 * buffers with the latest parameter contents.
884 */
885 MOJOSHADER_d3d11Shader *vs, *ps;
886 MOJOSHADER_d3d11GetBoundShaders(ctx, &vs, &ps);
887 update_uniform_buffer(ctx, vs);
888 update_uniform_buffer(ctx, ps);
889 } // MOJOSHADER_d3d11UnmapUniformBufferMemory
890
891 int MOJOSHADER_d3d11GetVertexAttribLocation(MOJOSHADER_d3d11Shader *vert,
892 MOJOSHADER_usage usage, int index)
893 {
894 if (vert == NULL)
895 return -1;
896
897 for (int i = 0; i < vert->parseData->attribute_count; i++)
898 {
899 if (vert->parseData->attributes[i].usage == usage &&
900 vert->parseData->attributes[i].index == index)
901 {
902 return i;
903 } // if
904 } // for
905
906 // failure, couldn't find requested attribute
907 return -1;
908 } // MOJOSHADER_d3d11GetVertexAttribLocation
909
910 int MOJOSHADER_d3d11CompileVertexShader(
911 MOJOSHADER_d3d11Context *ctx,
912 unsigned long long inputLayoutHash,
913 void* elements,
914 int elementCount,
915 void **bytecode,
916 int *bytecodeLength
917 ) {
918 MOJOSHADER_d3d11Shader *vshader = ctx->vertexShader;
919 ID3D11VertexShader *vs;
920 ID3D10Blob *blob;
921
922 // Don't compile if there's already a mapping for this layout.
923 for (int i = 0; i < vshader->numMaps; i++)
924 {
925 if (inputLayoutHash == vshader->shaderMaps[i].vertex.layoutHash)
926 {
927 blob = vshader->shaderMaps[i].vertex.blob;
928 *bytecode = ID3D10Blob_GetBufferPointer(blob);
929 *bytecodeLength = ID3D10Blob_GetBufferSize(blob);
930 return 0;
931 } // if
932 } // for
933
934 // Check for and replace non-float types
935 D3D11_INPUT_ELEMENT_DESC *d3dElements = (D3D11_INPUT_ELEMENT_DESC*) elements;
936 const char *origSource = vshader->parseData->output;
937 int srcLength = vshader->parseData->output_len;
938 char *newSource = (char*) origSource;
939 for (int i = 0; i < elementCount; i += 1)
940 {
941 D3D11_INPUT_ELEMENT_DESC e = d3dElements[i];
942
943 const char *replace;
944 if (element_is_uint(e.Format))
945 replace = " uint4";
946 else if (element_is_int(e.Format))
947 replace = " int4";
948 else
949 replace = NULL;
950
951 if (replace != NULL)
952 {
953 char sem[16];
954 memset(sem, '\0', sizeof(sem));
955 snprintf(sem, sizeof(sem), "%s%d", e.SemanticName, e.SemanticIndex);
956 // !!! FIXME: POSITIONT has no index. What to do? -caleb
957
958 if (newSource == origSource)
959 {
960 newSource = (char *) ctx->malloc_fn(srcLength + 1,
961 ctx->malloc_data);
962 strcpy(newSource, origSource);
963 } // if
964
965 char *ptr = strstr(newSource, sem);
966 assert(ptr != NULL && "Could not find semantic in shader source!");
967
968 int spaces = 0;
969 while (spaces < 3)
970 if (*(--ptr) == ' ') spaces++;
971 memcpy(ptr - strlen("float4"), replace, strlen(replace));
972 } // if
973 } // for
974
975 vs = compileVertexShader(ctx, vshader, newSource, srcLength, &blob);
976 if (newSource != origSource)
977 {
978 ctx->free_fn((void *) newSource, ctx->malloc_data);
979 } // if
980 if (vs == NULL)
981 {
982 // Error was already set, just return
983 return -1;
984 } // if
985
986 // Expand the map array, if needed
987 expand_map(ctx, vshader);
988
989 // Add the new mapping
990 vshader->shaderMaps[vshader->numMaps].vertex.layoutHash = inputLayoutHash;
991 vshader->shaderMaps[ctx->vertexShader->numMaps].val = vs;
992 vshader->shaderMaps[ctx->vertexShader->numMaps].vertex.blob = blob;
993 ctx->vertexShader->numMaps++;
994
995 // Return the bytecode info
996 *bytecode = ID3D10Blob_GetBufferPointer(blob);
997 *bytecodeLength = ID3D10Blob_GetBufferSize(blob);
998 return 0;
999 } // MOJOSHADER_d3d11CompileVertexShader
1000
1001 int MOJOSHADER_d3d11ProgramReady(
1002 MOJOSHADER_d3d11Context *ctx,
1003 unsigned long long inputLayoutHash
1004 ) {
1005 MOJOSHADER_d3d11Shader *vshader = ctx->vertexShader;
1006 MOJOSHADER_d3d11Shader *pshader = ctx->pixelShader;
1007 ID3D11VertexShader *realVS = NULL;
1008 ID3D11PixelShader *realPS = NULL;
1009
1010 // Vertex shader...
1011 if (ctx->vertexNeedsBound)
1012 {
1013 for (int i = 0; i < vshader->numMaps; i++)
1014 {
1015 if (inputLayoutHash == vshader->shaderMaps[i].vertex.layoutHash)
1016 {
1017 realVS = (ID3D11VertexShader *) vshader->shaderMaps[i].val;
1018 break;
1019 } // if
1020 } // for
1021
1022 if (realVS == NULL)
1023 {
1024 set_error("Vertex shader was not found, did you call d3d11CompileVertexShader?");
1025 return -1;
1026 } // if
1027
1028 ctx->vertexNeedsBound = 0;
1029 } // if
1030
1031 // Pixel shader...
1032 if (ctx->pixelNeedsBound)
1033 {
1034 // Is there already a mapping for the current vertex shader?
1035 for (int i = 0; i < pshader->numMaps; i++)
1036 {
1037 if (pshader->shaderMaps[i].pixel.vshader == vshader)
1038 {
1039 realPS = (ID3D11PixelShader *) pshader->shaderMaps[i].val;
1040 break;
1041 } // if
1042 } // for
1043
1044 // We have to create a new vertex/pixel shader mapping...
1045 if (realPS == NULL)
1046 {
1047 realPS = compilePixelShader(ctx, vshader, pshader);
1048
1049 if (realPS == NULL)
1050 {
1051 // Error already set by compilePixelShader, just return
1052 return -1;
1053 } // if
1054
1055 // Expand the map array, if needed
1056 expand_map(ctx, pshader);
1057
1058 // Add the new mapping
1059 pshader->shaderMaps[pshader->numMaps].pixel.vshader = vshader;
1060 pshader->shaderMaps[pshader->numMaps].val = realPS;
1061 pshader->numMaps++;
1062 } // if
1063 } // if
1064
1065 // Set shader state at the end, in case of errors above
1066 if (realVS != NULL)
1067 {
1068 ID3D11DeviceContext_VSSetShader(ctx->deviceContext, realVS, NULL, 0);
1069 ID3D11DeviceContext_VSSetConstantBuffers(ctx->deviceContext, 0, 1,
1070 &vshader->ubo);
1071 } // if
1072 if (realPS != NULL)
1073 {
1074 ID3D11DeviceContext_PSSetShader(ctx->deviceContext, realPS, NULL, 0);
1075 ID3D11DeviceContext_PSSetConstantBuffers(ctx->deviceContext, 0, 1,
1076 &pshader->ubo);
1077 } // if
1078 return 0;
1079 } // MOJOSHADER_d3d11ProgramReady
1080
1081 const char *MOJOSHADER_d3d11GetError(MOJOSHADER_d3d11Context *ctx)
1082 {
1083 return error_buffer;
1084 } // MOJOSHADER_d3d11GetError
1085
1086 #endif /* SUPPORT_PROFILE_HLSL */
1087
1088 // end of mojoshader_d3d11.c ...