-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMetalContext.mm
58 lines (48 loc) · 1.54 KB
/
MetalContext.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright 2014 Isis Innovation Limited and the authors of InfiniTAM
#import "MetalContext.h"
#import <Metal/Metal.h>
@implementation MetalContext
+(MetalContext*) instance
{
static MetalContext *gInstance = NULL;
@synchronized(self)
{
if (gInstance == NULL) gInstance = [[self alloc]initWithDevice:nil];
return gInstance;
}
}
+(int)roundUpTo16384:(int)size
{
float size_f = (float)size;
float size_div = size_f / 16384.0f;
float size_ceil = ceilf(size_div);
return (int)(size_ceil * 16384.0f);
}
- (instancetype)initWithDevice:(id<MTLDevice>)device
{
if ((self = [super init]))
{
_device = device ?: MTLCreateSystemDefaultDevice();
_library = [_device newDefaultLibrary];
_commandQueue = [_device newCommandQueue];
_commandBuffer = [_commandQueue commandBuffer];
}
return self;
}
@end
void allocateMetalData(void **data, void **metalBuffer, int size, bool roundUp)
{
int allocSize;
if (roundUp) allocSize = [MetalContext roundUpTo16384:size];
else allocSize = size;
data[0] = mmap(0, allocSize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
metalBuffer[0] = (void*)CFBridgingRetain(BUFFERNOCOPY(data[0], allocSize));
}
void freeMetalData(void **data, void **metalBuffer, int size, bool roundUp)
{
int allocSize;
if (roundUp) allocSize = [MetalContext roundUpTo16384:size];
else allocSize = size;
munmap(data[0], allocSize);
CFBridgingRelease(metalBuffer[0]);
}