SDL_render_metal.m 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #if defined(SDL_VIDEO_RENDER_METAL) && !defined(SDL_RENDER_DISABLED)
  20. #include "../SDL_sysrender.h"
  21. #include <Availability.h>
  22. #import <Metal/Metal.h>
  23. #import <QuartzCore/CAMetalLayer.h>
  24. #ifdef SDL_VIDEO_DRIVER_COCOA
  25. #import <AppKit/NSWindow.h>
  26. #import <AppKit/NSView.h>
  27. #endif
  28. #ifdef SDL_VIDEO_DRIVER_UIKIT
  29. #import <UIKit/UIKit.h>
  30. #endif
  31. /* Regenerate these with build-metal-shaders.sh */
  32. #ifdef __MACOS__
  33. #include "SDL_shaders_metal_macos.h"
  34. #elif defined(__TVOS__)
  35. #if TARGET_OS_SIMULATOR
  36. #include "SDL_shaders_metal_tvsimulator.h"
  37. #else
  38. #include "SDL_shaders_metal_tvos.h"
  39. #endif
  40. #else
  41. #if TARGET_OS_SIMULATOR
  42. #include "SDL_shaders_metal_iphonesimulator.h"
  43. #else
  44. #include "SDL_shaders_metal_ios.h"
  45. #endif
  46. #endif
  47. /* Apple Metal renderer implementation */
  48. /* macOS requires constants in a buffer to have a 256 byte alignment. */
  49. /* Use native type alignments from https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf */
  50. #if defined(__MACOS__) || TARGET_OS_SIMULATOR || TARGET_OS_MACCATALYST
  51. #define CONSTANT_ALIGN(x) (256)
  52. #else
  53. #define CONSTANT_ALIGN(x) (x < 4 ? 4 : x)
  54. #endif
  55. #define DEVICE_ALIGN(x) (x < 4 ? 4 : x)
  56. #define ALIGN_CONSTANTS(align, size) ((size + CONSTANT_ALIGN(align) - 1) & (~(CONSTANT_ALIGN(align) - 1)))
  57. static const size_t CONSTANTS_OFFSET_INVALID = 0xFFFFFFFF;
  58. static const size_t CONSTANTS_OFFSET_IDENTITY = 0;
  59. static const size_t CONSTANTS_OFFSET_HALF_PIXEL_TRANSFORM = ALIGN_CONSTANTS(16, CONSTANTS_OFFSET_IDENTITY + sizeof(float) * 16);
  60. static const size_t CONSTANTS_OFFSET_DECODE_JPEG = ALIGN_CONSTANTS(16, CONSTANTS_OFFSET_HALF_PIXEL_TRANSFORM + sizeof(float) * 16);
  61. static const size_t CONSTANTS_OFFSET_DECODE_BT601 = ALIGN_CONSTANTS(16, CONSTANTS_OFFSET_DECODE_JPEG + sizeof(float) * 4 * 4);
  62. static const size_t CONSTANTS_OFFSET_DECODE_BT709 = ALIGN_CONSTANTS(16, CONSTANTS_OFFSET_DECODE_BT601 + sizeof(float) * 4 * 4);
  63. static const size_t CONSTANTS_LENGTH = CONSTANTS_OFFSET_DECODE_BT709 + sizeof(float) * 4 * 4;
  64. typedef enum SDL_MetalVertexFunction
  65. {
  66. SDL_METAL_VERTEX_SOLID,
  67. SDL_METAL_VERTEX_COPY,
  68. } SDL_MetalVertexFunction;
  69. typedef enum SDL_MetalFragmentFunction
  70. {
  71. SDL_METAL_FRAGMENT_SOLID = 0,
  72. SDL_METAL_FRAGMENT_COPY,
  73. SDL_METAL_FRAGMENT_YUV,
  74. SDL_METAL_FRAGMENT_NV12,
  75. SDL_METAL_FRAGMENT_NV21,
  76. SDL_METAL_FRAGMENT_COUNT,
  77. } SDL_MetalFragmentFunction;
  78. typedef struct METAL_PipelineState
  79. {
  80. SDL_BlendMode blendMode;
  81. void *pipe;
  82. } METAL_PipelineState;
  83. typedef struct METAL_PipelineCache
  84. {
  85. METAL_PipelineState *states;
  86. int count;
  87. SDL_MetalVertexFunction vertexFunction;
  88. SDL_MetalFragmentFunction fragmentFunction;
  89. MTLPixelFormat renderTargetFormat;
  90. const char *label;
  91. } METAL_PipelineCache;
  92. /* Each shader combination used by drawing functions has a separate pipeline
  93. * cache, and we have a separate list of caches for each render target pixel
  94. * format. This is more efficient than iterating over a global cache to find
  95. * the pipeline based on the specified shader combination and RT pixel format,
  96. * since we know what the RT pixel format is when we set the render target, and
  97. * we know what the shader combination is inside each drawing function's code. */
  98. typedef struct METAL_ShaderPipelines
  99. {
  100. MTLPixelFormat renderTargetFormat;
  101. METAL_PipelineCache caches[SDL_METAL_FRAGMENT_COUNT];
  102. } METAL_ShaderPipelines;
  103. @interface METAL_RenderData : NSObject
  104. @property(nonatomic, retain) id<MTLDevice> mtldevice;
  105. @property(nonatomic, retain) id<MTLCommandQueue> mtlcmdqueue;
  106. @property(nonatomic, retain) id<MTLCommandBuffer> mtlcmdbuffer;
  107. @property(nonatomic, retain) id<MTLRenderCommandEncoder> mtlcmdencoder;
  108. @property(nonatomic, retain) id<MTLLibrary> mtllibrary;
  109. @property(nonatomic, retain) id<CAMetalDrawable> mtlbackbuffer;
  110. @property(nonatomic, retain) id<MTLSamplerState> mtlsamplernearest;
  111. @property(nonatomic, retain) id<MTLSamplerState> mtlsamplerlinear;
  112. @property(nonatomic, retain) id<MTLBuffer> mtlbufconstants;
  113. @property(nonatomic, retain) id<MTLBuffer> mtlbufquadindices;
  114. @property(nonatomic, assign) SDL_MetalView mtlview;
  115. @property(nonatomic, retain) CAMetalLayer *mtllayer;
  116. @property(nonatomic, retain) MTLRenderPassDescriptor *mtlpassdesc;
  117. @property(nonatomic, assign) METAL_ShaderPipelines *activepipelines;
  118. @property(nonatomic, assign) METAL_ShaderPipelines *allpipelines;
  119. @property(nonatomic, assign) int pipelinescount;
  120. @end
  121. @implementation METAL_RenderData
  122. @end
  123. @interface METAL_TextureData : NSObject
  124. @property(nonatomic, retain) id<MTLTexture> mtltexture;
  125. @property(nonatomic, retain) id<MTLTexture> mtltextureUv;
  126. @property(nonatomic, retain) id<MTLSamplerState> mtlsampler;
  127. @property(nonatomic, assign) SDL_MetalFragmentFunction fragmentFunction;
  128. #if SDL_HAVE_YUV
  129. @property(nonatomic, assign) BOOL yuv;
  130. @property(nonatomic, assign) BOOL nv12;
  131. @property(nonatomic, assign) size_t conversionBufferOffset;
  132. #endif
  133. @property(nonatomic, assign) BOOL hasdata;
  134. @property(nonatomic, retain) id<MTLBuffer> lockedbuffer;
  135. @property(nonatomic, assign) SDL_Rect lockedrect;
  136. @end
  137. @implementation METAL_TextureData
  138. @end
  139. static SDL_bool IsMetalAvailable()
  140. {
  141. #if (defined(__MACOS__) && (MAC_OS_X_VERSION_MIN_REQUIRED < 101100))
  142. // this checks a weak symbol.
  143. if (MTLCreateSystemDefaultDevice == NULL) { // probably on 10.10 or lower.
  144. SDL_SetError("Metal framework not available on this system");
  145. return SDL_FALSE;
  146. }
  147. #endif
  148. return SDL_TRUE;
  149. }
  150. static const MTLBlendOperation invalidBlendOperation = (MTLBlendOperation)0xFFFFFFFF;
  151. static const MTLBlendFactor invalidBlendFactor = (MTLBlendFactor)0xFFFFFFFF;
  152. static MTLBlendOperation GetBlendOperation(SDL_BlendOperation operation)
  153. {
  154. switch (operation) {
  155. case SDL_BLENDOPERATION_ADD:
  156. return MTLBlendOperationAdd;
  157. case SDL_BLENDOPERATION_SUBTRACT:
  158. return MTLBlendOperationSubtract;
  159. case SDL_BLENDOPERATION_REV_SUBTRACT:
  160. return MTLBlendOperationReverseSubtract;
  161. case SDL_BLENDOPERATION_MINIMUM:
  162. return MTLBlendOperationMin;
  163. case SDL_BLENDOPERATION_MAXIMUM:
  164. return MTLBlendOperationMax;
  165. default:
  166. return invalidBlendOperation;
  167. }
  168. }
  169. static MTLBlendFactor GetBlendFactor(SDL_BlendFactor factor)
  170. {
  171. switch (factor) {
  172. case SDL_BLENDFACTOR_ZERO:
  173. return MTLBlendFactorZero;
  174. case SDL_BLENDFACTOR_ONE:
  175. return MTLBlendFactorOne;
  176. case SDL_BLENDFACTOR_SRC_COLOR:
  177. return MTLBlendFactorSourceColor;
  178. case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR:
  179. return MTLBlendFactorOneMinusSourceColor;
  180. case SDL_BLENDFACTOR_SRC_ALPHA:
  181. return MTLBlendFactorSourceAlpha;
  182. case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA:
  183. return MTLBlendFactorOneMinusSourceAlpha;
  184. case SDL_BLENDFACTOR_DST_COLOR:
  185. return MTLBlendFactorDestinationColor;
  186. case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR:
  187. return MTLBlendFactorOneMinusDestinationColor;
  188. case SDL_BLENDFACTOR_DST_ALPHA:
  189. return MTLBlendFactorDestinationAlpha;
  190. case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA:
  191. return MTLBlendFactorOneMinusDestinationAlpha;
  192. default:
  193. return invalidBlendFactor;
  194. }
  195. }
  196. static NSString *GetVertexFunctionName(SDL_MetalVertexFunction function)
  197. {
  198. switch (function) {
  199. case SDL_METAL_VERTEX_SOLID:
  200. return @"SDL_Solid_vertex";
  201. case SDL_METAL_VERTEX_COPY:
  202. return @"SDL_Copy_vertex";
  203. default:
  204. return nil;
  205. }
  206. }
  207. static NSString *GetFragmentFunctionName(SDL_MetalFragmentFunction function)
  208. {
  209. switch (function) {
  210. case SDL_METAL_FRAGMENT_SOLID:
  211. return @"SDL_Solid_fragment";
  212. case SDL_METAL_FRAGMENT_COPY:
  213. return @"SDL_Copy_fragment";
  214. case SDL_METAL_FRAGMENT_YUV:
  215. return @"SDL_YUV_fragment";
  216. case SDL_METAL_FRAGMENT_NV12:
  217. return @"SDL_NV12_fragment";
  218. case SDL_METAL_FRAGMENT_NV21:
  219. return @"SDL_NV21_fragment";
  220. default:
  221. return nil;
  222. }
  223. }
  224. static id<MTLRenderPipelineState> MakePipelineState(METAL_RenderData *data, METAL_PipelineCache *cache,
  225. NSString *blendlabel, SDL_BlendMode blendmode)
  226. {
  227. MTLRenderPipelineDescriptor *mtlpipedesc;
  228. MTLVertexDescriptor *vertdesc;
  229. MTLRenderPipelineColorAttachmentDescriptor *rtdesc;
  230. NSError *err = nil;
  231. id<MTLRenderPipelineState> state;
  232. METAL_PipelineState pipeline;
  233. METAL_PipelineState *states;
  234. id<MTLFunction> mtlvertfn = [data.mtllibrary newFunctionWithName:GetVertexFunctionName(cache->vertexFunction)];
  235. id<MTLFunction> mtlfragfn = [data.mtllibrary newFunctionWithName:GetFragmentFunctionName(cache->fragmentFunction)];
  236. SDL_assert(mtlvertfn != nil);
  237. SDL_assert(mtlfragfn != nil);
  238. mtlpipedesc = [[MTLRenderPipelineDescriptor alloc] init];
  239. mtlpipedesc.vertexFunction = mtlvertfn;
  240. mtlpipedesc.fragmentFunction = mtlfragfn;
  241. vertdesc = [MTLVertexDescriptor vertexDescriptor];
  242. switch (cache->vertexFunction) {
  243. case SDL_METAL_VERTEX_SOLID:
  244. /* position (float2), color (uchar4normalized) */
  245. vertdesc.layouts[0].stride = sizeof(float) * 2 + sizeof(int);
  246. vertdesc.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
  247. vertdesc.attributes[0].format = MTLVertexFormatFloat2;
  248. vertdesc.attributes[0].offset = 0;
  249. vertdesc.attributes[0].bufferIndex = 0;
  250. vertdesc.attributes[1].format = MTLVertexFormatUChar4Normalized;
  251. vertdesc.attributes[1].offset = sizeof(float) * 2;
  252. vertdesc.attributes[1].bufferIndex = 0;
  253. break;
  254. case SDL_METAL_VERTEX_COPY:
  255. /* position (float2), color (uchar4normalized), texcoord (float2) */
  256. vertdesc.layouts[0].stride = sizeof(float) * 2 + sizeof(int) + sizeof(float) * 2;
  257. vertdesc.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
  258. vertdesc.attributes[0].format = MTLVertexFormatFloat2;
  259. vertdesc.attributes[0].offset = 0;
  260. vertdesc.attributes[0].bufferIndex = 0;
  261. vertdesc.attributes[1].format = MTLVertexFormatUChar4Normalized;
  262. vertdesc.attributes[1].offset = sizeof(float) * 2;
  263. vertdesc.attributes[1].bufferIndex = 0;
  264. vertdesc.attributes[2].format = MTLVertexFormatFloat2;
  265. vertdesc.attributes[2].offset = sizeof(float) * 2 + sizeof(int);
  266. vertdesc.attributes[2].bufferIndex = 0;
  267. break;
  268. }
  269. mtlpipedesc.vertexDescriptor = vertdesc;
  270. rtdesc = mtlpipedesc.colorAttachments[0];
  271. rtdesc.pixelFormat = cache->renderTargetFormat;
  272. if (blendmode != SDL_BLENDMODE_NONE) {
  273. rtdesc.blendingEnabled = YES;
  274. rtdesc.sourceRGBBlendFactor = GetBlendFactor(SDL_GetBlendModeSrcColorFactor(blendmode));
  275. rtdesc.destinationRGBBlendFactor = GetBlendFactor(SDL_GetBlendModeDstColorFactor(blendmode));
  276. rtdesc.rgbBlendOperation = GetBlendOperation(SDL_GetBlendModeColorOperation(blendmode));
  277. rtdesc.sourceAlphaBlendFactor = GetBlendFactor(SDL_GetBlendModeSrcAlphaFactor(blendmode));
  278. rtdesc.destinationAlphaBlendFactor = GetBlendFactor(SDL_GetBlendModeDstAlphaFactor(blendmode));
  279. rtdesc.alphaBlendOperation = GetBlendOperation(SDL_GetBlendModeAlphaOperation(blendmode));
  280. } else {
  281. rtdesc.blendingEnabled = NO;
  282. }
  283. mtlpipedesc.label = [@(cache->label) stringByAppendingString:blendlabel];
  284. state = [data.mtldevice newRenderPipelineStateWithDescriptor:mtlpipedesc error:&err];
  285. SDL_assert(err == nil);
  286. pipeline.blendMode = blendmode;
  287. pipeline.pipe = (void *)CFBridgingRetain(state);
  288. states = SDL_realloc(cache->states, (cache->count + 1) * sizeof(pipeline));
  289. if (states) {
  290. states[cache->count++] = pipeline;
  291. cache->states = states;
  292. return (__bridge id<MTLRenderPipelineState>)pipeline.pipe;
  293. } else {
  294. CFBridgingRelease(pipeline.pipe);
  295. return NULL;
  296. }
  297. }
  298. static void MakePipelineCache(METAL_RenderData *data, METAL_PipelineCache *cache, const char *label,
  299. MTLPixelFormat rtformat, SDL_MetalVertexFunction vertfn, SDL_MetalFragmentFunction fragfn)
  300. {
  301. SDL_zerop(cache);
  302. cache->vertexFunction = vertfn;
  303. cache->fragmentFunction = fragfn;
  304. cache->renderTargetFormat = rtformat;
  305. cache->label = label;
  306. /* Create pipeline states for the default blend modes. Custom blend modes
  307. * will be added to the cache on-demand. */
  308. MakePipelineState(data, cache, @" (blend=none)", SDL_BLENDMODE_NONE);
  309. MakePipelineState(data, cache, @" (blend=blend)", SDL_BLENDMODE_BLEND);
  310. MakePipelineState(data, cache, @" (blend=add)", SDL_BLENDMODE_ADD);
  311. MakePipelineState(data, cache, @" (blend=mod)", SDL_BLENDMODE_MOD);
  312. MakePipelineState(data, cache, @" (blend=mul)", SDL_BLENDMODE_MUL);
  313. }
  314. static void DestroyPipelineCache(METAL_PipelineCache *cache)
  315. {
  316. if (cache != NULL) {
  317. for (int i = 0; i < cache->count; i++) {
  318. CFBridgingRelease(cache->states[i].pipe);
  319. }
  320. SDL_free(cache->states);
  321. }
  322. }
  323. void MakeShaderPipelines(METAL_RenderData *data, METAL_ShaderPipelines *pipelines, MTLPixelFormat rtformat)
  324. {
  325. SDL_zerop(pipelines);
  326. pipelines->renderTargetFormat = rtformat;
  327. MakePipelineCache(data, &pipelines->caches[SDL_METAL_FRAGMENT_SOLID], "SDL primitives pipeline", rtformat, SDL_METAL_VERTEX_SOLID, SDL_METAL_FRAGMENT_SOLID);
  328. MakePipelineCache(data, &pipelines->caches[SDL_METAL_FRAGMENT_COPY], "SDL copy pipeline", rtformat, SDL_METAL_VERTEX_COPY, SDL_METAL_FRAGMENT_COPY);
  329. MakePipelineCache(data, &pipelines->caches[SDL_METAL_FRAGMENT_YUV], "SDL YUV pipeline", rtformat, SDL_METAL_VERTEX_COPY, SDL_METAL_FRAGMENT_YUV);
  330. MakePipelineCache(data, &pipelines->caches[SDL_METAL_FRAGMENT_NV12], "SDL NV12 pipeline", rtformat, SDL_METAL_VERTEX_COPY, SDL_METAL_FRAGMENT_NV12);
  331. MakePipelineCache(data, &pipelines->caches[SDL_METAL_FRAGMENT_NV21], "SDL NV21 pipeline", rtformat, SDL_METAL_VERTEX_COPY, SDL_METAL_FRAGMENT_NV21);
  332. }
  333. static METAL_ShaderPipelines *ChooseShaderPipelines(METAL_RenderData *data, MTLPixelFormat rtformat)
  334. {
  335. METAL_ShaderPipelines *allpipelines = data.allpipelines;
  336. int count = data.pipelinescount;
  337. for (int i = 0; i < count; i++) {
  338. if (allpipelines[i].renderTargetFormat == rtformat) {
  339. return &allpipelines[i];
  340. }
  341. }
  342. allpipelines = SDL_realloc(allpipelines, (count + 1) * sizeof(METAL_ShaderPipelines));
  343. if (allpipelines == NULL) {
  344. return NULL;
  345. }
  346. MakeShaderPipelines(data, &allpipelines[count], rtformat);
  347. data.allpipelines = allpipelines;
  348. data.pipelinescount = count + 1;
  349. return &data.allpipelines[count];
  350. }
  351. static void DestroyAllPipelines(METAL_ShaderPipelines *allpipelines, int count)
  352. {
  353. if (allpipelines != NULL) {
  354. for (int i = 0; i < count; i++) {
  355. for (int cache = 0; cache < SDL_METAL_FRAGMENT_COUNT; cache++) {
  356. DestroyPipelineCache(&allpipelines[i].caches[cache]);
  357. }
  358. }
  359. SDL_free(allpipelines);
  360. }
  361. }
  362. static inline id<MTLRenderPipelineState> ChoosePipelineState(METAL_RenderData *data, METAL_ShaderPipelines *pipelines, SDL_MetalFragmentFunction fragfn, SDL_BlendMode blendmode)
  363. {
  364. METAL_PipelineCache *cache = &pipelines->caches[fragfn];
  365. for (int i = 0; i < cache->count; i++) {
  366. if (cache->states[i].blendMode == blendmode) {
  367. return (__bridge id<MTLRenderPipelineState>)cache->states[i].pipe;
  368. }
  369. }
  370. return MakePipelineState(data, cache, [NSString stringWithFormat:@" (blend=custom 0x%x)", blendmode], blendmode);
  371. }
  372. static SDL_bool METAL_ActivateRenderCommandEncoder(SDL_Renderer *renderer, MTLLoadAction load, MTLClearColor *clear_color, id<MTLBuffer> vertex_buffer)
  373. {
  374. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  375. /* Our SetRenderTarget just signals that the next render operation should
  376. * set up a new render pass. This is where that work happens. */
  377. if (data.mtlcmdencoder == nil) {
  378. id<MTLTexture> mtltexture = nil;
  379. if (renderer->target != NULL) {
  380. METAL_TextureData *texdata = (__bridge METAL_TextureData *)renderer->target->driverdata;
  381. mtltexture = texdata.mtltexture;
  382. } else {
  383. if (data.mtlbackbuffer == nil) {
  384. /* The backbuffer's contents aren't guaranteed to persist after
  385. * presenting, so we can leave it undefined when loading it. */
  386. data.mtlbackbuffer = [data.mtllayer nextDrawable];
  387. if (load == MTLLoadActionLoad) {
  388. load = MTLLoadActionDontCare;
  389. }
  390. }
  391. if (data.mtlbackbuffer != nil) {
  392. mtltexture = data.mtlbackbuffer.texture;
  393. }
  394. }
  395. /* mtltexture can be nil here if macOS refused to give us a drawable,
  396. which apparently can happen for minimized windows, etc. */
  397. if (mtltexture == nil) {
  398. return SDL_FALSE;
  399. }
  400. if (load == MTLLoadActionClear) {
  401. SDL_assert(clear_color != NULL);
  402. data.mtlpassdesc.colorAttachments[0].clearColor = *clear_color;
  403. }
  404. data.mtlpassdesc.colorAttachments[0].loadAction = load;
  405. data.mtlpassdesc.colorAttachments[0].texture = mtltexture;
  406. data.mtlcmdbuffer = [data.mtlcmdqueue commandBuffer];
  407. data.mtlcmdencoder = [data.mtlcmdbuffer renderCommandEncoderWithDescriptor:data.mtlpassdesc];
  408. if (data.mtlbackbuffer != nil && mtltexture == data.mtlbackbuffer.texture) {
  409. data.mtlcmdencoder.label = @"SDL metal renderer backbuffer";
  410. } else {
  411. data.mtlcmdencoder.label = @"SDL metal renderer render target";
  412. }
  413. /* Set up buffer bindings for positions, texcoords, and color once here,
  414. * the offsets are adjusted in the code that uses them. */
  415. if (vertex_buffer != nil) {
  416. [data.mtlcmdencoder setVertexBuffer:vertex_buffer offset:0 atIndex:0];
  417. [data.mtlcmdencoder setFragmentBuffer:vertex_buffer offset:0 atIndex:0];
  418. }
  419. data.activepipelines = ChooseShaderPipelines(data, mtltexture.pixelFormat);
  420. // make sure this has a definite place in the queue. This way it will
  421. // execute reliably whether the app tries to make its own command buffers
  422. // or whatever. This means we can _always_ batch rendering commands!
  423. [data.mtlcmdbuffer enqueue];
  424. }
  425. return SDL_TRUE;
  426. }
  427. static void METAL_WindowEvent(SDL_Renderer *renderer, const SDL_WindowEvent *event)
  428. {
  429. }
  430. static int METAL_GetOutputSize(SDL_Renderer *renderer, int *w, int *h)
  431. {
  432. @autoreleasepool {
  433. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  434. if (w) {
  435. *w = (int)data.mtllayer.drawableSize.width;
  436. }
  437. if (h) {
  438. *h = (int)data.mtllayer.drawableSize.height;
  439. }
  440. return 0;
  441. }
  442. }
  443. static SDL_bool METAL_SupportsBlendMode(SDL_Renderer *renderer, SDL_BlendMode blendMode)
  444. {
  445. SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
  446. SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
  447. SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
  448. SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
  449. SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
  450. SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
  451. if (GetBlendFactor(srcColorFactor) == invalidBlendFactor ||
  452. GetBlendFactor(srcAlphaFactor) == invalidBlendFactor ||
  453. GetBlendOperation(colorOperation) == invalidBlendOperation ||
  454. GetBlendFactor(dstColorFactor) == invalidBlendFactor ||
  455. GetBlendFactor(dstAlphaFactor) == invalidBlendFactor ||
  456. GetBlendOperation(alphaOperation) == invalidBlendOperation) {
  457. return SDL_FALSE;
  458. }
  459. return SDL_TRUE;
  460. }
  461. static int METAL_CreateTexture(SDL_Renderer *renderer, SDL_Texture *texture, SDL_PropertiesID create_props)
  462. {
  463. @autoreleasepool {
  464. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  465. MTLPixelFormat pixfmt;
  466. MTLTextureDescriptor *mtltexdesc;
  467. id<MTLTexture> mtltexture, mtltextureUv;
  468. BOOL yuv, nv12;
  469. METAL_TextureData *texturedata;
  470. switch (texture->format) {
  471. case SDL_PIXELFORMAT_ABGR8888:
  472. pixfmt = MTLPixelFormatRGBA8Unorm;
  473. break;
  474. case SDL_PIXELFORMAT_ARGB8888:
  475. pixfmt = MTLPixelFormatBGRA8Unorm;
  476. break;
  477. case SDL_PIXELFORMAT_IYUV:
  478. case SDL_PIXELFORMAT_YV12:
  479. case SDL_PIXELFORMAT_NV12:
  480. case SDL_PIXELFORMAT_NV21:
  481. pixfmt = MTLPixelFormatR8Unorm;
  482. break;
  483. default:
  484. return SDL_SetError("Texture format %s not supported by Metal", SDL_GetPixelFormatName(texture->format));
  485. }
  486. mtltexdesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:pixfmt
  487. width:(NSUInteger)texture->w
  488. height:(NSUInteger)texture->h
  489. mipmapped:NO];
  490. /* Not available in iOS 8. */
  491. if ([mtltexdesc respondsToSelector:@selector(usage)]) {
  492. if (texture->access == SDL_TEXTUREACCESS_TARGET) {
  493. mtltexdesc.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget;
  494. } else {
  495. mtltexdesc.usage = MTLTextureUsageShaderRead;
  496. }
  497. }
  498. mtltexture = [data.mtldevice newTextureWithDescriptor:mtltexdesc];
  499. if (mtltexture == nil) {
  500. return SDL_SetError("Texture allocation failed");
  501. }
  502. mtltextureUv = nil;
  503. #if SDL_HAVE_YUV
  504. yuv = (texture->format == SDL_PIXELFORMAT_IYUV) || (texture->format == SDL_PIXELFORMAT_YV12);
  505. nv12 = (texture->format == SDL_PIXELFORMAT_NV12) || (texture->format == SDL_PIXELFORMAT_NV21);
  506. if (yuv) {
  507. mtltexdesc.pixelFormat = MTLPixelFormatR8Unorm;
  508. mtltexdesc.width = (texture->w + 1) / 2;
  509. mtltexdesc.height = (texture->h + 1) / 2;
  510. mtltexdesc.textureType = MTLTextureType2DArray;
  511. mtltexdesc.arrayLength = 2;
  512. } else if (nv12) {
  513. mtltexdesc.pixelFormat = MTLPixelFormatRG8Unorm;
  514. mtltexdesc.width = (texture->w + 1) / 2;
  515. mtltexdesc.height = (texture->h + 1) / 2;
  516. }
  517. if (yuv || nv12) {
  518. mtltextureUv = [data.mtldevice newTextureWithDescriptor:mtltexdesc];
  519. if (mtltextureUv == nil) {
  520. return SDL_SetError("Texture allocation failed");
  521. }
  522. }
  523. #endif /* SDL_HAVE_YUV */
  524. texturedata = [[METAL_TextureData alloc] init];
  525. if (texture->scaleMode == SDL_SCALEMODE_NEAREST) {
  526. texturedata.mtlsampler = data.mtlsamplernearest;
  527. } else {
  528. texturedata.mtlsampler = data.mtlsamplerlinear;
  529. }
  530. texturedata.mtltexture = mtltexture;
  531. texturedata.mtltextureUv = mtltextureUv;
  532. #if SDL_HAVE_YUV
  533. texturedata.yuv = yuv;
  534. texturedata.nv12 = nv12;
  535. if (yuv) {
  536. texturedata.fragmentFunction = SDL_METAL_FRAGMENT_YUV;
  537. } else if (texture->format == SDL_PIXELFORMAT_NV12) {
  538. texturedata.fragmentFunction = SDL_METAL_FRAGMENT_NV12;
  539. } else if (texture->format == SDL_PIXELFORMAT_NV21) {
  540. texturedata.fragmentFunction = SDL_METAL_FRAGMENT_NV21;
  541. } else
  542. #endif
  543. {
  544. texturedata.fragmentFunction = SDL_METAL_FRAGMENT_COPY;
  545. }
  546. #if SDL_HAVE_YUV
  547. if (yuv || nv12) {
  548. size_t offset = 0;
  549. SDL_YUV_CONVERSION_MODE mode = SDL_GetYUVConversionModeForResolution(texture->w, texture->h);
  550. switch (mode) {
  551. case SDL_YUV_CONVERSION_JPEG:
  552. offset = CONSTANTS_OFFSET_DECODE_JPEG;
  553. break;
  554. case SDL_YUV_CONVERSION_BT601:
  555. offset = CONSTANTS_OFFSET_DECODE_BT601;
  556. break;
  557. case SDL_YUV_CONVERSION_BT709:
  558. offset = CONSTANTS_OFFSET_DECODE_BT709;
  559. break;
  560. default:
  561. offset = 0;
  562. break;
  563. }
  564. texturedata.conversionBufferOffset = offset;
  565. }
  566. #endif
  567. texture->driverdata = (void *)CFBridgingRetain(texturedata);
  568. return 0;
  569. }
  570. }
  571. static void METAL_UploadTextureData(id<MTLTexture> texture, SDL_Rect rect, int slice,
  572. const void *pixels, int pitch)
  573. {
  574. [texture replaceRegion:MTLRegionMake2D(rect.x, rect.y, rect.w, rect.h)
  575. mipmapLevel:0
  576. slice:slice
  577. withBytes:pixels
  578. bytesPerRow:pitch
  579. bytesPerImage:0];
  580. }
  581. static MTLStorageMode METAL_GetStorageMode(id<MTLResource> resource)
  582. {
  583. /* iOS 8 does not have this method. */
  584. if ([resource respondsToSelector:@selector(storageMode)]) {
  585. return resource.storageMode;
  586. }
  587. return MTLStorageModeShared;
  588. }
  589. static int METAL_UpdateTextureInternal(SDL_Renderer *renderer, METAL_TextureData *texturedata,
  590. id<MTLTexture> texture, SDL_Rect rect, int slice,
  591. const void *pixels, int pitch)
  592. {
  593. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  594. SDL_Rect stagingrect = { 0, 0, rect.w, rect.h };
  595. MTLTextureDescriptor *desc;
  596. id<MTLTexture> stagingtex;
  597. id<MTLBlitCommandEncoder> blitcmd;
  598. /* If the texture is managed or shared and this is the first upload, we can
  599. * use replaceRegion to upload to it directly. Otherwise we upload the data
  600. * to a staging texture and copy that over. */
  601. if (!texturedata.hasdata && METAL_GetStorageMode(texture) != MTLStorageModePrivate) {
  602. METAL_UploadTextureData(texture, rect, slice, pixels, pitch);
  603. return 0;
  604. }
  605. desc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:texture.pixelFormat
  606. width:rect.w
  607. height:rect.h
  608. mipmapped:NO];
  609. if (desc == nil) {
  610. return SDL_OutOfMemory();
  611. }
  612. /* TODO: We could have a pool of textures or a MTLHeap we allocate from,
  613. * and release a staging texture back to the pool in the command buffer's
  614. * completion handler. */
  615. stagingtex = [data.mtldevice newTextureWithDescriptor:desc];
  616. if (stagingtex == nil) {
  617. return SDL_OutOfMemory();
  618. }
  619. METAL_UploadTextureData(stagingtex, stagingrect, 0, pixels, pitch);
  620. if (data.mtlcmdencoder != nil) {
  621. [data.mtlcmdencoder endEncoding];
  622. data.mtlcmdencoder = nil;
  623. }
  624. if (data.mtlcmdbuffer == nil) {
  625. data.mtlcmdbuffer = [data.mtlcmdqueue commandBuffer];
  626. }
  627. blitcmd = [data.mtlcmdbuffer blitCommandEncoder];
  628. [blitcmd copyFromTexture:stagingtex
  629. sourceSlice:0
  630. sourceLevel:0
  631. sourceOrigin:MTLOriginMake(0, 0, 0)
  632. sourceSize:MTLSizeMake(rect.w, rect.h, 1)
  633. toTexture:texture
  634. destinationSlice:slice
  635. destinationLevel:0
  636. destinationOrigin:MTLOriginMake(rect.x, rect.y, 0)];
  637. [blitcmd endEncoding];
  638. /* TODO: This isn't very efficient for the YUV formats, which call
  639. * UpdateTextureInternal multiple times in a row. */
  640. [data.mtlcmdbuffer commit];
  641. data.mtlcmdbuffer = nil;
  642. return 0;
  643. }
  644. static int METAL_UpdateTexture(SDL_Renderer *renderer, SDL_Texture *texture,
  645. const SDL_Rect *rect, const void *pixels, int pitch)
  646. {
  647. @autoreleasepool {
  648. METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata;
  649. if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture, *rect, 0, pixels, pitch) < 0) {
  650. return -1;
  651. }
  652. #if SDL_HAVE_YUV
  653. if (texturedata.yuv) {
  654. int Uslice = texture->format == SDL_PIXELFORMAT_YV12 ? 1 : 0;
  655. int Vslice = texture->format == SDL_PIXELFORMAT_YV12 ? 0 : 1;
  656. int UVpitch = (pitch + 1) / 2;
  657. SDL_Rect UVrect = { rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2 };
  658. /* Skip to the correct offset into the next texture */
  659. pixels = (const void *)((const Uint8 *)pixels + rect->h * pitch);
  660. if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltextureUv, UVrect, Uslice, pixels, UVpitch) < 0) {
  661. return -1;
  662. }
  663. /* Skip to the correct offset into the next texture */
  664. pixels = (const void *)((const Uint8 *)pixels + UVrect.h * UVpitch);
  665. if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltextureUv, UVrect, Vslice, pixels, UVpitch) < 0) {
  666. return -1;
  667. }
  668. }
  669. if (texturedata.nv12) {
  670. SDL_Rect UVrect = { rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2 };
  671. int UVpitch = 2 * ((pitch + 1) / 2);
  672. /* Skip to the correct offset into the next texture */
  673. pixels = (const void *)((const Uint8 *)pixels + rect->h * pitch);
  674. if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltextureUv, UVrect, 0, pixels, UVpitch) < 0) {
  675. return -1;
  676. }
  677. }
  678. #endif
  679. texturedata.hasdata = YES;
  680. return 0;
  681. }
  682. }
  683. #if SDL_HAVE_YUV
  684. static int METAL_UpdateTextureYUV(SDL_Renderer *renderer, SDL_Texture *texture,
  685. const SDL_Rect *rect,
  686. const Uint8 *Yplane, int Ypitch,
  687. const Uint8 *Uplane, int Upitch,
  688. const Uint8 *Vplane, int Vpitch)
  689. {
  690. @autoreleasepool {
  691. METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata;
  692. const int Uslice = 0;
  693. const int Vslice = 1;
  694. SDL_Rect UVrect = { rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2 };
  695. /* Bail out if we're supposed to update an empty rectangle */
  696. if (rect->w <= 0 || rect->h <= 0) {
  697. return 0;
  698. }
  699. if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture, *rect, 0, Yplane, Ypitch) < 0) {
  700. return -1;
  701. }
  702. if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltextureUv, UVrect, Uslice, Uplane, Upitch)) {
  703. return -1;
  704. }
  705. if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltextureUv, UVrect, Vslice, Vplane, Vpitch)) {
  706. return -1;
  707. }
  708. texturedata.hasdata = YES;
  709. return 0;
  710. }
  711. }
  712. static int METAL_UpdateTextureNV(SDL_Renderer *renderer, SDL_Texture *texture,
  713. const SDL_Rect *rect,
  714. const Uint8 *Yplane, int Ypitch,
  715. const Uint8 *UVplane, int UVpitch)
  716. {
  717. @autoreleasepool {
  718. METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata;
  719. SDL_Rect UVrect = { rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2 };
  720. /* Bail out if we're supposed to update an empty rectangle */
  721. if (rect->w <= 0 || rect->h <= 0) {
  722. return 0;
  723. }
  724. if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture, *rect, 0, Yplane, Ypitch) < 0) {
  725. return -1;
  726. }
  727. if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltextureUv, UVrect, 0, UVplane, UVpitch) < 0) {
  728. return -1;
  729. }
  730. texturedata.hasdata = YES;
  731. return 0;
  732. }
  733. }
  734. #endif
  735. static int METAL_LockTexture(SDL_Renderer *renderer, SDL_Texture *texture,
  736. const SDL_Rect *rect, void **pixels, int *pitch)
  737. {
  738. @autoreleasepool {
  739. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  740. METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata;
  741. int buffersize = 0;
  742. id<MTLBuffer> lockedbuffer = nil;
  743. if (rect->w <= 0 || rect->h <= 0) {
  744. return SDL_SetError("Invalid rectangle dimensions for LockTexture.");
  745. }
  746. *pitch = SDL_BYTESPERPIXEL(texture->format) * rect->w;
  747. #if SDL_HAVE_YUV
  748. if (texturedata.yuv || texturedata.nv12) {
  749. buffersize = ((*pitch) * rect->h) + (2 * (*pitch + 1) / 2) * ((rect->h + 1) / 2);
  750. } else
  751. #endif
  752. {
  753. buffersize = (*pitch) * rect->h;
  754. }
  755. lockedbuffer = [data.mtldevice newBufferWithLength:buffersize options:MTLResourceStorageModeShared];
  756. if (lockedbuffer == nil) {
  757. return SDL_OutOfMemory();
  758. }
  759. texturedata.lockedrect = *rect;
  760. texturedata.lockedbuffer = lockedbuffer;
  761. *pixels = [lockedbuffer contents];
  762. return 0;
  763. }
  764. }
  765. static void METAL_UnlockTexture(SDL_Renderer *renderer, SDL_Texture *texture)
  766. {
  767. @autoreleasepool {
  768. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  769. METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata;
  770. id<MTLBlitCommandEncoder> blitcmd;
  771. SDL_Rect rect = texturedata.lockedrect;
  772. int pitch = SDL_BYTESPERPIXEL(texture->format) * rect.w;
  773. SDL_Rect UVrect = { rect.x / 2, rect.y / 2, (rect.w + 1) / 2, (rect.h + 1) / 2 };
  774. if (texturedata.lockedbuffer == nil) {
  775. return;
  776. }
  777. if (data.mtlcmdencoder != nil) {
  778. [data.mtlcmdencoder endEncoding];
  779. data.mtlcmdencoder = nil;
  780. }
  781. if (data.mtlcmdbuffer == nil) {
  782. data.mtlcmdbuffer = [data.mtlcmdqueue commandBuffer];
  783. }
  784. blitcmd = [data.mtlcmdbuffer blitCommandEncoder];
  785. [blitcmd copyFromBuffer:texturedata.lockedbuffer
  786. sourceOffset:0
  787. sourceBytesPerRow:pitch
  788. sourceBytesPerImage:0
  789. sourceSize:MTLSizeMake(rect.w, rect.h, 1)
  790. toTexture:texturedata.mtltexture
  791. destinationSlice:0
  792. destinationLevel:0
  793. destinationOrigin:MTLOriginMake(rect.x, rect.y, 0)];
  794. #if SDL_HAVE_YUV
  795. if (texturedata.yuv) {
  796. int Uslice = texture->format == SDL_PIXELFORMAT_YV12 ? 1 : 0;
  797. int Vslice = texture->format == SDL_PIXELFORMAT_YV12 ? 0 : 1;
  798. int UVpitch = (pitch + 1) / 2;
  799. [blitcmd copyFromBuffer:texturedata.lockedbuffer
  800. sourceOffset:rect.h * pitch
  801. sourceBytesPerRow:UVpitch
  802. sourceBytesPerImage:UVpitch * UVrect.h
  803. sourceSize:MTLSizeMake(UVrect.w, UVrect.h, 1)
  804. toTexture:texturedata.mtltextureUv
  805. destinationSlice:Uslice
  806. destinationLevel:0
  807. destinationOrigin:MTLOriginMake(UVrect.x, UVrect.y, 0)];
  808. [blitcmd copyFromBuffer:texturedata.lockedbuffer
  809. sourceOffset:(rect.h * pitch) + UVrect.h * UVpitch
  810. sourceBytesPerRow:UVpitch
  811. sourceBytesPerImage:UVpitch * UVrect.h
  812. sourceSize:MTLSizeMake(UVrect.w, UVrect.h, 1)
  813. toTexture:texturedata.mtltextureUv
  814. destinationSlice:Vslice
  815. destinationLevel:0
  816. destinationOrigin:MTLOriginMake(UVrect.x, UVrect.y, 0)];
  817. }
  818. if (texturedata.nv12) {
  819. int UVpitch = 2 * ((pitch + 1) / 2);
  820. [blitcmd copyFromBuffer:texturedata.lockedbuffer
  821. sourceOffset:rect.h * pitch
  822. sourceBytesPerRow:UVpitch
  823. sourceBytesPerImage:0
  824. sourceSize:MTLSizeMake(UVrect.w, UVrect.h, 1)
  825. toTexture:texturedata.mtltextureUv
  826. destinationSlice:0
  827. destinationLevel:0
  828. destinationOrigin:MTLOriginMake(UVrect.x, UVrect.y, 0)];
  829. }
  830. #endif
  831. [blitcmd endEncoding];
  832. [data.mtlcmdbuffer commit];
  833. data.mtlcmdbuffer = nil;
  834. texturedata.lockedbuffer = nil; /* Retained property, so it calls release. */
  835. texturedata.hasdata = YES;
  836. }
  837. }
  838. static void METAL_SetTextureScaleMode(SDL_Renderer *renderer, SDL_Texture *texture, SDL_ScaleMode scaleMode)
  839. {
  840. @autoreleasepool {
  841. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  842. METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata;
  843. if (scaleMode == SDL_SCALEMODE_NEAREST) {
  844. texturedata.mtlsampler = data.mtlsamplernearest;
  845. } else {
  846. texturedata.mtlsampler = data.mtlsamplerlinear;
  847. }
  848. }
  849. }
  850. static int METAL_SetRenderTarget(SDL_Renderer *renderer, SDL_Texture *texture)
  851. {
  852. @autoreleasepool {
  853. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  854. if (data.mtlcmdencoder) {
  855. /* End encoding for the previous render target so we can set up a new
  856. * render pass for this one. */
  857. [data.mtlcmdencoder endEncoding];
  858. [data.mtlcmdbuffer commit];
  859. data.mtlcmdencoder = nil;
  860. data.mtlcmdbuffer = nil;
  861. }
  862. /* We don't begin a new render pass right away - we delay it until an actual
  863. * draw or clear happens. That way we can use hardware clears when possible,
  864. * which are only available when beginning a new render pass. */
  865. return 0;
  866. }
  867. }
  868. static int METAL_QueueSetViewport(SDL_Renderer *renderer, SDL_RenderCommand *cmd)
  869. {
  870. float projection[4][4]; /* Prepare an orthographic projection */
  871. const int w = cmd->data.viewport.rect.w;
  872. const int h = cmd->data.viewport.rect.h;
  873. const size_t matrixlen = sizeof(projection);
  874. float *matrix = (float *)SDL_AllocateRenderVertices(renderer, matrixlen, CONSTANT_ALIGN(16), &cmd->data.viewport.first);
  875. if (!matrix) {
  876. return -1;
  877. }
  878. SDL_memset(projection, '\0', matrixlen);
  879. if (w && h) {
  880. projection[0][0] = 2.0f / w;
  881. projection[1][1] = -2.0f / h;
  882. projection[3][0] = -1.0f;
  883. projection[3][1] = 1.0f;
  884. projection[3][3] = 1.0f;
  885. }
  886. SDL_memcpy(matrix, projection, matrixlen);
  887. return 0;
  888. }
  889. static int METAL_QueueSetDrawColor(SDL_Renderer *renderer, SDL_RenderCommand *cmd)
  890. {
  891. const size_t vertlen = sizeof(float) * 4;
  892. float *verts = (float *)SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(16), &cmd->data.color.first);
  893. if (!verts) {
  894. return -1;
  895. }
  896. /*
  897. * FIXME: not needed anymore, some cleanup to do
  898. *
  899. *(verts++) = ((float)cmd->data.color.r) / 255.0f;
  900. *(verts++) = ((float)cmd->data.color.g) / 255.0f;
  901. *(verts++) = ((float)cmd->data.color.b) / 255.0f;
  902. *(verts++) = ((float)cmd->data.color.a) / 255.0f;
  903. */
  904. return 0;
  905. }
  906. static int METAL_QueueDrawPoints(SDL_Renderer *renderer, SDL_RenderCommand *cmd, const SDL_FPoint *points, int count)
  907. {
  908. const SDL_Color color = {
  909. cmd->data.draw.r,
  910. cmd->data.draw.g,
  911. cmd->data.draw.b,
  912. cmd->data.draw.a
  913. };
  914. const size_t vertlen = (2 * sizeof(float) + sizeof(SDL_Color)) * count;
  915. float *verts = (float *)SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(8), &cmd->data.draw.first);
  916. if (!verts) {
  917. return -1;
  918. }
  919. cmd->data.draw.count = count;
  920. for (int i = 0; i < count; i++, points++) {
  921. *(verts++) = points->x;
  922. *(verts++) = points->y;
  923. *((SDL_Color *)verts++) = color;
  924. }
  925. return 0;
  926. }
  927. static int METAL_QueueDrawLines(SDL_Renderer *renderer, SDL_RenderCommand *cmd, const SDL_FPoint *points, int count)
  928. {
  929. const SDL_Color color = {
  930. cmd->data.draw.r,
  931. cmd->data.draw.g,
  932. cmd->data.draw.b,
  933. cmd->data.draw.a
  934. };
  935. size_t vertlen;
  936. float *verts;
  937. SDL_assert(count >= 2); /* should have been checked at the higher level. */
  938. vertlen = (2 * sizeof(float) + sizeof(SDL_Color)) * count;
  939. verts = (float *)SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(8), &cmd->data.draw.first);
  940. if (!verts) {
  941. return -1;
  942. }
  943. cmd->data.draw.count = count;
  944. for (int i = 0; i < count; i++, points++) {
  945. *(verts++) = points->x;
  946. *(verts++) = points->y;
  947. *((SDL_Color *)verts++) = color;
  948. }
  949. /* If the line segment is completely horizontal or vertical,
  950. make it one pixel longer, to satisfy the diamond-exit rule.
  951. We should probably do this for diagonal lines too, but we'd have to
  952. do some trigonometry to figure out the correct pixel and generally
  953. when we have problems with pixel perfection, it's for straight lines
  954. that are missing a pixel that frames something and not arbitrary
  955. angles. Maybe !!! FIXME for later, though. */
  956. points -= 2; /* update the last line. */
  957. verts -= 2 + 1;
  958. {
  959. const float xstart = points[0].x;
  960. const float ystart = points[0].y;
  961. const float xend = points[1].x;
  962. const float yend = points[1].y;
  963. if (ystart == yend) { /* horizontal line */
  964. verts[0] += (xend > xstart) ? 1.0f : -1.0f;
  965. } else if (xstart == xend) { /* vertical line */
  966. verts[1] += (yend > ystart) ? 1.0f : -1.0f;
  967. }
  968. }
  969. return 0;
  970. }
  971. static int METAL_QueueGeometry(SDL_Renderer *renderer, SDL_RenderCommand *cmd, SDL_Texture *texture,
  972. const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride,
  973. int num_vertices, const void *indices, int num_indices, int size_indices,
  974. float scale_x, float scale_y)
  975. {
  976. int count = indices ? num_indices : num_vertices;
  977. const size_t vertlen = (2 * sizeof(float) + sizeof(int) + (texture ? 2 : 0) * sizeof(float)) * count;
  978. float *verts = (float *)SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(8), &cmd->data.draw.first);
  979. if (!verts) {
  980. return -1;
  981. }
  982. cmd->data.draw.count = count;
  983. size_indices = indices ? size_indices : 0;
  984. for (int i = 0; i < count; i++) {
  985. int j;
  986. float *xy_;
  987. if (size_indices == 4) {
  988. j = ((const Uint32 *)indices)[i];
  989. } else if (size_indices == 2) {
  990. j = ((const Uint16 *)indices)[i];
  991. } else if (size_indices == 1) {
  992. j = ((const Uint8 *)indices)[i];
  993. } else {
  994. j = i;
  995. }
  996. xy_ = (float *)((char *)xy + j * xy_stride);
  997. *(verts++) = xy_[0] * scale_x;
  998. *(verts++) = xy_[1] * scale_y;
  999. *((SDL_Color *)verts++) = *(SDL_Color *)((char *)color + j * color_stride);
  1000. if (texture) {
  1001. float *uv_ = (float *)((char *)uv + j * uv_stride);
  1002. *(verts++) = uv_[0];
  1003. *(verts++) = uv_[1];
  1004. }
  1005. }
  1006. return 0;
  1007. }
  1008. typedef struct
  1009. {
  1010. __unsafe_unretained id<MTLRenderPipelineState> pipeline;
  1011. __unsafe_unretained id<MTLBuffer> vertex_buffer;
  1012. size_t constants_offset;
  1013. SDL_Texture *texture;
  1014. SDL_bool cliprect_dirty;
  1015. SDL_bool cliprect_enabled;
  1016. SDL_Rect cliprect;
  1017. SDL_bool viewport_dirty;
  1018. SDL_Rect viewport;
  1019. size_t projection_offset;
  1020. SDL_bool color_dirty;
  1021. size_t color_offset;
  1022. } METAL_DrawStateCache;
  1023. static SDL_bool SetDrawState(SDL_Renderer *renderer, const SDL_RenderCommand *cmd, const SDL_MetalFragmentFunction shader,
  1024. const size_t constants_offset, id<MTLBuffer> mtlbufvertex, METAL_DrawStateCache *statecache)
  1025. {
  1026. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  1027. const SDL_BlendMode blend = cmd->data.draw.blend;
  1028. size_t first = cmd->data.draw.first;
  1029. id<MTLRenderPipelineState> newpipeline;
  1030. if (!METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, statecache->vertex_buffer)) {
  1031. return SDL_FALSE;
  1032. }
  1033. if (statecache->viewport_dirty) {
  1034. MTLViewport viewport;
  1035. viewport.originX = statecache->viewport.x;
  1036. viewport.originY = statecache->viewport.y;
  1037. viewport.width = statecache->viewport.w;
  1038. viewport.height = statecache->viewport.h;
  1039. viewport.znear = 0.0;
  1040. viewport.zfar = 1.0;
  1041. [data.mtlcmdencoder setViewport:viewport];
  1042. [data.mtlcmdencoder setVertexBuffer:mtlbufvertex offset:statecache->projection_offset atIndex:2]; // projection
  1043. statecache->viewport_dirty = SDL_FALSE;
  1044. }
  1045. if (statecache->cliprect_dirty) {
  1046. SDL_Rect output;
  1047. SDL_Rect clip;
  1048. if (statecache->cliprect_enabled) {
  1049. clip = statecache->cliprect;
  1050. clip.x += statecache->viewport.x;
  1051. clip.y += statecache->viewport.y;
  1052. } else {
  1053. clip = statecache->viewport;
  1054. }
  1055. /* Set Scissor Rect Validation: w/h must be <= render pass */
  1056. SDL_zero(output);
  1057. if (renderer->target) {
  1058. output.w = renderer->target->w;
  1059. output.h = renderer->target->h;
  1060. } else {
  1061. METAL_GetOutputSize(renderer, &output.w, &output.h);
  1062. }
  1063. if (SDL_GetRectIntersection(&output, &clip, &clip)) {
  1064. MTLScissorRect mtlrect;
  1065. mtlrect.x = clip.x;
  1066. mtlrect.y = clip.y;
  1067. mtlrect.width = clip.w;
  1068. mtlrect.height = clip.h;
  1069. [data.mtlcmdencoder setScissorRect:mtlrect];
  1070. }
  1071. statecache->cliprect_dirty = SDL_FALSE;
  1072. }
  1073. if (statecache->color_dirty) {
  1074. [data.mtlcmdencoder setFragmentBufferOffset:statecache->color_offset atIndex:0];
  1075. statecache->color_dirty = SDL_FALSE;
  1076. }
  1077. newpipeline = ChoosePipelineState(data, data.activepipelines, shader, blend);
  1078. if (newpipeline != statecache->pipeline) {
  1079. [data.mtlcmdencoder setRenderPipelineState:newpipeline];
  1080. statecache->pipeline = newpipeline;
  1081. }
  1082. if (constants_offset != statecache->constants_offset) {
  1083. if (constants_offset != CONSTANTS_OFFSET_INVALID) {
  1084. [data.mtlcmdencoder setVertexBuffer:data.mtlbufconstants offset:constants_offset atIndex:3];
  1085. }
  1086. statecache->constants_offset = constants_offset;
  1087. }
  1088. [data.mtlcmdencoder setVertexBufferOffset:first atIndex:0]; /* position/texcoords */
  1089. return SDL_TRUE;
  1090. }
  1091. static SDL_bool SetCopyState(SDL_Renderer *renderer, const SDL_RenderCommand *cmd, const size_t constants_offset,
  1092. id<MTLBuffer> mtlbufvertex, METAL_DrawStateCache *statecache)
  1093. {
  1094. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  1095. SDL_Texture *texture = cmd->data.draw.texture;
  1096. METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata;
  1097. if (!SetDrawState(renderer, cmd, texturedata.fragmentFunction, constants_offset, mtlbufvertex, statecache)) {
  1098. return SDL_FALSE;
  1099. }
  1100. if (texture != statecache->texture) {
  1101. METAL_TextureData *oldtexturedata = NULL;
  1102. if (statecache->texture) {
  1103. oldtexturedata = (__bridge METAL_TextureData *)statecache->texture->driverdata;
  1104. }
  1105. if (!oldtexturedata || (texturedata.mtlsampler != oldtexturedata.mtlsampler)) {
  1106. [data.mtlcmdencoder setFragmentSamplerState:texturedata.mtlsampler atIndex:0];
  1107. }
  1108. [data.mtlcmdencoder setFragmentTexture:texturedata.mtltexture atIndex:0];
  1109. #if SDL_HAVE_YUV
  1110. if (texturedata.yuv || texturedata.nv12) {
  1111. [data.mtlcmdencoder setFragmentTexture:texturedata.mtltextureUv atIndex:1];
  1112. [data.mtlcmdencoder setFragmentBuffer:data.mtlbufconstants offset:texturedata.conversionBufferOffset atIndex:1];
  1113. }
  1114. #endif
  1115. statecache->texture = texture;
  1116. }
  1117. return SDL_TRUE;
  1118. }
  1119. static void METAL_InvalidateCachedState(SDL_Renderer *renderer)
  1120. {
  1121. // METAL_DrawStateCache only exists during a run of METAL_RunCommandQueue, so there's nothing to invalidate!
  1122. }
  1123. static int METAL_RunCommandQueue(SDL_Renderer *renderer, SDL_RenderCommand *cmd, void *vertices, size_t vertsize)
  1124. {
  1125. @autoreleasepool {
  1126. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  1127. id<MTLBuffer> mtlbufvertex = nil;
  1128. METAL_DrawStateCache statecache;
  1129. SDL_zero(statecache);
  1130. statecache.pipeline = nil;
  1131. statecache.vertex_buffer = nil;
  1132. statecache.constants_offset = CONSTANTS_OFFSET_INVALID;
  1133. statecache.texture = NULL;
  1134. statecache.color_dirty = SDL_TRUE;
  1135. statecache.cliprect_dirty = SDL_TRUE;
  1136. statecache.viewport_dirty = SDL_TRUE;
  1137. statecache.projection_offset = 0;
  1138. statecache.color_offset = 0;
  1139. // !!! FIXME: have a ring of pre-made MTLBuffers we cycle through? How expensive is creation?
  1140. if (vertsize > 0) {
  1141. /* We can memcpy to a shared buffer from the CPU and read it from the GPU
  1142. * without any extra copying. It's a bit slower on macOS to read shared
  1143. * data from the GPU than to read managed/private data, but we avoid the
  1144. * cost of copying the data and the code's simpler. Apple's best
  1145. * practices guide recommends this approach for streamed vertex data.
  1146. * TODO: this buffer is also used for constants. Is performance still
  1147. * good for those, or should we have a managed buffer for them? */
  1148. mtlbufvertex = [data.mtldevice newBufferWithLength:vertsize options:MTLResourceStorageModeShared];
  1149. mtlbufvertex.label = @"SDL vertex data";
  1150. SDL_memcpy([mtlbufvertex contents], vertices, vertsize);
  1151. statecache.vertex_buffer = mtlbufvertex;
  1152. }
  1153. // If there's a command buffer here unexpectedly (app requested one?). Commit it so we can start fresh.
  1154. [data.mtlcmdencoder endEncoding];
  1155. [data.mtlcmdbuffer commit];
  1156. data.mtlcmdencoder = nil;
  1157. data.mtlcmdbuffer = nil;
  1158. while (cmd) {
  1159. switch (cmd->command) {
  1160. case SDL_RENDERCMD_SETVIEWPORT:
  1161. {
  1162. SDL_memcpy(&statecache.viewport, &cmd->data.viewport.rect, sizeof(statecache.viewport));
  1163. statecache.projection_offset = cmd->data.viewport.first;
  1164. statecache.viewport_dirty = SDL_TRUE;
  1165. statecache.cliprect_dirty = SDL_TRUE;
  1166. break;
  1167. }
  1168. case SDL_RENDERCMD_SETCLIPRECT:
  1169. {
  1170. SDL_memcpy(&statecache.cliprect, &cmd->data.cliprect.rect, sizeof(statecache.cliprect));
  1171. statecache.cliprect_enabled = cmd->data.cliprect.enabled;
  1172. statecache.cliprect_dirty = SDL_TRUE;
  1173. break;
  1174. }
  1175. case SDL_RENDERCMD_SETDRAWCOLOR:
  1176. {
  1177. statecache.color_offset = cmd->data.color.first;
  1178. statecache.color_dirty = SDL_TRUE;
  1179. break;
  1180. }
  1181. case SDL_RENDERCMD_CLEAR:
  1182. {
  1183. /* If we're already encoding a command buffer, dump it without committing it. We'd just
  1184. clear all its work anyhow, and starting a new encoder will let us use a hardware clear
  1185. operation via MTLLoadActionClear. */
  1186. if (data.mtlcmdencoder != nil) {
  1187. [data.mtlcmdencoder endEncoding];
  1188. // !!! FIXME: have to commit, or an uncommitted but enqueued buffer will prevent the frame from finishing.
  1189. [data.mtlcmdbuffer commit];
  1190. data.mtlcmdencoder = nil;
  1191. data.mtlcmdbuffer = nil;
  1192. }
  1193. // force all this state to be reconfigured on next command buffer.
  1194. statecache.pipeline = nil;
  1195. statecache.constants_offset = CONSTANTS_OFFSET_INVALID;
  1196. statecache.texture = NULL;
  1197. statecache.color_dirty = SDL_TRUE;
  1198. statecache.cliprect_dirty = SDL_TRUE;
  1199. statecache.viewport_dirty = SDL_TRUE;
  1200. {
  1201. const Uint8 r = cmd->data.color.r;
  1202. const Uint8 g = cmd->data.color.g;
  1203. const Uint8 b = cmd->data.color.b;
  1204. const Uint8 a = cmd->data.color.a;
  1205. MTLClearColor color = MTLClearColorMake(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
  1206. // get new command encoder, set up with an initial clear operation.
  1207. // (this might fail, and future draw operations will notice.)
  1208. METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionClear, &color, mtlbufvertex);
  1209. }
  1210. break;
  1211. }
  1212. case SDL_RENDERCMD_DRAW_POINTS:
  1213. case SDL_RENDERCMD_DRAW_LINES:
  1214. {
  1215. const size_t count = cmd->data.draw.count;
  1216. const MTLPrimitiveType primtype = (cmd->command == SDL_RENDERCMD_DRAW_POINTS) ? MTLPrimitiveTypePoint : MTLPrimitiveTypeLineStrip;
  1217. if (SetDrawState(renderer, cmd, SDL_METAL_FRAGMENT_SOLID, CONSTANTS_OFFSET_HALF_PIXEL_TRANSFORM, mtlbufvertex, &statecache)) {
  1218. [data.mtlcmdencoder drawPrimitives:primtype vertexStart:0 vertexCount:count];
  1219. }
  1220. break;
  1221. }
  1222. case SDL_RENDERCMD_FILL_RECTS: /* unused */
  1223. break;
  1224. case SDL_RENDERCMD_COPY: /* unused */
  1225. break;
  1226. case SDL_RENDERCMD_COPY_EX: /* unused */
  1227. break;
  1228. case SDL_RENDERCMD_GEOMETRY:
  1229. {
  1230. const size_t count = cmd->data.draw.count;
  1231. SDL_Texture *texture = cmd->data.draw.texture;
  1232. if (texture) {
  1233. if (SetCopyState(renderer, cmd, CONSTANTS_OFFSET_IDENTITY, mtlbufvertex, &statecache)) {
  1234. [data.mtlcmdencoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:count];
  1235. }
  1236. } else {
  1237. if (SetDrawState(renderer, cmd, SDL_METAL_FRAGMENT_SOLID, CONSTANTS_OFFSET_IDENTITY, mtlbufvertex, &statecache)) {
  1238. [data.mtlcmdencoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:count];
  1239. }
  1240. }
  1241. break;
  1242. }
  1243. case SDL_RENDERCMD_NO_OP:
  1244. break;
  1245. }
  1246. cmd = cmd->next;
  1247. }
  1248. return 0;
  1249. }
  1250. }
  1251. static int METAL_RenderReadPixels(SDL_Renderer *renderer, const SDL_Rect *rect,
  1252. Uint32 pixel_format, void *pixels, int pitch)
  1253. {
  1254. @autoreleasepool {
  1255. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  1256. id<MTLTexture> mtltexture;
  1257. MTLRegion mtlregion;
  1258. size_t temp_pitch;
  1259. int status;
  1260. Uint32 temp_format;
  1261. void *temp_pixels;
  1262. if (!METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, nil)) {
  1263. return SDL_SetError("Failed to activate render command encoder (is your window in the background?");
  1264. }
  1265. [data.mtlcmdencoder endEncoding];
  1266. mtltexture = data.mtlpassdesc.colorAttachments[0].texture;
  1267. #ifdef __MACOS__
  1268. /* on macOS with managed-storage textures, we need to tell the driver to
  1269. * update the CPU-side copy of the texture data.
  1270. * NOTE: Currently all of our textures are managed on macOS. We'll need some
  1271. * extra copying for any private textures. */
  1272. if (METAL_GetStorageMode(mtltexture) == MTLStorageModeManaged) {
  1273. id<MTLBlitCommandEncoder> blit = [data.mtlcmdbuffer blitCommandEncoder];
  1274. [blit synchronizeResource:mtltexture];
  1275. [blit endEncoding];
  1276. }
  1277. #endif
  1278. /* Commit the current command buffer and wait until it's completed, to make
  1279. * sure the GPU has finished rendering to it by the time we read it. */
  1280. [data.mtlcmdbuffer commit];
  1281. [data.mtlcmdbuffer waitUntilCompleted];
  1282. data.mtlcmdencoder = nil;
  1283. data.mtlcmdbuffer = nil;
  1284. mtlregion = MTLRegionMake2D(rect->x, rect->y, rect->w, rect->h);
  1285. // we only do BGRA8 or RGBA8 at the moment, so 4 will do.
  1286. temp_pitch = rect->w * 4UL;
  1287. temp_pixels = SDL_malloc(temp_pitch * rect->h);
  1288. if (!temp_pixels) {
  1289. return -1;
  1290. }
  1291. [mtltexture getBytes:temp_pixels bytesPerRow:temp_pitch fromRegion:mtlregion mipmapLevel:0];
  1292. temp_format = (mtltexture.pixelFormat == MTLPixelFormatBGRA8Unorm) ? SDL_PIXELFORMAT_ARGB8888 : SDL_PIXELFORMAT_ABGR8888;
  1293. status = SDL_ConvertPixels(rect->w, rect->h, temp_format, temp_pixels, (int)temp_pitch, pixel_format, pixels, pitch);
  1294. SDL_free(temp_pixels);
  1295. return status;
  1296. }
  1297. }
  1298. static int METAL_RenderPresent(SDL_Renderer *renderer)
  1299. {
  1300. @autoreleasepool {
  1301. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  1302. SDL_bool ready = SDL_TRUE;
  1303. // If we don't have a command buffer, we can't present, so activate to get one.
  1304. if (data.mtlcmdencoder == nil) {
  1305. // We haven't even gotten a backbuffer yet? Clear it to black. Otherwise, load the existing data.
  1306. if (data.mtlbackbuffer == nil) {
  1307. MTLClearColor color = MTLClearColorMake(0.0f, 0.0f, 0.0f, 1.0f);
  1308. ready = METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionClear, &color, nil);
  1309. } else {
  1310. ready = METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, nil);
  1311. }
  1312. }
  1313. [data.mtlcmdencoder endEncoding];
  1314. // If we don't have a drawable to present, don't try to present it.
  1315. // But we'll still try to commit the command buffer in case it was already enqueued.
  1316. if (ready) {
  1317. SDL_assert(data.mtlbackbuffer != nil);
  1318. [data.mtlcmdbuffer presentDrawable:data.mtlbackbuffer];
  1319. }
  1320. [data.mtlcmdbuffer commit];
  1321. data.mtlcmdencoder = nil;
  1322. data.mtlcmdbuffer = nil;
  1323. data.mtlbackbuffer = nil;
  1324. if (renderer->hidden || !ready) {
  1325. return -1;
  1326. }
  1327. return 0;
  1328. }
  1329. }
  1330. static void METAL_DestroyTexture(SDL_Renderer *renderer, SDL_Texture *texture)
  1331. {
  1332. @autoreleasepool {
  1333. CFBridgingRelease(texture->driverdata);
  1334. texture->driverdata = NULL;
  1335. }
  1336. }
  1337. static void METAL_DestroyRenderer(SDL_Renderer *renderer)
  1338. {
  1339. @autoreleasepool {
  1340. if (renderer->driverdata) {
  1341. METAL_RenderData *data = CFBridgingRelease(renderer->driverdata);
  1342. if (data.mtlcmdencoder != nil) {
  1343. [data.mtlcmdencoder endEncoding];
  1344. }
  1345. DestroyAllPipelines(data.allpipelines, data.pipelinescount);
  1346. /* Release the metal view instead of destroying it,
  1347. in case we want to use it later (recreating the renderer)
  1348. */
  1349. /* SDL_Metal_DestroyView(data.mtlview); */
  1350. CFBridgingRelease(data.mtlview);
  1351. }
  1352. SDL_free(renderer);
  1353. }
  1354. }
  1355. static void *METAL_GetMetalLayer(SDL_Renderer *renderer)
  1356. {
  1357. @autoreleasepool {
  1358. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  1359. return (__bridge void *)data.mtllayer;
  1360. }
  1361. }
  1362. static void *METAL_GetMetalCommandEncoder(SDL_Renderer *renderer)
  1363. {
  1364. @autoreleasepool {
  1365. // note that data.mtlcmdencoder can be nil if METAL_ActivateRenderCommandEncoder fails.
  1366. // Before SDL 2.0.18, it might have returned a non-nil encoding that might not have been
  1367. // usable for presentation. Check your return values!
  1368. METAL_RenderData *data;
  1369. METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, nil);
  1370. data = (__bridge METAL_RenderData *)renderer->driverdata;
  1371. return (__bridge void *)data.mtlcmdencoder;
  1372. }
  1373. }
  1374. static int METAL_SetVSync(SDL_Renderer *renderer, const int vsync)
  1375. {
  1376. #if (defined(__MACOS__) && defined(MAC_OS_X_VERSION_10_13)) || TARGET_OS_MACCATALYST
  1377. if (@available(macOS 10.13, *)) {
  1378. METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata;
  1379. if (vsync) {
  1380. data.mtllayer.displaySyncEnabled = YES;
  1381. renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
  1382. } else {
  1383. data.mtllayer.displaySyncEnabled = NO;
  1384. renderer->info.flags &= ~SDL_RENDERER_PRESENTVSYNC;
  1385. }
  1386. return 0;
  1387. }
  1388. #endif
  1389. return SDL_SetError("This Apple OS does not support displaySyncEnabled!");
  1390. }
  1391. static SDL_MetalView GetWindowView(SDL_Window *window)
  1392. {
  1393. #ifdef SDL_VIDEO_DRIVER_COCOA
  1394. NSWindow *nswindow = (__bridge NSWindow *)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.cocoa.window", NULL);
  1395. NSInteger tag = (NSInteger)SDL_GetNumberProperty(SDL_GetWindowProperties(window), "SDL.window.cocoa.metal_view_tag", 0);
  1396. if (nswindow && tag) {
  1397. NSView *view = nswindow.contentView;
  1398. if (view.subviews.count > 0) {
  1399. view = view.subviews[0];
  1400. if (view.tag == tag) {
  1401. return (SDL_MetalView)CFBridgingRetain(view);
  1402. }
  1403. }
  1404. }
  1405. #endif
  1406. #ifdef SDL_VIDEO_DRIVER_UIKIT
  1407. UIWindow *uiwindow = (__bridge UIWindow *)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.uikit.window", NULL);
  1408. NSInteger tag = (NSInteger)SDL_GetNumberProperty(SDL_GetWindowProperties(window), "SDL.window.uikit.metal_view_tag", 0);
  1409. if (uiwindow && tag) {
  1410. UIView *view = uiwindow.rootViewController.view;
  1411. if (view.tag == tag) {
  1412. return (SDL_MetalView)CFBridgingRetain(view);
  1413. }
  1414. }
  1415. #endif
  1416. return nil;
  1417. }
  1418. static SDL_Renderer *METAL_CreateRenderer(SDL_Window *window, SDL_PropertiesID create_props)
  1419. {
  1420. @autoreleasepool {
  1421. SDL_Renderer *renderer = NULL;
  1422. METAL_RenderData *data = NULL;
  1423. id<MTLDevice> mtldevice = nil;
  1424. SDL_MetalView view = NULL;
  1425. CAMetalLayer *layer = nil;
  1426. NSError *err = nil;
  1427. dispatch_data_t mtllibdata;
  1428. char *constantdata;
  1429. int maxtexsize, quadcount = UINT16_MAX / 4;
  1430. UInt16 *indexdata;
  1431. size_t indicessize = sizeof(UInt16) * quadcount * 6;
  1432. MTLSamplerDescriptor *samplerdesc;
  1433. id<MTLCommandQueue> mtlcmdqueue;
  1434. id<MTLLibrary> mtllibrary;
  1435. id<MTLSamplerState> mtlsamplernearest, mtlsamplerlinear;
  1436. id<MTLBuffer> mtlbufconstantstaging, mtlbufquadindicesstaging, mtlbufconstants, mtlbufquadindices;
  1437. id<MTLCommandBuffer> cmdbuffer;
  1438. id<MTLBlitCommandEncoder> blitcmd;
  1439. /* Note: matrices are column major. */
  1440. float identitytransform[16] = {
  1441. 1.0f,
  1442. 0.0f,
  1443. 0.0f,
  1444. 0.0f,
  1445. 0.0f,
  1446. 1.0f,
  1447. 0.0f,
  1448. 0.0f,
  1449. 0.0f,
  1450. 0.0f,
  1451. 1.0f,
  1452. 0.0f,
  1453. 0.0f,
  1454. 0.0f,
  1455. 0.0f,
  1456. 1.0f,
  1457. };
  1458. float halfpixeltransform[16] = {
  1459. 1.0f,
  1460. 0.0f,
  1461. 0.0f,
  1462. 0.0f,
  1463. 0.0f,
  1464. 1.0f,
  1465. 0.0f,
  1466. 0.0f,
  1467. 0.0f,
  1468. 0.0f,
  1469. 1.0f,
  1470. 0.0f,
  1471. 0.5f,
  1472. 0.5f,
  1473. 0.0f,
  1474. 1.0f,
  1475. };
  1476. /* Metal pads float3s to 16 bytes. */
  1477. float decodetransformJPEG[4 * 4] = {
  1478. 0.0, -0.501960814, -0.501960814, 0.0, /* offset */
  1479. 1.0000, 0.0000, 1.4020, 0.0, /* Rcoeff */
  1480. 1.0000, -0.3441, -0.7141, 0.0, /* Gcoeff */
  1481. 1.0000, 1.7720, 0.0000, 0.0, /* Bcoeff */
  1482. };
  1483. float decodetransformBT601[4 * 4] = {
  1484. -0.0627451017, -0.501960814, -0.501960814, 0.0, /* offset */
  1485. 1.1644, 0.0000, 1.5960, 0.0, /* Rcoeff */
  1486. 1.1644, -0.3918, -0.8130, 0.0, /* Gcoeff */
  1487. 1.1644, 2.0172, 0.0000, 0.0, /* Bcoeff */
  1488. };
  1489. float decodetransformBT709[4 * 4] = {
  1490. 0.0, -0.501960814, -0.501960814, 0.0, /* offset */
  1491. 1.0000, 0.0000, 1.4020, 0.0, /* Rcoeff */
  1492. 1.0000, -0.3441, -0.7141, 0.0, /* Gcoeff */
  1493. 1.0000, 1.7720, 0.0000, 0.0, /* Bcoeff */
  1494. };
  1495. if (!IsMetalAvailable()) {
  1496. return NULL;
  1497. }
  1498. renderer = (SDL_Renderer *)SDL_calloc(1, sizeof(*renderer));
  1499. if (!renderer) {
  1500. return NULL;
  1501. }
  1502. #ifdef __MACOS__
  1503. if (SDL_GetHintBoolean(SDL_HINT_RENDER_METAL_PREFER_LOW_POWER_DEVICE, SDL_TRUE)) {
  1504. NSArray<id<MTLDevice>> *devices = MTLCopyAllDevices();
  1505. for (id<MTLDevice> device in devices) {
  1506. if (device.isLowPower) {
  1507. mtldevice = device;
  1508. break;
  1509. }
  1510. }
  1511. }
  1512. #endif
  1513. if (mtldevice == nil) {
  1514. mtldevice = MTLCreateSystemDefaultDevice();
  1515. }
  1516. if (mtldevice == nil) {
  1517. SDL_free(renderer);
  1518. SDL_SetError("Failed to obtain Metal device");
  1519. return NULL;
  1520. }
  1521. view = GetWindowView(window);
  1522. if (view == nil) {
  1523. view = SDL_Metal_CreateView(window);
  1524. }
  1525. if (view == NULL) {
  1526. SDL_free(renderer);
  1527. return NULL;
  1528. }
  1529. // !!! FIXME: error checking on all of this.
  1530. data = [[METAL_RenderData alloc] init];
  1531. if (data == nil) {
  1532. /* Release the metal view instead of destroying it,
  1533. in case we want to use it later (recreating the renderer)
  1534. */
  1535. /* SDL_Metal_DestroyView(view); */
  1536. CFBridgingRelease(view);
  1537. SDL_free(renderer);
  1538. return NULL;
  1539. }
  1540. renderer->driverdata = (void *)CFBridgingRetain(data);
  1541. renderer->window = window;
  1542. data.mtlview = view;
  1543. #ifdef __MACOS__
  1544. layer = (CAMetalLayer *)[(__bridge NSView *)view layer];
  1545. #else
  1546. layer = (CAMetalLayer *)[(__bridge UIView *)view layer];
  1547. #endif
  1548. layer.device = mtldevice;
  1549. /* Necessary for RenderReadPixels. */
  1550. layer.framebufferOnly = NO;
  1551. data.mtldevice = layer.device;
  1552. data.mtllayer = layer;
  1553. mtlcmdqueue = [data.mtldevice newCommandQueue];
  1554. data.mtlcmdqueue = mtlcmdqueue;
  1555. data.mtlcmdqueue.label = @"SDL Metal Renderer";
  1556. data.mtlpassdesc = [MTLRenderPassDescriptor renderPassDescriptor];
  1557. // The compiled .metallib is embedded in a static array in a header file
  1558. // but the original shader source code is in SDL_shaders_metal.metal.
  1559. mtllibdata = dispatch_data_create(sdl_metallib, sdl_metallib_len, dispatch_get_global_queue(0, 0), ^{
  1560. });
  1561. mtllibrary = [data.mtldevice newLibraryWithData:mtllibdata error:&err];
  1562. data.mtllibrary = mtllibrary;
  1563. SDL_assert(err == nil);
  1564. data.mtllibrary.label = @"SDL Metal renderer shader library";
  1565. /* Do some shader pipeline state loading up-front rather than on demand. */
  1566. data.pipelinescount = 0;
  1567. data.allpipelines = NULL;
  1568. ChooseShaderPipelines(data, MTLPixelFormatBGRA8Unorm);
  1569. samplerdesc = [[MTLSamplerDescriptor alloc] init];
  1570. samplerdesc.minFilter = MTLSamplerMinMagFilterNearest;
  1571. samplerdesc.magFilter = MTLSamplerMinMagFilterNearest;
  1572. mtlsamplernearest = [data.mtldevice newSamplerStateWithDescriptor:samplerdesc];
  1573. data.mtlsamplernearest = mtlsamplernearest;
  1574. samplerdesc.minFilter = MTLSamplerMinMagFilterLinear;
  1575. samplerdesc.magFilter = MTLSamplerMinMagFilterLinear;
  1576. mtlsamplerlinear = [data.mtldevice newSamplerStateWithDescriptor:samplerdesc];
  1577. data.mtlsamplerlinear = mtlsamplerlinear;
  1578. mtlbufconstantstaging = [data.mtldevice newBufferWithLength:CONSTANTS_LENGTH options:MTLResourceStorageModeShared];
  1579. constantdata = [mtlbufconstantstaging contents];
  1580. SDL_memcpy(constantdata + CONSTANTS_OFFSET_IDENTITY, identitytransform, sizeof(identitytransform));
  1581. SDL_memcpy(constantdata + CONSTANTS_OFFSET_HALF_PIXEL_TRANSFORM, halfpixeltransform, sizeof(halfpixeltransform));
  1582. SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_JPEG, decodetransformJPEG, sizeof(decodetransformJPEG));
  1583. SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_BT601, decodetransformBT601, sizeof(decodetransformBT601));
  1584. SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_BT709, decodetransformBT709, sizeof(decodetransformBT709));
  1585. mtlbufquadindicesstaging = [data.mtldevice newBufferWithLength:indicessize options:MTLResourceStorageModeShared];
  1586. /* Quads in the following vertex order (matches the FillRects vertices):
  1587. * 1---3
  1588. * | \ |
  1589. * 0---2
  1590. */
  1591. indexdata = [mtlbufquadindicesstaging contents];
  1592. for (int i = 0; i < quadcount; i++) {
  1593. indexdata[i * 6 + 0] = i * 4 + 0;
  1594. indexdata[i * 6 + 1] = i * 4 + 1;
  1595. indexdata[i * 6 + 2] = i * 4 + 2;
  1596. indexdata[i * 6 + 3] = i * 4 + 2;
  1597. indexdata[i * 6 + 4] = i * 4 + 1;
  1598. indexdata[i * 6 + 5] = i * 4 + 3;
  1599. }
  1600. mtlbufconstants = [data.mtldevice newBufferWithLength:CONSTANTS_LENGTH options:MTLResourceStorageModePrivate];
  1601. data.mtlbufconstants = mtlbufconstants;
  1602. data.mtlbufconstants.label = @"SDL constant data";
  1603. mtlbufquadindices = [data.mtldevice newBufferWithLength:indicessize options:MTLResourceStorageModePrivate];
  1604. data.mtlbufquadindices = mtlbufquadindices;
  1605. data.mtlbufquadindices.label = @"SDL quad index buffer";
  1606. cmdbuffer = [data.mtlcmdqueue commandBuffer];
  1607. blitcmd = [cmdbuffer blitCommandEncoder];
  1608. [blitcmd copyFromBuffer:mtlbufconstantstaging sourceOffset:0 toBuffer:mtlbufconstants destinationOffset:0 size:CONSTANTS_LENGTH];
  1609. [blitcmd copyFromBuffer:mtlbufquadindicesstaging sourceOffset:0 toBuffer:mtlbufquadindices destinationOffset:0 size:indicessize];
  1610. [blitcmd endEncoding];
  1611. [cmdbuffer commit];
  1612. // !!! FIXME: force more clears here so all the drawables are sane to start, and our static buffers are definitely flushed.
  1613. renderer->WindowEvent = METAL_WindowEvent;
  1614. renderer->GetOutputSize = METAL_GetOutputSize;
  1615. renderer->SupportsBlendMode = METAL_SupportsBlendMode;
  1616. renderer->CreateTexture = METAL_CreateTexture;
  1617. renderer->UpdateTexture = METAL_UpdateTexture;
  1618. #if SDL_HAVE_YUV
  1619. renderer->UpdateTextureYUV = METAL_UpdateTextureYUV;
  1620. renderer->UpdateTextureNV = METAL_UpdateTextureNV;
  1621. #endif
  1622. renderer->LockTexture = METAL_LockTexture;
  1623. renderer->UnlockTexture = METAL_UnlockTexture;
  1624. renderer->SetTextureScaleMode = METAL_SetTextureScaleMode;
  1625. renderer->SetRenderTarget = METAL_SetRenderTarget;
  1626. renderer->QueueSetViewport = METAL_QueueSetViewport;
  1627. renderer->QueueSetDrawColor = METAL_QueueSetDrawColor;
  1628. renderer->QueueDrawPoints = METAL_QueueDrawPoints;
  1629. renderer->QueueDrawLines = METAL_QueueDrawLines;
  1630. renderer->QueueGeometry = METAL_QueueGeometry;
  1631. renderer->InvalidateCachedState = METAL_InvalidateCachedState;
  1632. renderer->RunCommandQueue = METAL_RunCommandQueue;
  1633. renderer->RenderReadPixels = METAL_RenderReadPixels;
  1634. renderer->RenderPresent = METAL_RenderPresent;
  1635. renderer->DestroyTexture = METAL_DestroyTexture;
  1636. renderer->DestroyRenderer = METAL_DestroyRenderer;
  1637. renderer->SetVSync = METAL_SetVSync;
  1638. renderer->GetMetalLayer = METAL_GetMetalLayer;
  1639. renderer->GetMetalCommandEncoder = METAL_GetMetalCommandEncoder;
  1640. renderer->info = METAL_RenderDriver.info;
  1641. renderer->info.flags = SDL_RENDERER_ACCELERATED;
  1642. #if (defined(__MACOS__) && defined(MAC_OS_X_VERSION_10_13)) || TARGET_OS_MACCATALYST
  1643. if (@available(macOS 10.13, *)) {
  1644. data.mtllayer.displaySyncEnabled = SDL_GetBooleanProperty(create_props, "present_vsync", SDL_FALSE);
  1645. if (data.mtllayer.displaySyncEnabled) {
  1646. renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
  1647. }
  1648. } else
  1649. #endif
  1650. {
  1651. renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
  1652. }
  1653. /* https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf */
  1654. maxtexsize = 4096;
  1655. #if defined(__MACOS__) || TARGET_OS_MACCATALYST
  1656. maxtexsize = 16384;
  1657. #elif defined(__TVOS__)
  1658. maxtexsize = 8192;
  1659. #ifdef __TVOS_11_0
  1660. if (@available(tvOS 11.0, *)) {
  1661. if ([mtldevice supportsFeatureSet:MTLFeatureSet_tvOS_GPUFamily2_v1]) {
  1662. maxtexsize = 16384;
  1663. }
  1664. }
  1665. #endif
  1666. #else
  1667. #ifdef __IPHONE_11_0
  1668. #pragma clang diagnostic push
  1669. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  1670. if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily4_v1]) {
  1671. maxtexsize = 16384;
  1672. } else
  1673. #pragma clang diagnostic pop
  1674. #endif
  1675. #ifdef __IPHONE_10_0
  1676. if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1]) {
  1677. maxtexsize = 16384;
  1678. } else
  1679. #endif
  1680. if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v2] || [mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily1_v2]) {
  1681. maxtexsize = 8192;
  1682. } else {
  1683. maxtexsize = 4096;
  1684. }
  1685. #endif
  1686. renderer->info.max_texture_width = maxtexsize;
  1687. renderer->info.max_texture_height = maxtexsize;
  1688. return renderer;
  1689. }
  1690. }
  1691. SDL_RenderDriver METAL_RenderDriver = {
  1692. METAL_CreateRenderer,
  1693. {
  1694. "metal",
  1695. (SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC),
  1696. 6,
  1697. { SDL_PIXELFORMAT_ARGB8888,
  1698. SDL_PIXELFORMAT_ABGR8888,
  1699. SDL_PIXELFORMAT_YV12,
  1700. SDL_PIXELFORMAT_IYUV,
  1701. SDL_PIXELFORMAT_NV12,
  1702. SDL_PIXELFORMAT_NV21 },
  1703. 0,
  1704. 0,
  1705. }
  1706. };
  1707. #endif /* SDL_VIDEO_RENDER_METAL && !SDL_RENDER_DISABLED */