/
mojoshader_metal.c
553 lines (452 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
/**
* MojoShader; generate shader programs from bytecode of compiled
* Direct3D shaders.
*
* Please see the file LICENSE.txt in the source's root directory.
*
* This file written by Ryan C. Gordon.
*/
10
11
12
#define __MOJOSHADER_INTERNAL__ 1
#include "mojoshader_internal.h"
13
14
15
16
17
18
19
#if (defined(__APPLE__) && defined(__MACH__))
#define PLATFORM_APPLE 1
#endif /* (defined(__APPLE__) && defined(__MACH__)) */
typedef struct MOJOSHADER_mtlShader
{
const MOJOSHADER_parseData *parseData;
20
uint32 refcount;
21
void *handle; // MTLFunction*
22
23
} MOJOSHADER_mtlShader;
24
25
26
27
28
29
30
31
32
33
34
35
36
// profile-specific implementations...
#if SUPPORT_PROFILE_METAL && PLATFORM_APPLE
#ifdef MOJOSHADER_EFFECT_SUPPORT
#include "TargetConditionals.h"
#include <objc/message.h>
#define msg ((void* (*)(void*, void*))objc_msgSend)
#define msg_s ((void* (*)(void*, void*, const char*))objc_msgSend)
#define msg_p ((void* (*)(void*, void*, void*))objc_msgSend)
#define msg_uu ((void* (*)(void*, void*, uint64, uint64))objc_msgSend)
#define msg_ppp ((void* (*)(void*, void*, void*, void*, void*))objc_msgSend)
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Error state...
static char error_buffer[1024] = { '\0' };
static void set_error(const char *str)
{
snprintf(error_buffer, sizeof (error_buffer), "%s", str);
} // set_error
static inline void out_of_memory(void)
{
set_error("out of memory");
} // out_of_memory
// Max entries for each register file type...
#define MAX_REG_FILE_F 8192
#define MAX_REG_FILE_I 2047
#define MAX_REG_FILE_B 2047
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
typedef struct MOJOSHADER_mtlContext
{
// Allocators...
MOJOSHADER_malloc malloc_fn;
MOJOSHADER_free free_fn;
void *malloc_data;
// The constant register files...
// !!! FIXME: Man, it kills me how much memory this takes...
// !!! FIXME: ... make this dynamically allocated on demand.
float vs_reg_file_f[MAX_REG_FILE_F * 4];
int vs_reg_file_i[MAX_REG_FILE_I * 4];
uint8 vs_reg_file_b[MAX_REG_FILE_B];
float ps_reg_file_f[MAX_REG_FILE_F * 4];
int ps_reg_file_i[MAX_REG_FILE_I * 4];
uint8 ps_reg_file_b[MAX_REG_FILE_B];
// Pointer to the active MTLDevice.
void* device;
75
76
// The uniform MTLBuffer shared between all shaders in the context.
void *ubo;
77
78
79
80
81
// The current offsets into the UBO, per shader.
int vertexUniformOffset;
int pixelUniformOffset;
int totalUniformOffset;
82
83
84
85
86
87
88
89
// The currently bound shaders.
MOJOSHADER_mtlShader *vertexShader;
MOJOSHADER_mtlShader *pixelShader;
// Objective-C Selectors
void* classNSString;
void* selAlloc;
90
void* selContents;
91
92
93
void* selInitWithUTF8String;
void* selLength;
void* selLocalizedDescription;
94
void* selNewBufferWithLength;
95
void* selNewFunctionWithName;
96
97
98
void* selNewLibraryWithSource;
void* selRelease;
void* selUTF8String;
99
100
101
} MOJOSHADER_mtlContext;
static MOJOSHADER_mtlContext *ctx = NULL;
102
103
104
105
106
107
108
109
/* Uniform buffer utilities */
static inline int next_highest_alignment(int n)
{
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_SIMULATOR
int align = 16;
#else
110
// !!! FIXME: Will Apple Silicon Macs have a different minimum alignment?
111
112
113
114
115
116
117
118
int align = 256;
#endif
return align * ((n + align - 1) / align);
} // next_highest_alignment
static void update_uniform_buffer(MOJOSHADER_mtlShader *shader)
{
119
if (shader == NULL || shader->parseData->uniform_count == 0)
120
121
122
123
124
return;
float *regF; int *regI; uint8 *regB;
if (shader->parseData->shader_type == MOJOSHADER_TYPE_VERTEX)
{
125
ctx->vertexUniformOffset = ctx->totalUniformOffset;
126
127
128
regF = ctx->vs_reg_file_f;
regI = ctx->vs_reg_file_i;
regB = ctx->vs_reg_file_b;
129
130
131
} // if
else
{
132
ctx->pixelUniformOffset = ctx->totalUniformOffset;
133
134
135
regF = ctx->ps_reg_file_f;
regI = ctx->ps_reg_file_i;
regB = ctx->ps_reg_file_b;
136
137
} // else
138
void *contents = msg(ctx->ubo, ctx->selContents) + ctx->totalUniformOffset;
139
140
141
int offset = 0;
for (int i = 0; i < shader->parseData->uniform_count; i++)
{
142
143
144
if (shader->parseData->uniforms[i].constant)
continue;
145
146
int idx = shader->parseData->uniforms[i].index;
int arrayCount = shader->parseData->uniforms[i].array_count;
147
148
void *src = NULL;
149
150
151
152
153
int size = arrayCount ? arrayCount : 1;
switch (shader->parseData->uniforms[i].type)
{
case MOJOSHADER_UNIFORM_FLOAT:
154
155
src = ®F[4 * idx];
size *= 16;
156
157
158
break;
case MOJOSHADER_UNIFORM_INT:
159
160
src = ®I[4 * idx];
size *= 16;
161
162
163
break;
case MOJOSHADER_UNIFORM_BOOL:
164
src = ®B[idx];
165
166
167
168
169
170
171
break;
default:
assert(0); // This should never happen.
break;
} // switch
172
memcpy(contents + offset, src, size);
173
174
offset += size;
} // for
175
176
177
178
179
180
181
ctx->totalUniformOffset = next_highest_alignment(ctx->totalUniformOffset + offset);
if (ctx->totalUniformOffset >= (int) msg(ctx->ubo, ctx->selLength))
{
// !!! FIXME: Is there a better way to handle this?
assert(0 && "Uniform data exceeded the size of the buffer!");
} // if
182
183
184
185
} // update_uniform_buffer
/* Public API */
186
187
188
MOJOSHADER_mtlContext *MOJOSHADER_mtlCreateContext(void* mtlDevice,
MOJOSHADER_malloc m, MOJOSHADER_free f,
void *malloc_d)
189
{
190
191
192
193
194
MOJOSHADER_mtlContext *retval = NULL;
MOJOSHADER_mtlContext *current_ctx = ctx;
int i;
ctx = NULL;
195
196
197
198
if (m == NULL) m = MOJOSHADER_internal_malloc;
if (f == NULL) f = MOJOSHADER_internal_free;
199
ctx = (MOJOSHADER_mtlContext *) m(sizeof (MOJOSHADER_mtlContext), malloc_d);
200
if (ctx == NULL)
201
202
{
out_of_memory();
203
goto init_fail;
204
} // if
205
206
207
208
209
210
211
212
213
214
215
216
memset(ctx, '\0', sizeof (MOJOSHADER_mtlContext));
ctx->malloc_fn = m;
ctx->free_fn = f;
ctx->malloc_data = malloc_d;
// Initialize the Metal state
ctx->device = mtlDevice;
// Grab references to Objective-C selectors
ctx->classNSString = objc_getClass("NSString");
ctx->selAlloc = sel_registerName("alloc");
217
ctx->selContents = sel_registerName("contents");
218
219
220
ctx->selInitWithUTF8String = sel_registerName("initWithUTF8String:");
ctx->selLength = sel_registerName("length");
ctx->selLocalizedDescription = sel_registerName("localizedDescription");
221
ctx->selNewBufferWithLength = sel_registerName("newBufferWithLength:options:");
222
ctx->selNewFunctionWithName = sel_registerName("newFunctionWithName:");
223
224
225
ctx->selNewLibraryWithSource = sel_registerName("newLibraryWithSource:options:error:");
ctx->selRelease = sel_registerName("release");
ctx->selUTF8String = sel_registerName("UTF8String");
226
227
228
229
230
231
232
233
// Create the uniform buffer
ctx->ubo = msg_uu(mtlDevice, ctx->selNewBufferWithLength,
next_highest_alignment(1000000), 0);
retval = ctx;
ctx = current_ctx;
return retval;
234
235
236
237
init_fail:
if (ctx != NULL)
f(ctx, malloc_d);
238
239
ctx = current_ctx;
return NULL;
240
241
} // MOJOSHADER_mtlCreateContext
242
243
void MOJOSHADER_mtlMakeContextCurrent(MOJOSHADER_mtlContext *_ctx)
244
{
245
246
247
ctx = _ctx;
} // MOJOSHADER_mtlMakeContextCurrent
248
249
250
251
252
253
254
255
256
257
258
259
void *MOJOSHADER_mtlCompileLibrary(MOJOSHADER_effect *effect)
{
MOJOSHADER_malloc m = ctx->malloc_fn;
MOJOSHADER_free f = ctx->free_fn;
void *d = ctx->malloc_data;
int i, src_len, src_pos, output_len;
char *shader_source, *ptr;
const char *repl;
MOJOSHADER_effectObject *object;
MOJOSHADER_mtlShader *shader;
260
void *retval, *compileError, *shader_source_ns, *fnname;
261
262
// Count the number of shaders before allocating
263
src_len = 0;
264
265
for (i = 0; i < effect->object_count; i++)
{
266
object = &effect->objects[i];
267
268
269
if (object->type == MOJOSHADER_SYMTYPE_PIXELSHADER
|| object->type == MOJOSHADER_SYMTYPE_VERTEXSHADER)
{
270
if (!object->shader.is_preshader)
271
{
272
273
274
shader = (MOJOSHADER_mtlShader*) object->shader.shader;
src_len += shader->parseData->output_len;
} // if
275
276
277
} // if
} // for
278
279
// Allocate shader source buffer
shader_source = (char *) m(src_len + 1, d);
280
memset(shader_source, '\0', src_len + 1);
281
src_pos = 0;
282
283
284
285
// Copy all the source text into the buffer
for (i = 0; i < effect->object_count; i++)
{
286
object = &effect->objects[i];
287
288
289
290
291
if (object->type == MOJOSHADER_SYMTYPE_PIXELSHADER
|| object->type == MOJOSHADER_SYMTYPE_VERTEXSHADER)
{
if (!object->shader.is_preshader)
{
292
293
294
295
shader = (MOJOSHADER_mtlShader*) object->shader.shader;
memcpy(&shader_source[src_pos], shader->parseData->output,
shader->parseData->output_len);
src_pos += shader->parseData->output_len;
296
297
298
299
300
301
302
303
304
} // if
} // if
} // for
// Handle texcoord0 -> point_coord conversion
if (strstr(shader_source, "[[point_size]]"))
{
// !!! FIXME: This assumes all texcoord0 attributes in the effect are
// !!! FIXME: actually point coords! It ain't necessarily so! -caleb
305
repl = "[[ point_coord ]]";
306
307
308
309
while ((ptr = strstr(shader_source, "[[user(texcoord0)]]")))
{
memcpy(ptr, repl, strlen(repl));
310
// "float4" -> "float2"
311
312
313
314
315
316
317
318
319
int spaces = 0;
while (spaces < 2)
if (*(ptr--) == ' ')
spaces++;
memcpy(ptr, "2", sizeof(char));
} // while
} // if
// Compile the source into a library
320
321
322
323
324
compileError = NULL;
shader_source_ns = msg_s(
msg(ctx->classNSString, ctx->selAlloc),
ctx->selInitWithUTF8String,
shader_source
325
);
326
327
retval = msg_ppp(ctx->device, ctx->selNewLibraryWithSource,
shader_source_ns, NULL, &compileError);
328
f(shader_source, d);
329
msg(shader_source_ns, ctx->selRelease);
330
331
if (retval == NULL)
332
{
333
334
335
compileError = msg(compileError, ctx->selLocalizedDescription);
set_error((char*) msg(compileError, ctx->selUTF8String));
return NULL;
336
337
} // if
338
// Run through the shaders again, getting the function handles
339
340
for (i = 0; i < effect->object_count; i++)
{
341
object = &effect->objects[i];
342
343
344
345
346
347
if (object->type == MOJOSHADER_SYMTYPE_PIXELSHADER
|| object->type == MOJOSHADER_SYMTYPE_VERTEXSHADER)
{
if (object->shader.is_preshader)
continue;
348
349
350
351
352
353
354
355
356
357
358
359
shader = (MOJOSHADER_mtlShader*) object->shader.shader;
fnname = msg_s(
msg(ctx->classNSString, ctx->selAlloc),
ctx->selInitWithUTF8String,
shader->parseData->mainfn
);
shader->handle = msg_p(
retval,
ctx->selNewFunctionWithName,
fnname
);
msg(fnname, ctx->selRelease);
360
361
362
363
} // if
} // for
return retval;
364
} // MOJOSHADER_mtlCompileLibrary
365
366
367
MOJOSHADER_mtlShader *MOJOSHADER_mtlCompileShader(const char *mainfn,
368
369
370
371
372
373
const unsigned char *tokenbuf,
const unsigned int bufsize,
const MOJOSHADER_swizzle *swiz,
const unsigned int swizcount,
const MOJOSHADER_samplerMap *smap,
const unsigned int smapcount)
374
{
375
376
377
MOJOSHADER_malloc m = ctx->malloc_fn;
MOJOSHADER_free f = ctx->free_fn;
void *d = ctx->malloc_data;
378
379
380
381
382
const MOJOSHADER_parseData *pd = MOJOSHADER_parse("metal", mainfn, tokenbuf,
bufsize, swiz, swizcount,
smap, smapcount, m, f, d);
if (pd->error_count > 0)
383
{
384
385
386
387
// !!! FIXME: put multiple errors in the buffer? Don't use
// !!! FIXME: MOJOSHADER_mtlGetError() for this?
set_error(pd->errors[0].error);
goto compile_shader_fail;
388
389
} // if
390
391
392
MOJOSHADER_mtlShader *retval = (MOJOSHADER_mtlShader *) m(sizeof(MOJOSHADER_mtlShader), d);
if (retval == NULL)
goto compile_shader_fail;
393
394
395
retval->parseData = pd;
retval->refcount = 1;
396
retval->handle = NULL; // populated by MOJOSHADER_mtlCompileLibrary
397
398
return retval;
399
400
401
402
403
404
compile_shader_fail:
MOJOSHADER_freeParseData(retval->parseData);
f(retval, d);
return NULL;
} // MOJOSHADER_mtlCompileShader
405
406
407
408
409
410
411
void MOJOSHADER_mtlShaderAddRef(MOJOSHADER_mtlShader *shader)
{
if (shader != NULL)
shader->refcount++;
} // MOJOSHADER_mtlShaderAddRef
412
413
414
415
416
417
418
const MOJOSHADER_parseData *MOJOSHADER_mtlGetShaderParseData(
MOJOSHADER_mtlShader *shader)
{
return (shader != NULL) ? shader->parseData : NULL;
} // MOJOSHADER_mtlGetParseData
419
420
421
422
423
424
425
426
void MOJOSHADER_mtlBindShaders(MOJOSHADER_mtlShader *vshader,
MOJOSHADER_mtlShader *pshader)
{
// Use the last bound shaders in case of NULL
if (vshader != NULL)
ctx->vertexShader = vshader;
427
428
429
430
if (pshader != NULL)
ctx->pixelShader = pshader;
} // MOJOSHADER_mtlBindShaders
431
432
433
434
void MOJOSHADER_mtlGetBoundShaders(MOJOSHADER_mtlShader **vshader,
MOJOSHADER_mtlShader **pshader)
435
{
436
437
438
*vshader = ctx->vertexShader;
*pshader = ctx->pixelShader;
} // MOJOSHADER_mtlGetBoundShaders
439
440
441
442
443
444
445
446
447
448
449
450
void MOJOSHADER_mtlMapUniformBufferMemory(float **vsf, int **vsi, unsigned char **vsb,
float **psf, int **psi, unsigned char **psb)
{
*vsf = ctx->vs_reg_file_f;
*vsi = ctx->vs_reg_file_i;
*vsb = ctx->vs_reg_file_b;
*psf = ctx->ps_reg_file_f;
*psi = ctx->ps_reg_file_i;
*psb = ctx->ps_reg_file_b;
} // MOJOSHADER_mtlMapUniformBufferMemory
451
452
453
void MOJOSHADER_mtlUnmapUniformBufferMemory()
454
{
455
456
457
458
459
460
461
/* This has nothing to do with unmapping memory
* and everything to do with updating uniform
* buffers with the latest parameter contents.
*/
update_uniform_buffer(ctx->vertexShader);
update_uniform_buffer(ctx->pixelShader);
} // MOJOSHADER_mtlUnmapUniformBufferMemory
462
463
464
void MOJOSHADER_mtlGetUniformData(void **buf, int *voff, int *poff)
465
{
466
467
468
*buf = ctx->ubo;
*voff = ctx->vertexUniformOffset;
*poff = ctx->pixelUniformOffset;
469
} // MOJOSHADER_mtlGetUniformBuffers
470
471
472
473
474
475
476
void *MOJOSHADER_mtlGetFunctionHandle(MOJOSHADER_mtlShader *shader)
{
if (shader == NULL)
return NULL;
477
return shader->handle;
478
479
} // MOJOSHADER_mtlGetFunctionHandle
480
481
482
void MOJOSHADER_mtlEndFrame()
{
483
484
485
ctx->totalUniformOffset = 0;
ctx->vertexUniformOffset = 0;
ctx->pixelUniformOffset = 0;
486
487
} // MOJOSHADER_mtlEndFrame
488
489
490
491
492
493
494
495
496
int MOJOSHADER_mtlGetVertexAttribLocation(MOJOSHADER_mtlShader *vert,
MOJOSHADER_usage usage, int index)
{
if (vert == NULL)
return -1;
for (int i = 0; i < vert->parseData->attribute_count; i++)
{
497
498
if (vert->parseData->attributes[i].usage == usage &&
vert->parseData->attributes[i].index == index)
499
500
501
502
503
504
505
506
507
{
return i;
} // if
} // for
// failure, couldn't find requested attribute
return -1;
} // MOJOSHADER_mtlGetVertexAttribLocation
508
509
510
511
512
513
const char *MOJOSHADER_mtlGetError(void)
{
return error_buffer;
} // MOJOSHADER_mtlGetError
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
void MOJOSHADER_mtlDeleteLibrary(void *library)
{
msg(library, ctx->selRelease);
} // MOJOSHADER_mtlDeleteLibrary
void MOJOSHADER_mtlDeleteShader(MOJOSHADER_mtlShader *shader)
{
if (shader != NULL)
{
if (shader->refcount > 1)
shader->refcount--;
else
{
msg(shader->handle, ctx->selRelease);
MOJOSHADER_freeParseData(shader->parseData);
ctx->free_fn(shader, ctx->malloc_data);
} // else
} // if
} // MOJOSHADER_mtlDeleteShader
void MOJOSHADER_mtlDestroyContext(MOJOSHADER_mtlContext *_ctx)
{
MOJOSHADER_mtlContext *current_ctx = ctx;
ctx = _ctx;
if (ctx->ubo != NULL)
msg(ctx->ubo, ctx->selRelease);
if (ctx != NULL)
ctx->free_fn(ctx, ctx->malloc_data);
ctx = ((current_ctx == _ctx) ? NULL : current_ctx);
} // MOJOSHADER_mtlDestroyContext
550
551
552
553
#endif /* MOJOSHADER_EFFECT_SUPPORT */
#endif /* SUPPORT_PROFILE_METAL && PLATFORM_APPLE */
// end of mojoshader_metal.c ...