src/render/metal/SDL_render_metal.m
changeset 11729 d1ce8396c356
child 11730 ac6c607e065c
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/render/metal/SDL_render_metal.m	Thu Apr 21 03:16:44 2016 -0400
     1.3 @@ -0,0 +1,760 @@
     1.4 +/*
     1.5 +  Simple DirectMedia Layer
     1.6 +  Copyright (C) 1997-2015 Sam Lantinga <slouken@libsdl.org>
     1.7 +
     1.8 +  This software is provided 'as-is', without any express or implied
     1.9 +  warranty.  In no event will the authors be held liable for any damages
    1.10 +  arising from the use of this software.
    1.11 +
    1.12 +  Permission is granted to anyone to use this software for any purpose,
    1.13 +  including commercial applications, and to alter it and redistribute it
    1.14 +  freely, subject to the following restrictions:
    1.15 +
    1.16 +  1. The origin of this software must not be misrepresented; you must not
    1.17 +     claim that you wrote the original software. If you use this software
    1.18 +     in a product, an acknowledgment in the product documentation would be
    1.19 +     appreciated but is not required.
    1.20 +  2. Altered source versions must be plainly marked as such, and must not be
    1.21 +     misrepresented as being the original software.
    1.22 +  3. This notice may not be removed or altered from any source distribution.
    1.23 +*/
    1.24 +#include "../../SDL_internal.h"
    1.25 +
    1.26 +#if SDL_VIDEO_RENDER_METAL && !SDL_RENDER_DISABLED
    1.27 +
    1.28 +#include "SDL_hints.h"
    1.29 +#include "SDL_log.h"
    1.30 +#include "SDL_assert.h"
    1.31 +#include "SDL_syswm.h"
    1.32 +#include "../SDL_sysrender.h"
    1.33 +
    1.34 +#include <Cocoa/Cocoa.h>
    1.35 +#include <Metal/Metal.h>
    1.36 +#include <QuartzCore/CAMetalLayer.h>
    1.37 +
    1.38 +// these are in SDL_shaders_metal.c, regenerate it with build-metal-shaders.sh
    1.39 +extern const unsigned char sdl_metallib[];
    1.40 +extern const unsigned int sdl_metallib_len;
    1.41 +
    1.42 +
    1.43 +/* Apple Metal renderer implementation */
    1.44 +
    1.45 +static SDL_Renderer *METAL_CreateRenderer(SDL_Window * window, Uint32 flags);
    1.46 +static void METAL_WindowEvent(SDL_Renderer * renderer,
    1.47 +                           const SDL_WindowEvent *event);
    1.48 +static int METAL_GetOutputSize(SDL_Renderer * renderer, int *w, int *h);
    1.49 +static int METAL_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture);
    1.50 +static int METAL_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
    1.51 +                            const SDL_Rect * rect, const void *pixels,
    1.52 +                            int pitch);
    1.53 +static int METAL_UpdateTextureYUV(SDL_Renderer * renderer, SDL_Texture * texture,
    1.54 +                               const SDL_Rect * rect,
    1.55 +                               const Uint8 *Yplane, int Ypitch,
    1.56 +                               const Uint8 *Uplane, int Upitch,
    1.57 +                               const Uint8 *Vplane, int Vpitch);
    1.58 +static int METAL_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture,
    1.59 +                          const SDL_Rect * rect, void **pixels, int *pitch);
    1.60 +static void METAL_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture);
    1.61 +static int METAL_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture);
    1.62 +static int METAL_UpdateViewport(SDL_Renderer * renderer);
    1.63 +static int METAL_UpdateClipRect(SDL_Renderer * renderer);
    1.64 +static int METAL_RenderClear(SDL_Renderer * renderer);
    1.65 +static int METAL_RenderDrawPoints(SDL_Renderer * renderer,
    1.66 +                               const SDL_FPoint * points, int count);
    1.67 +static int METAL_RenderDrawLines(SDL_Renderer * renderer,
    1.68 +                              const SDL_FPoint * points, int count);
    1.69 +static int METAL_RenderFillRects(SDL_Renderer * renderer,
    1.70 +                              const SDL_FRect * rects, int count);
    1.71 +static int METAL_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture,
    1.72 +                         const SDL_Rect * srcrect, const SDL_FRect * dstrect);
    1.73 +static int METAL_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
    1.74 +                         const SDL_Rect * srcrect, const SDL_FRect * dstrect,
    1.75 +                         const double angle, const SDL_FPoint *center, const SDL_RendererFlip flip);
    1.76 +static int METAL_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
    1.77 +                               Uint32 pixel_format, void * pixels, int pitch);
    1.78 +static void METAL_RenderPresent(SDL_Renderer * renderer);
    1.79 +static void METAL_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture);
    1.80 +static void METAL_DestroyRenderer(SDL_Renderer * renderer);
    1.81 +
    1.82 +SDL_RenderDriver METAL_RenderDriver = {
    1.83 +    METAL_CreateRenderer,
    1.84 +    {
    1.85 +     "metal",
    1.86 +     (SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE),
    1.87 +     2,
    1.88 +     {SDL_PIXELFORMAT_ARGB8888, SDL_PIXELFORMAT_ABGR8888},
    1.89 +     4096,  // !!! FIXME: how do you query Metal for this?
    1.90 +     4096}
    1.91 +};
    1.92 +
    1.93 +typedef struct METAL_BufferList
    1.94 +{
    1.95 +    id<MTLBuffer> mtlbuffer;
    1.96 +    struct METAL_BufferPool *next;
    1.97 +} METAL_BufferList;
    1.98 +
    1.99 +typedef struct
   1.100 +{
   1.101 +    id<MTLDevice> mtldevice;
   1.102 +    id<MTLCommandQueue> mtlcmdqueue;
   1.103 +    id<MTLCommandBuffer> mtlcmdbuffer;
   1.104 +    id<MTLRenderCommandEncoder> mtlcmdencoder;
   1.105 +    id<MTLLibrary> mtllibrary;
   1.106 +    id<CAMetalDrawable> mtlbackbuffer;
   1.107 +    id<MTLRenderPipelineState> mtlpipelineprims[4];
   1.108 +    id<MTLRenderPipelineState> mtlpipelinecopy[4];
   1.109 +    id<MTLBuffer> mtlbufclearverts;
   1.110 +    CAMetalLayer *mtllayer;
   1.111 +    MTLRenderPassDescriptor *mtlpassdesc;
   1.112 +} METAL_RenderData;
   1.113 +
   1.114 +
   1.115 +static int
   1.116 +IsMetalAvailable(const SDL_SysWMinfo *syswm)
   1.117 +{
   1.118 +    if (syswm->subsystem != SDL_SYSWM_COCOA) {  // !!! FIXME: SDL_SYSWM_UIKIT for iOS, too!
   1.119 +        return SDL_SetError("Metal render target only supports Cocoa video target at the moment.");
   1.120 +    }
   1.121 +
   1.122 +    // this checks a weak symbol.
   1.123 +#if MAC_OS_X_VERSION_MIN_REQUIRED < 101100
   1.124 +    if (MTLCreateSystemDefaultDevice == NULL) {  // probably on 10.10 or lower.
   1.125 +        return SDL_SetError("Metal framework not available on this system");
   1.126 +    }
   1.127 +#endif
   1.128 +
   1.129 +    return 0;
   1.130 +}
   1.131 +
   1.132 +static id<MTLRenderPipelineState>
   1.133 +MakePipelineState(METAL_RenderData *data, NSString *label, NSString *vertfn,
   1.134 +                  NSString *fragfn, const SDL_BlendMode blendmode)
   1.135 +{
   1.136 +    id<MTLFunction> mtlvertfn = [data->mtllibrary newFunctionWithName:vertfn];
   1.137 +    id<MTLFunction> mtlfragfn = [data->mtllibrary newFunctionWithName:fragfn];
   1.138 +    SDL_assert(mtlvertfn != nil);
   1.139 +    SDL_assert(mtlfragfn != nil);
   1.140 +
   1.141 +    MTLRenderPipelineDescriptor *mtlpipedesc = [[MTLRenderPipelineDescriptor alloc] init];
   1.142 +    mtlpipedesc.vertexFunction = mtlvertfn;
   1.143 +    mtlpipedesc.fragmentFunction = mtlfragfn;
   1.144 +    mtlpipedesc.colorAttachments[0].pixelFormat = data->mtlbackbuffer.texture.pixelFormat;
   1.145 +
   1.146 +    switch (blendmode) {
   1.147 +        case SDL_BLENDMODE_NONE:
   1.148 +            mtlpipedesc.colorAttachments[0].blendingEnabled = NO;
   1.149 +            break;
   1.150 +
   1.151 +        case SDL_BLENDMODE_BLEND:
   1.152 +            mtlpipedesc.colorAttachments[0].blendingEnabled = YES;
   1.153 +            mtlpipedesc.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
   1.154 +            mtlpipedesc.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
   1.155 +            mtlpipedesc.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
   1.156 +            mtlpipedesc.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
   1.157 +            mtlpipedesc.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne;
   1.158 +            mtlpipedesc.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
   1.159 +            break;
   1.160 +
   1.161 +        case SDL_BLENDMODE_ADD:
   1.162 +            mtlpipedesc.colorAttachments[0].blendingEnabled = YES;
   1.163 +            mtlpipedesc.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
   1.164 +            mtlpipedesc.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
   1.165 +            mtlpipedesc.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
   1.166 +            mtlpipedesc.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOne;
   1.167 +            mtlpipedesc.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorZero;
   1.168 +            mtlpipedesc.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOne;
   1.169 +            break;
   1.170 +
   1.171 +        case SDL_BLENDMODE_MOD:
   1.172 +            mtlpipedesc.colorAttachments[0].blendingEnabled = YES;
   1.173 +            mtlpipedesc.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
   1.174 +            mtlpipedesc.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
   1.175 +            mtlpipedesc.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorZero;
   1.176 +            mtlpipedesc.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorSourceColor;
   1.177 +            mtlpipedesc.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorZero;
   1.178 +            mtlpipedesc.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOne;
   1.179 +            break;
   1.180 +    }
   1.181 +
   1.182 +    mtlpipedesc.label = label;
   1.183 +
   1.184 +    NSError *err = nil;
   1.185 +    id<MTLRenderPipelineState> retval = [data->mtldevice newRenderPipelineStateWithDescriptor:mtlpipedesc error:&err];
   1.186 +    SDL_assert(err == nil);
   1.187 +    [mtlpipedesc release];  // !!! FIXME: can these be reused for each creation, or does the pipeline obtain it?
   1.188 +    [mtlvertfn release];
   1.189 +    [mtlfragfn release];
   1.190 +    [label release];
   1.191 +
   1.192 +    return retval;
   1.193 +}
   1.194 +
   1.195 +static void
   1.196 +MakePipelineStates(METAL_RenderData *data, id<MTLRenderPipelineState> *states,
   1.197 +                   NSString *label, NSString *vertfn, NSString *fragfn)
   1.198 +{
   1.199 +    int i = 0;
   1.200 +    states[i++] = MakePipelineState(data, [label stringByAppendingString:@" (blendmode=none)"], vertfn, fragfn, SDL_BLENDMODE_NONE);
   1.201 +    states[i++] = MakePipelineState(data, [label stringByAppendingString:@" (blendmode=blend)"], vertfn, fragfn, SDL_BLENDMODE_BLEND);
   1.202 +    states[i++] = MakePipelineState(data, [label stringByAppendingString:@" (blendmode=add)"], vertfn, fragfn, SDL_BLENDMODE_ADD);
   1.203 +    states[i++] = MakePipelineState(data, [label stringByAppendingString:@" (blendmode=mod)"], vertfn, fragfn, SDL_BLENDMODE_MOD);
   1.204 +}
   1.205 +
   1.206 +static inline id<MTLRenderPipelineState>
   1.207 +ChoosePipelineState(id<MTLRenderPipelineState> *states, const SDL_BlendMode blendmode)
   1.208 +{
   1.209 +    switch (blendmode) {
   1.210 +        case SDL_BLENDMODE_NONE: return states[0];
   1.211 +        case SDL_BLENDMODE_BLEND: return states[1];
   1.212 +        case SDL_BLENDMODE_ADD: return states[2];
   1.213 +        case SDL_BLENDMODE_MOD: return states[3];
   1.214 +    }
   1.215 +    return nil;
   1.216 +}
   1.217 +
   1.218 +static SDL_Renderer *
   1.219 +METAL_CreateRenderer(SDL_Window * window, Uint32 flags)
   1.220 +{
   1.221 +    SDL_Renderer *renderer = NULL;
   1.222 +    METAL_RenderData *data = NULL;
   1.223 +    SDL_SysWMinfo syswm;
   1.224 +
   1.225 +    SDL_VERSION(&syswm.version);
   1.226 +    if (!SDL_GetWindowWMInfo(window, &syswm)) {
   1.227 +        return NULL;
   1.228 +    }
   1.229 +
   1.230 +    if (IsMetalAvailable(&syswm) == -1) {
   1.231 +        return NULL;
   1.232 +    }
   1.233 +
   1.234 +    data = (METAL_RenderData *) SDL_calloc(1, sizeof(*data));
   1.235 +    if (!data) {
   1.236 +        SDL_OutOfMemory();
   1.237 +        return NULL;
   1.238 +    }
   1.239 +
   1.240 +    renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer));
   1.241 +    if (!renderer) {
   1.242 +        SDL_free(data);
   1.243 +        SDL_OutOfMemory();
   1.244 +        return NULL;
   1.245 +    }
   1.246 +
   1.247 +    renderer->driverdata = data;
   1.248 +    renderer->window = window;
   1.249 +
   1.250 +    data->mtldevice = MTLCreateSystemDefaultDevice();  // !!! FIXME: MTLCopyAllDevices() can find other GPUs...
   1.251 +    if (data->mtldevice == nil) {
   1.252 +        SDL_free(renderer);
   1.253 +        SDL_free(data);
   1.254 +        SDL_SetError("Failed to obtain Metal device");
   1.255 +        return NULL;
   1.256 +    }
   1.257 +
   1.258 +    // !!! FIXME: error checking on all of this.
   1.259 +
   1.260 +    NSView *nsview = [syswm.info.cocoa.window contentView];
   1.261 +
   1.262 +    // !!! FIXME: on iOS, we need to override +[UIView layerClass] to return [CAMetalLayer class] right from the start, and that's more complicated.
   1.263 +    CAMetalLayer *layer = [CAMetalLayer layer];
   1.264 +
   1.265 +    layer.device = data->mtldevice;
   1.266 +    //layer.pixelFormat = MTLPixelFormatBGRA8Unorm;  // !!! FIXME: MTLPixelFormatBGRA8Unorm_sRGB ?
   1.267 +    layer.framebufferOnly = YES;
   1.268 +    //layer.drawableSize = (CGSize) [nsview convertRectToBacking:[nsview bounds]].size;
   1.269 +    //layer.colorspace = nil;
   1.270 +
   1.271 +    [nsview setWantsLayer:YES];
   1.272 +    [nsview setLayer:layer];
   1.273 +
   1.274 +    [layer retain];
   1.275 +    data->mtllayer = layer;
   1.276 +    data->mtlcmdqueue = [data->mtldevice newCommandQueue];
   1.277 +    data->mtlcmdqueue.label = @"SDL Metal Renderer";
   1.278 +
   1.279 +    data->mtlpassdesc = [MTLRenderPassDescriptor renderPassDescriptor];  // !!! FIXME: is this autoreleased?
   1.280 +
   1.281 +    // we don't specify a depth or stencil buffer because the render API doesn't currently use them.
   1.282 +    MTLRenderPassColorAttachmentDescriptor *colorAttachment = data->mtlpassdesc.colorAttachments[0];
   1.283 +    data->mtlbackbuffer = [data->mtllayer nextDrawable];
   1.284 +    colorAttachment.texture = data->mtlbackbuffer.texture;
   1.285 +    colorAttachment.loadAction = MTLLoadActionClear;
   1.286 +    colorAttachment.clearColor = MTLClearColorMake(0.0f, 0.0f, 0.0f, 1.0f);
   1.287 +    data->mtlcmdbuffer = [data->mtlcmdqueue commandBuffer];
   1.288 +
   1.289 +    // Just push a clear to the screen to start so we're in a good state.
   1.290 +    data->mtlcmdencoder = [data->mtlcmdbuffer renderCommandEncoderWithDescriptor:data->mtlpassdesc];
   1.291 +    data->mtlcmdencoder.label = @"Initial drawable clear";
   1.292 +
   1.293 +    METAL_RenderPresent(renderer);
   1.294 +
   1.295 +    renderer->WindowEvent = METAL_WindowEvent;
   1.296 +    renderer->GetOutputSize = METAL_GetOutputSize;
   1.297 +    renderer->CreateTexture = METAL_CreateTexture;
   1.298 +    renderer->UpdateTexture = METAL_UpdateTexture;
   1.299 +    renderer->UpdateTextureYUV = METAL_UpdateTextureYUV;
   1.300 +    renderer->LockTexture = METAL_LockTexture;
   1.301 +    renderer->UnlockTexture = METAL_UnlockTexture;
   1.302 +    renderer->SetRenderTarget = METAL_SetRenderTarget;
   1.303 +    renderer->UpdateViewport = METAL_UpdateViewport;
   1.304 +    renderer->UpdateClipRect = METAL_UpdateClipRect;
   1.305 +    renderer->RenderClear = METAL_RenderClear;
   1.306 +    renderer->RenderDrawPoints = METAL_RenderDrawPoints;
   1.307 +    renderer->RenderDrawLines = METAL_RenderDrawLines;
   1.308 +    renderer->RenderFillRects = METAL_RenderFillRects;
   1.309 +    renderer->RenderCopy = METAL_RenderCopy;
   1.310 +    renderer->RenderCopyEx = METAL_RenderCopyEx;
   1.311 +    renderer->RenderReadPixels = METAL_RenderReadPixels;
   1.312 +    renderer->RenderPresent = METAL_RenderPresent;
   1.313 +    renderer->DestroyTexture = METAL_DestroyTexture;
   1.314 +    renderer->DestroyRenderer = METAL_DestroyRenderer;
   1.315 +
   1.316 +    renderer->info = METAL_RenderDriver.info;
   1.317 +    renderer->info.flags = (SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE);
   1.318 +
   1.319 +    // !!! FIXME: how do you control this in Metal?
   1.320 +    renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
   1.321 +
   1.322 +    NSError *err = nil;
   1.323 +
   1.324 +    // The compiled .metallib is embedded in a static array in SDL_shaders_metal.c,
   1.325 +    //  but the original shader source code is in SDL_shaders_metal.metal.
   1.326 +    dispatch_data_t mtllibdata = dispatch_data_create(sdl_metallib, sdl_metallib_len, dispatch_get_global_queue(0, 0), ^{});
   1.327 +    data->mtllibrary = [data->mtldevice newLibraryWithData:mtllibdata error:&err];
   1.328 +    SDL_assert(err == nil);
   1.329 +    dispatch_release(mtllibdata);
   1.330 +    data->mtllibrary.label = @"SDL Metal renderer shader library";
   1.331 +
   1.332 +    MakePipelineStates(data, data->mtlpipelineprims, @"SDL primitives pipeline", @"SDL_Simple_vertex", @"SDL_Simple_fragment");
   1.333 +    MakePipelineStates(data, data->mtlpipelinecopy, @"SDL_RenderCopy pipeline", @"SDL_Copy_vertex", @"SDL_Copy_fragment");
   1.334 +
   1.335 +    static const float clearverts[] = { -1, -1, -1, 1, 1, 1, 1, -1, -1, -1 };
   1.336 +    data->mtlbufclearverts = [data->mtldevice newBufferWithBytes:clearverts length:sizeof(clearverts) options:MTLResourceCPUCacheModeWriteCombined|MTLResourceStorageModePrivate];
   1.337 +    data->mtlbufclearverts.label = @"SDL_RenderClear vertices";
   1.338 +
   1.339 +    // !!! FIXME: force more clears here so all the drawables are sane to start, and our static buffers are definitely flushed.
   1.340 +
   1.341 +    return renderer;
   1.342 +}
   1.343 +
   1.344 +static void
   1.345 +METAL_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event)
   1.346 +{
   1.347 +    if (event->event == SDL_WINDOWEVENT_SIZE_CHANGED ||
   1.348 +        event->event == SDL_WINDOWEVENT_SHOWN ||
   1.349 +        event->event == SDL_WINDOWEVENT_HIDDEN) {
   1.350 +        // !!! FIXME: write me
   1.351 +    }
   1.352 +}
   1.353 +
   1.354 +static int
   1.355 +METAL_GetOutputSize(SDL_Renderer * renderer, int *w, int *h)
   1.356 +{
   1.357 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.358 +    *w = (int) data->mtlbackbuffer.texture.width;
   1.359 +    *h = (int) data->mtlbackbuffer.texture.height;
   1.360 +    return 0;
   1.361 +}
   1.362 +
   1.363 +static int
   1.364 +METAL_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
   1.365 +{
   1.366 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.367 +    MTLPixelFormat mtlpixfmt;
   1.368 +
   1.369 +    switch (texture->format) {
   1.370 +        case SDL_PIXELFORMAT_ABGR8888: mtlpixfmt = MTLPixelFormatRGBA8Unorm; break;
   1.371 +        case SDL_PIXELFORMAT_ARGB8888: mtlpixfmt = MTLPixelFormatBGRA8Unorm; break;
   1.372 +        default: return SDL_SetError("Texture format %s not supported by Metal", SDL_GetPixelFormatName(texture->format));
   1.373 +    }
   1.374 +
   1.375 +    // !!! FIXME: autorelease or nah?
   1.376 +    MTLTextureDescriptor *mtltexdesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:mtlpixfmt
   1.377 +                                            width:(NSUInteger)texture->w height:(NSUInteger)texture->h mipmapped:NO];
   1.378 +
   1.379 +    id<MTLTexture> mtltexture = [data->mtldevice newTextureWithDescriptor:mtltexdesc];
   1.380 +    [mtltexdesc release];
   1.381 +    if (mtltexture == nil) {
   1.382 +        return SDL_SetError("Texture allocation failed");
   1.383 +    }
   1.384 +
   1.385 +    texture->driverdata = mtltexture;
   1.386 +
   1.387 +    return 0;
   1.388 +}
   1.389 +
   1.390 +static int
   1.391 +METAL_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
   1.392 +                 const SDL_Rect * rect, const void *pixels, int pitch)
   1.393 +{
   1.394 +    // !!! FIXME: this is a synchronous call; it doesn't return until data is uploaded in some form.
   1.395 +    // !!! FIXME:  Maybe move this off to a thread that marks the texture as uploaded and only stall the main thread if we try to
   1.396 +    // !!! FIXME:  use this texture before the marking is done? Is it worth it? Or will we basically always be uploading a bunch of
   1.397 +    // !!! FIXME:  stuff way ahead of time and/or using it immediately after upload?
   1.398 +    id<MTLTexture> mtltexture = (id<MTLTexture>) texture->driverdata;
   1.399 +    [mtltexture replaceRegion:MTLRegionMake2D(rect->x, rect->y, rect->w, rect->h) mipmapLevel:0 withBytes:pixels bytesPerRow:pitch];
   1.400 +    return 0;
   1.401 +}
   1.402 +
   1.403 +static int
   1.404 +METAL_UpdateTextureYUV(SDL_Renderer * renderer, SDL_Texture * texture,
   1.405 +                    const SDL_Rect * rect,
   1.406 +                    const Uint8 *Yplane, int Ypitch,
   1.407 +                    const Uint8 *Uplane, int Upitch,
   1.408 +                    const Uint8 *Vplane, int Vpitch)
   1.409 +{
   1.410 +    return SDL_Unsupported();  // !!! FIXME
   1.411 +}
   1.412 +
   1.413 +static int
   1.414 +METAL_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture,
   1.415 +               const SDL_Rect * rect, void **pixels, int *pitch)
   1.416 +{
   1.417 +    return SDL_Unsupported();   // !!! FIXME: write me
   1.418 +}
   1.419 +
   1.420 +static void
   1.421 +METAL_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture)
   1.422 +{
   1.423 +    // !!! FIXME: write me
   1.424 +}
   1.425 +
   1.426 +static int
   1.427 +METAL_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture)
   1.428 +{
   1.429 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.430 +    id<MTLTexture> mtltexture = texture ? (id<MTLTexture>) texture->driverdata : nil;
   1.431 +    data->mtlpassdesc.colorAttachments[0].texture = mtltexture;
   1.432 +    return 0;
   1.433 +}
   1.434 +
   1.435 +static int
   1.436 +METAL_UpdateViewport(SDL_Renderer * renderer)
   1.437 +{
   1.438 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.439 +    if (data->mtlcmdencoder != nil) {
   1.440 +        MTLViewport viewport;
   1.441 +        viewport.originX = renderer->viewport.x;
   1.442 +        viewport.originY = renderer->viewport.y;
   1.443 +        viewport.width = renderer->viewport.w;
   1.444 +        viewport.height = renderer->viewport.h;
   1.445 +        viewport.znear = 0.0;
   1.446 +        viewport.zfar = 1.0;
   1.447 +        [data->mtlcmdencoder setViewport:viewport];
   1.448 +    }
   1.449 +    return 0;
   1.450 +}
   1.451 +
   1.452 +static int
   1.453 +METAL_UpdateClipRect(SDL_Renderer * renderer)
   1.454 +{
   1.455 +    // !!! FIXME: should this care about the viewport?
   1.456 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.457 +    if (data->mtlcmdencoder != nil) {
   1.458 +        MTLScissorRect mtlrect;
   1.459 +        if (renderer->clipping_enabled) {
   1.460 +            const SDL_Rect *rect = &renderer->clip_rect;
   1.461 +            mtlrect.x = renderer->viewport.x + rect->x;
   1.462 +            mtlrect.y = renderer->viewport.x + rect->y;
   1.463 +            mtlrect.width = rect->w;
   1.464 +            mtlrect.height = rect->h;
   1.465 +        } else {
   1.466 +            mtlrect.x = renderer->viewport.x;
   1.467 +            mtlrect.y = renderer->viewport.y;
   1.468 +            mtlrect.width = renderer->viewport.w;
   1.469 +            mtlrect.height = renderer->viewport.h;
   1.470 +        }
   1.471 +        [data->mtlcmdencoder setScissorRect:mtlrect];
   1.472 +    }
   1.473 +    return 0;
   1.474 +}
   1.475 +
   1.476 +static int
   1.477 +METAL_RenderClear(SDL_Renderer * renderer)
   1.478 +{
   1.479 +    // We could dump the command buffer and force a clear on a new one, but this will respect the scissor state.
   1.480 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.481 +
   1.482 +    // !!! FIXME: render color should live in a dedicated uniform buffer.
   1.483 +    const float color[4] = { ((float)renderer->r) / 255.0f, ((float)renderer->g) / 255.0f, ((float)renderer->b) / 255.0f, ((float)renderer->a) / 255.0f };
   1.484 +
   1.485 +    MTLViewport viewport;  // RenderClear ignores the viewport state, though, so reset that.
   1.486 +    viewport.originX = viewport.originY = 0.0;
   1.487 +    viewport.width = data->mtlbackbuffer.texture.width;
   1.488 +    viewport.height = data->mtlbackbuffer.texture.height;
   1.489 +    viewport.znear = 0.0;
   1.490 +    viewport.zfar = 1.0;
   1.491 +
   1.492 +    // Draw as if we're doing a simple filled rect to the screen now.
   1.493 +    [data->mtlcmdencoder setViewport:viewport];
   1.494 +    [data->mtlcmdencoder setRenderPipelineState:ChoosePipelineState(data->mtlpipelineprims, renderer->blendMode)];
   1.495 +    [data->mtlcmdencoder setVertexBuffer:data->mtlbufclearverts offset:0 atIndex:0];
   1.496 +    [data->mtlcmdencoder setFragmentBytes:color length:sizeof(color) atIndex:0];
   1.497 +    [data->mtlcmdencoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:5];
   1.498 +
   1.499 +    // reset the viewport for the rest of our usual drawing work...
   1.500 +    viewport.originX = renderer->viewport.x;
   1.501 +    viewport.originY = renderer->viewport.y;
   1.502 +    viewport.width = renderer->viewport.w;
   1.503 +    viewport.height = renderer->viewport.h;
   1.504 +    viewport.znear = 0.0;
   1.505 +    viewport.zfar = 1.0;
   1.506 +    [data->mtlcmdencoder setViewport:viewport];
   1.507 +
   1.508 +    return 0;
   1.509 +}
   1.510 +
   1.511 +// normalize a value from 0.0f to len into -1.0f to 1.0f.
   1.512 +static inline float
   1.513 +norm(const float _val, const float len)
   1.514 +{
   1.515 +    const float val = (_val < 0.0f) ? 0.0f : (_val > len) ? len : _val;
   1.516 +    return ((val / len) * 2.0f) - 1.0f;  // !!! FIXME: is this right?
   1.517 +}
   1.518 +
   1.519 +// normalize a value from 0.0f to len into -1.0f to 1.0f.
   1.520 +static inline float
   1.521 +normy(const float _val, const float len)
   1.522 +{
   1.523 +    return norm(len - ((_val < 0.0f) ? 0.0f : (_val > len) ? len : _val), len);
   1.524 +}
   1.525 +
   1.526 +// normalize a value from 0.0f to len into 0.0f to 1.0f.
   1.527 +static inline float
   1.528 +normtex(const float _val, const float len)
   1.529 +{
   1.530 +    const float val = (_val < 0.0f) ? 0.0f : (_val > len) ? len : _val;
   1.531 +    return (val / len);
   1.532 +}
   1.533 +
   1.534 +static int
   1.535 +DrawVerts(SDL_Renderer * renderer, const SDL_FPoint * points, int count,
   1.536 +          const MTLPrimitiveType primtype)
   1.537 +{
   1.538 +    const size_t vertlen = (sizeof (float) * 2) * count;
   1.539 +    float *verts = SDL_malloc(vertlen);
   1.540 +    if (!verts) {
   1.541 +        return SDL_OutOfMemory();
   1.542 +    }
   1.543 +
   1.544 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.545 +
   1.546 +    // !!! FIXME: render color should live in a dedicated uniform buffer.
   1.547 +    const float color[4] = { ((float)renderer->r) / 255.0f, ((float)renderer->g) / 255.0f, ((float)renderer->b) / 255.0f, ((float)renderer->a) / 255.0f };
   1.548 +
   1.549 +    [data->mtlcmdencoder setRenderPipelineState:ChoosePipelineState(data->mtlpipelineprims, renderer->blendMode)];
   1.550 +    [data->mtlcmdencoder setFragmentBytes:color length:sizeof(color) atIndex:0];
   1.551 +
   1.552 +    const float w = (float) data->mtlpassdesc.colorAttachments[0].texture.width;
   1.553 +    const float h = (float) data->mtlpassdesc.colorAttachments[0].texture.height;
   1.554 +
   1.555 +    // !!! FIXME: we can convert this in the shader. This will save the malloc and for-loop, but we still need to upload.
   1.556 +    float *ptr = verts;
   1.557 +    for (int i = 0; i < count; i++, points++) {
   1.558 +        *ptr = norm(points->x, w); ptr++;
   1.559 +        *ptr = normy(points->y, h); ptr++;
   1.560 +    }
   1.561 +
   1.562 +    [data->mtlcmdencoder setVertexBytes:verts length:vertlen atIndex:0];
   1.563 +    [data->mtlcmdencoder drawPrimitives:primtype vertexStart:0 vertexCount:count];
   1.564 +
   1.565 +    SDL_free(verts);
   1.566 +    return 0;
   1.567 +}
   1.568 +
   1.569 +static int
   1.570 +METAL_RenderDrawPoints(SDL_Renderer * renderer, const SDL_FPoint * points, int count)
   1.571 +{
   1.572 +    return DrawVerts(renderer, points, count, MTLPrimitiveTypePoint);
   1.573 +}
   1.574 +
   1.575 +static int
   1.576 +METAL_RenderDrawLines(SDL_Renderer * renderer, const SDL_FPoint * points, int count)
   1.577 +{
   1.578 +    return DrawVerts(renderer, points, count, MTLPrimitiveTypeLineStrip);
   1.579 +}
   1.580 +
   1.581 +static int
   1.582 +METAL_RenderFillRects(SDL_Renderer * renderer, const SDL_FRect * rects, int count)
   1.583 +{
   1.584 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.585 +
   1.586 +    // !!! FIXME: render color should live in a dedicated uniform buffer.
   1.587 +    const float color[4] = { ((float)renderer->r) / 255.0f, ((float)renderer->g) / 255.0f, ((float)renderer->b) / 255.0f, ((float)renderer->a) / 255.0f };
   1.588 +
   1.589 +    [data->mtlcmdencoder setRenderPipelineState:ChoosePipelineState(data->mtlpipelineprims, renderer->blendMode)];
   1.590 +    [data->mtlcmdencoder setFragmentBytes:color length:sizeof(color) atIndex:0];
   1.591 +
   1.592 +    const float w = (float) data->mtlpassdesc.colorAttachments[0].texture.width;
   1.593 +    const float h = (float) data->mtlpassdesc.colorAttachments[0].texture.height;
   1.594 +
   1.595 +    for (int i = 0; i < count; i++, rects++) {
   1.596 +        if ((rects->w <= 0.0f) || (rects->h <= 0.0f)) continue;
   1.597 +
   1.598 +        const float verts[] = {
   1.599 +            norm(rects->x, w), normy(rects->y + rects->h, h),
   1.600 +            norm(rects->x, w), normy(rects->y, h),
   1.601 +            norm(rects->x + rects->w, w), normy(rects->y, h),
   1.602 +            norm(rects->x, w), normy(rects->y + rects->h, h),
   1.603 +            norm(rects->x + rects->w, w), normy(rects->y + rects->h, h)
   1.604 +        };
   1.605 +
   1.606 +        [data->mtlcmdencoder setVertexBytes:verts length:sizeof(verts) atIndex:0];
   1.607 +        [data->mtlcmdencoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:5];
   1.608 +    }
   1.609 +
   1.610 +    return 0;
   1.611 +}
   1.612 +
   1.613 +static int
   1.614 +METAL_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture,
   1.615 +              const SDL_Rect * srcrect, const SDL_FRect * dstrect)
   1.616 +{
   1.617 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.618 +    id<MTLTexture> mtltexture = (id<MTLTexture>) texture->driverdata;
   1.619 +    const float w = (float) data->mtlpassdesc.colorAttachments[0].texture.width;
   1.620 +    const float h = (float) data->mtlpassdesc.colorAttachments[0].texture.height;
   1.621 +    const float texw = (float) mtltexture.width;
   1.622 +    const float texh = (float) mtltexture.height;
   1.623 +
   1.624 +    const float xy[] = {
   1.625 +        norm(dstrect->x, w), normy(dstrect->y + dstrect->h, h),
   1.626 +        norm(dstrect->x, w), normy(dstrect->y, h),
   1.627 +        norm(dstrect->x + dstrect->w, w), normy(dstrect->y, h),
   1.628 +        norm(dstrect->x, w), normy(dstrect->y + dstrect->h, h),
   1.629 +        norm(dstrect->x + dstrect->w, w), normy(dstrect->y + dstrect->h, h)
   1.630 +    };
   1.631 +
   1.632 +    const float uv[] = {
   1.633 +        normtex(srcrect->x, texw), normtex(srcrect->y + srcrect->h, texh),
   1.634 +        normtex(srcrect->x, texw), normtex(srcrect->y, texh),
   1.635 +        normtex(srcrect->x + srcrect->w, texw), normtex(srcrect->y, texh),
   1.636 +        normtex(srcrect->x, texw), normtex(srcrect->y + srcrect->h, texh),
   1.637 +        normtex(srcrect->x + srcrect->w, texw), normtex(srcrect->y + srcrect->h, texh)
   1.638 +    };
   1.639 +
   1.640 +    float color[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
   1.641 +    if (texture->modMode) {
   1.642 +        color[0] = ((float)texture->r) / 255.0f;
   1.643 +        color[1] = ((float)texture->g) / 255.0f;
   1.644 +        color[2] = ((float)texture->b) / 255.0f;
   1.645 +        color[3] = ((float)texture->a) / 255.0f;
   1.646 +    }
   1.647 +
   1.648 +    [data->mtlcmdencoder setRenderPipelineState:ChoosePipelineState(data->mtlpipelinecopy, texture->blendMode)];
   1.649 +    [data->mtlcmdencoder setFragmentBytes:color length:sizeof(color) atIndex:0];
   1.650 +    [data->mtlcmdencoder setFragmentTexture:mtltexture atIndex:0];
   1.651 +    [data->mtlcmdencoder setVertexBytes:xy length:sizeof(xy) atIndex:0];
   1.652 +    [data->mtlcmdencoder setVertexBytes:uv length:sizeof(uv) atIndex:1];
   1.653 +    [data->mtlcmdencoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:5];
   1.654 +
   1.655 +    return 0;
   1.656 +}
   1.657 +
   1.658 +static int
   1.659 +METAL_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
   1.660 +              const SDL_Rect * srcrect, const SDL_FRect * dstrect,
   1.661 +              const double angle, const SDL_FPoint *center, const SDL_RendererFlip flip)
   1.662 +{
   1.663 +    return SDL_Unsupported();  // !!! FIXME
   1.664 +}
   1.665 +
   1.666 +static int
   1.667 +METAL_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
   1.668 +                    Uint32 pixel_format, void * pixels, int pitch)
   1.669 +{
   1.670 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.671 +    MTLRenderPassColorAttachmentDescriptor *colorAttachment = data->mtlpassdesc.colorAttachments[0];
   1.672 +    id<MTLTexture> mtltexture = colorAttachment.texture;
   1.673 +    MTLRegion mtlregion;
   1.674 +
   1.675 +    mtlregion.origin.x = rect->x;
   1.676 +    mtlregion.origin.y = rect->y;
   1.677 +    mtlregion.origin.z = 0;
   1.678 +    mtlregion.size.width = rect->w;
   1.679 +    mtlregion.size.height = rect->w;
   1.680 +    mtlregion.size.depth = 1;
   1.681 +
   1.682 +    // we only do BGRA8 or RGBA8 at the moment, so 4 will do.
   1.683 +    const int temp_pitch = rect->w * 4;
   1.684 +    void *temp_pixels = SDL_malloc(temp_pitch * rect->h);
   1.685 +    if (!temp_pixels) {
   1.686 +        return SDL_OutOfMemory();
   1.687 +    }
   1.688 +
   1.689 +    [mtltexture getBytes:temp_pixels bytesPerRow:temp_pitch fromRegion:mtlregion mipmapLevel:0];
   1.690 +
   1.691 +    const Uint32 temp_format = (mtltexture.pixelFormat == MTLPixelFormatBGRA8Unorm) ? SDL_PIXELFORMAT_ARGB8888 : SDL_PIXELFORMAT_ABGR8888;
   1.692 +    const int status = SDL_ConvertPixels(rect->w, rect->h, temp_format, temp_pixels, temp_pitch, pixel_format, pixels, pitch);
   1.693 +    SDL_free(temp_pixels);
   1.694 +    return status;
   1.695 +}
   1.696 +
   1.697 +static void
   1.698 +METAL_RenderPresent(SDL_Renderer * renderer)
   1.699 +{
   1.700 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.701 +    MTLRenderPassColorAttachmentDescriptor *colorAttachment = data->mtlpassdesc.colorAttachments[0];
   1.702 +    id<CAMetalDrawable> mtlbackbuffer = data->mtlbackbuffer;
   1.703 +
   1.704 +    [data->mtlcmdencoder endEncoding];
   1.705 +    [data->mtlcmdbuffer presentDrawable:mtlbackbuffer];
   1.706 +
   1.707 +    [data->mtlcmdbuffer addCompletedHandler:^(id <MTLCommandBuffer> mtlcmdbuffer){
   1.708 +        [mtlbackbuffer release];
   1.709 +    }];
   1.710 +
   1.711 +    [data->mtlcmdbuffer commit];
   1.712 +
   1.713 +    // Start next frame, once we can.
   1.714 +    // we don't specify a depth or stencil buffer because the render API doesn't currently use them.
   1.715 +    data->mtlbackbuffer = [data->mtllayer nextDrawable];
   1.716 +    SDL_assert(data->mtlbackbuffer);
   1.717 +    colorAttachment.texture = data->mtlbackbuffer.texture;
   1.718 +    colorAttachment.loadAction = MTLLoadActionDontCare;
   1.719 +    data->mtlcmdbuffer = [data->mtlcmdqueue commandBuffer];
   1.720 +    data->mtlcmdencoder = [data->mtlcmdbuffer renderCommandEncoderWithDescriptor:data->mtlpassdesc];
   1.721 +    data->mtlcmdencoder.label = @"SDL metal renderer frame";
   1.722 +
   1.723 +    // Set up our current renderer state for the next frame...
   1.724 +    METAL_UpdateViewport(renderer);
   1.725 +    METAL_UpdateClipRect(renderer);
   1.726 +}
   1.727 +
   1.728 +static void
   1.729 +METAL_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture)
   1.730 +{
   1.731 +    id<MTLTexture> mtltexture = (id<MTLTexture>) texture->driverdata;
   1.732 +    [mtltexture release];
   1.733 +    texture->driverdata = NULL;
   1.734 +}
   1.735 +
   1.736 +static void
   1.737 +METAL_DestroyRenderer(SDL_Renderer * renderer)
   1.738 +{
   1.739 +    METAL_RenderData *data = (METAL_RenderData *) renderer->driverdata;
   1.740 +
   1.741 +    if (data) {
   1.742 +        int i;
   1.743 +        [data->mtlcmdencoder endEncoding];
   1.744 +        [data->mtlcmdencoder release];
   1.745 +        [data->mtlcmdbuffer release];
   1.746 +        [data->mtlcmdqueue release];
   1.747 +        for (i = 0; i < 4; i++) {
   1.748 +            [data->mtlpipelineprims[i] release];
   1.749 +            [data->mtlpipelinecopy[i] release];
   1.750 +        }
   1.751 +        [data->mtlbufclearverts release];
   1.752 +        [data->mtllibrary release];
   1.753 +        [data->mtldevice release];
   1.754 +        [data->mtlpassdesc release];
   1.755 +        [data->mtllayer release];
   1.756 +        SDL_free(data);
   1.757 +    }
   1.758 +    SDL_free(renderer);
   1.759 +}
   1.760 +
   1.761 +#endif /* SDL_VIDEO_RENDER_METAL && !SDL_RENDER_DISABLED */
   1.762 +
   1.763 +/* vi: set ts=4 sw=4 expandtab: */