Skip to content

Commit

Permalink
metal: check success of device creation (libsdl-org#11367)
Browse files Browse the repository at this point in the history
When macOS runs under a virtual environment, it is possible that
MTLCreateSystemDefaultDevice() does not succeed.
Not checking this failure results in a crash down the road.
This change allows to skip GPU renderer and use an adequate fallback.

Co-authored-by: D.musique <d-musique@users.noreply.github.com>
  • Loading branch information
d-musique and d-musique authored Oct 29, 2024
1 parent feb1043 commit 35e53f7
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions src/gpu/metal/SDL_gpu_metal.m
Original file line number Diff line number Diff line change
Expand Up @@ -4166,33 +4166,40 @@ static void METAL_INTERNAL_DestroyBlitResources(
{
@autoreleasepool {
MetalRenderer *renderer;

// Allocate and zero out the renderer
renderer = (MetalRenderer *)SDL_calloc(1, sizeof(MetalRenderer));
id<MTLDevice> device = NULL;

// Create the Metal device and command queue
#ifdef SDL_PLATFORM_MACOS
if (preferLowPower) {
NSArray<id<MTLDevice>> *devices = MTLCopyAllDevices();
for (id<MTLDevice> device in devices) {
if (device.isLowPower) {
renderer->device = device;
for (id<MTLDevice> candidate in devices) {
if (candidate.isLowPower) {
device = candidate;
break;
}
}
}
#endif
if (renderer->device == NULL) {
renderer->device = MTLCreateSystemDefaultDevice();
if (device == NULL) {
device = MTLCreateSystemDefaultDevice();
if (device == NULL) {
SDL_SetError("Failed to create Metal device");
return NULL;
}
}
renderer->queue = [renderer->device newCommandQueue];

// Allocate and zero out the renderer
renderer = (MetalRenderer *)SDL_calloc(1, sizeof(MetalRenderer));

renderer->device = device;
renderer->queue = [device newCommandQueue];

// Print driver info
SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "SDL_GPU Driver: Metal");
SDL_LogInfo(
SDL_LOG_CATEGORY_GPU,
"Metal Device: %s",
[renderer->device.name UTF8String]);
[device.name UTF8String]);

// Remember debug mode
renderer->debugMode = debugMode;
Expand Down

0 comments on commit 35e53f7

Please sign in to comment.