SDL_render_metal.m 70 KB

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