8#include <QGuiApplication>
12#include <QTemporaryFile>
15#include <QtCore/qendian.h>
16#include <QOperatingSystemVersion>
18#include <QtCore/private/qcore_mac_p.h>
19#include <QtGui/private/qmetallayer_p.h>
20#include <QtGui/qpa/qplatformwindow_p.h>
23#include <AppKit/AppKit.h>
25#include <UIKit/UIKit.h>
28#include <QuartzCore/CATransaction.h>
30#include <Metal/Metal.h>
37
38
39
40
41
42
43
44
45
48#error ARC not supported
57#define QRHI_METAL_DISABLE_BINARY_ARCHIVE
62#define QRHI_METAL_COMMAND_BUFFERS_WITH_UNRETAINED_REFERENCES
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
105
106
107
108
109
110
111
112
115
116
117
118
121
122
123
124
125
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
149
150
153
154
169 nativeResourceBindingMap.clear();
174 [argumentEncoder release];
175 argumentEncoder = nil;
191 const QColor &colorClearValue,
192 const QRhiDepthStencilClearValue &depthStencilClearValue,
194 QRhiShadingRateMap *shadingRateMap);
196 bool preferArgumentBuffers,
197 QString *error, QByteArray *entryPoint, QShaderKey *activeKey);
221 id<MTLBuffer> buffers[QMTL_FRAMES_IN_FLIGHT];
224 id<MTLTexture> texture;
227 id<MTLTexture> texture;
228 id<MTLBuffer> stagingBuffers[QMTL_FRAMES_IN_FLIGHT];
229 id<MTLTexture> views[QRhi::MAX_MIP_LEVELS];
230 id<MTLTexture> samplingView;
231 id<MTLTexture> writeView;
234 id<MTLSamplerState> samplerState;
237 id<MTLBuffer> buffer;
240 id<MTLRenderPipelineState> pipelineState;
241 id<MTLDepthStencilState> depthStencilState;
242 std::array<id<MTLComputePipelineState>, 3> tessVertexComputeState;
243 id<MTLComputePipelineState> tessTessControlComputeState;
246 id<MTLComputePipelineState> pipelineState;
249 id<MTLRasterizationRateMap> rateMap;
252 id<MTLIndirectCommandBuffer> icb;
253 id<MTLBuffer> argBuffer;
332 int frameSlot, quint32 minBlockSize, quint32 *offset);
479 id<MTLTexture> dsTex = nil;
480 id<MTLTexture> dsResolveTex = nil;
481 bool hasStencil =
false;
482 bool depthNeedsStore =
false;
483 bool preserveColor =
false;
484 bool preserveDs =
false;
528 return vertexOrIndexCount * instanceCount *
sizeof(
float) * 60;
537 return patchCount *
sizeof(
float) * 128;
585 if (importDevice->dev) {
586 d->dev = (id<MTLDevice>) importDevice->dev;
588 if (importedCmdQueue)
589 d->cmdQueue = (id<MTLCommandQueue>) importDevice->cmdQueue;
591 qWarning(
"No MTLDevice given, cannot import");
605 return (v + byteAlign - 1) & ~(byteAlign - 1);
610 QMacAutoReleasePool pool;
613 id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
627 return [cmdQueue commandBufferWithUnretainedReferences];
629 return [cmdQueue commandBuffer];
640 MTLBinaryArchiveDescriptor *binArchDesc = [MTLBinaryArchiveDescriptor
new];
641 binArchDesc.url = sourceFileUrl;
643 binArch = [dev newBinaryArchiveWithDescriptor: binArchDesc error: &err];
644 [binArchDesc release];
646 const QString msg = QString::fromNSString(err.localizedDescription);
647 qWarning(
"newBinaryArchiveWithDescriptor failed: %s", qPrintable(msg));
660 d->dev = MTLCreateSystemDefaultDevice();
663 qWarning(
"No MTLDevice");
667 const QString deviceName = QString::fromNSString([d->dev name]);
668 qCDebug(QRHI_LOG_INFO,
"Metal device: %s", qPrintable(deviceName));
669 driverInfoStruct.deviceName = deviceName.toUtf8();
676 const MTLDeviceLocation deviceLocation = [d->dev location];
677 switch (deviceLocation) {
678 case MTLDeviceLocationBuiltIn:
679 driverInfoStruct.deviceType = QRhiDriverInfo::IntegratedDevice;
681 case MTLDeviceLocationSlot:
682 driverInfoStruct.deviceType = QRhiDriverInfo::DiscreteDevice;
684 case MTLDeviceLocationExternal:
685 driverInfoStruct.deviceType = QRhiDriverInfo::ExternalDevice;
691 driverInfoStruct.deviceType = QRhiDriverInfo::IntegratedDevice;
694 const QOperatingSystemVersion ver = QOperatingSystemVersion::current();
695 osMajor = ver.majorVersion();
696 osMinor = ver.minorVersion();
699 [d->cmdQueue retain];
701 d->cmdQueue = [d->dev newCommandQueue];
703 d->captureMgr = [MTLCaptureManager sharedCaptureManager];
707 d->captureScope = [d->captureMgr newCaptureScopeWithCommandQueue: d->cmdQueue];
708 const QString label = QString::asprintf(
"Qt capture scope for QRhi %p",
this);
709 d->captureScope.label = label.toNSString();
711#if defined(Q_OS_MACOS) || defined(Q_OS_VISIONOS)
712 caps.maxTextureSize = 16384;
713 caps.baseVertexAndInstance =
true;
714 caps.isAppleGPU = [d->dev supportsFamily:MTLGPUFamilyApple7];
715 caps.maxThreadGroupSize = 1024;
716 caps.multiView =
true;
717#elif defined(Q_OS_TVOS)
718 if ([d->dev supportsFamily:MTLGPUFamilyApple3])
719 caps.maxTextureSize = 16384;
721 caps.maxTextureSize = 8192;
722 caps.baseVertexAndInstance =
false;
723 caps.isAppleGPU =
true;
724#elif defined(Q_OS_IOS)
725 if ([d->dev supportsFamily:MTLGPUFamilyApple3]) {
726 caps.maxTextureSize = 16384;
727 caps.baseVertexAndInstance =
true;
728 }
else if ([d->dev supportsFamily:MTLGPUFamilyApple2]) {
729 caps.maxTextureSize = 8192;
730 caps.baseVertexAndInstance =
false;
732 caps.maxTextureSize = 4096;
733 caps.baseVertexAndInstance =
false;
735 caps.isAppleGPU =
true;
736 if ([d->dev supportsFamily:MTLGPUFamilyApple4])
737 caps.maxThreadGroupSize = 1024;
738 if ([d->dev supportsFamily:MTLGPUFamilyApple5])
739 caps.multiView =
true;
745 caps.usePrivateStaticBuffers = caps.isAppleGPU;
746 if (qEnvironmentVariableIntValue(
"QT_METAL_NO_PRIVATE_STATIC_BUFFERS"))
747 caps.usePrivateStaticBuffers =
false;
749 caps.supportedSampleCounts = { 1 };
750 for (
int sampleCount : { 2, 4, 8 }) {
751 if ([d->dev supportsTextureSampleCount: sampleCount])
752 caps.supportedSampleCounts.append(sampleCount);
755 caps.indirectCommandBuffers = ([d->dev supportsFamily:MTLGPUFamilyApple5]
756 || [d->dev supportsFamily:MTLGPUFamilyMac2])
757 && [d->dev supportsFamily:MTLGPUFamilyMetal3];
759 caps.shadingRateMap = [d->dev supportsRasterizationRateMapWithLayerCount: 1];
760 if (caps.shadingRateMap && caps.multiView)
761 caps.shadingRateMap = [d->dev supportsRasterizationRateMapWithLayerCount: 2];
764 caps.depthClamp = [d->dev supportsFamily:MTLGPUFamilyApple3];
766#if defined(Q_OS_MACOS) || defined(Q_OS_VISIONOS)
767 caps.fragmentStoresAndAtomics =
true;
769 caps.fragmentStoresAndAtomics = [d->dev supportsFamily:MTLGPUFamilyApple3];
772 if (rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
773 d->setupBinaryArchive();
775 nativeHandlesStruct.dev = (MTLDevice *) d->dev;
776 nativeHandlesStruct.cmdQueue = (MTLCommandQueue *) d->cmdQueue;
786 for (QMetalShader &s : d->shaderCache)
788 d->shaderCache.clear();
790 [d->captureScope release];
791 d->captureScope = nil;
793 for (
auto *pools : { d->argBufPool, d->bufStagingPool }) {
794 for (
int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
795 [pools[i].buf release];
797 pools[i].capacity = 0;
802 [d->icbArgumentBuffer release];
803 d->icbArgumentBuffer = nil;
805 [d->icbRangeBuffer release];
806 d->icbRangeBuffer = nil;
808 [d->icbNoCountBuffer release];
809 d->icbNoCountBuffer = nil;
811 [d->icbEncodeFunction release];
812 d->icbEncodeFunction = nil;
814 [d->icbEncodeFunctionU32 release];
815 d->icbEncodeFunctionU32 = nil;
817 [d->icbEncodeFunctionU16 release];
818 d->icbEncodeFunctionU16 = nil;
820 [d->icbEncodePipeline release];
821 d->icbEncodePipeline = nil;
823 [d->icbEncodePipelineU32 release];
824 d->icbEncodePipelineU32 = nil;
826 [d->icbEncodePipelineU16 release];
827 d->icbEncodePipelineU16 = nil;
835 [d->binArch release];
838 [d->cmdQueue release];
849 return caps.supportedSampleCounts;
854 Q_UNUSED(sampleCount);
855 return { QSize(1, 1) };
860 return new QMetalSwapChain(
this);
863QRhiBuffer *
QRhiMetal::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
865 return new QMetalBuffer(
this, type, usage, size);
892 static constexpr QMatrix4x4 m(1.0f, 0.0f, 0.0f, 0.0f,
893 0.0f, 1.0f, 0.0f, 0.0f,
894 0.0f, 0.0f, 0.5f, 0.5f,
895 0.0f, 0.0f, 0.0f, 1.0f);
903 bool supportsFamilyMac2 =
false;
904 bool supportsFamilyApple3 =
false;
907 supportsFamilyMac2 =
true;
909 supportsFamilyApple3 =
true;
911 supportsFamilyApple3 =
true;
915 if (format == QRhiTexture::BC5)
918 if (!supportsFamilyApple3) {
919 if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ETC2_RGBA8)
921 if (format >= QRhiTexture::ASTC_4x4 && format <= QRhiTexture::ASTC_12x12)
925 if (!supportsFamilyMac2)
926 if (format >= QRhiTexture::BC1 && format <= QRhiTexture::BC7)
935 case QRhi::MultisampleTexture:
937 case QRhi::MultisampleRenderBuffer:
939 case QRhi::DebugMarkers:
941 case QRhi::Timestamps:
943 case QRhi::Instancing:
945 case QRhi::CustomInstanceStepRate:
947 case QRhi::PrimitiveRestart:
949 case QRhi::NonDynamicUniformBuffers:
951 case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
953 case QRhi::NPOTTextureRepeat:
955 case QRhi::RedOrAlpha8IsRed:
957 case QRhi::ElementIndexUint:
961 case QRhi::FragmentStoresAndAtomics:
962 return caps.fragmentStoresAndAtomics;
963 case QRhi::WideLines:
965 case QRhi::VertexShaderPointSize:
967 case QRhi::BaseVertex:
968 return caps.baseVertexAndInstance;
969 case QRhi::BaseInstance:
970 return caps.baseVertexAndInstance;
971 case QRhi::TriangleFanTopology:
973 case QRhi::ReadBackNonUniformBuffer:
975 case QRhi::ReadBackNonBaseMipLevel:
977 case QRhi::TexelFetch:
979 case QRhi::RenderToNonBaseMipLevel:
981 case QRhi::IntAttributes:
983 case QRhi::ScreenSpaceDerivatives:
985 case QRhi::ReadBackAnyTextureFormat:
987 case QRhi::PipelineCacheDataLoadSave:
993 case QRhi::ImageDataStride:
995 case QRhi::RenderBufferImport:
997 case QRhi::ThreeDimensionalTextures:
999 case QRhi::RenderTo3DTextureSlice:
1001 case QRhi::TextureArrays:
1003 case QRhi::Tessellation:
1005 case QRhi::GeometryShader:
1007 case QRhi::TextureArrayRange:
1009 case QRhi::NonFillPolygonMode:
1011 case QRhi::OneDimensionalTextures:
1013 case QRhi::OneDimensionalTextureMipmaps:
1015 case QRhi::HalfAttributes:
1017 case QRhi::RenderToOneDimensionalTexture:
1019 case QRhi::ThreeDimensionalTextureMipmaps:
1021 case QRhi::MultiView:
1022 return caps.multiView;
1023 case QRhi::TextureViewFormat:
1025 case QRhi::ResolveDepthStencil:
1027 case QRhi::VariableRateShading:
1029 case QRhi::VariableRateShadingMap:
1030 return caps.shadingRateMap;
1031 case QRhi::VariableRateShadingMapWithTexture:
1033 case QRhi::DualSourceBlend:
1034 case QRhi::PerRenderTargetBlending:
1035 case QRhi::SampleVariables:
1037 case QRhi::InstanceIndexIncludesBaseInstance:
1039 case QRhi::DepthClamp:
1040 return caps.depthClamp;
1041 case QRhi::DrawIndirect:
1043 case QRhi::BaseInstanceIndirect:
1044 return caps.baseVertexAndInstance;
1045 case QRhi::DrawIndirectMulti:
1046 return caps.indirectCommandBuffers;
1047 case QRhi::ShaderDrawParameters:
1049 case QRhi::PushConstants:
1051 case QRhi::DrawIndirectCount:
1052 return caps.indirectCommandBuffers;
1053 case QRhi::DispatchIndirect:
1055 case QRhi::BufferToBufferCopy:
1057 case QRhi::StaticBuffersOnGpuTimeline:
1058 return caps.usePrivateStaticBuffers;
1068 case QRhi::TextureSizeMin:
1070 case QRhi::TextureSizeMax:
1071 return caps.maxTextureSize;
1072 case QRhi::MaxColorAttachments:
1074 case QRhi::FramesInFlight:
1075 return QMTL_FRAMES_IN_FLIGHT;
1076 case QRhi::MaxAsyncReadbackFrames:
1077 return QMTL_FRAMES_IN_FLIGHT;
1078 case QRhi::MaxThreadGroupsPerDimension:
1080 case QRhi::MaxThreadsPerThreadGroup:
1082 case QRhi::MaxThreadGroupX:
1084 case QRhi::MaxThreadGroupY:
1086 case QRhi::MaxThreadGroupZ:
1087 return caps.maxThreadGroupSize;
1088 case QRhi::TextureArraySizeMax:
1090 case QRhi::MaxUniformBufferRange:
1092 case QRhi::MaxVertexInputs:
1094 case QRhi::MaxVertexOutputs:
1096 case QRhi::MaxPushConstantsSize:
1098 case QRhi::MaxVertexStorageBuffers:
1099 case QRhi::MaxFragmentStorageBuffers:
1101 case QRhi::MaxStorageBufferBindings:
1102 case QRhi::MaxStorageImageBindings:
1104 case QRhi::ShadingRateImageTileSize:
1114 return &nativeHandlesStruct;
1119 return driverInfoStruct;
1125 result.totalPipelineCreationTime = totalPipelineCreationTime();
1142 for (QMetalShader &s : d->shaderCache)
1145 d->shaderCache.clear();
1167 if (!d->binArch || !rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
1172 qCDebug(QRHI_LOG_INFO,
"pipelineCacheData: Failed to create temporary file for Metal");
1177 const QString fn = QFileInfo(tmp.fileName()).absoluteFilePath();
1178 NSURL *url = QUrl::fromLocalFile(fn).toNSURL();
1180 if (![d->binArch serializeToURL: url error: &err]) {
1181 const QString msg = QString::fromNSString(err.localizedDescription);
1183 qCDebug(QRHI_LOG_INFO,
"Failed to serialize MTLBinaryArchive: %s", qPrintable(msg));
1188 if (!f.open(QIODevice::ReadOnly)) {
1189 qCDebug(QRHI_LOG_INFO,
"pipelineCacheData: Failed to reopen temporary file");
1192 const QByteArray blob = f.readAll();
1196 const quint32 dataSize = quint32(blob.size());
1198 data.resize(headerSize + dataSize);
1201 header.rhiId = pipelineCacheRhiId();
1202 header.arch = quint32(
sizeof(
void*));
1203 header.dataSize = quint32(dataSize);
1204 header.osMajor = osMajor;
1205 header.osMinor = osMinor;
1206 const size_t driverStrLen = qMin(
sizeof(header
.driver) - 1, size_t(driverInfoStruct.deviceName.length()));
1208 memcpy(header.driver, driverInfoStruct.deviceName.constData(), driverStrLen);
1209 header.driver[driverStrLen] =
'\0';
1211 memcpy(data.data(), &header, headerSize);
1212 memcpy(data.data() + headerSize, blob.constData(), dataSize);
1222 if (data.size() < qsizetype(headerSize)) {
1223 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob size (header incomplete)");
1227 const size_t dataOffset = headerSize;
1229 memcpy(&header, data.constData(), headerSize);
1231 const quint32 rhiId = pipelineCacheRhiId();
1232 if (header.rhiId != rhiId) {
1233 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: The data is for a different QRhi version or backend (%u, %u)",
1234 rhiId, header.rhiId);
1238 const quint32 arch = quint32(
sizeof(
void*));
1239 if (header.arch != arch) {
1240 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Architecture does not match (%u, %u)",
1245 if (header.osMajor != osMajor || header.osMinor != osMinor) {
1246 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: OS version does not match (%u.%u, %u.%u)",
1247 osMajor, osMinor, header.osMajor, header.osMinor);
1251 const size_t driverStrLen = qMin(
sizeof(header
.driver) - 1, size_t(driverInfoStruct.deviceName.length()));
1252 if (strncmp(header
.driver, driverInfoStruct.deviceName.constData(), driverStrLen)) {
1253 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Metal device name does not match");
1257 if (quint64(data.size()) < quint64(dataOffset) + header.dataSize) {
1258 qCDebug(QRHI_LOG_INFO,
"setPipelineCacheData: Invalid blob size (data incomplete)");
1262 const char *p = data.constData() + dataOffset;
1266 qCDebug(QRHI_LOG_INFO,
"pipelineCacheData: Failed to create temporary file for Metal");
1269 tmp.write(p, header.dataSize);
1272 const QString fn = QFileInfo(tmp.fileName()).absoluteFilePath();
1273 NSURL *url = QUrl::fromLocalFile(fn).toNSURL();
1274 if (
d->setupBinaryArchive(url))
1275 qCDebug(QRHI_LOG_INFO,
"Created MTLBinaryArchive with initial data of %u bytes", header.dataSize);
1278QRhiRenderBuffer *
QRhiMetal::createRenderBuffer(QRhiRenderBuffer::Type type,
const QSize &pixelSize,
1279 int sampleCount, QRhiRenderBuffer::Flags flags,
1280 QRhiTexture::Format backingFormatHint)
1282 return new QMetalRenderBuffer(
this, type, pixelSize, sampleCount, flags, backingFormatHint);
1286 const QSize &pixelSize,
int depth,
int arraySize,
1287 int sampleCount, QRhiTexture::Flags flags)
1289 return new QMetalTexture(
this, format, pixelSize, depth, arraySize, sampleCount, flags);
1293 QRhiSampler::Filter mipmapMode,
1294 QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
1296 return new QMetalSampler(
this, magFilter, minFilter, mipmapMode, u, v, w);
1301 return new QMetalShadingRateMap(
this);
1305 QRhiTextureRenderTarget::Flags flags)
1312 return new QMetalGraphicsPipeline(
this);
1317 return new QMetalComputePipeline(
this);
1322 return new QMetalShaderResourceBindings(
this);
1333 const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[],
1336 const QShader::NativeResourceBindingMap *map = nativeResourceBindingMaps[stageIndex];
1337 if (!map || map->isEmpty())
1340 auto it = map->constFind(binding);
1341 if (it != map->cend())
1353 case QRhiShaderResourceBinding::ImageLoad:
1354 return MTLResourceUsageRead;
1355 case QRhiShaderResourceBinding::ImageStore:
1356 return MTLResourceUsageWrite;
1358 return MTLResourceUsageRead | MTLResourceUsageWrite;
1366 for (
const QMetalShaderResourceBindingsData::Stage::Texture &t : res.textures) {
1367 switch (encoderStage) {
1368 case QMetalShaderResourceBindingsData::VERTEX:
1369 [cbD->d->currentRenderPassEncoder useResource: t.mtltex usage: t.usage stages: MTLRenderStageVertex];
1371 case QMetalShaderResourceBindingsData::FRAGMENT:
1372 [cbD->d->currentRenderPassEncoder useResource: t.mtltex usage: t.usage stages: MTLRenderStageFragment];
1374 case QMetalShaderResourceBindingsData::COMPUTE:
1375 [cbD->d->currentComputePassEncoder useResource: t.mtltex usage: t.usage];
1385 const QRhiBatchedBindings<id<MTLBuffer>>::Batch &bufferBatch,
1386 const QRhiBatchedBindings<NSUInteger>::Batch &offsetBatch)
1389 case QMetalShaderResourceBindingsData::VERTEX:
1390 [cbD->d->currentRenderPassEncoder setVertexBuffers: bufferBatch.resources.constData()
1391 offsets: offsetBatch.resources.constData()
1392 withRange: NSMakeRange(bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
1394 case QMetalShaderResourceBindingsData::FRAGMENT:
1395 [cbD->d->currentRenderPassEncoder setFragmentBuffers: bufferBatch.resources.constData()
1396 offsets: offsetBatch.resources.constData()
1397 withRange: NSMakeRange(bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
1399 case QMetalShaderResourceBindingsData::COMPUTE:
1400 [cbD->d->currentComputePassEncoder setBuffers: bufferBatch.resources.constData()
1401 offsets: offsetBatch.resources.constData()
1402 withRange: NSMakeRange(bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
1416 const QRhiBatchedBindings<id<MTLTexture>>::Batch &textureBatch)
1419 case QMetalShaderResourceBindingsData::VERTEX:
1420 [cbD->d->currentRenderPassEncoder setVertexTextures: textureBatch.resources.constData()
1421 withRange: NSMakeRange(textureBatch.startBinding, NSUInteger(textureBatch.resources.count()))];
1423 case QMetalShaderResourceBindingsData::FRAGMENT:
1424 [cbD->d->currentRenderPassEncoder setFragmentTextures: textureBatch.resources.constData()
1425 withRange: NSMakeRange(textureBatch.startBinding, NSUInteger(textureBatch.resources.count()))];
1427 case QMetalShaderResourceBindingsData::COMPUTE:
1428 [cbD->d->currentComputePassEncoder setTextures: textureBatch.resources.constData()
1429 withRange: NSMakeRange(textureBatch.startBinding, NSUInteger(textureBatch.resources.count()))];
1443 const QRhiBatchedBindings<id<MTLSamplerState>>::Batch &samplerBatch)
1445 switch (encoderStage) {
1446 case QMetalShaderResourceBindingsData::VERTEX:
1447 [cbD->d->currentRenderPassEncoder setVertexSamplerStates: samplerBatch.resources.constData()
1448 withRange: NSMakeRange(samplerBatch.startBinding, NSUInteger(samplerBatch.resources.count()))];
1450 case QMetalShaderResourceBindingsData::FRAGMENT:
1451 [cbD->d->currentRenderPassEncoder setFragmentSamplerStates: samplerBatch.resources.constData()
1452 withRange: NSMakeRange(samplerBatch.startBinding, NSUInteger(samplerBatch.resources.count()))];
1454 case QMetalShaderResourceBindingsData::COMPUTE:
1455 [cbD->d->currentComputePassEncoder setSamplerStates: samplerBatch.resources.constData()
1456 withRange: NSMakeRange(samplerBatch.startBinding, NSUInteger(samplerBatch.resources.count()))];
1478 for (
int i = 0, ie = bindingData->res[resourceStage].bufferBatches.batches.count(); i != ie; ++i) {
1479 const auto &bufferBatch(bindingData->res[resourceStage].bufferBatches.batches[i]);
1480 const auto &offsetBatch(bindingData->res[resourceStage].bufferOffsetBatches.batches[i]);
1481 bindStageBuffers(cbD, encoderStage, bufferBatch, offsetBatch);
1484 for (
int i = 0, ie = bindingData->res[resourceStage].textureBatches.batches.count(); i != ie; ++i) {
1485 const auto &batch(bindingData->res[resourceStage].textureBatches.batches[i]);
1486 bindStageTextures(cbD, encoderStage, batch);
1489 for (
int i = 0, ie = bindingData->res[resourceStage].samplerBatches.batches.count(); i != ie; ++i) {
1490 const auto &batch(bindingData->res[resourceStage].samplerBatches.batches[i]);
1491 bindStageSamplers(cbD, encoderStage, batch);
1494 if (bindingData->res[resourceStage].usesArgumentBuffer)
1495 declareStageArgumentBufferResources(cbD, encoderStage, bindingData->res[resourceStage]);
1501 case QMetalShaderResourceBindingsData::VERTEX:
1502 return QRhiShaderResourceBinding::StageFlag::VertexStage;
1503 case QMetalShaderResourceBindingsData::TESSCTRL:
1504 return QRhiShaderResourceBinding::StageFlag::TessellationControlStage;
1505 case QMetalShaderResourceBindingsData::TESSEVAL:
1506 return QRhiShaderResourceBinding::StageFlag::TessellationEvaluationStage;
1507 case QMetalShaderResourceBindingsData::FRAGMENT:
1508 return QRhiShaderResourceBinding::StageFlag::FragmentStage;
1509 case QMetalShaderResourceBindingsData::COMPUTE:
1510 return QRhiShaderResourceBinding::StageFlag::ComputeStage;
1513 Q_UNREACHABLE_RETURN(QRhiShaderResourceBinding::StageFlag::VertexStage);
1518 int dynamicOffsetCount,
1519 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets,
1520 bool offsetOnlyChange,
1521 const QShader::NativeResourceBindingMap *nativeResourceBindingMaps[
SUPPORTED_STAGES],
1526 for (
const QRhiShaderResourceBinding &binding : std::as_const(srbD->sortedBindings)) {
1527 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(binding);
1528 switch (b->type()) {
1529 case QRhiShaderResourceBinding::UniformBuffer:
1531 QMetalBuffer *bufD =
QRHI_RES(QMetalBuffer, b->ubuf().buf);
1532 id<MTLBuffer> mtlbuf = bufD->d->buf[bufD->d->slotted ? currentFrameSlot : 0];
1533 quint32 offset = b->ubuf().offset;
1534 for (
int i = 0; i < dynamicOffsetCount; ++i) {
1535 const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]);
1536 if (dynOfs.first == b->binding) {
1537 offset = dynOfs.second;
1542 for (
int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1543 if (b->stage.testFlag(toRhiSrbStage(stage))) {
1544 const int nativeBinding = mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Buffer);
1545 if (nativeBinding >= 0)
1546 bindingData.res[stage].buffers.append({ nativeBinding, mtlbuf, offset });
1551 case QRhiShaderResourceBinding::SampledTexture:
1552 case QRhiShaderResourceBinding::Texture:
1553 case QRhiShaderResourceBinding::Sampler:
1555 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
1556 for (
int elem = 0; elem < data->count(); ++elem) {
1557 QMetalTexture *texD =
QRHI_RES(QMetalTexture, data->texSamplers[elem].tex);
1558 QMetalSampler *samplerD =
QRHI_RES(QMetalSampler, data->texSamplers[elem].sampler);
1560 for (
int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1561 if (b->stage.testFlag(toRhiSrbStage(stage))) {
1566 const int textureBinding = mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Texture);
1567 const int samplerBinding = texD && samplerD ? mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Sampler)
1568 : (samplerD ? mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Texture) : -1);
1569 if (textureBinding >= 0 && texD)
1570 bindingData.res[stage].textures.append({ textureBinding + elem, texD->d->textureForSampling(), MTLResourceUsageRead });
1571 if (samplerBinding >= 0)
1572 bindingData.res[stage].samplers.append({ samplerBinding + elem, samplerD->d->samplerState });
1578 case QRhiShaderResourceBinding::ImageLoad:
1579 case QRhiShaderResourceBinding::ImageStore:
1580 case QRhiShaderResourceBinding::ImageLoadStore:
1582 QMetalTexture *texD =
QRHI_RES(QMetalTexture, b->simage().tex);
1583 id<MTLTexture> t = texD->d->viewForLevel(b->simage().level);
1585 for (
int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1586 if (b->stage.testFlag(toRhiSrbStage(stage))) {
1587 const int nativeBinding = mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Texture);
1588 if (nativeBinding >= 0)
1589 bindingData.res[stage].textures.append({ nativeBinding, t, storageImageUsage(b->type()) });
1594 case QRhiShaderResourceBinding::BufferLoad:
1595 case QRhiShaderResourceBinding::BufferStore:
1596 case QRhiShaderResourceBinding::BufferLoadStore:
1598 QMetalBuffer *bufD =
QRHI_RES(QMetalBuffer, b->sbuf().buf);
1599 id<MTLBuffer> mtlbuf = bufD->d->buf[bufD->d->slotted ? currentFrameSlot : 0];
1600 quint32 offset = b->sbuf().offset;
1601 for (
int stage = 0; stage < SUPPORTED_STAGES; ++stage) {
1602 if (b->stage.testFlag(toRhiSrbStage(stage))) {
1603 const int nativeBinding = mapBinding(b->binding, stage, nativeResourceBindingMaps, BindingType::Buffer);
1604 if (nativeBinding >= 0)
1605 bindingData.res[stage].buffers.append({ nativeBinding, mtlbuf, offset });
1621 if (!shader || !shader->argumentEncoder)
1628 if (offsetOnlyChange) {
1630 cbD
->d->currentShaderResourceBindingState.res[stage]);
1632 for (
const QMetalShaderResourceBindingsData::Stage::Buffer &b : prev.buffers) {
1633 if (b.nativeBinding == shader->argumentBufferIndex) {
1634 res.samplers.clear();
1635 res.buffers.append(b);
1636 res.usesArgumentBuffer =
true;
1649 const quint32 argBufAlignment = qMax(quint32(shader->argumentEncoder.alignment),
1651 quint32 argBufOffset = 0;
1652 id<MTLBuffer> argBuf =
d->allocArgumentBuffer(quint32(shader->argumentEncoder.encodedLength),
1653 argBufAlignment, currentFrameSlot, &argBufOffset);
1659 qWarning(
"Failed to allocate Metal argument buffer");
1660 res.textures.clear();
1661 res.samplers.clear();
1664 [shader->argumentEncoder setArgumentBuffer: argBuf offset: argBufOffset];
1665 for (
const QMetalShaderResourceBindingsData::Stage::Texture &t : std::as_const(res.textures))
1666 [shader->argumentEncoder setTexture: t.mtltex atIndex: NSUInteger(t.nativeBinding)];
1667 for (
const QMetalShaderResourceBindingsData::Stage::Sampler &sm : std::as_const(res.samplers))
1668 [shader->argumentEncoder setSamplerState: sm.mtlsampler atIndex: NSUInteger(sm.nativeBinding)];
1669 res.samplers.clear();
1690 for (
const QMetalShaderResourceBindingsData::Stage::Buffer &buf : std::as_const(bindingData.res[stage].buffers)) {
1691 bindingData.res[stage].bufferBatches.feed(buf.nativeBinding, buf.mtlbuf);
1692 bindingData.res[stage].bufferOffsetBatches.feed(buf.nativeBinding, buf.offset);
1695 bindingData.res[stage].bufferBatches.finish();
1696 bindingData.res[stage].bufferOffsetBatches.finish();
1698 for (
int i = 0, ie = bindingData.res[stage].bufferBatches.batches.count(); i != ie; ++i) {
1699 const auto &bufferBatch(bindingData.res[stage].bufferBatches.batches[i]);
1700 const auto &offsetBatch(bindingData.res[stage].bufferOffsetBatches.batches[i]);
1702 if (cbD
->d->currentShaderResourceBindingState.res[stage].bufferBatches.batches.count() > i
1703 && cbD
->d->currentShaderResourceBindingState.res[stage].bufferOffsetBatches.batches.count() > i
1704 && bufferBatch == cbD
->d->currentShaderResourceBindingState.res[stage].bufferBatches.batches[i]
1705 && offsetBatch == cbD
->d->currentShaderResourceBindingState.res[stage].bufferOffsetBatches.batches[i])
1709 bindStageBuffers(cbD, stage, bufferBatch, offsetBatch);
1712 if (offsetOnlyChange)
1715 if (bindingData.res[stage].usesArgumentBuffer) {
1716 declareStageArgumentBufferResources(cbD, stage, bindingData.res[stage]);
1728 for (
const QMetalShaderResourceBindingsData::Stage::Texture &t : std::as_const(bindingData.res[stage].textures))
1729 bindingData.res[stage].textureBatches.feed(t.nativeBinding, t.mtltex);
1731 for (
const QMetalShaderResourceBindingsData::Stage::Sampler &s : std::as_const(bindingData.res[stage].samplers))
1732 bindingData.res[stage].samplerBatches.feed(s.nativeBinding, s.mtlsampler);
1734 bindingData.res[stage].textureBatches.finish();
1735 bindingData.res[stage].samplerBatches.finish();
1737 for (
int i = 0, ie = bindingData.res[stage].textureBatches.batches.count(); i != ie; ++i) {
1738 const auto &batch(bindingData.res[stage].textureBatches.batches[i]);
1740 if (cbD
->d->currentShaderResourceBindingState.res[stage].textureBatches.batches.count() > i
1741 && batch == cbD
->d->currentShaderResourceBindingState.res[stage].textureBatches.batches[i])
1745 bindStageTextures(cbD, stage, batch);
1748 for (
int i = 0, ie = bindingData.res[stage].samplerBatches.batches.count(); i != ie; ++i) {
1749 const auto &batch(bindingData.res[stage].samplerBatches.batches[i]);
1751 if (cbD
->d->currentShaderResourceBindingState.res[stage].samplerBatches.batches.count() > i
1752 && batch == cbD
->d->currentShaderResourceBindingState.res[stage].samplerBatches.batches[i])
1756 bindStageSamplers(cbD, stage, batch);
1760 cbD
->d->currentShaderResourceBindingState = bindingData;
1765 const QList<QShaderDescription::PushConstantBlock> blocks = s.desc.pushConstantBlocks();
1766 return blocks.isEmpty() ? 0 : quint32(blocks.first().size);
1771 return s.nativeShaderInfo.extraBufferBindings.value(QShaderPrivate::MslPushConstantBufferBinding, -1);
1784 [cbD->d->currentRenderPassEncoder setRenderPipelineState: d->ps];
1786 if (cbD
->d->currentDepthStencilState !=
d->ds) {
1787 [cbD->d->currentRenderPassEncoder setDepthStencilState: d->ds];
1788 cbD
->d->currentDepthStencilState =
d->ds;
1791 [cbD->d->currentRenderPassEncoder setCullMode: d->cullMode];
1795 [cbD->d->currentRenderPassEncoder setTriangleFillMode: d->triangleFillMode];
1798 if (rhiD->caps.depthClamp) {
1800 [cbD->d->currentRenderPassEncoder setDepthClipMode: d->depthClipMode];
1805 [cbD->d->currentRenderPassEncoder setFrontFacingWinding: d->winding];
1808 if (!qFuzzyCompare(
d->depthBias, cbD->currentDepthBiasValues.first)
1811 [cbD->d->currentRenderPassEncoder setDepthBias: d->depthBias
1812 slopeScale: d->slopeScaledDepthBias
1817 if (m_stencilTest) {
1818 const quint32 ref = m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef)
1819 ? cbD->currentStencilRef : 0;
1820 if (cbD->appliedStencilRef != ref) {
1821 [cbD->d->currentRenderPassEncoder setStencilReferenceValue: ref];
1822 cbD->appliedStencilRef = ref;
1827 const int vsIdx = mtlPushConstantBufferIndex(
d->vs);
1828 const int fsIdx = mtlPushConstantBufferIndex(
d->fs);
1829 if (vsIdx >= 0 || fsIdx >= 0) {
1830 const quint32 blockSize = qMax(mtlPushConstantBlockSize(d->vs), mtlPushConstantBlockSize(d->fs));
1831 if (quint32(cbD->pushConstantData.size()) < blockSize)
1832 cbD->pushConstantData.resize(
int(blockSize), 0);
1833 const NSUInteger total = NSUInteger(cbD->pushConstantData.size());
1835 [cbD->d->currentRenderPassEncoder setVertexBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(vsIdx)];
1837 [cbD->d->currentRenderPassEncoder setFragmentBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(fsIdx)];
1859 if (!psD
->d->tess.enabled && !psD
->d->tess.failed)
1864 for (QMetalBuffer *workBuf : psD->d->extraBufMgr.deviceLocalWorkBuffers) {
1865 if (workBuf && workBuf->lastActiveFrameSlot == currentFrameSlot)
1866 workBuf->lastActiveFrameSlot = -1;
1868 for (QMetalBuffer *workBuf : psD->d->extraBufMgr.hostVisibleWorkBuffers) {
1869 if (workBuf && workBuf->lastActiveFrameSlot == currentFrameSlot)
1870 workBuf->lastActiveFrameSlot = -1;
1877 int dynamicOffsetCount,
1878 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets)
1887 srb = gfxPsD->m_shaderResourceBindings;
1889 srb = compPsD->m_shaderResourceBindings;
1893 bool hasSlottedResourceInSrb =
false;
1894 bool hasDynamicOffsetInSrb =
false;
1895 bool resNeedsRebind =
false;
1897 bool pipelineChanged =
false;
1910 QMap<QRhiShaderResourceBinding::StageFlag, QMap<
int, quint32>> storageBufferSizes;
1913 for (
int i = 0, ie = srbD->sortedBindings.count(); i != ie; ++i) {
1914 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->sortedBindings.at(i));
1916 switch (b->type()) {
1917 case QRhiShaderResourceBinding::UniformBuffer:
1920 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer));
1921 sanityCheckResourceOwnership(bufD);
1924 hasSlottedResourceInSrb =
true;
1925 if (b->ubuf().hasDynamicOffset)
1926 hasDynamicOffsetInSrb =
true;
1927 if (bufD
->generation != bd.ubuf.generation || bufD->m_id != bd.ubuf.id) {
1928 resNeedsRebind =
true;
1929 bd.ubuf.id = bufD->m_id;
1935 case QRhiShaderResourceBinding::SampledTexture:
1936 case QRhiShaderResourceBinding::Texture:
1937 case QRhiShaderResourceBinding::Sampler:
1939 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
1940 if (bd.stex.d.size() != data->count()) {
1941 bd.stex.d.resize(data->count());
1942 resNeedsRebind =
true;
1944 for (
int elem = 0; elem < data->count(); ++elem) {
1947 Q_ASSERT(texD || samplerD);
1948 sanityCheckResourceOwnership(texD);
1949 sanityCheckResourceOwnership(samplerD);
1950 const quint64 texId = texD ? texD->m_id : 0;
1952 const quint64 samplerId = samplerD ? samplerD->m_id : 0;
1953 const uint samplerGen = samplerD ? samplerD
->generation : 0;
1954 if (texGen != bd.stex.d[elem].texGeneration
1955 || texId != bd.stex.d[elem].texId
1956 || samplerGen != bd.stex.d[elem].samplerGeneration
1957 || samplerId != bd.stex.d[elem].samplerId)
1959 resNeedsRebind =
true;
1960 bd.stex.d[elem].texId = texId;
1961 bd.stex.d[elem].texGeneration = texGen;
1962 bd.stex.d[elem].samplerId = samplerId;
1963 bd.stex.d[elem].samplerGeneration = samplerGen;
1972 case QRhiShaderResourceBinding::ImageLoad:
1973 case QRhiShaderResourceBinding::ImageStore:
1974 case QRhiShaderResourceBinding::ImageLoadStore:
1977 sanityCheckResourceOwnership(texD);
1978 if (texD
->generation != bd.simage.generation || texD->m_id != bd.simage.id) {
1979 resNeedsRebind =
true;
1980 bd.simage.id = texD->m_id;
1986 case QRhiShaderResourceBinding::BufferLoad:
1987 case QRhiShaderResourceBinding::BufferStore:
1988 case QRhiShaderResourceBinding::BufferLoadStore:
1991 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::StorageBuffer));
1992 sanityCheckResourceOwnership(bufD);
1994 if (needsBufferSizeBuffer) {
1995 for (
int i = 0; i < 6; ++i) {
1996 const QRhiShaderResourceBinding::StageFlag stage =
1997 QRhiShaderResourceBinding::StageFlag(1 << i);
1998 if (b->stage.testFlag(stage)) {
1999 storageBufferSizes[stage][b->binding] = b->sbuf().maybeSize ? b->sbuf().maybeSize : bufD->size();
2005 if (bufD
->generation != bd.sbuf.generation || bufD->m_id != bd.sbuf.id) {
2006 resNeedsRebind =
true;
2007 bd.sbuf.id = bufD->m_id;
2019 if (needsBufferSizeBuffer) {
2021 QVarLengthArray<std::pair<QMetalShader *, QRhiShaderResourceBinding::StageFlag>, 4> shaders;
2025 Q_ASSERT(compPsD
->d->cs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding));
2026 shaders.append({&compPsD->d->cs, QRhiShaderResourceBinding::StageFlag::ComputeStage});
2029 if (gfxPsD
->d->tess.enabled) {
2039 Q_ASSERT(gfxPsD
->d->tess.compVs[0].desc.storageBlocks() == gfxPsD
->d->tess.compVs[1].desc.storageBlocks());
2040 Q_ASSERT(gfxPsD
->d->tess.compVs[0].desc.storageBlocks() == gfxPsD
->d->tess.compVs[2].desc.storageBlocks());
2041 Q_ASSERT(gfxPsD
->d->tess.compVs[0].nativeResourceBindingMap == gfxPsD
->d->tess.compVs[1].nativeResourceBindingMap);
2042 Q_ASSERT(gfxPsD
->d->tess.compVs[0].nativeResourceBindingMap == gfxPsD
->d->tess.compVs[2].nativeResourceBindingMap);
2043 Q_ASSERT(gfxPsD
->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)
2044 == gfxPsD
->d->tess.compVs[1].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding));
2045 Q_ASSERT(gfxPsD
->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)
2046 == gfxPsD
->d->tess.compVs[2].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding));
2047 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding]
2048 == gfxPsD->d->tess.compVs[1].nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding]);
2049 Q_ASSERT(gfxPsD->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding]
2050 == gfxPsD->d->tess.compVs[2].nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding]);
2052 if (gfxPsD
->d->tess.compVs[0].nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2053 shaders.append({&gfxPsD->d->tess.compVs[0], QRhiShaderResourceBinding::StageFlag::VertexStage});
2055 if (gfxPsD
->d->tess.compTesc.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2056 shaders.append({&gfxPsD->d->tess.compTesc, QRhiShaderResourceBinding::StageFlag::TessellationControlStage});
2058 if (gfxPsD
->d->tess.vertTese.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2059 shaders.append({&gfxPsD->d->tess.vertTese, QRhiShaderResourceBinding::StageFlag::TessellationEvaluationStage});
2062 if (gfxPsD
->d->vs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2063 shaders.append({&gfxPsD->d->vs, QRhiShaderResourceBinding::StageFlag::VertexStage});
2065 if (gfxPsD
->d->fs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding))
2066 shaders.append({&gfxPsD->d->fs, QRhiShaderResourceBinding::StageFlag::FragmentStage});
2070 for (
const auto &shader : shaders) {
2072 const int binding = shader.first->nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding];
2075 if (!(storageBufferSizes.contains(shader.second) && storageBufferSizes[shader.second].contains(binding))) {
2077 int maxNativeBinding = 0;
2078 for (
const QShaderDescription::StorageBlock &block : shader.first->desc.storageBlocks())
2079 maxNativeBinding = qMax(maxNativeBinding, shader.first->nativeResourceBindingMap[block.binding].first);
2081 const int size = (maxNativeBinding + 1) *
sizeof(
int);
2083 Q_ASSERT(offset + size <= bufD->size());
2084 srbD->sortedBindings.append(QRhiShaderResourceBinding::bufferLoad(binding, shader.second, bufD, offset, size));
2086 QMetalShaderResourceBindings::BoundResourceData bd;
2087 bd.sbuf.id = bufD->m_id;
2088 bd.sbuf.generation = bufD->generation;
2089 srbD->boundResourceData.append(bd);
2093 QVarLengthArray<
int, 8> bufferSizeBufferData;
2094 Q_ASSERT(storageBufferSizes.contains(shader.second));
2095 const QMap<
int, quint32> &sizes(storageBufferSizes[shader.second]);
2096 for (
const QShaderDescription::StorageBlock &block : shader.first->desc.storageBlocks()) {
2097 const int index = shader.first->nativeResourceBindingMap[block.binding].first;
2103 if (bufferSizeBufferData.size() <= index)
2104 bufferSizeBufferData.resize(index + 1);
2106 Q_ASSERT(sizes.contains(block.binding));
2107 bufferSizeBufferData[index] = sizes[block.binding];
2110 QRhiBufferData data;
2111 const quint32 size = bufferSizeBufferData.size() *
sizeof(
int);
2112 data.assign(
reinterpret_cast<
const char *>(bufferSizeBufferData.constData()), size);
2113 Q_ASSERT(offset + size <= bufD->size());
2114 bufD->d->pendingUpdates[bufD->d->slotted ? currentFrameSlot : 0].append({ offset, data });
2117 offset += ((size + 31) / 32) * 32;
2125 const int resSlot = hasSlottedResourceInSrb ? currentFrameSlot : 0;
2127 resNeedsRebind =
true;
2133 if (hasDynamicOffsetInSrb || resNeedsRebind || srbChanged || srbRebuilt || pipelineChanged) {
2134 const QShader::NativeResourceBindingMap *resBindMaps[
SUPPORTED_STAGES] = {
nullptr,
nullptr,
nullptr,
nullptr,
nullptr };
2139 if (gfxPsD
->d->tess.enabled) {
2142 Q_ASSERT(gfxPsD
->d->tess.compVs[0].nativeResourceBindingMap == gfxPsD
->d->tess.compVs[1].nativeResourceBindingMap);
2143 Q_ASSERT(gfxPsD
->d->tess.compVs[0].nativeResourceBindingMap == gfxPsD
->d->tess.compVs[2].nativeResourceBindingMap);
2162 const bool offsetOnlyChange = hasDynamicOffsetInSrb && !resNeedsRebind
2163 && !srbChanged && !srbRebuilt && !pipelineChanged;
2164 enqueueShaderResourceBindings(srbD, cbD, dynamicOffsetCount, dynamicOffsets, offsetOnlyChange,
2165 resBindMaps, shaders);
2170 int startBinding,
int bindingCount,
const QRhiCommandBuffer::VertexInput *bindings,
2171 QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
2176 QRhiBatchedBindings<id<MTLBuffer> > buffers;
2177 QRhiBatchedBindings<NSUInteger> offsets;
2178 for (
int i = 0; i < bindingCount; ++i) {
2182 id<MTLBuffer> mtlbuf = bufD->d->buf[bufD->d->slotted ? currentFrameSlot : 0];
2183 buffers.feed(startBinding + i, mtlbuf);
2184 offsets.feed(startBinding + i, bindings[i].second);
2199 || buffers != cbD
->d->currentVertexInputsBuffers
2200 || offsets != cbD
->d->currentVertexInputOffsets)
2203 cbD
->d->currentVertexInputsBuffers = buffers;
2204 cbD
->d->currentVertexInputOffsets = offsets;
2206 for (
int i = 0, ie = buffers.batches.count(); i != ie; ++i) {
2207 const auto &bufferBatch(buffers.batches[i]);
2208 const auto &offsetBatch(offsets.batches[i]);
2209 [cbD->d->currentRenderPassEncoder setVertexBuffers:
2210 bufferBatch.resources.constData()
2211 offsets: offsetBatch.resources.constData()
2212 withRange: NSMakeRange(uint(firstVertexBinding) + bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
2221 cbD->currentIndexOffset = indexOffset;
2222 cbD->currentIndexFormat = indexFormat;
2233QSize
QRhiMetal::outputSizeForTarget(QRhiRenderTarget *target)
2235 QRhiShadingRateMap *srm =
nullptr;
2236 switch (target->resourceType()) {
2237 case QRhiResource::TextureRenderTarget:
2238 srm =
QRHI_RES(QMetalTextureRenderTarget, target)->m_desc.shadingRateMap();
2240 case QRhiResource::SwapChainRenderTarget:
2241 srm =
QRHI_RES(QMetalSwapChainRenderTarget, target)->swapChain()->shadingRateMap();
2248 const QSize logicalSize = srm->logicalSize();
2249 if (logicalSize.isValid())
2253 return target->pixelSize();
2260 const QSize outputSize = outputSizeForTarget(cbD->currentTarget);
2261 std::array<
float, 4> vp = cbD->currentViewport.viewport();
2262 float x = 0, y = 0, w = 0, h = 0;
2264 if (qFuzzyIsNull(vp[2]) && qFuzzyIsNull(vp[3])) {
2267 w = outputSize.width();
2268 h = outputSize.height();
2271 qrhi_toTopLeftRenderTargetRect<
Bounded>(outputSize, vp, &x, &y, &w, &h);
2275 s.x = NSUInteger(x);
2276 s.y = NSUInteger(y);
2277 s.width = NSUInteger(w);
2278 s.height = NSUInteger(h);
2279 [cbD->d->currentRenderPassEncoder setScissorRect: s];
2286 const QSize outputSize = outputSizeForTarget(cbD->currentTarget);
2290 if (!qrhi_toTopLeftRenderTargetRect<
UnBounded>(outputSize, viewport.viewport(), &x, &y, &w, &h))
2294 vp.originX =
double(x);
2295 vp.originY =
double(y);
2296 vp.width =
double(w);
2297 vp.height =
double(h);
2298 vp.znear =
double(viewport.minDepth());
2299 vp.zfar =
double(viewport.maxDepth());
2301 [cbD->d->currentRenderPassEncoder setViewport: vp];
2303 cbD->currentViewport = viewport;
2317 const QSize outputSize = outputSizeForTarget(cbD->currentTarget);
2321 if (!qrhi_toTopLeftRenderTargetRect<
Bounded>(outputSize, scissor.scissor(), &x, &y, &w, &h))
2325 s.x = NSUInteger(x);
2326 s.y = NSUInteger(y);
2327 s.width = NSUInteger(w);
2328 s.height = NSUInteger(h);
2330 [cbD->d->currentRenderPassEncoder setScissorRect: s];
2333 cbD->currentScissor = scissor;
2341 [cbD->d->currentRenderPassEncoder setBlendColorRed: c.redF()
2342 green: c.greenF() blue: c.blueF() alpha: c.alphaF()];
2345 cbD->currentBlendConstants = c;
2353 [cbD->d->currentRenderPassEncoder setStencilReferenceValue: refValue];
2355 cbD->currentStencilRef = refValue;
2356 cbD->appliedStencilRef = refValue;
2366 auto patch = [cbD, offset, size, data](quint32 blockSize) {
2367 const quint32 total = qMax(blockSize, offset + size);
2368 if (quint32(cbD->pushConstantData.size()) < total)
2369 cbD->pushConstantData.resize(
int(total), 0);
2370 memcpy(cbD->pushConstantData.data() + offset, data, size);
2378 const int idx = mtlPushConstantBufferIndex(psD
->d->cs);
2380 qWarning(
"No pipeline with a push constant block is active; setPushConstants ignored");
2383 const quint32 total = patch(mtlPushConstantBlockSize(psD->d->cs));
2384 [cbD->d->currentComputePassEncoder setBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(idx)];
2389 if (psD
->d->tess.enabled) {
2390 qWarning(
"Push constants are not supported with tessellation on Metal");
2393 const int vsIdx = mtlPushConstantBufferIndex(psD
->d->vs);
2394 const int fsIdx = mtlPushConstantBufferIndex(psD
->d->fs);
2395 if (vsIdx < 0 && fsIdx < 0) {
2396 qWarning(
"No pipeline with a push constant block is active; setPushConstants ignored");
2399 const quint32 total = patch(qMax(mtlPushConstantBlockSize(psD->d->vs), mtlPushConstantBlockSize(psD->d->fs)));
2401 [cbD->d->currentRenderPassEncoder setVertexBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(vsIdx)];
2403 [cbD->d->currentRenderPassEncoder setFragmentBytes: cbD->pushConstantData.constData() length: total atIndex: NSUInteger(fsIdx)];
2410 Q_UNUSED(coarsePixelSize);
2415 switch (cbD->currentTarget->resourceType()) {
2416 case QRhiResource::SwapChainRenderTarget:
2418 case QRhiResource::TextureRenderTarget:
2429 return tex && tex.storageMode != MTLStorageModeMemoryless;
2439 return finalAction == MTLStoreActionDontCare ? MTLStoreActionStore
2440 : MTLStoreActionStoreAndMultisampleResolve;
2450 for (
const auto &[index, finalAction] : std::as_const(cbD->d->deferredColorStoreActions))
2451 [cbD->d->currentRenderPassEncoder setColorStoreAction:
2452 interruptionStoreAction(finalAction, passIsEnding) atIndex: index];
2454 if (cbD->d->deferredDepthStoreAction != MTLStoreActionUnknown) {
2455 [cbD->d->currentRenderPassEncoder setDepthStoreAction:
2456 interruptionStoreAction(cbD->d->deferredDepthStoreAction, passIsEnding)];
2458 if (cbD->d->deferredStencilStoreAction != MTLStoreActionUnknown) {
2459 [cbD->d->currentRenderPassEncoder setStencilStoreAction:
2460 interruptionStoreAction(cbD->d->deferredStencilStoreAction, passIsEnding)];
2469 for (qsizetype i = 0; i < cbD->d->openDebugGroups.size(); ++i)
2470 [cbD->d->currentRenderPassEncoder popDebugGroup];
2471 [cbD->d->currentRenderPassEncoder endEncoding];
2472 cbD
->d->currentRenderPassEncoder = nil;
2477 id<MTLComputeCommandEncoder> maybeComputeEncoder)
2479 if (cbD
->d->currentRenderPassEncoder)
2482 if (!maybeComputeEncoder)
2483 maybeComputeEncoder = [cbD->d->cb computeCommandEncoder];
2485 return maybeComputeEncoder;
2489 id<MTLComputeCommandEncoder> computeEncoder)
2491 if (computeEncoder) {
2492 [computeEncoder endEncoding];
2493 computeEncoder = nil;
2497 if (!cbD
->d->currentPassRpDesc)
2506 const auto canLoad = [](MTLRenderPassAttachmentDescriptor *att) {
2507 return att.storeAction != MTLStoreActionDontCare && canStoreAttachment(att.texture);
2510 QVarLengthArray<MTLLoadAction, 4> oldColorLoad;
2512 oldColorLoad.append(cbD
->d->currentPassRpDesc.colorAttachments[i].loadAction);
2513 if (canLoad(cbD
->d->currentPassRpDesc.colorAttachments[i]))
2514 cbD
->d->currentPassRpDesc.colorAttachments[i].loadAction = MTLLoadActionLoad;
2517 MTLLoadAction oldDepthLoad;
2518 MTLLoadAction oldStencilLoad;
2520 oldDepthLoad = cbD
->d->currentPassRpDesc.depthAttachment.loadAction;
2521 if (canLoad(cbD
->d->currentPassRpDesc.depthAttachment))
2522 cbD
->d->currentPassRpDesc.depthAttachment.loadAction = MTLLoadActionLoad;
2524 oldStencilLoad = cbD
->d->currentPassRpDesc.stencilAttachment.loadAction;
2525 if (canLoad(cbD
->d->currentPassRpDesc.stencilAttachment))
2526 cbD
->d->currentPassRpDesc.stencilAttachment.loadAction = MTLLoadActionLoad;
2533 const QRhiViewport prevViewport = cbD->currentViewport;
2535 const QRhiScissor prevScissor = cbD->currentScissor;
2537 const QColor prevBlendConstants = cbD->currentBlendConstants;
2538 const quint32 prevStencilRef = cbD->currentStencilRef;
2546 const QVarLengthArray<
char, 128> prevPushConstantData = cbD->pushConstantData;
2548 cbD
->d->currentRenderPassEncoder = [cbD->d->cb renderCommandEncoderWithDescriptor: cbD->d->currentPassRpDesc];
2551 for (
const QByteArray &name : std::as_const(cbD->d->openDebugGroups))
2552 [cbD->d->currentRenderPassEncoder pushDebugGroup: [NSString stringWithUTF8String: name.constData()]];
2554 cbD->pushConstantData = prevPushConstantData;
2560 if (!qFuzzyIsNull(prevViewport.viewport()[2]) || !qFuzzyIsNull(prevViewport.viewport()[3]))
2561 rhiD->setViewport(cbD, prevViewport);
2563 rhiD->setScissor(cbD, prevScissor);
2564 else if (prevHasDefaultScissor)
2566 if (prevHasBlendConstants)
2567 rhiD->setBlendConstants(cbD, prevBlendConstants);
2568 cbD->currentStencilRef = prevStencilRef;
2571 cbD
->d->currentPassRpDesc.colorAttachments[i].loadAction = oldColorLoad[i];
2575 cbD
->d->currentPassRpDesc.depthAttachment.loadAction = oldDepthLoad;
2576 cbD
->d->currentPassRpDesc.stencilAttachment.loadAction = oldStencilLoad;
2585 if (graphicsPipeline
->d->tess.failed)
2589 const quint32 instanceCount = indexed ? args.drawIndexed.instanceCount : args.draw.instanceCount;
2590 const quint32 vertexOrIndexCount = indexed ? args.drawIndexed.indexCount : args.draw.vertexCount;
2594 const quint32 patchCount = tess.patchCountForDrawCall(vertexOrIndexCount, instanceCount);
2600 id<MTLComputeCommandEncoder> vertTescComputeEncoder
2601 = tempComputeEncoder(
this, cbD, cbD->d->tessellationComputeEncoder);
2602 cbD
->d->tessellationComputeEncoder = vertTescComputeEncoder;
2606 id<MTLComputeCommandEncoder> computeEncoder = vertTescComputeEncoder;
2607 QShader::Variant shaderVariant = QShader::NonIndexedVertexAsComputeShader;
2609 shaderVariant = QShader::UInt16IndexedVertexAsComputeShader;
2611 shaderVariant = QShader::UInt32IndexedVertexAsComputeShader;
2612 const int varIndex = QMetalGraphicsPipelineData::Tessellation::vsCompVariantToIndex(shaderVariant);
2613 id<MTLComputePipelineState> computePipelineState = tess.vsCompPipeline(
this, shaderVariant);
2614 [computeEncoder setComputePipelineState: computePipelineState];
2619 cbD
->d->currentComputePassEncoder = computeEncoder;
2621 cbD
->d->currentComputePassEncoder = nil;
2623 const QMap<
int,
int> &ebb(tess.compVs[varIndex].nativeShaderInfo.extraBufferBindings);
2624 const int outputBufferBinding = ebb.value(QShaderPrivate::MslTessVertTescOutputBufferBinding, -1);
2625 const int indexBufferBinding = ebb.value(QShaderPrivate::MslTessVertIndicesBufferBinding, -1);
2627 if (outputBufferBinding >= 0) {
2628 const quint32 workBufSize = tess.vsCompOutputBufferSize(vertexOrIndexCount, instanceCount);
2629 vertOutBuf = extraBufMgr.acquireWorkBuffer(
this, workBufSize);
2632 [computeEncoder setBuffer: vertOutBuf->d->buf[0] offset: 0 atIndex: outputBufferBinding];
2635 if (indexBufferBinding >= 0)
2636 [computeEncoder setBuffer: (id<MTLBuffer>) args.drawIndexed.indexBuffer offset: 0 atIndex: indexBufferBinding];
2638 for (
int i = 0, ie = cbD
->d->currentVertexInputsBuffers.batches.count(); i != ie; ++i) {
2639 const auto &bufferBatch(cbD
->d->currentVertexInputsBuffers.batches[i]);
2640 const auto &offsetBatch(cbD
->d->currentVertexInputOffsets.batches[i]);
2641 [computeEncoder setBuffers: bufferBatch.resources.constData()
2642 offsets: offsetBatch.resources.constData()
2643 withRange: NSMakeRange(uint(cbD->d->currentFirstVertexBinding) + bufferBatch.startBinding, NSUInteger(bufferBatch.resources.count()))];
2647 [computeEncoder setStageInRegion: MTLRegionMake2D(args.drawIndexed.vertexOffset, args.drawIndexed.firstInstance,
2648 args.drawIndexed.indexCount, args.drawIndexed.instanceCount)];
2650 [computeEncoder setStageInRegion: MTLRegionMake2D(args.draw.firstVertex, args.draw.firstInstance,
2651 args.draw.vertexCount, args.draw.instanceCount)];
2654 [computeEncoder dispatchThreads: MTLSizeMake(vertexOrIndexCount, instanceCount, 1)
2655 threadsPerThreadgroup: MTLSizeMake(computePipelineState.threadExecutionWidth, 1, 1)];
2660 id<MTLComputeCommandEncoder> computeEncoder = vertTescComputeEncoder;
2661 id<MTLComputePipelineState> computePipelineState = tess.tescCompPipeline(
this);
2662 [computeEncoder setComputePipelineState: computePipelineState];
2664 cbD
->d->currentComputePassEncoder = computeEncoder;
2666 cbD
->d->currentComputePassEncoder = nil;
2668 const QMap<
int,
int> &ebb(tess.compTesc.nativeShaderInfo.extraBufferBindings);
2669 const int outputBufferBinding = ebb.value(QShaderPrivate::MslTessVertTescOutputBufferBinding, -1);
2670 const int patchOutputBufferBinding = ebb.value(QShaderPrivate::MslTessTescPatchOutputBufferBinding, -1);
2671 const int tessFactorBufferBinding = ebb.value(QShaderPrivate::MslTessTescTessLevelBufferBinding, -1);
2672 const int paramsBufferBinding = ebb.value(QShaderPrivate::MslTessTescParamsBufferBinding, -1);
2673 const int inputBufferBinding = ebb.value(QShaderPrivate::MslTessTescInputBufferBinding, -1);
2675 if (outputBufferBinding >= 0) {
2676 const quint32 workBufSize = tess.tescCompOutputBufferSize(patchCount);
2677 tescOutBuf = extraBufMgr.acquireWorkBuffer(
this, workBufSize);
2680 [computeEncoder setBuffer: tescOutBuf->d->buf[0] offset: 0 atIndex: outputBufferBinding];
2683 if (patchOutputBufferBinding >= 0) {
2684 const quint32 workBufSize = tess.tescCompPatchOutputBufferSize(patchCount);
2685 tescPatchOutBuf = extraBufMgr.acquireWorkBuffer(
this, workBufSize);
2686 if (!tescPatchOutBuf)
2688 [computeEncoder setBuffer: tescPatchOutBuf->d->buf[0] offset: 0 atIndex: patchOutputBufferBinding];
2691 if (tessFactorBufferBinding >= 0) {
2692 tescFactorBuf = extraBufMgr.acquireWorkBuffer(
this, patchCount *
sizeof(MTLQuadTessellationFactorsHalf));
2693 [computeEncoder setBuffer: tescFactorBuf->d->buf[0] offset: 0 atIndex: tessFactorBufferBinding];
2696 if (paramsBufferBinding >= 0) {
2698 quint32 inControlPointCount;
2705 params.patchCount = patchCount;
2706 id<MTLBuffer> paramsBuf = tescParamsBuf
->d->buf[0];
2707 char *p =
reinterpret_cast<
char *>([paramsBuf contents]);
2708 memcpy(p, ¶ms,
sizeof(params));
2709 [computeEncoder setBuffer: paramsBuf offset: 0 atIndex: paramsBufferBinding];
2712 if (vertOutBuf && inputBufferBinding >= 0)
2713 [computeEncoder setBuffer: vertOutBuf->d->buf[0] offset: 0 atIndex: inputBufferBinding];
2715 int sgSize =
int(computePipelineState.threadExecutionWidth);
2716 int wgSize = std::lcm(tess.outControlPointCount, sgSize);
2717 while (wgSize > caps.maxThreadGroupSize) {
2719 wgSize = std::lcm(tess.outControlPointCount, sgSize);
2721 [computeEncoder dispatchThreads: MTLSizeMake(patchCount * tess.outControlPointCount, 1, 1)
2722 threadsPerThreadgroup: MTLSizeMake(wgSize, 1, 1)];
2730 endTempComputeEncoding(
this, cbD, cbD
->d->tessellationComputeEncoder);
2731 cbD
->d->tessellationComputeEncoder = nil;
2740 id<MTLRenderCommandEncoder> renderEncoder = cbD
->d->currentRenderPassEncoder;
2745 const QMap<
int,
int> &ebb(tess.compTesc.nativeShaderInfo.extraBufferBindings);
2746 const int outputBufferBinding = ebb.value(QShaderPrivate::MslTessVertTescOutputBufferBinding, -1);
2747 const int patchOutputBufferBinding = ebb.value(QShaderPrivate::MslTessTescPatchOutputBufferBinding, -1);
2748 const int tessFactorBufferBinding = ebb.value(QShaderPrivate::MslTessTescTessLevelBufferBinding, -1);
2750 if (outputBufferBinding >= 0 && tescOutBuf)
2751 [renderEncoder setVertexBuffer: tescOutBuf->d->buf[0] offset: 0 atIndex: outputBufferBinding];
2753 if (patchOutputBufferBinding >= 0 && tescPatchOutBuf)
2754 [renderEncoder setVertexBuffer: tescPatchOutBuf->d->buf[0] offset: 0 atIndex: patchOutputBufferBinding];
2756 if (tessFactorBufferBinding >= 0 && tescFactorBuf) {
2757 [renderEncoder setTessellationFactorBuffer: tescFactorBuf->d->buf[0] offset: 0 instanceStride: 0];
2758 [renderEncoder setVertexBuffer: tescFactorBuf->d->buf[0] offset: 0 atIndex: tessFactorBufferBinding];
2761 [cbD->d->currentRenderPassEncoder drawPatches: tess.outControlPointCount
2763 patchCount: patchCount
2764 patchIndexBuffer: nil
2765 patchIndexBufferOffset: 0
2775 if (multiViewCount <= 1)
2779 const int viewMaskBufBinding = ebb.value(QShaderPrivate::MslMultiViewMaskBufferBinding, -1);
2780 if (viewMaskBufBinding == -1) {
2781 qWarning(
"No extra buffer for multiview in the vertex shader; was it built with --view-count specified?");
2788 multiViewInfo.viewOffset = 0;
2789 multiViewInfo.viewCount = quint32(multiViewCount);
2793 id<MTLBuffer> mtlbuf = buf
->d->buf[0];
2794 char *p =
reinterpret_cast<
char *>([mtlbuf contents]);
2795 memcpy(p, &multiViewInfo,
sizeof(multiViewInfo));
2796 [cbD->d->currentRenderPassEncoder setVertexBuffer: mtlbuf offset: 0 atIndex: viewMaskBufBinding];
2800 *instanceCount *= multiViewCount;
2805 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
2814 a.draw.vertexCount = vertexCount;
2815 a.draw.instanceCount = instanceCount;
2816 a.draw.firstVertex = firstVertex;
2817 a.draw.firstInstance = firstInstance;
2822 adjustForMultiViewDraw(&instanceCount, cb);
2824 if (caps.baseVertexAndInstance) {
2825 [cbD->d->currentRenderPassEncoder drawPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
2826 vertexStart: firstVertex vertexCount: vertexCount instanceCount: instanceCount baseInstance: firstInstance];
2828 [cbD->d->currentRenderPassEncoder drawPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
2829 vertexStart: firstVertex vertexCount: vertexCount instanceCount: instanceCount];
2834 quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
2842 const quint32 indexOffset = cbD->currentIndexOffset + firstIndex * (cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? 2 : 4);
2843 Q_ASSERT(indexOffset == aligned(indexOffset, 4u));
2846 id<MTLBuffer> mtlibuf = ibufD->d->buf[ibufD->d->slotted ? currentFrameSlot : 0];
2851 a.type = cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? TessDrawArgs::U16Indexed : TessDrawArgs::U32Indexed;
2852 a.drawIndexed.indexCount = indexCount;
2853 a.drawIndexed.instanceCount = instanceCount;
2854 a.drawIndexed.firstIndex = firstIndex;
2855 a.drawIndexed.vertexOffset = vertexOffset;
2856 a.drawIndexed.firstInstance = firstInstance;
2857 a.drawIndexed.indexBuffer = mtlibuf;
2862 adjustForMultiViewDraw(&instanceCount, cb);
2864 if (caps.baseVertexAndInstance) {
2865 [cbD->d->currentRenderPassEncoder drawIndexedPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
2866 indexCount: indexCount
2867 indexType: cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
2868 indexBuffer: mtlibuf
2869 indexBufferOffset: indexOffset
2870 instanceCount: instanceCount
2871 baseVertex: vertexOffset
2872 baseInstance: firstInstance];
2874 [cbD->d->currentRenderPassEncoder drawIndexedPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
2875 indexCount: indexCount
2876 indexType: cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
2877 indexBuffer: mtlibuf
2878 indexBufferOffset: indexOffset
2879 instanceCount: instanceCount];
2886 if (!caps.indirectCommandBuffers)
2887 return "indirect command buffers are not supported on this device";
2891 return "the current graphics pipeline was not created with UsesIndirectDraws";
2894 return "the current graphics pipeline uses tessellation";
2896 return "the shaders of the current graphics pipeline sample textures but have no "
2897 "argument buffer variant, which Metal requires for a pipeline that supports "
2898 "indirect command buffers; rebuild them with qsb --msl-argument-buffers "
2899 "(or use MSLARGUMENTBUFFERS with qt_add_shaders)";
2909 if (!
d->icbEncodePipeline) {
2911 NSString *src = [NSString stringWithUTF8String:s_icbEncodeMsl];
2912 MTLCompileOptions *opts = [MTLCompileOptions
new];
2913 opts.languageVersion = MTLLanguageVersion2_1;
2914 id<MTLLibrary> lib = [d->dev newLibraryWithSource:src options:opts error:&err];
2917 qWarning(
"Failed to compile ICB encode kernel: %s",
2918 qPrintable(QString::fromNSString(err.localizedDescription)));
2922 d->icbEncodeFunction = [lib newFunctionWithName:@
"encode_icb"];
2923 d->icbEncodeFunctionU32 = [lib newFunctionWithName:@
"encode_icb_indexed_u32"];
2924 d->icbEncodeFunctionU16 = [lib newFunctionWithName:@
"encode_icb_indexed_u16"];
2926 if (!
d->icbEncodeFunction || !
d->icbEncodeFunctionU32 || !
d->icbEncodeFunctionU16) {
2927 qWarning(
"ICB encode kernel functions not found");
2931 NSError *errU32 = nil;
2932 NSError *errU16 = nil;
2933 d->icbEncodePipeline = [d->dev newComputePipelineStateWithFunction:d->icbEncodeFunction error:&err];
2934 d->icbEncodePipelineU32 = [d->dev newComputePipelineStateWithFunction:d->icbEncodeFunctionU32 error:&errU32];
2935 d->icbEncodePipelineU16 = [d->dev newComputePipelineStateWithFunction:d->icbEncodeFunctionU16 error:&errU16];
2936 if (!
d->icbEncodePipeline || !
d->icbEncodePipelineU32 || !
d->icbEncodePipelineU16) {
2937 NSError *firstErr = !
d->icbEncodePipeline ? err
2938 : (!
d->icbEncodePipelineU32 ? errU32 : errU16);
2939 qWarning(
"Failed to create ICB encode compute pipeline: %s",
2940 qPrintable(QString::fromNSString(firstErr.localizedDescription)));
2946 if (!
d->icbRangeBuffer) {
2947 d->icbRangeBuffer = [d->dev newBufferWithLength:
sizeof(MTLIndirectCommandBufferExecutionRange)
2948 options:MTLResourceStorageModePrivate];
2949 static constexpr quint32 noCount = 0xFFFFFFFFu;
2950 d->icbNoCountBuffer = [d->dev newBufferWithBytes:&noCount
2951 length:
sizeof(noCount)
2952 options:MTLResourceStorageModeShared];
2953 if (!
d->icbRangeBuffer || !
d->icbNoCountBuffer) {
2954 qWarning(
"Failed to create ICB helper buffers");
2968 if (!
d->icb ||
d->icbCapacity < maxDrawCount) {
2973 e.stagingIcbBuffer.icb =
d->icb;
2974 e.stagingIcbBuffer.argBuffer =
d->icbArgumentBuffer;
2975 d->releaseQueue.append(e);
2978 d->icbArgumentBuffer = nil;
2980 MTLIndirectCommandBufferDescriptor *icbDesc = [MTLIndirectCommandBufferDescriptor
new];
2981 icbDesc.commandTypes = MTLIndirectCommandTypeDraw | MTLIndirectCommandTypeDrawIndexed;
2982 icbDesc.inheritPipelineState = YES;
2983 icbDesc.inheritBuffers = YES;
2984 icbDesc.maxVertexBufferBindCount = 0;
2985 icbDesc.maxFragmentBufferBindCount = 0;
2986 d->icb = [d->dev newIndirectCommandBufferWithDescriptor:icbDesc
2987 maxCommandCount:maxDrawCount
2988 options:MTLResourceStorageModePrivate];
2991 qWarning(
"Failed to create MTLIndirectCommandBuffer");
2995 d->icbCapacity = maxDrawCount;
2997 id<MTLArgumentEncoder> argEnc = [d->icbEncodeFunction newArgumentEncoderWithBufferIndex:1];
2998 d->icbArgumentBuffer = [d->dev newBufferWithLength:argEnc.encodedLength
2999 options:MTLResourceStorageModeShared];
3000 [argEnc setArgumentBuffer:d->icbArgumentBuffer offset:0];
3001 [argEnc setIndirectCommandBuffer:d->icb atIndex:0];
3012 id<MTLComputeCommandEncoder> computeEncoder,
3013 id<MTLIndirectCommandBuffer> targetIcb,
3014 id<MTLBuffer> targetArgBuffer,
3015 id<MTLBuffer> targetRangeBuffer,
3017 QRhiCommandBuffer::IndexFormat indexFormat,
3018 MTLPrimitiveType primitiveType,
3019 id<MTLBuffer> indirectBufMtl, quint32 indirectBufferOffset,
3020 id<MTLBuffer> indexBufMtl, quint32 indexBufferOffset,
3021 id<MTLBuffer> countBufMtl, quint32 countBufferOffset,
3022 quint32 maxDrawCount, quint32 stride)
3024 id<MTLComputePipelineState> computePipeline = d->icbEncodePipeline;
3026 computePipeline = indexFormat == QRhiCommandBuffer::IndexUInt16
3027 ? d->icbEncodePipelineU16 : d->icbEncodePipelineU32;
3029 uint32_t maxDrawCountVal = maxDrawCount;
3030 uint32_t metalPrimType = uint32_t(primitiveType);
3031 uint32_t strideVal = stride;
3033 [computeEncoder setComputePipelineState:computePipeline];
3034 [computeEncoder setBuffer:indirectBufMtl offset:indirectBufferOffset atIndex:0];
3035 [computeEncoder setBuffer:targetArgBuffer offset:0 atIndex:1];
3036 [computeEncoder setBytes:&maxDrawCountVal length:
sizeof(uint32_t) atIndex:2];
3038 [computeEncoder setBuffer:indexBufMtl offset:indexBufferOffset atIndex:3];
3039 [computeEncoder setBytes:&metalPrimType length:
sizeof(uint32_t) atIndex:4];
3040 [computeEncoder setBytes:&strideVal length:
sizeof(uint32_t) atIndex:5];
3041 [computeEncoder setBuffer:countBufMtl ? countBufMtl : d->icbNoCountBuffer
3042 offset:countBufMtl ? countBufferOffset : 0
3044 [computeEncoder setBuffer:targetRangeBuffer offset:0 atIndex:7];
3045 [computeEncoder useResource:targetIcb usage:MTLResourceUsageWrite];
3046 [computeEncoder useResource:indirectBufMtl usage:MTLResourceUsageRead];
3048 [computeEncoder useResource:indexBufMtl usage:MTLResourceUsageRead];
3050 NSUInteger tw = computePipeline.threadExecutionWidth;
3051 [computeEncoder dispatchThreads:MTLSizeMake(maxDrawCount, 1, 1)
3052 threadsPerThreadgroup:MTLSizeMake(tw, 1, 1)];
3062 QMetalBuffer *indirectBufD, quint32 indirectBufferOffset,
3064 quint32 maxDrawCount, quint32 stride)
3070 if (indexed && !indexBufD)
3073 if (!prepareIcb(maxDrawCount))
3078 id<MTLBuffer> indirectBufMtl = indirectBufD->d->buf[indirectBufD->d->slotted ? currentFrameSlot : 0];
3080 id<MTLBuffer> countBufMtl = nil;
3084 countBufMtl = countBufD->d->buf[countBufD->d->slotted ? currentFrameSlot : 0];
3091 const auto savedVertexBuffers = cbD
->d->currentVertexInputsBuffers;
3092 const auto savedVertexOffsets = cbD
->d->currentVertexInputOffsets;
3093 const quint32 savedIndexOffset = cbD->currentIndexOffset;
3094 const QRhiCommandBuffer::IndexFormat savedIndexFormat = cbD->currentIndexFormat;
3095 id<MTLBuffer> indexBufMtl = indexed
3096 ? indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0] : nil;
3101 id<MTLComputeCommandEncoder> computeEncoder = [cbD->d->cb computeCommandEncoder];
3102 encodeIcbWithCompute(
d, computeEncoder,
d->icb,
d->icbArgumentBuffer,
d->icbRangeBuffer,
3103 indexed, savedIndexFormat, savedPipeline
->d->primitiveType,
3104 indirectBufMtl, indirectBufferOffset,
3105 indexBufMtl, savedIndexOffset,
3106 countBufMtl, countBufferOffset,
3107 maxDrawCount, stride);
3110 endTempComputeEncoding(
this, cbD, computeEncoder);
3119 if (savedFirstVertexBinding >= 0) {
3121 cbD
->d->currentVertexInputsBuffers = savedVertexBuffers;
3122 cbD
->d->currentVertexInputOffsets = savedVertexOffsets;
3123 for (
int i = 0, ie = savedVertexBuffers.batches.count(); i != ie; ++i) {
3124 const auto &bufferBatch(savedVertexBuffers.batches[i]);
3125 const auto &offsetBatch(savedVertexOffsets.batches[i]);
3126 [cbD->d->currentRenderPassEncoder setVertexBuffers:
3127 bufferBatch.resources.constData()
3128 offsets: offsetBatch.resources.constData()
3129 withRange: NSMakeRange(uint(savedFirstVertexBinding) + bufferBatch.startBinding,
3130 NSUInteger(bufferBatch.resources.count()))];
3135 cbD->currentIndexOffset = savedIndexOffset;
3136 cbD->currentIndexFormat = savedIndexFormat;
3140 [cbD->d->currentRenderPassEncoder useResource:indirectBufMtl
3141 usage:MTLResourceUsageRead
3142 stages:MTLRenderStageVertex | MTLRenderStageFragment];
3144 [cbD->d->currentRenderPassEncoder useResource:indexBufMtl
3145 usage:MTLResourceUsageRead
3146 stages:MTLRenderStageVertex | MTLRenderStageFragment];
3148 [cbD->d->currentRenderPassEncoder executeCommandsInBuffer:d->icb
3149 indirectBuffer:d->icbRangeBuffer
3150 indirectBufferOffset:0];
3163 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
3171 id<MTLBuffer> indirectBufMtl = indirectBufD->d->buf[indirectBufD->d->slotted ? currentFrameSlot : 0];
3173 if (drawCount > ICB_DRAW_COUNT_THRESHOLD && !icbUnavailableReason(cbD)
3174 && icbDraw(cbD,
false, indirectBufD, indirectBufferOffset,
nullptr, 0, drawCount, stride))
3180 NSUInteger offset = indirectBufferOffset;
3181 for (quint32 i = 0; i < drawCount; ++i) {
3182 [cbD->d->currentRenderPassEncoder drawPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
3183 indirectBuffer: indirectBufMtl
3184 indirectBufferOffset: offset];
3190 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
3199 id<MTLBuffer> indexBufMtl = indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0];
3204 id<MTLBuffer> indirectBufMtl = indirectBufD->d->buf[indirectBufD->d->slotted ? currentFrameSlot : 0];
3206 if (drawCount > ICB_DRAW_COUNT_THRESHOLD && !icbUnavailableReason(cbD)
3207 && icbDraw(cbD,
true, indirectBufD, indirectBufferOffset,
nullptr, 0, drawCount, stride))
3213 NSUInteger offset = indirectBufferOffset;
3214 for (quint32 i = 0; i < drawCount; ++i) {
3215 [cbD->d->currentRenderPassEncoder drawIndexedPrimitives: cbD->currentGraphicsPipeline->d->primitiveType
3216 indexType: cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
3217 indexBuffer: indexBufMtl
3218 indexBufferOffset: cbD->currentIndexOffset
3219 indirectBuffer: indirectBufMtl
3220 indirectBufferOffset: offset];
3230 NSString *str = [NSString stringWithUTF8String: name.constData()];
3233 case QMetalCommandBuffer::RenderPass:
3234 [cbD->d->currentRenderPassEncoder pushDebugGroup: str];
3235 cbD
->d->openDebugGroups.append(name);
3237 case QMetalCommandBuffer::ComputePass:
3238 [cbD->d->currentComputePassEncoder pushDebugGroup: str];
3241 [cbD->d->cb pushDebugGroup: str];
3253 case QMetalCommandBuffer::RenderPass:
3254 [cbD->d->currentRenderPassEncoder popDebugGroup];
3255 if (!cbD
->d->openDebugGroups.isEmpty())
3256 cbD
->d->openDebugGroups.removeLast();
3258 case QMetalCommandBuffer::ComputePass:
3259 [cbD->d->currentComputePassEncoder popDebugGroup];
3262 [cbD->d->cb popDebugGroup];
3273 NSString *str = [NSString stringWithUTF8String: msg.constData()];
3275 case QMetalCommandBuffer::RenderPass:
3276 [cbD->d->currentRenderPassEncoder insertDebugSignpost: str];
3278 case QMetalCommandBuffer::ComputePass:
3279 [cbD->d->currentComputePassEncoder insertDebugSignpost: str];
3288 return QRHI_RES(QMetalCommandBuffer, cb)->nativeHandles();
3314 currentFrameSlot = swapChainD->currentFrameSlot;
3319 dispatch_semaphore_wait(swapChainD->d->sem[currentFrameSlot], DISPATCH_TIME_FOREVER);
3327 for (QMetalSwapChain *sc : std::as_const(swapchains)) {
3328 if (sc != swapChainD)
3329 sc->waitUntilCompleted(currentFrameSlot);
3332 [d->captureScope beginScope];
3334 swapChainD->cbWrapper.d->cb =
d->newCommandBuffer();
3338 colorAtt.tex = swapChainD->d->msaaTex[currentFrameSlot];
3345 swapChainD
->rtWrapper.d->fb.dsTex = swapChainD
->ds ? swapChainD->ds->d->tex : nil;
3353 d->argBufPool[currentFrameSlot].offset = 0;
3355 d->globalFrameId += 1;
3358 swapChainD->cbWrapper.resetState(swapChainD->d->lastGpuTime[currentFrameSlot]);
3359 swapChainD->d->lastGpuTime[currentFrameSlot] = 0;
3362 return QRhi::FrameOpSuccess;
3371 id<MTLCommandBuffer> commandBuffer = swapChainD->cbWrapper.d->cb;
3373 __block
int thisFrameSlot = currentFrameSlot;
3374 [commandBuffer addCompletedHandler: ^(id<MTLCommandBuffer> cb) {
3375 swapChainD->d->lastGpuTime[thisFrameSlot] += cb.GPUEndTime - cb.GPUStartTime;
3376 dispatch_semaphore_signal(swapChainD->d->sem[thisFrameSlot]);
3383 id<MTLTexture> drawableTexture = [swapChainD->d->curDrawable.texture retain];
3384 [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer>) {
3385 [drawableTexture release];
3389 if (flags.testFlag(QRhi::SkipPresent)) {
3391 [commandBuffer commit];
3393 if (id<CAMetalDrawable> drawable = swapChainD->d->curDrawable) {
3395 if (swapChainD
->d->layer.presentsWithTransaction) {
3396 [commandBuffer commit];
3398 auto *metalLayer = swapChainD
->d->layer;
3399 auto presentWithTransaction = ^{
3400 [commandBuffer waitUntilScheduled];
3407 const auto surfaceSize = QSizeF::fromCGSize(metalLayer.bounds.size) * metalLayer.contentsScale;
3408 const auto textureSize = QSizeF(drawable.texture.width, drawable.texture.height);
3409 if (textureSize == surfaceSize) {
3412 qCDebug(QRHI_LOG_INFO) <<
"Skipping" << drawable <<
"due to texture size"
3413 << textureSize <<
"not matching surface size" << surfaceSize;
3417 if (NSThread.currentThread == NSThread.mainThread) {
3418 presentWithTransaction();
3420 auto *qtMetalLayer = qt_objc_cast<QMetalLayer*>(swapChainD->d->layer);
3421 Q_ASSERT(qtMetalLayer);
3423 qtMetalLayer.mainThreadPresentation = presentWithTransaction;
3427 auto *qtMetalLayer = qt_objc_cast<QMetalLayer*>(swapChainD->d->layer);
3428 [commandBuffer addScheduledHandler:^(id<MTLCommandBuffer>) {
3434 if (qtMetalLayer.displayLock.tryLockForRead()) {
3436 qtMetalLayer.displayLock.unlock();
3438 qCDebug(QRHI_LOG_INFO) <<
"Skipping" << drawable
3439 <<
"due to" << qtMetalLayer <<
"needing display";
3445 [commandBuffer commit];
3449 [commandBuffer commit];
3456 [swapChainD->d->curDrawable release];
3457 swapChainD
->d->curDrawable = nil;
3459 [d->captureScope endScope];
3463 return QRhi::FrameOpSuccess;
3470 currentFrameSlot = (currentFrameSlot + 1) % QMTL_FRAMES_IN_FLIGHT;
3472 for (QMetalSwapChain *sc : std::as_const(swapchains))
3473 sc->waitUntilCompleted(currentFrameSlot);
3475 d->ofr.active =
true;
3476 *cb = &
d->ofr.cbWrapper;
3477 d->ofr.cbWrapper.d->cb =
d->newCommandBuffer();
3479 d->argBufPool[currentFrameSlot].offset = 0;
3481 d->globalFrameId += 1;
3484 d->ofr.cbWrapper.resetState(
d->ofr.lastGpuTime);
3485 d->ofr.lastGpuTime = 0;
3488 return QRhi::FrameOpSuccess;
3494 Q_ASSERT(
d->ofr.active);
3495 d->ofr.active =
false;
3497 id<MTLCommandBuffer> cb =
d->ofr.cbWrapper.d->cb;
3501 [cb waitUntilCompleted];
3503 d->ofr.lastGpuTime += cb.GPUEndTime - cb.GPUStartTime;
3507 return QRhi::FrameOpSuccess;
3512 id<MTLCommandBuffer> cb = nil;
3515 if (
d->ofr.active) {
3518 cb =
d->ofr.cbWrapper.d->cb;
3523 cb = swapChainD->cbWrapper.d->cb;
3527 for (QMetalSwapChain *sc : std::as_const(swapchains)) {
3528 for (
int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i) {
3529 if (currentSwapChain && sc == currentSwapChain && i == currentFrameSlot) {
3534 sc->waitUntilCompleted(i);
3540 [cb waitUntilCompleted];
3544 if (
d->ofr.active) {
3545 d->ofr.lastGpuTime += cb.GPUEndTime - cb.GPUStartTime;
3546 d->ofr.cbWrapper.d->cb =
d->newCommandBuffer();
3548 swapChainD->d->lastGpuTime[currentFrameSlot] += cb.GPUEndTime - cb.GPUStartTime;
3549 swapChainD->cbWrapper.d->cb =
d->newCommandBuffer();
3557 return QRhi::FrameOpSuccess;
3561 const QColor &colorClearValue,
3562 const QRhiDepthStencilClearValue &depthStencilClearValue,
3564 QRhiShadingRateMap *shadingRateMap)
3566 MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
3567 MTLClearColor c = MTLClearColorMake(colorClearValue.redF(), colorClearValue.greenF(), colorClearValue.blueF(),
3568 colorClearValue.alphaF());
3570 for (uint i = 0; i < uint(colorAttCount); ++i) {
3571 rp.colorAttachments[i].loadAction = MTLLoadActionClear;
3572 rp.colorAttachments[i].storeAction = MTLStoreActionStore;
3573 rp.colorAttachments[i].clearColor = c;
3576 if (hasDepthStencil) {
3577 rp.depthAttachment.loadAction = MTLLoadActionClear;
3578 rp.depthAttachment.storeAction = MTLStoreActionDontCare;
3579 rp.stencilAttachment.loadAction = MTLLoadActionClear;
3580 rp.stencilAttachment.storeAction = MTLStoreActionDontCare;
3581 rp.depthAttachment.clearDepth =
double(depthStencilClearValue.depthClearValue());
3582 rp.stencilAttachment.clearStencil = depthStencilClearValue.stencilClearValue();
3586 rp.rasterizationRateMap =
QRHI_RES(QMetalShadingRateMap, shadingRateMap)->d->rateMap;
3594 const qsizetype imageSizeBytes = subresDesc.image().isNull() ?
3595 subresDesc.data().size() : subresDesc.image().sizeInBytes();
3596 if (imageSizeBytes > 0)
3597 size += aligned<qsizetype>(imageSizeBytes, QRhiMetalData::TEXBUF_ALIGN);
3602 int layer,
int level,
const QRhiTextureSubresourceUploadDescription &subresDesc,
3605 const QPoint dp = subresDesc.destinationTopLeft();
3606 const QByteArray rawData = subresDesc.data();
3607 QImage img = subresDesc.image();
3608 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
3609 id<MTLBlitCommandEncoder> blitEnc = (id<MTLBlitCommandEncoder>) blitEncPtr;
3611 if (!img.isNull()) {
3612 const qsizetype fullImageSizeBytes = img.sizeInBytes();
3613 QSize size = img.size();
3614 int bpl = img.bytesPerLine();
3616 if (!subresDesc.sourceSize().isEmpty() || !subresDesc.sourceTopLeft().isNull()) {
3617 const int sx = subresDesc.sourceTopLeft().x();
3618 const int sy = subresDesc.sourceTopLeft().y();
3619 if (!subresDesc.sourceSize().isEmpty())
3620 size = subresDesc.sourceSize();
3621 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
3622 if (size.width() == img.width()) {
3623 const int bpc = qMax(1, img.depth() / 8);
3624 Q_ASSERT(size.height() * img.bytesPerLine() <= fullImageSizeBytes);
3625 memcpy(
reinterpret_cast<
char *>(mp) + *curOfs,
3626 img.constBits() + sy * img.bytesPerLine() + sx * bpc,
3627 size.height() * img.bytesPerLine());
3629 img = img.copy(sx, sy, size.width(), size.height());
3630 bpl = img.bytesPerLine();
3631 Q_ASSERT(img.sizeInBytes() <= fullImageSizeBytes);
3632 memcpy(
reinterpret_cast<
char *>(mp) + *curOfs, img.constBits(), size_t(img.sizeInBytes()));
3635 size = clampedSubResourceUploadSize(size, dp, level, texD->m_pixelSize);
3636 memcpy(
reinterpret_cast<
char *>(mp) + *curOfs, img.constBits(), size_t(fullImageSizeBytes));
3639 [blitEnc copyFromBuffer: texD->d->stagingBuf[currentFrameSlot]
3640 sourceOffset: NSUInteger(*curOfs)
3641 sourceBytesPerRow: NSUInteger(bpl)
3642 sourceBytesPerImage: 0
3643 sourceSize: MTLSizeMake(NSUInteger(size.width()), NSUInteger(size.height()), 1)
3644 toTexture: texD->d->tex
3645 destinationSlice: NSUInteger(is3D ? 0 : layer)
3646 destinationLevel: NSUInteger(level)
3647 destinationOrigin: MTLOriginMake(NSUInteger(dp.x()), NSUInteger(dp.y()), NSUInteger(is3D ? layer : 0))
3648 options: MTLBlitOptionNone];
3650 *curOfs += aligned<qsizetype>(fullImageSizeBytes, QRhiMetalData::TEXBUF_ALIGN);
3651 }
else if (!rawData.isEmpty() && isCompressedFormat(texD->m_format)) {
3652 const QSize subresSize = q->sizeForMipLevel(level, texD->m_pixelSize);
3653 const int subresw = subresSize.width();
3654 const int subresh = subresSize.height();
3656 if (subresDesc.sourceSize().isEmpty()) {
3660 w = subresDesc.sourceSize().width();
3661 h = subresDesc.sourceSize().height();
3664 const QSize clamped = clampedCompressedSubResourceUploadSizeForSourceData(texD->m_format,
3667 if (clamped.height() == 0)
3669 h = clamped.height();
3673 compressedFormatInfo(texD->m_format, QSize(w, h), &bpl,
nullptr, &blockDim);
3675 const int dx = aligned(dp.x(), blockDim.width());
3676 const int dy = aligned(dp.y(), blockDim.height());
3677 if (dx + w != subresw)
3678 w = aligned(w, blockDim.width());
3679 if (dy + h != subresh)
3680 h = aligned(h, blockDim.height());
3682 memcpy(
reinterpret_cast<
char *>(mp) + *curOfs, rawData.constData(), size_t(rawData.size()));
3684 [blitEnc copyFromBuffer: texD->d->stagingBuf[currentFrameSlot]
3685 sourceOffset: NSUInteger(*curOfs)
3686 sourceBytesPerRow: bpl
3687 sourceBytesPerImage: 0
3688 sourceSize: MTLSizeMake(NSUInteger(w), NSUInteger(h), 1)
3689 toTexture: texD->d->tex
3690 destinationSlice: NSUInteger(is3D ? 0 : layer)
3691 destinationLevel: NSUInteger(level)
3692 destinationOrigin: MTLOriginMake(NSUInteger(dx), NSUInteger(dy), NSUInteger(is3D ? layer : 0))
3693 options: MTLBlitOptionNone];
3695 *curOfs += aligned<qsizetype>(rawData.size(), QRhiMetalData::TEXBUF_ALIGN);
3696 }
else if (!rawData.isEmpty()) {
3697 const QSize subresSize = q->sizeForMipLevel(level, texD->m_pixelSize);
3698 const int subresw = subresSize.width();
3699 const int subresh = subresSize.height();
3701 if (subresDesc.sourceSize().isEmpty()) {
3705 w = subresDesc.sourceSize().width();
3706 h = subresDesc.sourceSize().height();
3709 QSize size = clampedSubResourceUploadSize(QSize(w, h), dp, level, texD->m_pixelSize);
3710 quint32 bytesPerPixel = 0;
3711 textureFormatInfo(texD->m_format, size,
nullptr,
nullptr, &bytesPerPixel);
3712 size = clampedSubResourceUploadSizeForSourceData(size, subresDesc.dataStride(),
3713 bytesPerPixel, rawData.size());
3718 if (subresDesc.dataStride())
3719 bpl = subresDesc.dataStride();
3721 textureFormatInfo(texD->m_format, QSize(w, h), &bpl,
nullptr,
nullptr);
3723 memcpy(
reinterpret_cast<
char *>(mp) + *curOfs, rawData.constData(), size_t(rawData.size()));
3725 if (!size.isEmpty()) {
3726 [blitEnc copyFromBuffer: texD->d->stagingBuf[currentFrameSlot]
3727 sourceOffset: NSUInteger(*curOfs)
3728 sourceBytesPerRow: bpl
3729 sourceBytesPerImage: 0
3730 sourceSize: MTLSizeMake(NSUInteger(w), NSUInteger(h), 1)
3731 toTexture: texD->d->tex
3732 destinationSlice: NSUInteger(is3D ? 0 : layer)
3733 destinationLevel: NSUInteger(level)
3734 destinationOrigin: MTLOriginMake(NSUInteger(dp.x()), NSUInteger(dp.y()), NSUInteger(is3D ? layer : 0))
3735 options: MTLBlitOptionNone];
3738 *curOfs += aligned<qsizetype>(rawData.size(), QRhiMetalData::TEXBUF_ALIGN);
3740 qWarning(
"Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
3749 id<MTLBlitCommandEncoder> blitEnc = nil;
3750 auto ensureBlit = [&blitEnc, cbD,
this]() {
3752 blitEnc = [cbD->d->cb blitCommandEncoder];
3754 [blitEnc pushDebugGroup: @
"Resource updates"];
3762 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
3763 for (
int i = 0, ie = bufD
->d->slotted ? QMTL_FRAMES_IN_FLIGHT : 1; i != ie; ++i) {
3764 if (u.offset == 0 && u.data.size() == bufD->m_size)
3765 bufD
->d->pendingUpdates[i].clear();
3766 bufD
->d->pendingUpdates[i].append({ u.offset, u.data });
3770 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
3771 Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
3773 const quint32 size = quint32(u.data.size());
3775 quint32 stagingOffset = 0;
3776 id<MTLBuffer> stagingBuf =
d->allocBufferStaging(size, currentFrameSlot, &stagingOffset);
3778 char *p =
reinterpret_cast<
char *>([stagingBuf contents]);
3779 memcpy(p + stagingOffset, u.data.constData(), size);
3781 [blitEnc copyFromBuffer: stagingBuf
3782 sourceOffset: stagingOffset
3783 toBuffer: bufD->d->buf[0]
3784 destinationOffset: u.offset
3787 qWarning(
"Failed to allocate staging buffer of size %u for buffer upload", size);
3792 for (
int i = 0, ie = bufD
->d->slotted ? QMTL_FRAMES_IN_FLIGHT : 1; i != ie; ++i)
3793 bufD
->d->pendingUpdates[i].append({ u.offset, u.data });
3798 const int idx = bufD->d->slotted ? currentFrameSlot : 0;
3799 if (bufD->m_type == QRhiBuffer::Dynamic) {
3800 char *p =
reinterpret_cast<
char *>([bufD->d->buf[idx] contents]);
3802 u.result->data.resize(u.readSize);
3803 memcpy(u.result->data.data(), p + u.offset, size_t(u.readSize));
3805 if (u.result->completed)
3806 u.result->completed();
3817 readback.readSize = u.readSize;
3818 readback.result = u.result;
3819 readback.buf = [d->dev newBufferWithLength: u.readSize
3820 options: MTLResourceStorageModeShared];
3823 [blitEnc copyFromBuffer: bufD->d->buf[idx]
3824 sourceOffset: u.offset
3825 toBuffer: readback.buf
3826 destinationOffset: 0
3829 d->activeBufferReadbacks.append(readback);
3835 Q_ASSERT(dstD->m_type != QRhiBuffer::Dynamic && srcD->m_type != QRhiBuffer::Dynamic);
3838 const int srcIdx = srcD->d->slotted ? currentFrameSlot : 0;
3839 const int dstSlotCount = dstD
->d->slotted ? QMTL_FRAMES_IN_FLIGHT : 1;
3849 for (
int i = 0; i != dstSlotCount; ++i)
3853 for (
int i = 0; i != dstSlotCount; ++i) {
3854 [blitEnc copyFromBuffer: srcD->d->buf[srcIdx]
3855 sourceOffset: u.srcOffset
3856 toBuffer: dstD->d->buf[i]
3857 destinationOffset: u.offset
3864 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic && !bufD->d->slotted);
3867 [blitEnc fillBuffer: bufD->d->buf[0]
3868 range: NSMakeRange(u.offset, u.readSize)
3869 value: u.fillValue];
3878 qsizetype stagingSize = 0;
3879 for (
const auto &subres : u.subresDesc)
3880 stagingSize += subresUploadByteSize(subres.desc);
3883 Q_ASSERT(!utexD->d->stagingBuf[currentFrameSlot]);
3884 utexD->d->stagingBuf[currentFrameSlot] = [d->dev newBufferWithLength: NSUInteger(stagingSize)
3885 options: MTLResourceStorageModeShared];
3887 void *mp = [utexD->d->stagingBuf[currentFrameSlot] contents];
3888 qsizetype curOfs = 0;
3889 for (
const auto &subres : u.subresDesc)
3890 enqueueSubresUpload(utexD, mp, blitEnc, subres.layer, subres.level, subres.desc, &curOfs);
3897 e.stagingBuffer.buffer = utexD->d->stagingBuf[currentFrameSlot];
3898 utexD->d->stagingBuf[currentFrameSlot] = nil;
3899 d->releaseQueue.append(e);
3904 const bool srcIs3D = srcD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
3905 const bool dstIs3D = dstD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
3906 const QPoint dp = u.desc.destinationTopLeft();
3907 const QSize mipSize = q->sizeForMipLevel(u.desc.sourceLevel(), srcD->m_pixelSize);
3908 const QSize copySize = u.desc.pixelSize().isEmpty() ? mipSize : u.desc.pixelSize();
3909 const QPoint sp = u.desc.sourceTopLeft();
3912 [blitEnc copyFromTexture: srcD->d->tex
3913 sourceSlice: NSUInteger(srcIs3D ? 0 : u.desc.sourceLayer())
3914 sourceLevel: NSUInteger(u.desc.sourceLevel())
3915 sourceOrigin: MTLOriginMake(NSUInteger(sp.x()), NSUInteger(sp.y()), NSUInteger(srcIs3D ? u.desc.sourceLayer() : 0))
3916 sourceSize: MTLSizeMake(NSUInteger(copySize.width()), NSUInteger(copySize.height()), 1)
3917 toTexture: dstD->d->tex
3918 destinationSlice: NSUInteger(dstIs3D ? 0 : u.desc.destinationLayer())
3919 destinationLevel: NSUInteger(u.desc.destinationLevel())
3920 destinationOrigin: MTLOriginMake(NSUInteger(dp.x()), NSUInteger(dp.y()), NSUInteger(dstIs3D ? u.desc.destinationLayer() : 0))];
3926 readback.desc = u.rb;
3927 readback.result = u.result;
3936 qWarning(
"Multisample texture cannot be read back");
3939 is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
3940 if (u.rb.rect().isValid())
3943 rect = QRect({0, 0}, q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize));
3944 readback.format = texD->m_format;
3950 if (u.rb.rect().isValid())
3953 rect = QRect({0, 0}, swapChainD->pixelSize);
3954 readback.format = swapChainD
->d->rhiColorFormat;
3958 src = colorAtt.resolveTex ? colorAtt.resolveTex : colorAtt.tex;
3960 readback.pixelSize = rect.size();
3963 textureFormatInfo(readback.format, readback.pixelSize, &bpl, &readback.bufSize,
nullptr);
3974 const MTLPixelFormat mtlFormat = texD ? texD->d->format : MTLPixelFormatInvalid;
3975 const bool isDepthFormat = texD && (readback.format == QRhiTexture::D16
3976 || readback.format == QRhiTexture::D24
3977 || readback.format == QRhiTexture::D24S8
3978 || readback.format == QRhiTexture::D32F
3979 || readback.format == QRhiTexture::D32FS8);
3980 const bool nativeLayout = (readback.format == QRhiTexture::D16 && mtlFormat == MTLPixelFormatDepth16Unorm)
3981 || (readback.format == QRhiTexture::D32F && mtlFormat == MTLPixelFormatDepth32Float);
3982 const bool usePlanes = isDepthFormat && !nativeLayout;
3983 bool combinedMtlFormat = mtlFormat == MTLPixelFormatDepth32Float_Stencil8;
3985 if (mtlFormat == MTLPixelFormatDepth24Unorm_Stencil8)
3986 combinedMtlFormat =
true;
3988 const bool hasStencil = isStencilSupportingFormat(readback.format);
3989 quint32 depthPlaneBytesPerRow = 0;
3993 depthPlaneBytesPerRow = quint32(rect.width()) * 4;
3994 readback.depthPlaneByteSize = depthPlaneBytesPerRow * quint32(rect.height());
3996 readback.stencilPlaneByteSize = quint32(rect.width()) * quint32(rect.height());
3998 || mtlFormat == MTLPixelFormatDepth32Float_Stencil8;
4000 const quint32 stagingBufSize = usePlanes
4001 ? readback.depthPlaneByteSize + readback.stencilPlaneByteSize
4003 readback.buf = [d->dev newBufferWithLength: stagingBufSize options: MTLResourceStorageModeShared];
4006 const auto blit = [&](quint32 destinationOffset, quint32 destinationBytesPerRow, MTLBlitOption options) {
4007 [blitEnc copyFromTexture: src
4008 sourceSlice: NSUInteger(is3D ? 0 : u.rb.layer())
4009 sourceLevel: NSUInteger(u.rb.level())
4010 sourceOrigin: MTLOriginMake(NSUInteger(rect.x()), NSUInteger(rect.y()), NSUInteger(is3D ? u.rb.layer() : 0))
4011 sourceSize: MTLSizeMake(NSUInteger(rect.width()), NSUInteger(rect.height()), 1)
4012 toBuffer: readback.buf
4013 destinationOffset: destinationOffset
4014 destinationBytesPerRow: destinationBytesPerRow
4015 destinationBytesPerImage: 0
4019 blit(0, depthPlaneBytesPerRow,
4020 combinedMtlFormat ? MTLBlitOptionDepthFromDepthStencil : MTLBlitOptionNone);
4022 blit(readback.depthPlaneByteSize, quint32(rect.width()), MTLBlitOptionStencilFromDepthStencil);
4024 blit(0, bpl, MTLBlitOptionNone);
4027 d->activeTextureReadbacks.append(readback);
4031 [blitEnc generateMipmapsForTexture: utexD->d->tex];
4038 [blitEnc popDebugGroup];
4039 [blitEnc endEncoding];
4048 if (bufD
->d->pendingUpdates[slot].isEmpty())
4053 void *p = [bufD->d->buf[slot] contents];
4054 quint32 changeBegin = UINT32_MAX;
4055 quint32 changeEnd = 0;
4056 for (
const QMetalBufferData::BufferUpdate &u : std::as_const(bufD->d->pendingUpdates[slot])) {
4057 memcpy(
static_cast<
char *>(p) + u.offset, u.data.constData(), size_t(u.data.size()));
4058 if (u.offset < changeBegin)
4059 changeBegin = u.offset;
4060 if (u.offset + u.data.size() > changeEnd)
4061 changeEnd = u.offset + u.data.size();
4064 if (changeBegin < UINT32_MAX && changeBegin < changeEnd && bufD->d->managed)
4065 [bufD->d->buf[slot] didModifyRange: NSMakeRange(NSUInteger(changeBegin), NSUInteger(changeEnd - changeBegin))];
4068 bufD
->d->pendingUpdates[slot].clear();
4078 Q_ASSERT(
QRHI_RES(QMetalCommandBuffer, cb)->recordingPass == QMetalCommandBuffer::NoPass);
4084 QRhiRenderTarget *rt,
4085 const QColor &colorClearValue,
4086 const QRhiDepthStencilClearValue &depthStencilClearValue,
4087 QRhiResourceUpdateBatch *resourceUpdates,
4093 if (resourceUpdates)
4097 switch (rt->resourceType()) {
4098 case QRhiResource::SwapChainRenderTarget:
4102 QRhiShadingRateMap *shadingRateMap = rtSc->swapChain()->shadingRateMap();
4105 depthStencilClearValue,
4113 if (!swapChainD
->d->curDrawable) {
4114 QMacAutoReleasePool pool;
4115 swapChainD
->d->curDrawable = [[swapChainD->d->layer nextDrawable] retain];
4117 if (!swapChainD
->d->curDrawable) {
4118 qWarning(
"No drawable");
4121 cbD
->d->currentPassRpDesc = nil;
4123 id<MTLTexture> scTex = swapChainD
->d->curDrawable.texture;
4128 color0.resolveTex = scTex;
4135 QRHI_RES(QMetalShadingRateMap, shadingRateMap)->lastActiveFrameSlot = currentFrameSlot;
4138 case QRhiResource::TextureRenderTarget:
4142 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QMetalTexture, QMetalRenderBuffer>(rtTex->description(), rtD->currentResIdList))
4146 depthStencilClearValue,
4148 rtTex->m_desc.shadingRateMap());
4149 if (rtD->fb.preserveColor) {
4151 cbD
->d->currentPassRpDesc.colorAttachments[i].loadAction = MTLLoadActionLoad;
4154 cbD
->d->currentPassRpDesc.depthAttachment.loadAction = MTLLoadActionLoad;
4155 cbD
->d->currentPassRpDesc.stencilAttachment.loadAction = MTLLoadActionLoad;
4157 int colorAttCount = 0;
4158 for (
auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments();
4162 if (it->texture()) {
4164 if (it->multiViewCount() >= 2)
4165 cbD
->d->currentPassRpDesc.renderTargetArrayLength = NSUInteger(it->multiViewCount());
4166 }
else if (it->renderBuffer()) {
4169 if (it->resolveTexture())
4172 if (rtTex->m_desc.depthStencilBuffer())
4174 if (rtTex->m_desc.depthTexture()) {
4177 if (depthTexture->arraySize() >= 2) {
4178 const int depthLayer = rtTex->m_desc.depthLayer();
4179 if (depthLayer >= 0) {
4180 cbD
->d->currentPassRpDesc.depthAttachment.slice = NSUInteger(depthLayer);
4181 cbD
->d->currentPassRpDesc.stencilAttachment.slice = NSUInteger(depthLayer);
4182 if (colorAttCount == 0)
4183 cbD
->d->currentPassRpDesc.renderTargetArrayLength = 1;
4184 }
else if (colorAttCount == 0) {
4185 cbD
->d->currentPassRpDesc.renderTargetArrayLength = NSUInteger(depthTexture->arraySize());
4189 if (rtTex->m_desc.depthResolveTexture())
4191 if (rtTex->m_desc.shadingRateMap())
4200 cbD
->d->deferredColorStoreActions.clear();
4201 cbD
->d->deferredDepthStoreAction = MTLStoreActionUnknown;
4202 cbD
->d->deferredStencilStoreAction = MTLStoreActionUnknown;
4204 cbD
->d->currentPassRpDesc.colorAttachments[i].texture = rtD->fb.colorAtt[i].tex;
4205 cbD
->d->currentPassRpDesc.colorAttachments[i].slice = NSUInteger(rtD->fb.colorAtt[i].arrayLayer);
4206 cbD
->d->currentPassRpDesc.colorAttachments[i].depthPlane = NSUInteger(rtD->fb.colorAtt[i].slice);
4207 cbD
->d->currentPassRpDesc.colorAttachments[i].level = NSUInteger(rtD->fb.colorAtt[i].level);
4208 if (rtD->fb.colorAtt[i].resolveTex) {
4209 const MTLStoreAction storeAction = rtD->fb.preserveColor ? MTLStoreActionStoreAndMultisampleResolve
4210 : MTLStoreActionMultisampleResolve;
4214 cbD
->d->currentPassRpDesc.colorAttachments[i].storeAction = MTLStoreActionUnknown;
4215 cbD
->d->deferredColorStoreActions.append({ i, storeAction });
4216 cbD
->d->currentPassRpDesc.colorAttachments[i].resolveTexture = rtD->fb.colorAtt[i].resolveTex;
4217 cbD
->d->currentPassRpDesc.colorAttachments[i].resolveSlice = NSUInteger(rtD->fb.colorAtt[i].resolveLayer);
4218 cbD
->d->currentPassRpDesc.colorAttachments[i].resolveLevel = NSUInteger(rtD->fb.colorAtt[i].resolveLevel);
4223 Q_ASSERT(rtD->fb.dsTex);
4224 cbD
->d->currentPassRpDesc.depthAttachment.texture = rtD->fb.dsTex;
4225 cbD
->d->currentPassRpDesc.stencilAttachment.texture = rtD->fb.hasStencil ? rtD->fb.dsTex : nil;
4226 if (rtD->fb.depthNeedsStore) {
4227 cbD
->d->currentPassRpDesc.depthAttachment.storeAction = MTLStoreActionStore;
4228 if (rtD->fb.hasStencil)
4229 cbD
->d->currentPassRpDesc.stencilAttachment.storeAction = MTLStoreActionStore;
4230 }
else if (canStoreAttachment(rtD->fb.dsTex)) {
4234 cbD
->d->currentPassRpDesc.depthAttachment.storeAction = MTLStoreActionUnknown;
4235 cbD
->d->deferredDepthStoreAction = MTLStoreActionDontCare;
4236 if (rtD->fb.hasStencil) {
4237 cbD
->d->currentPassRpDesc.stencilAttachment.storeAction = MTLStoreActionUnknown;
4238 cbD
->d->deferredStencilStoreAction = MTLStoreActionDontCare;
4241 if (rtD->fb.dsResolveTex) {
4242 const MTLStoreAction dsStoreAction = rtD->fb.depthNeedsStore ? MTLStoreActionStoreAndMultisampleResolve
4243 : MTLStoreActionMultisampleResolve;
4249 const bool deferrable = canStoreAttachment(rtD->fb.dsTex);
4250 cbD
->d->currentPassRpDesc.depthAttachment.storeAction = deferrable ? MTLStoreActionUnknown
4253 cbD
->d->deferredDepthStoreAction = dsStoreAction;
4254 cbD
->d->currentPassRpDesc.depthAttachment.resolveTexture = rtD->fb.dsResolveTex;
4255 if (rtD->fb.hasStencil) {
4256 cbD
->d->currentPassRpDesc.stencilAttachment.resolveTexture = rtD->fb.dsResolveTex;
4257 cbD
->d->currentPassRpDesc.stencilAttachment.storeAction = deferrable ? MTLStoreActionUnknown
4260 cbD
->d->deferredStencilStoreAction = dsStoreAction;
4265 cbD
->d->currentRenderPassEncoder = cbD->d->currentPassRpDesc
4266 ? [cbD->d->cb renderCommandEncoderWithDescriptor: cbD->d->currentPassRpDesc]
4272 cbD->currentTarget = rt;
4281 [cbD->d->currentRenderPassEncoder endEncoding];
4284 cbD->currentTarget =
nullptr;
4286 if (resourceUpdates)
4291 QRhiResourceUpdateBatch *resourceUpdates,
4297 if (resourceUpdates)
4300 cbD
->d->currentComputePassEncoder = [cbD->d->cb computeCommandEncoder];
4310 [cbD->d->currentComputePassEncoder endEncoding];
4313 if (resourceUpdates)
4328 [cbD->d->currentComputePassEncoder setComputePipelineState: psD->d->ps];
4340 [cbD->d->currentComputePassEncoder dispatchThreadgroups: MTLSizeMake(NSUInteger(x), NSUInteger(y), NSUInteger(z))
4341 threadsPerThreadgroup: psD->d->localSize];
4345 quint32 indirectBufferOffset)
4354 id<MTLBuffer> indirectBufMtl = indirectBufD->d->buf[indirectBufD->d->slotted ? currentFrameSlot : 0];
4361 [cbD->d->currentComputePassEncoder
4362 dispatchThreadgroupsWithIndirectBuffer: indirectBufMtl
4363 indirectBufferOffset: indirectBufferOffset
4364 threadsPerThreadgroup: psD->d->localSize];
4368 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
4369 QRhiBuffer *countBuffer, quint32 countBufferOffset,
4370 quint32 maxDrawCount, quint32 stride)
4378 qWarning(
"drawIndirectCount is not available because %s; skipping", reason);
4382 icbDraw(cbD,
false,
QRHI_RES(QMetalBuffer, indirectBuffer), indirectBufferOffset,
4383 QRHI_RES(QMetalBuffer, countBuffer), countBufferOffset, maxDrawCount, stride);
4387 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
4388 QRhiBuffer *countBuffer, quint32 countBufferOffset,
4389 quint32 maxDrawCount, quint32 stride)
4397 qWarning(
"drawIndexedIndirectCount is not available because %s; skipping", reason);
4402 qWarning(
"drawIndexedIndirectCount called without an index buffer bound; skipping");
4406 icbDraw(cbD,
true,
QRHI_RES(QMetalBuffer, indirectBuffer), indirectBufferOffset,
4407 QRHI_RES(QMetalBuffer, countBuffer), countBufferOffset, maxDrawCount, stride);
4451 e.stagingIcbBuffer.icb = slot.icb;
4452 e.stagingIcbBuffer.argBuffer = slot.argBuffer;
4453 rhiD
->d->releaseQueue.append(e);
4455 if (slot.rangeBuffer) {
4459 e.stagingBuffer.buffer = slot.rangeBuffer;
4460 rhiD
->d->releaseQueue.append(e);
4476 return icbD
->d->frameSlots[0].icb != nil;
4484 if (!rhiD->caps.indirectCommandBuffers)
4491 MTLIndirectCommandBufferDescriptor *icbDesc = [MTLIndirectCommandBufferDescriptor
new];
4492 icbDesc.commandTypes = icbD->type() == QRhiIndirectCommandBuffer::IndexedDraws
4493 ? MTLIndirectCommandTypeDrawIndexed : MTLIndirectCommandTypeDraw;
4495 icbDesc.inheritPipelineState = YES;
4496 icbDesc.inheritBuffers = YES;
4497 icbDesc.maxVertexBufferBindCount = 0;
4498 icbDesc.maxFragmentBufferBindCount = 0;
4503 slot.icb = [rhiD->d->dev newIndirectCommandBufferWithDescriptor:icbDesc
4504 maxCommandCount:icbD->maxCommandCount()
4505 options:gpu ? MTLResourceStorageModePrivate
4506 : MTLResourceStorageModeShared];
4508 qWarning(
"Failed to create MTLIndirectCommandBuffer");
4513 slot.rangeBuffer = [rhiD->d->dev newBufferWithLength:
sizeof(MTLIndirectCommandBufferExecutionRange)
4514 options:MTLResourceStorageModePrivate];
4515 id<MTLArgumentEncoder> argEnc = [rhiD->d->icbEncodeFunction newArgumentEncoderWithBufferIndex:1];
4516 slot.argBuffer = [rhiD->d->dev newBufferWithLength:argEnc.encodedLength
4517 options:MTLResourceStorageModeShared];
4518 if (slot.rangeBuffer && slot.argBuffer) {
4519 [argEnc setArgumentBuffer:slot.argBuffer offset:0];
4520 [argEnc setIndirectCommandBuffer:slot.icb atIndex:0];
4522 qWarning(
"Failed to create MTLIndirectCommandBuffer helper buffers");
4534 [icbD->d->frameSlots[i].icb release];
4535 [icbD->d->frameSlots[i].rangeBuffer release];
4536 [icbD->d->frameSlots[i].argBuffer release];
4537 icbD
->d->frameSlots[i] = {};
4548 quint32 maxCommandCount)
4574 m_gpuBuiltCommandCount = 0;
4579 rhiD->unregisterResource(
this);
4590 if (!m_maxCommandCount) {
4591 qWarning(
"QRhiIndirectCommandBuffer: maxCommandCount is 0");
4598 rhiD->registerResource(
this);
4602QRhiIndirectCommandBuffer *
QRhiMetal::createIndirectCommandBuffer(QRhiIndirectCommandBuffer::Type type,
4603 quint32 maxCommandCount)
4605 return new QMetalIndirectCommandBuffer(
this, type, maxCommandCount);
4609 QRhiIndirectCommandBuffer *icb)
4621 MTLPrimitiveType primitiveType,
4622 id<MTLBuffer> indexBufMtl, quint32 indexOffset,
4623 QRhiCommandBuffer::IndexFormat indexFormat)
4625 const bool indexed = icbD->type() == QRhiIndirectCommandBuffer::IndexedDraws;
4628 && slot.generation == icbD->contentsGeneration()
4629 && slot.primitiveType == primitiveType
4630 && (!indexed || (slot.indexBuf == indexBufMtl
4631 && slot.indexOffset == indexOffset
4632 && slot.indexFormat == indexFormat));
4638 MTLPrimitiveType primitiveType,
4639 id<MTLBuffer> indexBufMtl, quint32 indexOffset,
4640 QRhiCommandBuffer::IndexFormat indexFormat)
4642 const bool indexed = icbD->type() == QRhiIndirectCommandBuffer::IndexedDraws;
4644 if (qrhimtl_icbSlotMatches(icbD, slot, primitiveType, indexBufMtl, indexOffset, indexFormat))
4647 const quint32 count = icbD->recordedCommandCount();
4649 const MTLIndexType indexType = indexFormat == QRhiCommandBuffer::IndexUInt16
4650 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32;
4651 const quint32 indexSize = indexFormat == QRhiCommandBuffer::IndexUInt16 ? 2 : 4;
4653 for (quint32 i = 0; i < count; ++i) {
4655 id<MTLIndirectRenderCommand> rc = [slot.icb indirectRenderCommandAtIndex:i];
4656 [rc drawIndexedPrimitives:primitiveType
4657 indexCount:c.indexCount
4659 indexBuffer:indexBufMtl
4660 indexBufferOffset:indexOffset + c.firstIndex * indexSize
4661 instanceCount:c.instanceCount
4662 baseVertex:c.vertexOffset
4663 baseInstance:c.firstInstance];
4666 const QRhiIndirectDrawCommand *cmds = icbD->drawCommands();
4667 for (quint32 i = 0; i < count; ++i) {
4668 const QRhiIndirectDrawCommand &c(cmds[i]);
4669 id<MTLIndirectRenderCommand> rc = [slot.icb indirectRenderCommandAtIndex:i];
4670 [rc drawPrimitives:primitiveType
4671 vertexStart:c.firstVertex
4672 vertexCount:c.vertexCount
4673 instanceCount:c.instanceCount
4674 baseInstance:c.firstInstance];
4679 if (count < icbD->maxCommandCount())
4680 [slot.icb resetWithRange:NSMakeRange(count, icbD->maxCommandCount() - count)];
4682 slot.generation = icbD->contentsGeneration();
4683 slot.primitiveType = primitiveType;
4684 slot.indexBuf = indexBufMtl;
4685 slot.indexOffset = indexOffset;
4686 slot.indexFormat = indexFormat;
4692 quint32 firstCommand, quint32 count,
4693 int currentFrameSlot)
4697 if (icbD->type() == QRhiIndirectCommandBuffer::IndexedDraws) {
4701 id<MTLBuffer> indexBufMtl = indexBufD
->d->buf[indexBufD
->d->slotted ? currentFrameSlot : 0];
4702 const MTLIndexType indexType = cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16
4703 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32;
4704 const quint32 indexSize = cbD->currentIndexFormat == QRhiCommandBuffer::IndexUInt16 ? 2 : 4;
4706 for (quint32 i = 0; i < count; ++i) {
4708 [cbD->d->currentRenderPassEncoder drawIndexedPrimitives: primitiveType
4709 indexCount: c.indexCount
4710 indexType: indexType
4711 indexBuffer: indexBufMtl
4712 indexBufferOffset: cbD->currentIndexOffset + c.firstIndex * indexSize
4713 instanceCount: c.instanceCount
4714 baseVertex: c.vertexOffset
4715 baseInstance: c.firstInstance];
4718 const QRhiIndirectDrawCommand *cmds = icbD->drawCommands();
4719 for (quint32 i = 0; i < count; ++i) {
4720 const QRhiIndirectDrawCommand &c(cmds[firstCommand + i]);
4721 [cbD->d->currentRenderPassEncoder drawPrimitives: primitiveType
4722 vertexStart: c.firstVertex
4723 vertexCount: c.vertexCount
4724 instanceCount: c.instanceCount
4725 baseInstance: c.firstInstance];
4731 quint32 firstCommand, quint32 commandCount)
4739 const bool indexed = icb->type() == QRhiIndirectCommandBuffer::IndexedDraws;
4743 qWarning(
"executeIndirect: the indirect command buffer was built for a different "
4744 "topology than the current graphics pipeline uses; skipping");
4749 const quint32 total = icbD->commandCount();
4750 const bool deviceCount = icbD
->d->buildInfo.countBuffer !=
nullptr;
4751 NSRange range = NSMakeRange(0, total);
4757 if (firstCommand != 0 || commandCount < total) {
4758 qWarning(
"executeIndirect: firstCommand and commandCount cannot be honoured "
4759 "together with a device-side count; executing all %u command(s)", total);
4762 if (firstCommand >= total)
4764 const quint32 count = qMin(commandCount, total - firstCommand);
4767 range = NSMakeRange(firstCommand, count);
4770 if (indexed && icbD
->d->buildInfo.indexBuffer) {
4772 id<MTLBuffer> indexBufMtl = indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0];
4773 [cbD->d->currentRenderPassEncoder useResource:indexBufMtl
4774 usage:MTLResourceUsageRead
4775 stages:MTLRenderStageVertex | MTLRenderStageFragment];
4778 [cbD->d->currentRenderPassEncoder executeCommandsInBuffer:slot.icb
4779 indirectBuffer:slot.rangeBuffer
4780 indirectBufferOffset:0];
4782 [cbD->d->currentRenderPassEncoder executeCommandsInBuffer:slot.icb withRange:range];
4788 const QRhiIndirectCommandBufferBuildInfo &info(icbD
->d->buildInfo);
4789 if (info.countBuffer) {
4790 qWarning(
"executeIndirect: a device-side count needs an indirect command buffer, "
4791 "which is not available here; skipping");
4794 const quint32 canonicalStride = indexed ?
sizeof(QRhiIndexedIndirectDrawCommand)
4795 :
sizeof(QRhiIndirectDrawCommand);
4796 const quint32 stride = info.stride ? info.stride : canonicalStride;
4797 const quint32 total = icbD->commandCount();
4798 if (firstCommand >= total)
4800 const quint32 count = qMin(commandCount, total - firstCommand);
4803 const quint32 offset = info.sourceBufferOffset + firstCommand * stride;
4805 drawIndexedIndirect(cb, info.sourceBuffer, offset, count, stride);
4807 drawIndirect(cb, info.sourceBuffer, offset, count, stride);
4811 const quint32 total = icbD->recordedCommandCount();
4812 if (firstCommand >= total)
4814 const quint32 count = qMin(commandCount, total - firstCommand);
4821 qrhimtl_replayIcbOnCpu(cbD, icbD, firstCommand, count, currentFrameSlot);
4826 id<MTLBuffer> indexBufMtl = nil;
4827 quint32 indexOffset = 0;
4833 indexBufMtl = indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0];
4834 indexOffset = cbD->currentIndexOffset;
4838 if (slot.usedInFrameId == d->globalFrameId
4839 && !qrhimtl_icbSlotMatches(icbD, slot, primitiveType, indexBufMtl, indexOffset,
4840 cbD->currentIndexFormat))
4845 qWarning(
"executeIndirect: the same indirect command buffer is executed more than once "
4846 "in a frame, with different contents, topology or index buffer state; "
4847 "falling back to individual draw calls");
4848 qrhimtl_replayIcbOnCpu(cbD, icbD, firstCommand, count, currentFrameSlot);
4852 qrhimtl_encodeIcbFromCpu(icbD, slot, primitiveType,
4853 indexBufMtl, indexOffset, cbD->currentIndexFormat);
4858 [cbD->d->currentRenderPassEncoder useResource:indexBufMtl
4859 usage:MTLResourceUsageRead
4860 stages:MTLRenderStageVertex | MTLRenderStageFragment];
4862 [cbD->d->currentRenderPassEncoder executeCommandsInBuffer:slot.icb
4863 withRange:NSMakeRange(firstCommand, count)];
4864 slot.usedInFrameId =
d->globalFrameId;
4868 const QRhiIndirectCommandBufferBuildInfo &info)
4876 const bool indexed = icb->type() == QRhiIndirectCommandBuffer::IndexedDraws;
4878 if (indexed && !info.indexBuffer) {
4879 qWarning(
"buildIndirect: an IndexedDraws indirect command buffer needs an "
4880 "index buffer in QRhiIndirectCommandBufferBuildInfo; skipping");
4884 quint32 count = info.commandCount ? info.commandCount : icbD->m_maxCommandCount;
4885 if (count > icbD->m_maxCommandCount) {
4886 qWarning(
"QRhiIndirectCommandBuffer: buildIndirect() with commandCount %u exceeds "
4887 "maxCommandCount %u; clamping", count, icbD->m_maxCommandCount);
4888 count = icbD->m_maxCommandCount;
4890 icbD->m_gpuBuilt =
true;
4891 icbD->m_gpuBuiltCommandCount = count;
4896 icbD
->d->buildInfo = info;
4906 id<MTLBuffer> srcBufMtl = srcBufD->d->buf[srcBufD->d->slotted ? currentFrameSlot : 0];
4908 id<MTLBuffer> indexBufMtl = nil;
4912 indexBufMtl = indexBufD->d->buf[indexBufD->d->slotted ? currentFrameSlot : 0];
4915 id<MTLBuffer> countBufMtl = nil;
4916 if (info.countBuffer) {
4920 countBufMtl = countBufD->d->buf[countBufD->d->slotted ? currentFrameSlot : 0];
4923 const quint32 stride = info.stride ? info.stride
4924 : (indexed ?
sizeof(QRhiIndexedIndirectDrawCommand)
4925 :
sizeof(QRhiIndirectDrawCommand));
4929 id<MTLComputeCommandEncoder> computeEncoder = [cbD->d->cb computeCommandEncoder];
4930 encodeIcbWithCompute(
d, computeEncoder, slot.icb, slot.argBuffer, slot.rangeBuffer,
4931 indexed, info.indexFormat,
4932 toMetalPrimitiveType(info.topology),
4933 srcBufMtl, info.sourceBufferOffset,
4934 indexBufMtl, info.indexBufferOffset,
4935 countBufMtl, info.countBufferOffset,
4936 icbD->commandCount(), stride);
4937 [computeEncoder endEncoding];
4941 icbD
->d->buildInfo = info;
4949 for (
int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i)
4950 [e.buffer.buffers[i] release];
4955 [e.renderbuffer.texture release];
4960 [e.texture.texture release];
4961 for (
int i = 0; i < QMTL_FRAMES_IN_FLIGHT; ++i)
4962 [e.texture.stagingBuffers[i] release];
4963 for (
int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i)
4964 [e.texture.views[i] release];
4965 [e.texture.samplingView release];
4966 [e.texture.writeView release];
4971 [e.sampler.samplerState release];
4976 qsizetype keepBegin =
d->releaseQueue.size();
4977 for (qsizetype i = keepBegin - 1; i >= 0; --i) {
4979 if (forced || currentFrameSlot == e.lastActiveFrameSlot || e.lastActiveFrameSlot < 0) {
4993 case QRhiMetalData::DeferredReleaseEntry::StagingBuffer:
4994 [e.stagingBuffer.buffer release];
4996 case QRhiMetalData::DeferredReleaseEntry::GraphicsPipeline:
4997 [e.graphicsPipeline.pipelineState release];
4998 [e.graphicsPipeline.depthStencilState release];
4999 [e.graphicsPipeline.tessVertexComputeState[0] release];
5000 [e.graphicsPipeline.tessVertexComputeState[1] release];
5001 [e.graphicsPipeline.tessVertexComputeState[2] release];
5002 [e.graphicsPipeline.tessTessControlComputeState release];
5004 case QRhiMetalData::DeferredReleaseEntry::ComputePipeline:
5005 [e.computePipeline.pipelineState release];
5007 case QRhiMetalData::DeferredReleaseEntry::ShadingRateMap:
5008 [e.shadingRateMap.rateMap release];
5010 case QRhiMetalData::DeferredReleaseEntry::StagingIcbBuffer:
5011 [e.stagingIcbBuffer.icb release];
5012 [e.stagingIcbBuffer.argBuffer release];
5017 }
else if (--keepBegin != i) {
5018 d->releaseQueue[keepBegin] =
std::move(
d->releaseQueue[i]);
5022 d->releaseQueue.remove(0, keepBegin);
5027 QVarLengthArray<std::function<
void()>, 4> completedCallbacks;
5029 for (
int i =
d->activeTextureReadbacks.count() - 1; i >= 0; --i) {
5031 if (forced || currentFrameSlot == readback.activeFrameSlot || readback.activeFrameSlot < 0) {
5032 readback.result->format = readback.format;
5033 readback.result->pixelSize = readback.pixelSize;
5034 readback.result->data.resize(
int(readback.bufSize));
5035 const void *p = [readback.buf contents];
5036 if (readback.depthPlaneByteSize) {
5044 const quint32 pixelCount = quint32(readback.pixelSize.width()) * quint32(readback.pixelSize.height());
5045 const char *depthPlane =
static_cast<
const char *>(p);
5046 const quint8 *stencilPlane =
reinterpret_cast<
const quint8 *>(depthPlane + readback.depthPlaneByteSize);
5047 char *dst = readback.result->data.data();
5048 for (quint32 px = 0; px < pixelCount; ++px) {
5049 const quint32 depthWord = qFromUnaligned<quint32>(depthPlane + px * 4);
5050 const float depthF = readback
.depthPlaneIsFloat ? qFromUnaligned<
float>(depthPlane + px * 4) : 0.0f;
5051 const quint32 stencil = readback.stencilPlaneByteSize ? stencilPlane[px] : 0;
5052 switch (readback.format) {
5053 case QRhiTexture::D16:
5054 qToUnaligned(quint16(qRound(qBound(0.0f, depthF, 1.0f) * 65535.0f)), dst + px * 2);
5056 case QRhiTexture::D32FS8:
5057 qToUnaligned(depthWord, dst + px * 8);
5058 qToUnaligned(stencil, dst + px * 8 + 4);
5063 ? quint32(qBound(0.0f, depthF, 1.0f) * 16777215.0f + 0.5f)
5064 : depthWord & 0x00FFFFFFu;
5065 qToUnaligned((depth24 << 8) | stencil, dst + px * 4);
5071 memcpy(readback.result->data.data(), p, readback.bufSize);
5073 [readback.buf release];
5075 if (readback.result->completed)
5076 completedCallbacks.append(readback.result->completed);
5078 d->activeTextureReadbacks.remove(i);
5082 for (
int i =
d->activeBufferReadbacks.count() - 1; i >= 0; --i) {
5084 if (forced || currentFrameSlot == readback.activeFrameSlot
5085 || readback.activeFrameSlot < 0) {
5086 readback.result->data.resize(readback.readSize);
5087 char *p =
reinterpret_cast<
char *>([readback.buf contents]);
5089 memcpy(readback.result->data.data(), p, size_t(readback.readSize));
5090 [readback.buf release];
5092 if (readback.result->completed)
5093 completedCallbacks.append(readback.result->completed);
5095 d->activeBufferReadbacks.remove(i);
5099 for (
auto f : completedCallbacks)
5127 e.buffer.buffers[i] =
d->buf[i];
5129 d->pendingUpdates[i].clear();
5134 rhiD
->d->releaseQueue.append(e);
5135 rhiD->unregisterResource(
this);
5144 if (m_usage.testFlag(QRhiBuffer::StorageBuffer) && m_type == Dynamic) {
5145 qWarning(
"StorageBuffer cannot be combined with Dynamic");
5149 const quint32 nonZeroSize = m_size <= 0 ? 256 : m_size;
5150 const quint32 roundedSize = m_usage.testFlag(QRhiBuffer::UniformBuffer) ? aligned(nonZeroSize, 256u) : nonZeroSize;
5154 MTLResourceOptions opts = MTLResourceStorageModeShared;
5158 const bool internalHostWritable = (
int(m_usage) & (WorkBufPoolUsage | InternalHostWritable)) != 0;
5160 if (m_type != Dynamic && !internalHostWritable && rhiD->caps.usePrivateStaticBuffers) {
5161 opts = MTLResourceStorageModePrivate;
5166 if (!rhiD->caps.isAppleGPU && m_type != Dynamic) {
5167 opts = MTLResourceStorageModeManaged;
5174 d->slotted = !m_usage.testFlag(QRhiBuffer::StorageBuffer)
5175 && !internalHostWritable;
5180 d->buf[i] = [rhiD->d->dev newBufferWithLength: roundedSize options: opts];
5181 if (!m_objectName.isEmpty()) {
5183 d->buf[i].label = [NSString stringWithUTF8String: m_objectName.constData()];
5185 const QByteArray name = m_objectName +
'/' + QByteArray::number(i);
5186 d->buf[i].label = [NSString stringWithUTF8String: name.constData()];
5194 rhiD->registerResource(
this);
5202 Q_ASSERT(
sizeof(b.objects) /
sizeof(b.objects[0]) >= size_t(QMTL_FRAMES_IN_FLIGHT));
5206 b.objects[i] = &
d->buf[i];
5208 b.slotCount = QMTL_FRAMES_IN_FLIGHT;
5215 return { { &
d->buf[0] }, 1 };
5225 Q_ASSERT(m_type == Dynamic);
5228 Q_ASSERT(rhiD->inFrame);
5229 const int slot =
d->slotted ? rhiD->currentFrameSlot : 0;
5230 void *p = [d->buf[slot] contents];
5231 return static_cast<
char *>(p);
5246 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
5248 case QRhiTexture::RGBA8:
5249 return srgb ? MTLPixelFormatRGBA8Unorm_sRGB : MTLPixelFormatRGBA8Unorm;
5250 case QRhiTexture::BGRA8:
5251 return srgb ? MTLPixelFormatBGRA8Unorm_sRGB : MTLPixelFormatBGRA8Unorm;
5252 case QRhiTexture::R8:
5254 return MTLPixelFormatR8Unorm;
5256 return srgb ? MTLPixelFormatR8Unorm_sRGB : MTLPixelFormatR8Unorm;
5258 case QRhiTexture::R8SI:
5259 return MTLPixelFormatR8Sint;
5260 case QRhiTexture::R8UI:
5261 return MTLPixelFormatR8Uint;
5262 case QRhiTexture::RG8:
5264 return MTLPixelFormatRG8Unorm;
5266 return srgb ? MTLPixelFormatRG8Unorm_sRGB : MTLPixelFormatRG8Unorm;
5268 case QRhiTexture::R16:
5269 return MTLPixelFormatR16Unorm;
5270 case QRhiTexture::RG16:
5271 return MTLPixelFormatRG16Unorm;
5272 case QRhiTexture::RED_OR_ALPHA8:
5273 return MTLPixelFormatR8Unorm;
5275 case QRhiTexture::RGBA16F:
5276 return MTLPixelFormatRGBA16Float;
5277 case QRhiTexture::RGBA32F:
5278 return MTLPixelFormatRGBA32Float;
5279 case QRhiTexture::R16F:
5280 return MTLPixelFormatR16Float;
5281 case QRhiTexture::R32F:
5282 return MTLPixelFormatR32Float;
5284 case QRhiTexture::RGB10A2:
5285 return MTLPixelFormatRGB10A2Unorm;
5287 case QRhiTexture::R32SI:
5288 return MTLPixelFormatR32Sint;
5289 case QRhiTexture::R32UI:
5290 return MTLPixelFormatR32Uint;
5291 case QRhiTexture::RG32SI:
5292 return MTLPixelFormatRG32Sint;
5293 case QRhiTexture::RG32UI:
5294 return MTLPixelFormatRG32Uint;
5295 case QRhiTexture::RGBA32SI:
5296 return MTLPixelFormatRGBA32Sint;
5297 case QRhiTexture::RGBA32UI:
5298 return MTLPixelFormatRGBA32Uint;
5301 case QRhiTexture::D16:
5302 return MTLPixelFormatDepth16Unorm;
5303 case QRhiTexture::D24:
5304 return [d->d->dev isDepth24Stencil8PixelFormatSupported] ? MTLPixelFormatDepth24Unorm_Stencil8 : MTLPixelFormatDepth32Float;
5305 case QRhiTexture::D24S8:
5306 return [d->d->dev isDepth24Stencil8PixelFormatSupported] ? MTLPixelFormatDepth24Unorm_Stencil8 : MTLPixelFormatDepth32Float_Stencil8;
5308 case QRhiTexture::D16:
5309 return MTLPixelFormatDepth32Float;
5310 case QRhiTexture::D24:
5311 return MTLPixelFormatDepth32Float;
5312 case QRhiTexture::D24S8:
5313 return MTLPixelFormatDepth32Float_Stencil8;
5315 case QRhiTexture::D32F:
5316 return MTLPixelFormatDepth32Float;
5317 case QRhiTexture::D32FS8:
5318 return MTLPixelFormatDepth32Float_Stencil8;
5321 case QRhiTexture::BC1:
5322 return srgb ? MTLPixelFormatBC1_RGBA_sRGB : MTLPixelFormatBC1_RGBA;
5323 case QRhiTexture::BC2:
5324 return srgb ? MTLPixelFormatBC2_RGBA_sRGB : MTLPixelFormatBC2_RGBA;
5325 case QRhiTexture::BC3:
5326 return srgb ? MTLPixelFormatBC3_RGBA_sRGB : MTLPixelFormatBC3_RGBA;
5327 case QRhiTexture::BC4:
5328 return MTLPixelFormatBC4_RUnorm;
5329 case QRhiTexture::BC5:
5330 qWarning(
"QRhiMetal does not support BC5");
5331 return MTLPixelFormatInvalid;
5332 case QRhiTexture::BC6H:
5333 return MTLPixelFormatBC6H_RGBUfloat;
5334 case QRhiTexture::BC7:
5335 return srgb ? MTLPixelFormatBC7_RGBAUnorm_sRGB : MTLPixelFormatBC7_RGBAUnorm;
5337 case QRhiTexture::BC1:
5338 case QRhiTexture::BC2:
5339 case QRhiTexture::BC3:
5340 case QRhiTexture::BC4:
5341 case QRhiTexture::BC5:
5342 case QRhiTexture::BC6H:
5343 case QRhiTexture::BC7:
5344 qWarning(
"QRhiMetal: BCx compression not supported on this platform");
5345 return MTLPixelFormatInvalid;
5349 case QRhiTexture::ETC2_RGB8:
5350 return srgb ? MTLPixelFormatETC2_RGB8_sRGB : MTLPixelFormatETC2_RGB8;
5351 case QRhiTexture::ETC2_RGB8A1:
5352 return srgb ? MTLPixelFormatETC2_RGB8A1_sRGB : MTLPixelFormatETC2_RGB8A1;
5353 case QRhiTexture::ETC2_RGBA8:
5354 return srgb ? MTLPixelFormatEAC_RGBA8_sRGB : MTLPixelFormatEAC_RGBA8;
5356 case QRhiTexture::ASTC_4x4:
5357 return srgb ? MTLPixelFormatASTC_4x4_sRGB : MTLPixelFormatASTC_4x4_LDR;
5358 case QRhiTexture::ASTC_5x4:
5359 return srgb ? MTLPixelFormatASTC_5x4_sRGB : MTLPixelFormatASTC_5x4_LDR;
5360 case QRhiTexture::ASTC_5x5:
5361 return srgb ? MTLPixelFormatASTC_5x5_sRGB : MTLPixelFormatASTC_5x5_LDR;
5362 case QRhiTexture::ASTC_6x5:
5363 return srgb ? MTLPixelFormatASTC_6x5_sRGB : MTLPixelFormatASTC_6x5_LDR;
5364 case QRhiTexture::ASTC_6x6:
5365 return srgb ? MTLPixelFormatASTC_6x6_sRGB : MTLPixelFormatASTC_6x6_LDR;
5366 case QRhiTexture::ASTC_8x5:
5367 return srgb ? MTLPixelFormatASTC_8x5_sRGB : MTLPixelFormatASTC_8x5_LDR;
5368 case QRhiTexture::ASTC_8x6:
5369 return srgb ? MTLPixelFormatASTC_8x6_sRGB : MTLPixelFormatASTC_8x6_LDR;
5370 case QRhiTexture::ASTC_8x8:
5371 return srgb ? MTLPixelFormatASTC_8x8_sRGB : MTLPixelFormatASTC_8x8_LDR;
5372 case QRhiTexture::ASTC_10x5:
5373 return srgb ? MTLPixelFormatASTC_10x5_sRGB : MTLPixelFormatASTC_10x5_LDR;
5374 case QRhiTexture::ASTC_10x6:
5375 return srgb ? MTLPixelFormatASTC_10x6_sRGB : MTLPixelFormatASTC_10x6_LDR;
5376 case QRhiTexture::ASTC_10x8:
5377 return srgb ? MTLPixelFormatASTC_10x8_sRGB : MTLPixelFormatASTC_10x8_LDR;
5378 case QRhiTexture::ASTC_10x10:
5379 return srgb ? MTLPixelFormatASTC_10x10_sRGB : MTLPixelFormatASTC_10x10_LDR;
5380 case QRhiTexture::ASTC_12x10:
5381 return srgb ? MTLPixelFormatASTC_12x10_sRGB : MTLPixelFormatASTC_12x10_LDR;
5382 case QRhiTexture::ASTC_12x12:
5383 return srgb ? MTLPixelFormatASTC_12x12_sRGB : MTLPixelFormatASTC_12x12_LDR;
5385 case QRhiTexture::ETC2_RGB8:
5386 if (d->caps.isAppleGPU)
5387 return srgb ? MTLPixelFormatETC2_RGB8_sRGB : MTLPixelFormatETC2_RGB8;
5388 qWarning(
"QRhiMetal: ETC2 compression not supported on this platform");
5389 return MTLPixelFormatInvalid;
5390 case QRhiTexture::ETC2_RGB8A1:
5391 if (d->caps.isAppleGPU)
5392 return srgb ? MTLPixelFormatETC2_RGB8A1_sRGB : MTLPixelFormatETC2_RGB8A1;
5393 qWarning(
"QRhiMetal: ETC2 compression not supported on this platform");
5394 return MTLPixelFormatInvalid;
5395 case QRhiTexture::ETC2_RGBA8:
5396 if (d->caps.isAppleGPU)
5397 return srgb ? MTLPixelFormatEAC_RGBA8_sRGB : MTLPixelFormatEAC_RGBA8;
5398 qWarning(
"QRhiMetal: ETC2 compression not supported on this platform");
5399 return MTLPixelFormatInvalid;
5400 case QRhiTexture::ASTC_4x4:
5401 if (d->caps.isAppleGPU)
5402 return srgb ? MTLPixelFormatASTC_4x4_sRGB : MTLPixelFormatASTC_4x4_LDR;
5403 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5404 return MTLPixelFormatInvalid;
5405 case QRhiTexture::ASTC_5x4:
5406 if (d->caps.isAppleGPU)
5407 return srgb ? MTLPixelFormatASTC_5x4_sRGB : MTLPixelFormatASTC_5x4_LDR;
5408 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5409 return MTLPixelFormatInvalid;
5410 case QRhiTexture::ASTC_5x5:
5411 if (d->caps.isAppleGPU)
5412 return srgb ? MTLPixelFormatASTC_5x5_sRGB : MTLPixelFormatASTC_5x5_LDR;
5413 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5414 return MTLPixelFormatInvalid;
5415 case QRhiTexture::ASTC_6x5:
5416 if (d->caps.isAppleGPU)
5417 return srgb ? MTLPixelFormatASTC_6x5_sRGB : MTLPixelFormatASTC_6x5_LDR;
5418 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5419 return MTLPixelFormatInvalid;
5420 case QRhiTexture::ASTC_6x6:
5421 if (d->caps.isAppleGPU)
5422 return srgb ? MTLPixelFormatASTC_6x6_sRGB : MTLPixelFormatASTC_6x6_LDR;
5423 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5424 return MTLPixelFormatInvalid;
5425 case QRhiTexture::ASTC_8x5:
5426 if (d->caps.isAppleGPU)
5427 return srgb ? MTLPixelFormatASTC_8x5_sRGB : MTLPixelFormatASTC_8x5_LDR;
5428 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5429 return MTLPixelFormatInvalid;
5430 case QRhiTexture::ASTC_8x6:
5431 if (d->caps.isAppleGPU)
5432 return srgb ? MTLPixelFormatASTC_8x6_sRGB : MTLPixelFormatASTC_8x6_LDR;
5433 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5434 return MTLPixelFormatInvalid;
5435 case QRhiTexture::ASTC_8x8:
5436 if (d->caps.isAppleGPU)
5437 return srgb ? MTLPixelFormatASTC_8x8_sRGB : MTLPixelFormatASTC_8x8_LDR;
5438 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5439 return MTLPixelFormatInvalid;
5440 case QRhiTexture::ASTC_10x5:
5441 if (d->caps.isAppleGPU)
5442 return srgb ? MTLPixelFormatASTC_10x5_sRGB : MTLPixelFormatASTC_10x5_LDR;
5443 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5444 return MTLPixelFormatInvalid;
5445 case QRhiTexture::ASTC_10x6:
5446 if (d->caps.isAppleGPU)
5447 return srgb ? MTLPixelFormatASTC_10x6_sRGB : MTLPixelFormatASTC_10x6_LDR;
5448 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5449 return MTLPixelFormatInvalid;
5450 case QRhiTexture::ASTC_10x8:
5451 if (d->caps.isAppleGPU)
5452 return srgb ? MTLPixelFormatASTC_10x8_sRGB : MTLPixelFormatASTC_10x8_LDR;
5453 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5454 return MTLPixelFormatInvalid;
5455 case QRhiTexture::ASTC_10x10:
5456 if (d->caps.isAppleGPU)
5457 return srgb ? MTLPixelFormatASTC_10x10_sRGB : MTLPixelFormatASTC_10x10_LDR;
5458 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5459 return MTLPixelFormatInvalid;
5460 case QRhiTexture::ASTC_12x10:
5461 if (d->caps.isAppleGPU)
5462 return srgb ? MTLPixelFormatASTC_12x10_sRGB : MTLPixelFormatASTC_12x10_LDR;
5463 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5464 return MTLPixelFormatInvalid;
5465 case QRhiTexture::ASTC_12x12:
5466 if (d->caps.isAppleGPU)
5467 return srgb ? MTLPixelFormatASTC_12x12_sRGB : MTLPixelFormatASTC_12x12_LDR;
5468 qWarning(
"QRhiMetal: ASTC compression not supported on this platform");
5469 return MTLPixelFormatInvalid;
5474 return MTLPixelFormatInvalid;
5479 int sampleCount, QRhiRenderBuffer::Flags flags,
5480 QRhiTexture::Format backingFormatHint)
5501 e.renderbuffer.texture =
d->tex;
5506 rhiD
->d->releaseQueue.append(e);
5507 rhiD->unregisterResource(
this);
5516 if (m_pixelSize.isEmpty())
5520 samples = rhiD->effectiveSampleCount(m_sampleCount);
5522 MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init];
5523 desc.textureType = samples > 1 ? MTLTextureType2DMultisample : MTLTextureType2D;
5524 desc.width = NSUInteger(m_pixelSize.width());
5525 desc.height = NSUInteger(m_pixelSize.height());
5527 desc.sampleCount = NSUInteger(
samples);
5528 desc.resourceOptions = MTLResourceStorageModePrivate;
5529 desc.usage = MTLTextureUsageRenderTarget;
5534 const bool canBeMemoryless = !m_flags.testFlag(QRhiRenderBuffer::NoTransientBacking);
5539 if (rhiD->caps.isAppleGPU && canBeMemoryless) {
5540 desc.storageMode = MTLStorageModeMemoryless;
5541 d->format = MTLPixelFormatDepth32Float_Stencil8;
5543 desc.storageMode = MTLStorageModePrivate;
5544 d->format = rhiD->d->dev.depth24Stencil8PixelFormatSupported
5545 ? MTLPixelFormatDepth24Unorm_Stencil8 : MTLPixelFormatDepth32Float_Stencil8;
5548 desc.storageMode = canBeMemoryless ? MTLStorageModeMemoryless : MTLStorageModePrivate;
5549 d->format = MTLPixelFormatDepth32Float_Stencil8;
5551 desc.pixelFormat =
d->format;
5554 desc.storageMode = MTLStorageModePrivate;
5555 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
5556 d->format = toMetalTextureFormat(m_backingFormatHint, {}, rhiD);
5558 d->format = MTLPixelFormatRGBA8Unorm;
5559 desc.pixelFormat =
d->format;
5566 d->tex = [rhiD->d->dev newTextureWithDescriptor: desc];
5569 if (!m_objectName.isEmpty())
5570 d->tex.label = [NSString stringWithUTF8String: m_objectName.constData()];
5574 rhiD->registerResource(
this);
5580 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
5581 return m_backingFormatHint;
5583 return m_type == Color ? QRhiTexture::RGBA8 : QRhiTexture::UnknownFormat;
5587 int arraySize,
int sampleCount, Flags flags)
5592 d->stagingBuf[i] = nil;
5594 for (
int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i)
5595 d->perLevelViews[i] = nil;
5613 e.texture.texture =
d->owns ? d->tex : nil;
5617 e.texture.stagingBuffers[i] =
d->stagingBuf[i];
5618 d->stagingBuf[i] = nil;
5621 for (
int i = 0; i < QRhi::MAX_MIP_LEVELS; ++i) {
5622 e.texture.views[i] =
d->perLevelViews[i];
5623 d->perLevelViews[i] = nil;
5626 e.texture.samplingView =
d->samplingView;
5627 d->samplingView = nil;
5628 e.texture.writeView =
d->writeView;
5633 rhiD
->d->releaseQueue.append(e);
5634 rhiD->unregisterResource(
this);
5643 const bool isCube = m_flags.testFlag(CubeMap);
5644 const bool is3D = m_flags.testFlag(ThreeDimensional);
5645 const bool isArray = m_flags.testFlag(TextureArray);
5646 const bool hasMipMaps = m_flags.testFlag(MipMapped);
5647 const bool is1D = m_flags.testFlag(OneDimensional);
5649 const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
5650 : (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
5653 d->format = toMetalTextureFormat(m_format, m_flags, rhiD);
5654 if (m_writeViewFormat.format != UnknownFormat) {
5655 d->viewFormat = toMetalTextureFormat(m_writeViewFormat.format,
5656 m_writeViewFormat.srgb ? sRGB : Flags(), rhiD);
5658 d->viewFormat =
d->format;
5660 if (m_readViewFormat.format != UnknownFormat) {
5661 d->viewFormatForSampling = toMetalTextureFormat(m_readViewFormat.format,
5662 m_readViewFormat.srgb ? sRGB : Flags(), rhiD);
5664 d->viewFormatForSampling =
d->format;
5666 mipLevelCount = hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1;
5667 samples = rhiD->effectiveSampleCount(m_sampleCount);
5670 qWarning(
"Cubemap texture cannot be multisample");
5674 qWarning(
"3D texture cannot be multisample");
5678 qWarning(
"Multisample texture cannot have mipmaps");
5682 if (isCube && is3D) {
5683 qWarning(
"Texture cannot be both cube and 3D");
5686 if (isArray && is3D) {
5687 qWarning(
"Texture cannot be both array and 3D");
5691 qWarning(
"Texture cannot be both 1D and 3D");
5694 if (is1D && isCube) {
5695 qWarning(
"Texture cannot be both 1D and cube");
5698 if (m_depth > 1 && !is3D) {
5699 qWarning(
"Texture cannot have a depth of %d when it is not 3D", m_depth);
5702 if (m_arraySize > 0 && !isArray) {
5703 qWarning(
"Texture cannot have an array size of %d when it is not an array", m_arraySize);
5706 if (m_arraySize < 1 && isArray) {
5707 qWarning(
"Texture is an array but array size is %d", m_arraySize);
5711 if (!rhiD->textureFormatInfo(m_format, size,
nullptr,
nullptr,
nullptr))
5715 *adjustedSize = size;
5723 if (!prepareCreate(&size))
5726 MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init];
5728 const bool isCube = m_flags.testFlag(CubeMap);
5729 const bool is3D = m_flags.testFlag(ThreeDimensional);
5730 const bool isArray = m_flags.testFlag(TextureArray);
5731 const bool is1D = m_flags.testFlag(OneDimensional);
5733 desc.textureType = MTLTextureTypeCube;
5735 desc.textureType = MTLTextureType3D;
5737 desc.textureType = isArray ? MTLTextureType1DArray : MTLTextureType1D;
5738 }
else if (isArray) {
5739 desc.textureType = samples > 1 ? MTLTextureType2DMultisampleArray : MTLTextureType2DArray;
5741 desc.textureType = samples > 1 ? MTLTextureType2DMultisample : MTLTextureType2D;
5743 desc.pixelFormat =
d->format;
5744 desc.width = NSUInteger(size.width());
5745 desc.height = NSUInteger(size.height());
5746 desc.depth = is3D ? qMax(1, m_depth) : 1;
5749 desc.sampleCount = NSUInteger(
samples);
5751 desc.arrayLength = NSUInteger(qMax(0, m_arraySize));
5752 desc.resourceOptions = MTLResourceStorageModePrivate;
5753 desc.storageMode = MTLStorageModePrivate;
5754 desc.usage = MTLTextureUsageShaderRead;
5755 if (m_flags.testFlag(RenderTarget))
5756 desc.usage |= MTLTextureUsageRenderTarget;
5757 if (m_flags.testFlag(UsedWithLoadStore))
5758 desc.usage |= MTLTextureUsageShaderWrite;
5764 const bool writeViewChangesFormat = m_writeViewFormat.format != UnknownFormat
5765 && m_writeViewFormat.format != m_format;
5766 const bool readViewChangesFormat = m_readViewFormat.format != UnknownFormat
5767 && m_readViewFormat.format != m_format;
5768 if (writeViewChangesFormat || readViewChangesFormat)
5769 desc.usage |= MTLTextureUsagePixelFormatView;
5772 d->tex = [rhiD->d->dev newTextureWithDescriptor: desc];
5775 if (!m_objectName.isEmpty())
5776 d->tex.label = [NSString stringWithUTF8String: m_objectName.constData()];
5785 rhiD->registerResource(
this);
5791 id<MTLTexture> tex = id<MTLTexture>(src.object);
5795 if (!prepareCreate())
5808 rhiD->registerResource(
this);
5814 return {quint64(
d->tex), 0};
5819 Q_ASSERT(!samplingView && !writeView);
5821 const bool isCube =
q->m_flags.testFlag(QRhiTexture::CubeMap);
5822 const bool isArray =
q->m_flags.testFlag(QRhiTexture::TextureArray);
5823 const bool hasArrayRange = isArray &&
q->m_arrayRangeStart >= 0 &&
q->m_arrayRangeLength >= 0;
5824 const NSUInteger sliceCount = isCube ? 6 : (isArray ? NSUInteger(qMax(0,
q->m_arraySize)) : 1);
5826 const MTLTextureType type = [tex textureType];
5828 id<MTLTexture> newSamplingView = nil;
5829 id<MTLTexture> newWriteView = nil;
5831 if (viewFormatForSampling != format || hasArrayRange) {
5832 const NSRange slices = hasArrayRange
5833 ? NSMakeRange(NSUInteger(
q->m_arrayRangeStart), NSUInteger(
q->m_arrayRangeLength))
5834 : NSMakeRange(0, sliceCount);
5835 newSamplingView = [tex newTextureViewWithPixelFormat: viewFormatForSampling
5836 textureType: type levels: levels slices: slices];
5837 if (!newSamplingView) {
5838 qWarning(
"QRhiMetal: Failed to create texture view used for sampling");
5843 if (viewFormat != format) {
5844 newWriteView = [tex newTextureViewWithPixelFormat: viewFormat
5845 textureType: type levels: levels
5846 slices: NSMakeRange(0, sliceCount)];
5847 if (!newWriteView) {
5848 qWarning(
"QRhiMetal: Failed to create texture view used for rendering");
5849 [newSamplingView release];
5854 samplingView = newSamplingView;
5855 writeView = newWriteView;
5862 if (perLevelViews[level])
5863 return perLevelViews[level];
5865 const MTLTextureType type = [tex textureType];
5866 const bool isCube =
q->m_flags.testFlag(QRhiTexture::CubeMap);
5867 const bool isArray =
q->m_flags.testFlag(QRhiTexture::TextureArray);
5868 id<MTLTexture> view = [tex newTextureViewWithPixelFormat: viewFormat textureType: type
5869 levels: NSMakeRange(NSUInteger(level), 1)
5870 slices: NSMakeRange(0, isCube ? 6 : (isArray ? qMax(0, q->m_arraySize) : 1))];
5872 perLevelViews[level] = view;
5877 AddressMode u, AddressMode v, AddressMode w)
5891 if (!
d->samplerState)
5898 e.sampler.samplerState =
d->samplerState;
5899 d->samplerState = nil;
5903 rhiD
->d->releaseQueue.append(e);
5904 rhiD->unregisterResource(
this);
5911 case QRhiSampler::Nearest:
5912 return MTLSamplerMinMagFilterNearest;
5913 case QRhiSampler::Linear:
5914 return MTLSamplerMinMagFilterLinear;
5917 return MTLSamplerMinMagFilterNearest;
5924 case QRhiSampler::None:
5925 return MTLSamplerMipFilterNotMipmapped;
5926 case QRhiSampler::Nearest:
5927 return MTLSamplerMipFilterNearest;
5928 case QRhiSampler::Linear:
5929 return MTLSamplerMipFilterLinear;
5932 return MTLSamplerMipFilterNotMipmapped;
5939 case QRhiSampler::Repeat:
5940 return MTLSamplerAddressModeRepeat;
5941 case QRhiSampler::ClampToEdge:
5942 return MTLSamplerAddressModeClampToEdge;
5943 case QRhiSampler::Mirror:
5944 return MTLSamplerAddressModeMirrorRepeat;
5947 return MTLSamplerAddressModeClampToEdge;
5954 case QRhiSampler::Never:
5955 return MTLCompareFunctionNever;
5956 case QRhiSampler::Less:
5957 return MTLCompareFunctionLess;
5958 case QRhiSampler::Equal:
5959 return MTLCompareFunctionEqual;
5960 case QRhiSampler::LessOrEqual:
5961 return MTLCompareFunctionLessEqual;
5962 case QRhiSampler::Greater:
5963 return MTLCompareFunctionGreater;
5964 case QRhiSampler::NotEqual:
5965 return MTLCompareFunctionNotEqual;
5966 case QRhiSampler::GreaterOrEqual:
5967 return MTLCompareFunctionGreaterEqual;
5968 case QRhiSampler::Always:
5969 return MTLCompareFunctionAlways;
5972 return MTLCompareFunctionNever;
5978 if (
d->samplerState)
5981 MTLSamplerDescriptor *desc = [[MTLSamplerDescriptor alloc] init];
5982 desc.minFilter = toMetalFilter(m_minFilter);
5983 desc.magFilter = toMetalFilter(m_magFilter);
5984 desc.mipFilter = toMetalMipmapMode(m_mipmapMode);
5985 desc.sAddressMode = toMetalAddressMode(m_addressU);
5986 desc.tAddressMode = toMetalAddressMode(m_addressV);
5987 desc.rAddressMode = toMetalAddressMode(m_addressW);
5988 desc.compareFunction = toMetalTextureCompareFunction(m_compareOp);
5994 desc.supportArgumentBuffers = rhiD->caps.indirectCommandBuffers ? YES : NO;
5995 d->samplerState = [rhiD->d->dev newSamplerStateWithDescriptor: desc];
5997 if (!
d->samplerState) {
6001 qWarning(
"Failed to create Metal sampler state. The number of unique sampler "
6002 "states with argument buffer support may have exceeded the limit of %u.",
6003 uint(rhiD
->d->dev.maxArgumentBufferSamplerCount));
6009 rhiD->registerResource(
this);
6034 e.shadingRateMap.rateMap =
d->rateMap;
6039 rhiD
->d->releaseQueue.append(e);
6040 rhiD->unregisterResource(
this);
6049 d->rateMap = (id<MTLRasterizationRateMap>) (quintptr(src.object));
6053 [d->rateMap retain];
6058 rhiD->registerResource(
this);
6067 const MTLSize screenSize = [d->rateMap screenSize];
6068 return QSize(
int(screenSize.width),
int(screenSize.height));
6076 serializedFormatData.reserve(16);
6088 rhiD->unregisterResource(
this);
6122 serializedFormatData.clear();
6123 auto p =
std::back_inserter(serializedFormatData);
6145 rhiD->registerResource(rpD,
false);
6151 return serializedFormatData;
6173 return d->pixelSize;
6187 const QRhiTextureRenderTargetDescription &desc,
6204 rhiD->unregisterResource(
this);
6209 const int colorAttachmentCount =
int(m_desc.colorAttachmentCount());
6214 for (
int i = 0; i < colorAttachmentCount; ++i) {
6215 const QRhiColorAttachment *colorAtt = m_desc.colorAttachmentAt(i);
6221 if (m_desc.depthTexture())
6223 else if (m_desc.depthStencilBuffer())
6224 rpD
->dsFormat =
int(
QRHI_RES(QMetalRenderBuffer, m_desc.depthStencilBuffer())->d->format);
6231 rhiD->registerResource(rpD,
false);
6238 Q_ASSERT(m_desc.colorAttachmentCount() > 0 || m_desc.depthTexture());
6239 Q_ASSERT(!m_desc.depthStencilBuffer() || !m_desc.depthTexture());
6240 const bool hasDepthStencil = m_desc.depthStencilBuffer() || m_desc.depthTexture();
6244 for (
auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
6248 Q_ASSERT(texD || rbD);
6249 id<MTLTexture> dst = nil;
6252 dst = texD
->d->textureForWrite();
6253 if (attIndex == 0) {
6254 d->pixelSize = rhiD->q->sizeForMipLevel(it->level(), texD->pixelSize());
6257 is3D = texD->flags().testFlag(QRhiTexture::ThreeDimensional);
6260 if (attIndex == 0) {
6261 d->pixelSize = rbD->pixelSize();
6268 colorAtt
.slice = is3D ? it->layer() : 0;
6269 colorAtt
.level = it->level();
6271 colorAtt.resolveTex = resTexD ? resTexD->d->textureForWrite() : nil;
6274 d->fb.colorAtt[attIndex] = colorAtt;
6278 if (hasDepthStencil) {
6279 if (m_desc.depthTexture()) {
6281 d->fb.dsTex = depthTexD
->d->textureForWrite();
6282 d->fb.hasStencil = rhiD->isStencilSupportingFormat(depthTexD->format());
6283 d->fb.depthNeedsStore = !m_flags.testFlag(DoNotStoreDepthStencilContents) && !m_desc.depthResolveTexture();
6284 d->fb.preserveDs = m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents);
6286 d->pixelSize = depthTexD->pixelSize();
6291 d->fb.dsTex = depthRbD
->d->tex;
6292 d->fb.hasStencil =
true;
6293 d->fb.depthNeedsStore =
false;
6294 d->fb.preserveDs =
false;
6296 d->pixelSize = depthRbD->pixelSize();
6300 if (m_desc.depthResolveTexture()) {
6302 d->fb.dsResolveTex = depthResolveTexD
->d->textureForWrite();
6310 d->fb.preserveColor = m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
6312 QRhiRenderTargetAttachmentTracker::updateResIdList<QMetalTexture, QMetalRenderBuffer>(m_desc, &d->currentResIdList);
6314 rhiD->registerResource(
this,
false);
6320 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QMetalTexture, QMetalRenderBuffer>(m_desc, d->currentResIdList))
6323 return d->pixelSize;
6348 sortedBindings.clear();
6353 rhiD->unregisterResource(
this);
6358 if (!sortedBindings.isEmpty())
6362 if (!rhiD->sanityCheckShaderResourceBindings(
this))
6365 rhiD->updateLayoutDesc(
this);
6367 std::copy(m_bindings.cbegin(), m_bindings.cend(),
std::back_inserter(sortedBindings));
6368 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
6369 if (!sortedBindings.isEmpty())
6370 maxBinding = QRhiImplementation::shaderResourceBindingData(sortedBindings.last())->binding;
6374 boundResourceData.resize(sortedBindings.count());
6376 for (BoundResourceData &bd : boundResourceData)
6380 rhiD->registerResource(
this,
false);
6386 sortedBindings.clear();
6387 std::copy(m_bindings.cbegin(), m_bindings.cend(),
std::back_inserter(sortedBindings));
6388 if (!flags.testFlag(BindingsAreSorted))
6389 std::sort(sortedBindings.begin(), sortedBindings.end(), QRhiImplementation::sortedBindingLessThan);
6391 for (BoundResourceData &bd : boundResourceData)
6418 d->tess.compVs[0].destroy();
6419 d->tess.compVs[1].destroy();
6420 d->tess.compVs[2].destroy();
6422 d->tess.compTesc.destroy();
6423 d->tess.vertTese.destroy();
6425 qDeleteAll(
d->extraBufMgr.deviceLocalWorkBuffers);
6426 d->extraBufMgr.deviceLocalWorkBuffers.clear();
6427 qDeleteAll(
d->extraBufMgr.hostVisibleWorkBuffers);
6428 d->extraBufMgr.hostVisibleWorkBuffers.clear();
6433 if (!
d->ps && !
d->ds
6434 && !
d->tess.vertexComputeState[0] && !
d->tess.vertexComputeState[1] && !
d->tess.vertexComputeState[2]
6435 && !
d->tess.tessControlComputeState)
6443 e.graphicsPipeline.pipelineState =
d->ps;
6444 e.graphicsPipeline.depthStencilState =
d->ds;
6445 e.graphicsPipeline.tessVertexComputeState =
d->tess.vertexComputeState;
6446 e.graphicsPipeline.tessTessControlComputeState =
d->tess.tessControlComputeState;
6449 d->tess.vertexComputeState = {};
6450 d->tess.tessControlComputeState = nil;
6454 rhiD
->d->releaseQueue.append(e);
6455 rhiD->unregisterResource(
this);
6462 case QRhiVertexInputAttribute::Float4:
6463 return MTLVertexFormatFloat4;
6464 case QRhiVertexInputAttribute::Float3:
6465 return MTLVertexFormatFloat3;
6466 case QRhiVertexInputAttribute::Float2:
6467 return MTLVertexFormatFloat2;
6468 case QRhiVertexInputAttribute::Float:
6469 return MTLVertexFormatFloat;
6470 case QRhiVertexInputAttribute::UNormByte4:
6471 return MTLVertexFormatUChar4Normalized;
6472 case QRhiVertexInputAttribute::UNormByte2:
6473 return MTLVertexFormatUChar2Normalized;
6474 case QRhiVertexInputAttribute::UNormByte:
6475 return MTLVertexFormatUCharNormalized;
6476 case QRhiVertexInputAttribute::UInt4:
6477 return MTLVertexFormatUInt4;
6478 case QRhiVertexInputAttribute::UInt3:
6479 return MTLVertexFormatUInt3;
6480 case QRhiVertexInputAttribute::UInt2:
6481 return MTLVertexFormatUInt2;
6482 case QRhiVertexInputAttribute::UInt:
6483 return MTLVertexFormatUInt;
6484 case QRhiVertexInputAttribute::SInt4:
6485 return MTLVertexFormatInt4;
6486 case QRhiVertexInputAttribute::SInt3:
6487 return MTLVertexFormatInt3;
6488 case QRhiVertexInputAttribute::SInt2:
6489 return MTLVertexFormatInt2;
6490 case QRhiVertexInputAttribute::SInt:
6491 return MTLVertexFormatInt;
6492 case QRhiVertexInputAttribute::Half4:
6493 return MTLVertexFormatHalf4;
6494 case QRhiVertexInputAttribute::Half3:
6495 return MTLVertexFormatHalf3;
6496 case QRhiVertexInputAttribute::Half2:
6497 return MTLVertexFormatHalf2;
6498 case QRhiVertexInputAttribute::Half:
6499 return MTLVertexFormatHalf;
6500 case QRhiVertexInputAttribute::UShort4:
6501 return MTLVertexFormatUShort4;
6502 case QRhiVertexInputAttribute::UShort3:
6503 return MTLVertexFormatUShort3;
6504 case QRhiVertexInputAttribute::UShort2:
6505 return MTLVertexFormatUShort2;
6506 case QRhiVertexInputAttribute::UShort:
6507 return MTLVertexFormatUShort;
6508 case QRhiVertexInputAttribute::SShort4:
6509 return MTLVertexFormatShort4;
6510 case QRhiVertexInputAttribute::SShort3:
6511 return MTLVertexFormatShort3;
6512 case QRhiVertexInputAttribute::SShort2:
6513 return MTLVertexFormatShort2;
6514 case QRhiVertexInputAttribute::SShort:
6515 return MTLVertexFormatShort;
6518 return MTLVertexFormatFloat4;
6525 case QRhiGraphicsPipeline::Zero:
6526 return MTLBlendFactorZero;
6527 case QRhiGraphicsPipeline::One:
6528 return MTLBlendFactorOne;
6529 case QRhiGraphicsPipeline::SrcColor:
6530 return MTLBlendFactorSourceColor;
6531 case QRhiGraphicsPipeline::OneMinusSrcColor:
6532 return MTLBlendFactorOneMinusSourceColor;
6533 case QRhiGraphicsPipeline::DstColor:
6534 return MTLBlendFactorDestinationColor;
6535 case QRhiGraphicsPipeline::OneMinusDstColor:
6536 return MTLBlendFactorOneMinusDestinationColor;
6537 case QRhiGraphicsPipeline::SrcAlpha:
6538 return MTLBlendFactorSourceAlpha;
6539 case QRhiGraphicsPipeline::OneMinusSrcAlpha:
6540 return MTLBlendFactorOneMinusSourceAlpha;
6541 case QRhiGraphicsPipeline::DstAlpha:
6542 return MTLBlendFactorDestinationAlpha;
6543 case QRhiGraphicsPipeline::OneMinusDstAlpha:
6544 return MTLBlendFactorOneMinusDestinationAlpha;
6545 case QRhiGraphicsPipeline::ConstantColor:
6546 return MTLBlendFactorBlendColor;
6547 case QRhiGraphicsPipeline::ConstantAlpha:
6548 return MTLBlendFactorBlendAlpha;
6549 case QRhiGraphicsPipeline::OneMinusConstantColor:
6550 return MTLBlendFactorOneMinusBlendColor;
6551 case QRhiGraphicsPipeline::OneMinusConstantAlpha:
6552 return MTLBlendFactorOneMinusBlendAlpha;
6553 case QRhiGraphicsPipeline::SrcAlphaSaturate:
6554 return MTLBlendFactorSourceAlphaSaturated;
6555 case QRhiGraphicsPipeline::Src1Color:
6556 return MTLBlendFactorSource1Color;
6557 case QRhiGraphicsPipeline::OneMinusSrc1Color:
6558 return MTLBlendFactorOneMinusSource1Color;
6559 case QRhiGraphicsPipeline::Src1Alpha:
6560 return MTLBlendFactorSource1Alpha;
6561 case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
6562 return MTLBlendFactorOneMinusSource1Alpha;
6565 return MTLBlendFactorZero;
6572 case QRhiGraphicsPipeline::Add:
6573 return MTLBlendOperationAdd;
6574 case QRhiGraphicsPipeline::Subtract:
6575 return MTLBlendOperationSubtract;
6576 case QRhiGraphicsPipeline::ReverseSubtract:
6577 return MTLBlendOperationReverseSubtract;
6578 case QRhiGraphicsPipeline::Min:
6579 return MTLBlendOperationMin;
6580 case QRhiGraphicsPipeline::Max:
6581 return MTLBlendOperationMax;
6584 return MTLBlendOperationAdd;
6591 if (c.testFlag(QRhiGraphicsPipeline::R))
6592 f |= MTLColorWriteMaskRed;
6593 if (c.testFlag(QRhiGraphicsPipeline::G))
6594 f |= MTLColorWriteMaskGreen;
6595 if (c.testFlag(QRhiGraphicsPipeline::B))
6596 f |= MTLColorWriteMaskBlue;
6597 if (c.testFlag(QRhiGraphicsPipeline::A))
6598 f |= MTLColorWriteMaskAlpha;
6605 case QRhiGraphicsPipeline::Never:
6606 return MTLCompareFunctionNever;
6607 case QRhiGraphicsPipeline::Less:
6608 return MTLCompareFunctionLess;
6609 case QRhiGraphicsPipeline::Equal:
6610 return MTLCompareFunctionEqual;
6611 case QRhiGraphicsPipeline::LessOrEqual:
6612 return MTLCompareFunctionLessEqual;
6613 case QRhiGraphicsPipeline::Greater:
6614 return MTLCompareFunctionGreater;
6615 case QRhiGraphicsPipeline::NotEqual:
6616 return MTLCompareFunctionNotEqual;
6617 case QRhiGraphicsPipeline::GreaterOrEqual:
6618 return MTLCompareFunctionGreaterEqual;
6619 case QRhiGraphicsPipeline::Always:
6620 return MTLCompareFunctionAlways;
6623 return MTLCompareFunctionAlways;
6630 case QRhiGraphicsPipeline::StencilZero:
6631 return MTLStencilOperationZero;
6632 case QRhiGraphicsPipeline::Keep:
6633 return MTLStencilOperationKeep;
6634 case QRhiGraphicsPipeline::Replace:
6635 return MTLStencilOperationReplace;
6636 case QRhiGraphicsPipeline::IncrementAndClamp:
6637 return MTLStencilOperationIncrementClamp;
6638 case QRhiGraphicsPipeline::DecrementAndClamp:
6639 return MTLStencilOperationDecrementClamp;
6640 case QRhiGraphicsPipeline::Invert:
6641 return MTLStencilOperationInvert;
6642 case QRhiGraphicsPipeline::IncrementAndWrap:
6643 return MTLStencilOperationIncrementWrap;
6644 case QRhiGraphicsPipeline::DecrementAndWrap:
6645 return MTLStencilOperationDecrementWrap;
6648 return MTLStencilOperationKeep;
6655 case QRhiGraphicsPipeline::Triangles:
6656 return MTLPrimitiveTypeTriangle;
6657 case QRhiGraphicsPipeline::TriangleStrip:
6658 return MTLPrimitiveTypeTriangleStrip;
6659 case QRhiGraphicsPipeline::Lines:
6660 return MTLPrimitiveTypeLine;
6661 case QRhiGraphicsPipeline::LineStrip:
6662 return MTLPrimitiveTypeLineStrip;
6663 case QRhiGraphicsPipeline::Points:
6664 return MTLPrimitiveTypePoint;
6667 return MTLPrimitiveTypeTriangle;
6674 case QRhiGraphicsPipeline::Triangles:
6675 case QRhiGraphicsPipeline::TriangleStrip:
6676 case QRhiGraphicsPipeline::TriangleFan:
6677 return MTLPrimitiveTopologyClassTriangle;
6678 case QRhiGraphicsPipeline::Lines:
6679 case QRhiGraphicsPipeline::LineStrip:
6680 return MTLPrimitiveTopologyClassLine;
6681 case QRhiGraphicsPipeline::Points:
6682 return MTLPrimitiveTopologyClassPoint;
6685 return MTLPrimitiveTopologyClassTriangle;
6692 case QRhiGraphicsPipeline::None:
6693 return MTLCullModeNone;
6694 case QRhiGraphicsPipeline::Front:
6695 return MTLCullModeFront;
6696 case QRhiGraphicsPipeline::Back:
6697 return MTLCullModeBack;
6700 return MTLCullModeNone;
6707 case QRhiGraphicsPipeline::Fill:
6708 return MTLTriangleFillModeFill;
6709 case QRhiGraphicsPipeline::Line:
6710 return MTLTriangleFillModeLines;
6713 return MTLTriangleFillModeFill;
6720 case QShaderDescription::CwTessellationWindingOrder:
6721 return MTLWindingClockwise;
6722 case QShaderDescription::CcwTessellationWindingOrder:
6723 return MTLWindingCounterClockwise;
6726 return MTLWindingCounterClockwise;
6733 case QShaderDescription::EqualTessellationPartitioning:
6734 return MTLTessellationPartitionModePow2;
6735 case QShaderDescription::FractionalEvenTessellationPartitioning:
6736 return MTLTessellationPartitionModeFractionalEven;
6737 case QShaderDescription::FractionalOddTessellationPartitioning:
6738 return MTLTessellationPartitionModeFractionalOdd;
6741 return MTLTessellationPartitionModePow2;
6747 int v = version.version();
6748 return MTLLanguageVersion(((v / 10) << 16) + (v % 10));
6752 int frameSlot, quint32 minBlockSize, quint32 *offset)
6755 const quint32 alignedSize = aligned<quint32>(size, alignment);
6756 if (pool.offset + alignedSize > pool.capacity) {
6766 e.stagingBuffer.buffer = pool.buf;
6767 releaseQueue.append(e);
6769 pool.capacity = qMax(pool.capacity * 2, qMax(alignedSize, minBlockSize));
6770 pool.buf = [dev newBufferWithLength: pool.capacity options: MTLResourceStorageModeShared];
6777 *offset = pool.offset;
6778 pool.offset += alignedSize;
6784 return allocFromStagingArea(&argBufPool[frameSlot], size, alignment, frameSlot, 16384, offset);
6789 id<MTLBuffer> buf = [dev newBufferWithLength: size options: MTLResourceStorageModeShared];
6795 e.stagingBuffer.buffer = buf;
6796 releaseQueue.append(e);
6802 if (size > LARGE_STAGING_ALLOC) {
6804 return newOneShotStagingBuffer(size, frameSlot);
6809 const quint32 alignedSize = aligned<quint32>(size, 4u);
6810 area.bytesNeeded += alignedSize;
6812 if (area.offset + alignedSize > area.capacity) {
6814 return newOneShotStagingBuffer(size, frameSlot);
6817 *offset = area.offset;
6818 area.offset += alignedSize;
6825 const quint32 needed = area.bytesNeeded;
6826 area.bytesNeeded = 0;
6829 bool resize =
false;
6830 quint32 newCapacity = 0;
6831 if (needed > area.capacity) {
6838 newCapacity = qMin(qNextPowerOfTwo(needed), STAGING_AREA_MAX);
6841 }
else if (needed <= area.capacity / 4 && area.capacity > 0) {
6847 newCapacity = needed ? qMax(area.capacity / 2, STAGING_AREA_MIN) : 0;
6855 if (resize && newCapacity != area.capacity) {
6860 e.stagingBuffer.buffer = area.buf;
6861 releaseQueue.append(e);
6866 area.buf = [dev newBufferWithLength: newCapacity options: MTLResourceStorageModeShared];
6868 area.capacity = newCapacity;
6874 bool preferArgumentBuffers,
6875 QString *error, QByteArray *entryPoint, QShaderKey *activeKey)
6877 QVarLengthArray<
int, 8> versions;
6878 versions << 30 << 24 << 23 << 22 << 21 << 20 << 12;
6888 QVarLengthArray<QShader::Variant, 2> variants;
6889 if (preferArgumentBuffers)
6890 variants << QShader::ArgumentBufferShader;
6891 variants << shaderVariant;
6893 const QList<QShaderKey> shaders = shader.availableShaders();
6895 auto findKey = [&shaders, &versions, &variants](QShader::Source source, QShaderKey *result) {
6896 for (
const QShader::Variant &variant : variants) {
6897 for (
const int &version : versions) {
6898 const QShaderKey key = { source, version, variant };
6899 if (shaders.contains(key)) {
6910 if (findKey(QShader::Source::MetalLibShader, &key)) {
6911 QShaderCode mtllib = shader.shader(key);
6912 dispatch_data_t data = dispatch_data_create(mtllib.shader().constData(),
6913 size_t(mtllib.shader().size()),
6914 dispatch_get_global_queue(0, 0),
6915 DISPATCH_DATA_DESTRUCTOR_DEFAULT);
6917 id<MTLLibrary> lib = [dev newLibraryWithData: data error: &err];
6918 dispatch_release(data);
6920 *entryPoint = mtllib.entryPoint();
6924 const QString msg = QString::fromNSString(err.localizedDescription);
6925 qWarning(
"Failed to load metallib from baked shader: %s", qPrintable(msg));
6929 if (!findKey(QShader::Source::MslShader, &key)) {
6930 qWarning() <<
"No MSL code found in baked shader" << shader;
6934 QShaderCode mslSource = shader.shader(key);
6936 NSString *src = [NSString stringWithUTF8String: mslSource.shader().constData()];
6937 MTLCompileOptions *opts = [[MTLCompileOptions alloc] init];
6938 opts.languageVersion = toMetalLanguageVersion(key.sourceVersion());
6940 id<MTLLibrary> lib = [dev newLibraryWithSource: src options: opts error: &err];
6948 const QString msg = QString::fromNSString(err.localizedDescription);
6953 *entryPoint = mslSource.entryPoint();
6960 return [lib newFunctionWithName:[NSString stringWithUTF8String:entryPoint.constData()]];
6965 MTLRenderPipelineDescriptor *rpDesc =
reinterpret_cast<MTLRenderPipelineDescriptor *>(metalRpDesc);
6969 rpDesc.colorAttachments[0].pixelFormat = MTLPixelFormat(rpD
->colorFormat[0]);
6970 rpDesc.colorAttachments[0].writeMask = MTLColorWriteMaskAll;
6971 rpDesc.colorAttachments[0].blendingEnabled =
false;
6973 Q_ASSERT(m_targetBlends.count() == rpD->colorAttachmentCount
6974 || (m_targetBlends.isEmpty() && rpD->colorAttachmentCount == 1));
6976 for (uint i = 0, ie = uint(m_targetBlends.count()); i != ie; ++i) {
6977 const QRhiGraphicsPipeline::TargetBlend &b(m_targetBlends[
int(i)]);
6978 rpDesc.colorAttachments[i].pixelFormat = MTLPixelFormat(rpD
->colorFormat[i]);
6979 rpDesc.colorAttachments[i].blendingEnabled = b.enable;
6980 rpDesc.colorAttachments[i].sourceRGBBlendFactor = toMetalBlendFactor(b.srcColor);
6981 rpDesc.colorAttachments[i].destinationRGBBlendFactor = toMetalBlendFactor(b.dstColor);
6982 rpDesc.colorAttachments[i].rgbBlendOperation = toMetalBlendOp(b.opColor);
6983 rpDesc.colorAttachments[i].sourceAlphaBlendFactor = toMetalBlendFactor(b.srcAlpha);
6984 rpDesc.colorAttachments[i].destinationAlphaBlendFactor = toMetalBlendFactor(b.dstAlpha);
6985 rpDesc.colorAttachments[i].alphaBlendOperation = toMetalBlendOp(b.opAlpha);
6986 rpDesc.colorAttachments[i].writeMask = toMetalColorWriteMask(b.colorWrite);
6993 MTLPixelFormat fmt = MTLPixelFormat(rpD
->dsFormat);
6994 rpDesc.depthAttachmentPixelFormat = fmt;
6995#if defined(Q_OS_MACOS)
6996 if (fmt != MTLPixelFormatDepth16Unorm && fmt != MTLPixelFormatDepth32Float)
6998 if (fmt != MTLPixelFormatDepth32Float)
7000 rpDesc.stencilAttachmentPixelFormat = fmt;
7004 rpDesc.rasterSampleCount = NSUInteger(rhiD->effectiveSampleCount(m_sampleCount));
7009 MTLDepthStencilDescriptor *dsDesc =
reinterpret_cast<MTLDepthStencilDescriptor *>(metalDsDesc);
7011 dsDesc.depthCompareFunction = m_depthTest ? toMetalCompareOp(m_depthOp) : MTLCompareFunctionAlways;
7012 dsDesc.depthWriteEnabled = m_depthWrite;
7013 if (m_stencilTest) {
7014 dsDesc.frontFaceStencil = [[MTLStencilDescriptor alloc] init];
7015 dsDesc.frontFaceStencil.stencilFailureOperation = toMetalStencilOp(m_stencilFront.failOp);
7016 dsDesc.frontFaceStencil.depthFailureOperation = toMetalStencilOp(m_stencilFront.depthFailOp);
7017 dsDesc.frontFaceStencil.depthStencilPassOperation = toMetalStencilOp(m_stencilFront.passOp);
7018 dsDesc.frontFaceStencil.stencilCompareFunction = toMetalCompareOp(m_stencilFront.compareOp);
7019 dsDesc.frontFaceStencil.readMask = m_stencilReadMask;
7020 dsDesc.frontFaceStencil.writeMask = m_stencilWriteMask;
7022 dsDesc.backFaceStencil = [[MTLStencilDescriptor alloc] init];
7023 dsDesc.backFaceStencil.stencilFailureOperation = toMetalStencilOp(m_stencilBack.failOp);
7024 dsDesc.backFaceStencil.depthFailureOperation = toMetalStencilOp(m_stencilBack.depthFailOp);
7025 dsDesc.backFaceStencil.depthStencilPassOperation = toMetalStencilOp(m_stencilBack.passOp);
7026 dsDesc.backFaceStencil.stencilCompareFunction = toMetalCompareOp(m_stencilBack.compareOp);
7027 dsDesc.backFaceStencil.readMask = m_stencilReadMask;
7028 dsDesc.backFaceStencil.writeMask = m_stencilWriteMask;
7034 d->winding = m_frontFace == CCW ? MTLWindingCounterClockwise : MTLWindingClockwise;
7035 d->cullMode = toMetalCullMode(m_cullMode);
7036 d->triangleFillMode = toMetalTriangleFillMode(m_polygonMode);
7037 d->depthClipMode = m_depthClamp ? MTLDepthClipModeClamp : MTLDepthClipModeClip;
7049 for (
auto it = vertexInputLayout.cbeginAttributes(), itEnd = vertexInputLayout.cendAttributes();
7052 const uint loc = uint(it->location());
7053 desc.attributes[loc].format =
decltype(desc.attributes[loc].format)(toMetalAttributeFormat(it->format()));
7054 desc.attributes[loc].offset = NSUInteger(it->offset());
7055 desc.attributes[loc].bufferIndex = NSUInteger(firstVertexBinding + it->binding());
7057 int bindingIndex = 0;
7058 const NSUInteger viewCount = qMax<NSUInteger>(1, q->multiViewCount());
7059 for (
auto it = vertexInputLayout.cbeginBindings(), itEnd = vertexInputLayout.cendBindings();
7060 it != itEnd; ++it, ++bindingIndex)
7062 const uint layoutIdx = uint(firstVertexBinding + bindingIndex);
7063 desc.layouts[layoutIdx].stepFunction =
7064 it->classification() == QRhiVertexInputBinding::PerInstance
7065 ? MTLVertexStepFunctionPerInstance : MTLVertexStepFunctionPerVertex;
7066 desc.layouts[layoutIdx].stepRate = NSUInteger(it->instanceStepRate());
7067 if (desc.layouts[layoutIdx].stepFunction == MTLVertexStepFunctionPerInstance)
7068 desc.layouts[layoutIdx].stepRate *= viewCount;
7069 desc.layouts[layoutIdx].stride = it->stride();
7080 for (
auto it = vertexInputLayout.cbeginAttributes(), itEnd = vertexInputLayout.cendAttributes();
7083 const uint loc = uint(it->location());
7084 desc.attributes[loc].format =
decltype(desc.attributes[loc].format)(toMetalAttributeFormat(it->format()));
7085 desc.attributes[loc].offset = NSUInteger(it->offset());
7086 desc.attributes[loc].bufferIndex = NSUInteger(firstVertexBinding + it->binding());
7088 int bindingIndex = 0;
7089 for (
auto it = vertexInputLayout.cbeginBindings(), itEnd = vertexInputLayout.cendBindings();
7090 it != itEnd; ++it, ++bindingIndex)
7092 const uint layoutIdx = uint(firstVertexBinding + bindingIndex);
7093 if (desc.indexBufferIndex) {
7094 desc.layouts[layoutIdx].stepFunction =
7095 it->classification() == QRhiVertexInputBinding::PerInstance
7096 ? MTLStepFunctionThreadPositionInGridY : MTLStepFunctionThreadPositionInGridXIndexed;
7098 desc.layouts[layoutIdx].stepFunction =
7099 it->classification() == QRhiVertexInputBinding::PerInstance
7100 ? MTLStepFunctionThreadPositionInGridY : MTLStepFunctionThreadPositionInGridX;
7102 desc.layouts[layoutIdx].stepRate = NSUInteger(it->instanceStepRate());
7103 desc.layouts[layoutIdx].stride = it->stride();
7110 NSArray *binArchArray = [NSArray arrayWithObjects: binArch, nil];
7111 rpDesc.binaryArchives = binArchArray;
7119 if (![binArch addRenderPipelineFunctionsWithDescriptor: rpDesc error: &err]) {
7120 const QString msg = QString::fromNSString(err.localizedDescription);
7121 qWarning(
"Failed to collect render pipeline functions to binary archive: %s", qPrintable(msg));
7128 return !desc.combinedImageSamplers().isEmpty()
7129 || !desc.separateImages().isEmpty()
7130 || !desc.storageImages().isEmpty();
7135 for (
const QShaderKey &k : shader.availableShaders()) {
7136 if (k.sourceVariant() == QShader::ArgumentBufferShader)
7144 const int index = shader->nativeShaderInfo.extraBufferBindings.value(QShaderPrivate::MslArgumentBufferBinding, -1);
7147 shader->argumentEncoder = [shader->func newArgumentEncoderWithBufferIndex: NSUInteger(index)];
7158 const bool wantArgumentBuffers = m_flags.testFlag(UsesIndirectDraws) && rhiD->caps.indirectCommandBuffers;
7160 MTLVertexDescriptor *vertexDesc = [MTLVertexDescriptor vertexDescriptor];
7161 d->setupVertexInputDescriptor(vertexDesc);
7163 MTLRenderPipelineDescriptor *rpDesc = [[MTLRenderPipelineDescriptor alloc] init];
7164 rpDesc.vertexDescriptor = vertexDesc;
7172 for (
const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
7173 const QShader shader = shaderStage.shader();
7174 const bool argumentBufferBuild = wantArgumentBuffers && hasArgumentBufferVariant(shader);
7175 auto cacheIt = rhiD->d->shaderCache.constFind({ shaderStage, argumentBufferBuild });
7176 if (cacheIt != rhiD->d->shaderCache.constEnd()) {
7177 switch (shaderStage.type()) {
7178 case QRhiShaderStage::Vertex:
7181 [d->vs.func retain];
7182 [d->vs.argumentEncoder retain];
7183 rpDesc.vertexFunction = d->vs.func;
7185 case QRhiShaderStage::Fragment:
7188 [d->fs.func retain];
7189 [d->fs.argumentEncoder retain];
7190 rpDesc.fragmentFunction = d->fs.func;
7197 QByteArray entryPoint;
7198 QShaderKey activeKey;
7199 id<MTLLibrary> lib = rhiD->d->createMetalLib(shader, shaderStage.shaderVariant(),
7200 argumentBufferBuild,
7201 &error, &entryPoint, &activeKey);
7203 qWarning(
"MSL shader compilation failed: %s", qPrintable(error));
7206 id<MTLFunction> func = rhiD->d->createMSLShaderFunction(lib, entryPoint);
7208 qWarning(
"MSL function for entry point %s not found", entryPoint.constData());
7212 if (rhiD->d->shaderCache.count() >= QRhiMetal::MAX_SHADER_CACHE_ENTRIES) {
7214 for (QMetalShader &s : rhiD->d->shaderCache)
7216 rhiD->d->shaderCache.clear();
7218 switch (shaderStage.type()) {
7219 case QRhiShaderStage::Vertex:
7222 d->vs.nativeResourceBindingMap = shader.nativeResourceBindingMap(activeKey);
7223 d->vs.desc = shader.description();
7224 d->vs.nativeShaderInfo = shader.nativeShaderInfo(activeKey);
7225 setupArgumentBufferEncoder(&d->vs);
7226 rhiD->d->shaderCache.insert({ shaderStage, argumentBufferBuild }, d->vs);
7228 [d->vs.func retain];
7229 [d->vs.argumentEncoder retain];
7230 rpDesc.vertexFunction = func;
7232 case QRhiShaderStage::Fragment:
7235 d->fs.nativeResourceBindingMap = shader.nativeResourceBindingMap(activeKey);
7236 d->fs.desc = shader.description();
7237 d->fs.nativeShaderInfo = shader.nativeShaderInfo(activeKey);
7238 setupArgumentBufferEncoder(&d->fs);
7239 rhiD->d->shaderCache.insert({ shaderStage, argumentBufferBuild }, d->fs);
7241 [d->fs.func retain];
7242 [d->fs.argumentEncoder retain];
7243 rpDesc.fragmentFunction = func;
7259 return !usesTextures(s.desc) || s.argumentBufferIndex >= 0;
7261 d->icbCapable = wantArgumentBuffers && icbSafe(
d->vs) && icbSafe(
d->fs);
7263 rpDesc.supportIndirectCommandBuffers = YES;
7265 if (m_multiViewCount >= 2)
7266 rpDesc.inputPrimitiveTopology = toMetalPrimitiveTopologyClass(m_topology);
7268 rhiD
->d->trySeedingRenderPipelineFromBinaryArchive(rpDesc);
7270 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
7271 rhiD
->d->addRenderPipelineToBinaryArchive(rpDesc);
7274 d->ps = [rhiD->d->dev newRenderPipelineStateWithDescriptor: rpDesc error: &err];
7277 const QString msg = QString::fromNSString(err.localizedDescription);
7278 qWarning(
"Failed to create render pipeline state: %s", qPrintable(msg));
7282 MTLDepthStencilDescriptor *dsDesc = [[MTLDepthStencilDescriptor alloc] init];
7284 d->ds = [rhiD->d->dev newDepthStencilStateWithDescriptor: dsDesc];
7287 d->primitiveType = toMetalPrimitiveType(m_topology);
7295 switch (vertexCompVariant) {
7296 case QShader::NonIndexedVertexAsComputeShader:
7298 case QShader::UInt32IndexedVertexAsComputeShader:
7300 case QShader::UInt16IndexedVertexAsComputeShader:
7310 const int varIndex = vsCompVariantToIndex(vertexCompVariant);
7311 if (varIndex >= 0 && vertexComputeState[varIndex])
7312 return vertexComputeState[varIndex];
7314 id<MTLFunction> func = nil;
7316 func = compVs[varIndex].func;
7319 qWarning(
"No compute function found for vertex shader translated for tessellation, this should not happen");
7323 const QMap<
int,
int> &ebb(compVs[varIndex].nativeShaderInfo.extraBufferBindings);
7324 const int indexBufferBinding = ebb.value(QShaderPrivate::MslTessVertIndicesBufferBinding, -1);
7326 MTLComputePipelineDescriptor *cpDesc = [MTLComputePipelineDescriptor
new];
7327 cpDesc.computeFunction = func;
7328 cpDesc.threadGroupSizeIsMultipleOfThreadExecutionWidth = YES;
7329 cpDesc.stageInputDescriptor = [MTLStageInputOutputDescriptor stageInputOutputDescriptor];
7330 if (indexBufferBinding >= 0) {
7331 if (vertexCompVariant == QShader::UInt32IndexedVertexAsComputeShader) {
7332 cpDesc.stageInputDescriptor.indexType = MTLIndexTypeUInt32;
7333 cpDesc.stageInputDescriptor.indexBufferIndex = indexBufferBinding;
7334 }
else if (vertexCompVariant == QShader::UInt16IndexedVertexAsComputeShader) {
7335 cpDesc.stageInputDescriptor.indexType = MTLIndexTypeUInt16;
7336 cpDesc.stageInputDescriptor.indexBufferIndex = indexBufferBinding;
7339 q->setupStageInputDescriptor(cpDesc.stageInputDescriptor);
7341 rhiD
->d->trySeedingComputePipelineFromBinaryArchive(cpDesc);
7343 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
7344 rhiD
->d->addComputePipelineToBinaryArchive(cpDesc);
7347 id<MTLComputePipelineState> ps = [rhiD->d->dev newComputePipelineStateWithDescriptor: cpDesc
7348 options: MTLPipelineOptionNone
7353 const QString msg = QString::fromNSString(err.localizedDescription);
7354 qWarning(
"Failed to create compute pipeline state: %s", qPrintable(msg));
7356 vertexComputeState[varIndex] = ps;
7364 if (tessControlComputeState)
7365 return tessControlComputeState;
7367 MTLComputePipelineDescriptor *cpDesc = [MTLComputePipelineDescriptor
new];
7368 cpDesc.computeFunction = compTesc.func;
7370 rhiD
->d->trySeedingComputePipelineFromBinaryArchive(cpDesc);
7372 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
7373 rhiD
->d->addComputePipelineToBinaryArchive(cpDesc);
7376 id<MTLComputePipelineState> ps = [rhiD->d->dev newComputePipelineStateWithDescriptor: cpDesc
7377 options: MTLPipelineOptionNone
7382 const QString msg = QString::fromNSString(err.localizedDescription);
7383 qWarning(
"Failed to create compute pipeline state: %s", qPrintable(msg));
7385 tessControlComputeState = ps;
7393 return (indices >> index) & 0x1;
7396static inline void takeIndex(quint32 index, quint64 &indices)
7398 indices |= 1 << index;
7407 static const int maxVertexAttributes = 31;
7409 for (
int index = 0; index < maxVertexAttributes; ++index) {
7410 if (!indexTaken(index, indices))
7414 Q_UNREACHABLE_RETURN(-1);
7417static inline int aligned(quint32 offset, quint32 alignment)
7419 return ((offset + alignment - 1) / alignment) * alignment;
7427 for (
const int dim : variable.arrayDims)
7430 if (variable.type == QShaderDescription::VariableType::Struct) {
7431 for (
int element = 0; element < elements; ++element) {
7432 for (
const auto &member : variable.structMembers) {
7433 addUnusedVertexAttribute(member, rhiD, offset, vertexAlignment);
7437 const QRhiVertexInputAttribute::Format format = rhiD->shaderDescVariableFormatToVertexInputFormat(variable.type);
7438 const quint32 size = rhiD->byteSizePerVertexForVertexInputFormat(format);
7441 const quint32 alignment = size;
7442 vertexAlignment =
std::max(vertexAlignment, alignment);
7444 for (
int element = 0; element < elements; ++element) {
7446 offset = aligned(offset, alignment);
7453static void addVertexAttribute(
const T &variable,
int binding,
QRhiMetal *rhiD,
int &index, quint32 &offset, MTLVertexAttributeDescriptorArray *attributes, quint64 &indices, quint32 &vertexAlignment)
7457 for (
const int dim : variable.arrayDims)
7460 if (variable.type == QShaderDescription::VariableType::Struct) {
7461 for (
int element = 0; element < elements; ++element) {
7462 for (
const auto &member : variable.structMembers) {
7463 addVertexAttribute(member, binding, rhiD, index, offset, attributes, indices, vertexAlignment);
7467 const QRhiVertexInputAttribute::Format format = rhiD->shaderDescVariableFormatToVertexInputFormat(variable.type);
7468 const quint32 size = rhiD->byteSizePerVertexForVertexInputFormat(format);
7471 const quint32 alignment = size;
7472 vertexAlignment =
std::max(vertexAlignment, alignment);
7474 for (
int element = 0; element < elements; ++element) {
7475 Q_ASSERT(!indexTaken(index, indices));
7478 offset = aligned(offset, alignment);
7480 attributes[index].bufferIndex = binding;
7481 attributes[index].format = toMetalAttributeFormat(format);
7482 attributes[index].offset = offset;
7484 takeIndex(index, indices);
7486 if (indexTaken(index, indices))
7487 index = nextAttributeIndex(indices);
7494static inline bool matches(
const QList<QShaderDescription::BlockVariable> &a,
const QList<QShaderDescription::BlockVariable> &b)
7496 if (a.size() == b.size()) {
7498 for (
int i = 0; i < a.size() && match; ++i) {
7499 match &= a[i].type == b[i].type
7500 && a[i].arrayDims == b[i].arrayDims
7501 && matches(a[i].structMembers, b[i].structMembers);
7509static inline bool matches(
const QShaderDescription::InOutVariable &a,
const QShaderDescription::InOutVariable &b)
7511 return a.location == b.location
7513 && a.perPatch == b.perPatch
7514 && matches(a.structMembers, b.structMembers);
7563 if (pipeline
->d->ps)
7564 return pipeline
->d->ps;
7566 MTLRenderPipelineDescriptor *rpDesc = [[MTLRenderPipelineDescriptor alloc] init];
7567 MTLVertexDescriptor *vertexDesc = [MTLVertexDescriptor vertexDescriptor];
7570 const QMap<
int,
int> &ebb(compTesc.nativeShaderInfo.extraBufferBindings);
7571 const int tescOutputBufferBinding = ebb.value(QShaderPrivate::MslTessVertTescOutputBufferBinding, -1);
7572 const int tescPatchOutputBufferBinding = ebb.value(QShaderPrivate::MslTessTescPatchOutputBufferBinding, -1);
7573 const int tessFactorBufferBinding = ebb.value(QShaderPrivate::MslTessTescTessLevelBufferBinding, -1);
7574 quint32 offsetInTescOutput = 0;
7575 quint32 offsetInTescPatchOutput = 0;
7576 quint32 offsetInTessFactorBuffer = 0;
7577 quint32 tescOutputAlignment = 0;
7578 quint32 tescPatchOutputAlignment = 0;
7579 quint32 tessFactorAlignment = 0;
7580 QSet<
int> usedBuffers;
7583 QMap<
int, QShaderDescription::InOutVariable> tescOutVars;
7584 for (
const auto &tescOutVar : compTesc.desc.outputVariables())
7585 tescOutVars[tescOutVar.location] = tescOutVar;
7588 QMap<
int, QShaderDescription::InOutVariable> teseInVars;
7589 for (
const auto &teseInVar : vertTese.desc.inputVariables())
7590 teseInVars[teseInVar.location] = teseInVar;
7593 quint64 indices = 0;
7595 for (QShaderDescription::InOutVariable &tescOutVar : tescOutVars) {
7597 int index = tescOutVar.location;
7599 quint32 *offset =
nullptr;
7600 quint32 *alignment =
nullptr;
7602 if (tescOutVar.perPatch) {
7603 binding = tescPatchOutputBufferBinding;
7604 offset = &offsetInTescPatchOutput;
7605 alignment = &tescPatchOutputAlignment;
7607 tescOutVar.arrayDims.removeLast();
7608 binding = tescOutputBufferBinding;
7609 offset = &offsetInTescOutput;
7610 alignment = &tescOutputAlignment;
7613 if (teseInVars.contains(index)) {
7615 if (!matches(teseInVars[index], tescOutVar)) {
7616 qWarning() <<
"mismatched tessellation control output -> tesssellation evaluation input at location" << index;
7617 qWarning() <<
" tesc out:" << tescOutVar;
7618 qWarning() <<
" tese in:" << teseInVars[index];
7621 if (binding != -1) {
7622 addVertexAttribute(tescOutVar, binding, rhiD, index, *offset, vertexDesc.attributes, indices, *alignment);
7623 usedBuffers << binding;
7625 qWarning() <<
"baked tessellation control shader missing output buffer binding information";
7626 addUnusedVertexAttribute(tescOutVar, rhiD, *offset, *alignment);
7630 qWarning() <<
"missing tessellation evaluation input for tessellation control output:" << tescOutVar;
7631 addUnusedVertexAttribute(tescOutVar, rhiD, *offset, *alignment);
7634 teseInVars.remove(tescOutVar.location);
7637 for (
const QShaderDescription::InOutVariable &teseInVar : teseInVars)
7638 qWarning() <<
"missing tessellation control output for tessellation evaluation input:" << teseInVar;
7641 QMap<QShaderDescription::BuiltinType, QShaderDescription::BuiltinVariable> tescOutBuiltins;
7642 for (
const auto &tescOutBuiltin : compTesc.desc.outputBuiltinVariables())
7643 tescOutBuiltins[tescOutBuiltin.type] = tescOutBuiltin;
7646 QMap<QShaderDescription::BuiltinType, QShaderDescription::BuiltinVariable> teseInBuiltins;
7647 for (
const auto &teseInBuiltin : vertTese.desc.inputBuiltinVariables())
7648 teseInBuiltins[teseInBuiltin.type] = teseInBuiltin;
7650 const bool trianglesMode = vertTese.desc.tessellationMode() == QShaderDescription::TrianglesTessellationMode;
7651 bool tessLevelAdded =
false;
7653 for (
const QShaderDescription::BuiltinVariable &builtin : tescOutBuiltins) {
7655 QShaderDescription::InOutVariable variable;
7657 quint32 *offset =
nullptr;
7658 quint32 *alignment =
nullptr;
7660 switch (builtin.type) {
7661 case QShaderDescription::BuiltinType::PositionBuiltin:
7662 variable.type = QShaderDescription::VariableType::Vec4;
7663 binding = tescOutputBufferBinding;
7664 offset = &offsetInTescOutput;
7665 alignment = &tescOutputAlignment;
7667 case QShaderDescription::BuiltinType::PointSizeBuiltin:
7668 variable.type = QShaderDescription::VariableType::Float;
7669 binding = tescOutputBufferBinding;
7670 offset = &offsetInTescOutput;
7671 alignment = &tescOutputAlignment;
7673 case QShaderDescription::BuiltinType::ClipDistanceBuiltin:
7674 variable.type = QShaderDescription::VariableType::Float;
7675 variable.arrayDims = builtin.arrayDims;
7676 binding = tescOutputBufferBinding;
7677 offset = &offsetInTescOutput;
7678 alignment = &tescOutputAlignment;
7680 case QShaderDescription::BuiltinType::TessLevelOuterBuiltin:
7681 variable.type = QShaderDescription::VariableType::Half4;
7682 binding = tessFactorBufferBinding;
7683 offset = &offsetInTessFactorBuffer;
7684 tessLevelAdded = trianglesMode;
7685 alignment = &tessFactorAlignment;
7687 case QShaderDescription::BuiltinType::TessLevelInnerBuiltin:
7688 if (trianglesMode) {
7689 if (!tessLevelAdded) {
7690 variable.type = QShaderDescription::VariableType::Half4;
7691 binding = tessFactorBufferBinding;
7692 offsetInTessFactorBuffer = 0;
7693 offset = &offsetInTessFactorBuffer;
7694 alignment = &tessFactorAlignment;
7695 tessLevelAdded =
true;
7697 teseInBuiltins.remove(builtin.type);
7701 variable.type = QShaderDescription::VariableType::Half2;
7702 binding = tessFactorBufferBinding;
7703 offsetInTessFactorBuffer = 8;
7704 offset = &offsetInTessFactorBuffer;
7705 alignment = &tessFactorAlignment;
7713 if (teseInBuiltins.contains(builtin.type)) {
7714 if (binding != -1) {
7715 int index = nextAttributeIndex(indices);
7716 addVertexAttribute(variable, binding, rhiD, index, *offset, vertexDesc.attributes, indices, *alignment);
7717 usedBuffers << binding;
7719 qWarning() <<
"baked tessellation control shader missing output buffer binding information";
7720 addUnusedVertexAttribute(variable, rhiD, *offset, *alignment);
7723 addUnusedVertexAttribute(variable, rhiD, *offset, *alignment);
7726 teseInBuiltins.remove(builtin.type);
7729 for (
const QShaderDescription::BuiltinVariable &builtin : teseInBuiltins) {
7730 switch (builtin.type) {
7731 case QShaderDescription::BuiltinType::PositionBuiltin:
7732 case QShaderDescription::BuiltinType::PointSizeBuiltin:
7733 case QShaderDescription::BuiltinType::ClipDistanceBuiltin:
7734 qWarning() <<
"missing tessellation control output for tessellation evaluation builtin input:" << builtin;
7741 if (usedBuffers.contains(tescOutputBufferBinding)) {
7742 vertexDesc.layouts[tescOutputBufferBinding].stepFunction = MTLVertexStepFunctionPerPatchControlPoint;
7743 vertexDesc.layouts[tescOutputBufferBinding].stride = aligned(offsetInTescOutput, tescOutputAlignment);
7746 if (usedBuffers.contains(tescPatchOutputBufferBinding)) {
7747 vertexDesc.layouts[tescPatchOutputBufferBinding].stepFunction = MTLVertexStepFunctionPerPatch;
7748 vertexDesc.layouts[tescPatchOutputBufferBinding].stride = aligned(offsetInTescPatchOutput, tescPatchOutputAlignment);
7751 if (usedBuffers.contains(tessFactorBufferBinding)) {
7752 vertexDesc.layouts[tessFactorBufferBinding].stepFunction = MTLVertexStepFunctionPerPatch;
7753 vertexDesc.layouts[tessFactorBufferBinding].stride = trianglesMode ?
sizeof(MTLTriangleTessellationFactorsHalf) :
sizeof(MTLQuadTessellationFactorsHalf);
7756 rpDesc.vertexDescriptor = vertexDesc;
7757 rpDesc.vertexFunction = vertTese.func;
7758 rpDesc.fragmentFunction = pipeline
->d->fs.func;
7764 rpDesc.tessellationOutputWindingOrder = toMetalTessellationWindingOrder(vertTese.desc.tessellationWindingOrder());
7766 rpDesc.tessellationPartitionMode = toMetalTessellationPartitionMode(vertTese.desc.tessellationPartitioning());
7771 rhiD
->d->trySeedingRenderPipelineFromBinaryArchive(rpDesc);
7773 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
7774 rhiD
->d->addRenderPipelineToBinaryArchive(rpDesc);
7777 id<MTLRenderPipelineState> ps = [rhiD->d->dev newRenderPipelineStateWithDescriptor: rpDesc error: &err];
7780 const QString msg = QString::fromNSString(err.localizedDescription);
7781 qWarning(
"Failed to create render pipeline state for tessellation: %s", qPrintable(msg));
7785 pipeline
->d->ps = ps;
7792 QVector<QMetalBuffer *> *workBuffers = type == WorkBufType::DeviceLocal ? &deviceLocalWorkBuffers : &hostVisibleWorkBuffers;
7795 for (QMetalBuffer *workBuf : *workBuffers) {
7796 if (workBuf && workBuf->lastActiveFrameSlot == -1 && workBuf->size() >= size) {
7797 workBuf->lastActiveFrameSlot = rhiD->currentFrameSlot;
7804 if (workBuffers->count() > QMTL_FRAMES_IN_FLIGHT * 8) {
7805 for (QMetalBuffer *workBuf : *workBuffers) {
7806 if (workBuf && workBuf->lastActiveFrameSlot == -1) {
7807 workBuf->setSize(size);
7808 if (workBuf->create()) {
7809 workBuf->lastActiveFrameSlot = rhiD->currentFrameSlot;
7820 buf =
new QMetalBuffer(rhiD, QRhiBuffer::Static, QRhiBuffer::UsageFlags(QMetalBuffer::WorkBufPoolUsage), size);
7823 buf =
new QMetalBuffer(rhiD, QRhiBuffer::Dynamic, QRhiBuffer::UsageFlags(QMetalBuffer::WorkBufPoolUsage), size);
7827 workBuffers->append(buf);
7831 qWarning(
"Failed to acquire work buffer of size %u", size);
7839 QByteArray entryPoint;
7840 QShaderKey activeKey;
7842 const QShaderDescription tescDesc = tesc.description();
7843 const QShaderDescription teseDesc = tese.description();
7844 d->tess.inControlPointCount = uint(m_patchControlPointCount);
7845 d->tess.outControlPointCount = tescDesc.tessellationOutputVertexCount();
7846 if (!
d->tess.outControlPointCount)
7847 d->tess.outControlPointCount = teseDesc.tessellationOutputVertexCount();
7849 if (!
d->tess.outControlPointCount) {
7850 qWarning(
"Failed to determine output vertex count from the tessellation control or evaluation shader, cannot tessellate");
7851 d->tess.enabled =
false;
7852 d->tess.failed =
true;
7856 if (m_multiViewCount >= 2)
7857 qWarning(
"Multiview is not supported with tessellation");
7865 bool variantsPresent[3] = {};
7866 const QVector<QShaderKey> tessVertKeys = tessVert.availableShaders();
7867 for (
const QShaderKey &k : tessVertKeys) {
7868 switch (k.sourceVariant()) {
7869 case QShader::NonIndexedVertexAsComputeShader:
7870 variantsPresent[0] =
true;
7872 case QShader::UInt32IndexedVertexAsComputeShader:
7873 variantsPresent[1] =
true;
7875 case QShader::UInt16IndexedVertexAsComputeShader:
7876 variantsPresent[2] =
true;
7882 if (!(variantsPresent[0] && variantsPresent[1] && variantsPresent[2])) {
7883 qWarning(
"Vertex shader is not prepared for Metal tessellation. Cannot tessellate. "
7884 "Perhaps the relevant variants (UInt32IndexedVertexAsComputeShader et al) were not generated? "
7885 "Try passing --msltess to qsb.");
7886 d->tess.enabled =
false;
7887 d->tess.failed =
true;
7892 for (QShader::Variant variant : {
7893 QShader::NonIndexedVertexAsComputeShader,
7894 QShader::UInt32IndexedVertexAsComputeShader,
7895 QShader::UInt16IndexedVertexAsComputeShader })
7897 id<MTLLibrary> lib = rhiD->d->createMetalLib(tessVert, variant,
false, &error, &entryPoint, &activeKey);
7899 qWarning(
"MSL shader compilation failed for vertex-as-compute shader %d: %s",
int(variant), qPrintable(error));
7900 d->tess.enabled =
false;
7901 d->tess.failed =
true;
7904 id<MTLFunction> func = rhiD->d->createMSLShaderFunction(lib, entryPoint);
7906 qWarning(
"MSL function for entry point %s not found", entryPoint.constData());
7908 d->tess.enabled =
false;
7909 d->tess.failed =
true;
7912 QMetalShader &compVs(d->tess.compVs[varIndex]);
7915 compVs.desc = tessVert.description();
7916 compVs.nativeResourceBindingMap = tessVert.nativeResourceBindingMap(activeKey);
7917 compVs.nativeShaderInfo = tessVert.nativeShaderInfo(activeKey);
7920 if (!d->tess.vsCompPipeline(rhiD, variant)) {
7921 qWarning(
"Failed to pre-generate compute pipeline for vertex compute shader (tessellation variant %d)",
int(variant));
7922 d->tess.enabled =
false;
7923 d->tess.failed =
true;
7931 id<MTLLibrary> tessControlLib = rhiD
->d->createMetalLib(tesc, QShader::StandardShader,
false, &error, &entryPoint, &activeKey);
7932 if (!tessControlLib) {
7933 qWarning(
"MSL shader compilation failed for tessellation control compute shader: %s", qPrintable(error));
7934 d->tess.enabled =
false;
7935 d->tess.failed =
true;
7938 id<MTLFunction> tessControlFunc = rhiD
->d->createMSLShaderFunction(tessControlLib, entryPoint);
7939 if (!tessControlFunc) {
7940 qWarning(
"MSL function for entry point %s not found", entryPoint.constData());
7941 [tessControlLib release];
7942 d->tess.enabled =
false;
7943 d->tess.failed =
true;
7946 d->tess.compTesc.lib = tessControlLib;
7947 d->tess.compTesc.func = tessControlFunc;
7948 d->tess.compTesc.desc = tesc.description();
7949 d->tess.compTesc.nativeResourceBindingMap = tesc.nativeResourceBindingMap(activeKey);
7950 d->tess.compTesc.nativeShaderInfo = tesc.nativeShaderInfo(activeKey);
7951 if (!
d->tess.tescCompPipeline(rhiD)) {
7952 qWarning(
"Failed to pre-generate compute pipeline for tessellation control shader");
7953 d->tess.enabled =
false;
7954 d->tess.failed =
true;
7959 id<MTLLibrary> tessEvalLib = rhiD
->d->createMetalLib(tese, QShader::StandardShader,
false, &error, &entryPoint, &activeKey);
7961 qWarning(
"MSL shader compilation failed for tessellation evaluation vertex shader: %s", qPrintable(error));
7962 d->tess.enabled =
false;
7963 d->tess.failed =
true;
7966 id<MTLFunction> tessEvalFunc = rhiD
->d->createMSLShaderFunction(tessEvalLib, entryPoint);
7967 if (!tessEvalFunc) {
7968 qWarning(
"MSL function for entry point %s not found", entryPoint.constData());
7969 [tessEvalLib release];
7970 d->tess.enabled =
false;
7971 d->tess.failed =
true;
7974 d->tess.vertTese.lib = tessEvalLib;
7975 d->tess.vertTese.func = tessEvalFunc;
7976 d->tess.vertTese.desc = tese.description();
7977 d->tess.vertTese.nativeResourceBindingMap = tese.nativeResourceBindingMap(activeKey);
7978 d->tess.vertTese.nativeShaderInfo = tese.nativeShaderInfo(activeKey);
7980 id<MTLLibrary> fragLib = rhiD
->d->createMetalLib(tessFrag, QShader::StandardShader,
false, &error, &entryPoint, &activeKey);
7982 qWarning(
"MSL shader compilation failed for fragment shader: %s", qPrintable(error));
7983 d->tess.enabled =
false;
7984 d->tess.failed =
true;
7987 id<MTLFunction> fragFunc = rhiD
->d->createMSLShaderFunction(fragLib, entryPoint);
7989 qWarning(
"MSL function for entry point %s not found", entryPoint.constData());
7991 d->tess.enabled =
false;
7992 d->tess.failed =
true;
7995 d->fs.lib = fragLib;
7996 d->fs.func = fragFunc;
7997 d->fs.desc = tessFrag.description();
7998 d->fs.nativeShaderInfo = tessFrag.nativeShaderInfo(activeKey);
7999 d->fs.nativeResourceBindingMap = tessFrag.nativeResourceBindingMap(activeKey);
8001 if (!
d->tess.teseFragRenderPipeline(rhiD,
this)) {
8002 qWarning(
"Failed to pre-generate render pipeline for tessellation evaluation + fragment shader");
8003 d->tess.enabled =
false;
8004 d->tess.failed =
true;
8008 MTLDepthStencilDescriptor *dsDesc = [[MTLDepthStencilDescriptor alloc] init];
8010 d->ds = [rhiD->d->dev newDepthStencilStateWithDescriptor: dsDesc];
8024 rhiD->pipelineCreationStart();
8025 if (!rhiD->sanityCheckGraphicsPipeline(
this))
8033 for (
const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
8034 switch (shaderStage.type()) {
8035 case QRhiShaderStage::Vertex:
8036 tessVert = shaderStage.shader();
8038 case QRhiShaderStage::TessellationControl:
8039 tesc = shaderStage.shader();
8041 case QRhiShaderStage::TessellationEvaluation:
8042 tese = shaderStage.shader();
8044 case QRhiShaderStage::Fragment:
8045 tessFrag = shaderStage.shader();
8051 d->tess.enabled = tesc.isValid() && tese.isValid() && m_topology == Patches && m_patchControlPointCount > 0;
8052 d->tess.failed =
false;
8054 bool ok = d->tess.enabled ? createTessellationPipelines(tessVert, tesc, tese, tessFrag) : createVertexFragmentPipeline();
8060 QVarLengthArray<QMetalShader *, 6> shaders;
8061 if (
d->tess.enabled) {
8062 shaders.append(&
d->tess.compVs[0]);
8063 shaders.append(&
d->tess.compVs[1]);
8064 shaders.append(&
d->tess.compVs[2]);
8065 shaders.append(&
d->tess.compTesc);
8066 shaders.append(&
d->tess.vertTese);
8068 shaders.append(&
d->vs);
8070 shaders.append(&
d->fs);
8072 for (QMetalShader *shader : shaders) {
8073 if (shader->nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)) {
8074 const int binding = shader->nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding];
8075 shader->nativeResourceBindingMap[binding] = {binding, -1};
8076 int maxNativeBinding = 0;
8077 for (
const QShaderDescription::StorageBlock &block : shader->desc.storageBlocks())
8078 maxNativeBinding = qMax(maxNativeBinding, shader->nativeResourceBindingMap[block.binding].first);
8082 buffers += ((maxNativeBinding + 1 + 7) / 8) * 8;
8089 QRhiBuffer::UsageFlags(
int(QRhiBuffer::StorageBuffer)
8090 | QMetalBuffer::InternalHostWritable),
8091 buffers *
sizeof(
int));
8097 rhiD->pipelineCreationEnd();
8100 rhiD->registerResource(
this);
8129 e.computePipeline.pipelineState =
d->ps;
8134 rhiD
->d->releaseQueue.append(e);
8135 rhiD->unregisterResource(
this);
8142 NSArray *binArchArray = [NSArray arrayWithObjects: binArch, nil];
8143 cpDesc.binaryArchives = binArchArray;
8151 if (![binArch addComputePipelineFunctionsWithDescriptor: cpDesc error: &err]) {
8152 const QString msg = QString::fromNSString(err.localizedDescription);
8153 qWarning(
"Failed to collect compute pipeline functions to binary archive: %s", qPrintable(msg));
8164 rhiD->pipelineCreationStart();
8166 auto cacheIt = rhiD
->d->shaderCache.constFind({ m_shaderStage,
false });
8167 if (cacheIt != rhiD
->d->shaderCache.constEnd()) {
8170 const QShader shader = m_shaderStage.shader();
8172 QByteArray entryPoint;
8173 QShaderKey activeKey;
8174 id<MTLLibrary> lib = rhiD
->d->createMetalLib(shader, m_shaderStage.shaderVariant(),
false,
8175 &error, &entryPoint, &activeKey);
8177 qWarning(
"MSL shader compilation failed: %s", qPrintable(error));
8180 id<MTLFunction> func = rhiD
->d->createMSLShaderFunction(lib, entryPoint);
8182 qWarning(
"MSL function for entry point %s not found", entryPoint.constData());
8188 d->cs.localSize = shader.description().computeShaderLocalSize();
8189 d->cs.nativeResourceBindingMap = shader.nativeResourceBindingMap(activeKey);
8190 d->cs.desc = shader.description();
8191 d->cs.nativeShaderInfo = shader.nativeShaderInfo(activeKey);
8198 setupArgumentBufferEncoder(&
d->cs);
8201 if (
d->cs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)) {
8202 const int binding = d->cs.nativeShaderInfo.extraBufferBindings[QShaderPrivate::MslBufferSizeBufferBinding];
8203 d->cs.nativeResourceBindingMap[binding] = {binding, -1};
8206 if (rhiD->d->shaderCache.count() >= QRhiMetal::MAX_SHADER_CACHE_ENTRIES) {
8207 for (QMetalShader &s : rhiD->d->shaderCache)
8209 rhiD
->d->shaderCache.clear();
8211 rhiD
->d->shaderCache.insert({ m_shaderStage,
false },
d->cs);
8215 [d->cs.func retain];
8216 [d->cs.argumentEncoder retain];
8218 if (
d->cs.argumentBufferIndex >= 0 && !rhiD->caps.indirectCommandBuffers) {
8222 qWarning(
"The ArgumentBufferShader variant of a compute shader cannot be used on this device");
8226 d->localSize = MTLSizeMake(
d->cs.localSize[0],
d->cs.localSize[1],
d->cs.localSize[2]);
8228 MTLComputePipelineDescriptor *cpDesc = [MTLComputePipelineDescriptor
new];
8229 cpDesc.computeFunction =
d->cs.func;
8231 rhiD
->d->trySeedingComputePipelineFromBinaryArchive(cpDesc);
8233 if (rhiD->rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
8234 rhiD
->d->addComputePipelineToBinaryArchive(cpDesc);
8237 d->ps = [rhiD->d->dev newComputePipelineStateWithDescriptor: cpDesc
8238 options: MTLPipelineOptionNone
8243 const QString msg = QString::fromNSString(err.localizedDescription);
8244 qWarning(
"Failed to create compute pipeline state: %s", qPrintable(msg));
8249 if (
d->cs.nativeShaderInfo.extraBufferBindings.contains(QShaderPrivate::MslBufferSizeBufferBinding)) {
8251 for (
const QShaderDescription::StorageBlock &block : d->cs.desc.storageBlocks())
8252 buffers = qMax(buffers, d->cs.nativeResourceBindingMap[block.binding].first);
8256 if (!d->bufferSizeBuffer)
8257 d->bufferSizeBuffer =
new QMetalBuffer(rhiD, QRhiBuffer::Static,
8258 QRhiBuffer::UsageFlags(
int(QRhiBuffer::StorageBuffer)
8259 | QMetalBuffer::InternalHostWritable),
8260 buffers *
sizeof(
int));
8266 rhiD->pipelineCreationEnd();
8269 rhiD->registerResource(
this);
8293 nativeHandlesStruct.commandBuffer = (MTLCommandBuffer *) d->cb;
8294 nativeHandlesStruct.encoder = (MTLRenderCommandEncoder *) d->currentRenderPassEncoder;
8295 return &nativeHandlesStruct;
8301 d->currentRenderPassEncoder = nil;
8302 d->currentComputePassEncoder = nil;
8303 d->tessellationComputeEncoder = nil;
8304 d->currentPassRpDesc = nil;
8311 currentTarget =
nullptr;
8312 d->openDebugGroups.clear();
8321 pushConstantData.clear();
8328 currentIndexOffset = 0;
8329 currentIndexFormat = QRhiCommandBuffer::IndexUInt16;
8334 currentDepthBiasValues = { 0.0f, 0.0f };
8336 currentScissor = {};
8337 currentViewport = {};
8339 currentBlendConstants = {};
8340 currentStencilRef = 0;
8341 appliedStencilRef.reset();
8343 d->currentShaderResourceBindingState = {};
8344 d->currentDepthStencilState = nil;
8346 d->currentVertexInputsBuffers.clear();
8347 d->currentVertexInputOffsets.clear();
8357 d->sem[i] =
nullptr;
8358 d->msaaTex[i] = nil;
8378 dispatch_release(
d->sem[i]);
8379 d->sem[i] =
nullptr;
8384 [d->msaaTex[i] release];
8385 d->msaaTex[i] = nil;
8391 [d->curDrawable release];
8392 d->curDrawable = nil;
8396 rhiD->swapchains.remove(
this);
8397 rhiD->unregisterResource(
this);
8417 CALayer *layer =
nullptr;
8419 if (
auto *cocoaWindow = window->nativeInterface<QNativeInterface::Private::QCocoaWindow>())
8420 layer = cocoaWindow->contentLayer();
8422 layer =
reinterpret_cast<UIView *>(window->winId()).layer;
8425 return static_cast<CAMetalLayer *>(layer);
8441 CAMetalLayer *layer =
d->layer;
8443 layer = qrhi_objectFromProxyData<CAMetalLayer>(&m_proxyData, m_window, QRhi::Metal, 0);
8446 int height = (
int)layer.bounds.size.height;
8447 int width = (
int)layer.bounds.size.width;
8448 width *= layer.contentsScale;
8449 height *= layer.contentsScale;
8450 return QSize(width, height);
8455 if (f == HDRExtendedSrgbLinear) {
8456 return hdrInfo().limits.colorComponentValue.maxPotentialColorComponentValue > 1.0f;
8457 }
else if (f == HDR10) {
8458 return hdrInfo().limits.colorComponentValue.maxPotentialColorComponentValue > 1.0f;
8459 }
else if (f == HDRExtendedDisplayP3Linear) {
8460 return hdrInfo().limits.colorComponentValue.maxPotentialColorComponentValue > 1.0f;
8479 rpD->dsFormat = rhiD->d->dev.depth24Stencil8PixelFormatSupported
8480 ? MTLPixelFormatDepth24Unorm_Stencil8 : MTLPixelFormatDepth32Float_Stencil8;
8482 rpD
->dsFormat = MTLPixelFormatDepth32Float_Stencil8;
8489 rhiD->registerResource(rpD,
false);
8496 samples = rhiD->effectiveSampleCount(m_sampleCount);
8498 if (m_format == HDRExtendedSrgbLinear || m_format == HDRExtendedDisplayP3Linear) {
8499 d->colorFormat = MTLPixelFormatRGBA16Float;
8500 d->rhiColorFormat = QRhiTexture::RGBA16F;
8503 if (m_format == HDR10) {
8504 d->colorFormat = MTLPixelFormatRGB10A2Unorm;
8505 d->rhiColorFormat = QRhiTexture::RGB10A2;
8508 d->colorFormat = m_flags.testFlag(sRGB) ? MTLPixelFormatBGRA8Unorm_sRGB : MTLPixelFormatBGRA8Unorm;
8509 d->rhiColorFormat = QRhiTexture::BGRA8;
8518 dispatch_semaphore_t sem =
d->sem[slot];
8519 dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
8520 dispatch_semaphore_signal(sem);
8527 const bool needsRegistration = !
window ||
window != m_window;
8529 if (window && window != m_window)
8534 if (needsRegistration || !rhiD->swapchains.contains(
this))
8535 rhiD->swapchains.insert(
this);
8539 if (window->surfaceType() != QSurface::MetalSurface) {
8540 qWarning(
"QMetalSwapChain only supports MetalSurface windows");
8544 d->layer = qrhi_objectFromProxyData<CAMetalLayer>(&m_proxyData, window, QRhi::Metal, 0);
8548 if (
d->colorFormat !=
d->layer.pixelFormat)
8549 d->layer.pixelFormat =
d->colorFormat;
8551 if (m_format == HDRExtendedSrgbLinear) {
8552 d->layer.colorspace = CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB);
8553 d->layer.wantsExtendedDynamicRangeContent = YES;
8554 }
else if (m_format == HDR10) {
8555 d->layer.colorspace = CGColorSpaceCreateWithName(kCGColorSpaceITUR_2100_PQ);
8556 d->layer.wantsExtendedDynamicRangeContent = YES;
8557 }
else if (m_format == HDRExtendedDisplayP3Linear) {
8558 d->layer.colorspace = CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearDisplayP3);
8559 d->layer.wantsExtendedDynamicRangeContent = YES;
8562 if (m_flags.testFlag(UsedAsTransferSource))
8563 d->layer.framebufferOnly = NO;
8566 if (m_flags.testFlag(NoVSync))
8567 d->layer.displaySyncEnabled = NO;
8570 if (m_flags.testFlag(SurfaceHasPreMulAlpha)) {
8571 d->layer.opaque = NO;
8572 }
else if (m_flags.testFlag(SurfaceHasNonPreMulAlpha)) {
8577 d->layer.opaque = NO;
8579 d->layer.opaque = YES;
8585 int width = (
int)
d->layer.bounds.size.width;
8586 int height = (
int)
d->layer.bounds.size.height;
8587 CGSize layerSize = CGSizeMake(width, height);
8588 const float scaleFactor =
d->layer.contentsScale;
8589 layerSize.width *= scaleFactor;
8590 layerSize.height *= scaleFactor;
8591 d->layer.drawableSize = layerSize;
8593 m_currentPixelSize = QSizeF::fromCGSize(layerSize).toSize();
8594 pixelSize = m_currentPixelSize;
8596 [d->layer setDevice: rhiD->d->dev];
8598 [d->curDrawable release];
8599 d->curDrawable = nil;
8602 d->lastGpuTime[i] = 0;
8604 d->sem[i] = dispatch_semaphore_create(QMTL_FRAMES_IN_FLIGHT - 1);
8610 ds = m_depthStencil ?
QRHI_RES(QMetalRenderBuffer, m_depthStencil) :
nullptr;
8611 if (m_depthStencil && m_depthStencil->sampleCount() != m_sampleCount) {
8612 qWarning(
"Depth-stencil buffer's sampleCount (%d) does not match color buffers' sample count (%d). Expect problems.",
8613 m_depthStencil->sampleCount(), m_sampleCount);
8615 if (m_depthStencil && m_depthStencil->pixelSize() != pixelSize) {
8616 if (m_depthStencil->flags().testFlag(QRhiRenderBuffer::UsedWithSwapChainOnly)) {
8617 m_depthStencil->setPixelSize(pixelSize);
8618 if (!m_depthStencil->create())
8619 qWarning(
"Failed to rebuild swapchain's associated depth-stencil buffer for size %dx%d",
8620 pixelSize.width(), pixelSize.height());
8622 qWarning(
"Depth-stencil buffer's size (%dx%d) does not match the layer size (%dx%d). Expect problems.",
8623 m_depthStencil->pixelSize().width(), m_depthStencil->pixelSize().height(),
8624 pixelSize.width(), pixelSize.height());
8628 rtWrapper.setRenderPassDescriptor(m_renderPassDesc);
8635 qCDebug(QRHI_LOG_INFO,
"got CAMetalLayer, pixel size %dx%d (scale %.2f)",
8636 pixelSize.width(), pixelSize.height(), scaleFactor);
8639 MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init];
8640 desc.textureType = MTLTextureType2DMultisample;
8641 desc.pixelFormat =
d->colorFormat;
8642 desc.width = NSUInteger(pixelSize.width());
8643 desc.height = NSUInteger(pixelSize.height());
8644 desc.sampleCount = NSUInteger(
samples);
8645 desc.resourceOptions = MTLResourceStorageModePrivate;
8646 desc.storageMode = MTLStorageModePrivate;
8647 desc.usage = MTLTextureUsageRenderTarget;
8649 if (
d->msaaTex[i]) {
8653 e.renderbuffer.texture =
d->msaaTex[i];
8654 rhiD
->d->releaseQueue.append(e);
8656 d->msaaTex[i] = [rhiD->d->dev newTextureWithDescriptor: desc];
8661 rhiD->registerResource(
this);
8670 info.limits.colorComponentValue.maxColorComponentValue = 1;
8671 info.limits.colorComponentValue.maxPotentialColorComponentValue = 1;
8677#if defined(Q_OS_MACOS)
8678 NSView *view =
reinterpret_cast<NSView *>(m_window->winId());
8679 NSScreen *screen = view.window.screen;
8680 info.limits.colorComponentValue.maxColorComponentValue = screen.maximumExtendedDynamicRangeColorComponentValue;
8681 info.limits.colorComponentValue.maxPotentialColorComponentValue = screen.maximumPotentialExtendedDynamicRangeColorComponentValue;
8682#elif defined(Q_OS_IOS)
8683 UIView *view =
reinterpret_cast<UIView *>(m_window->winId());
8684 UIScreen *screen = view.window.windowScene.screen;
8685 info.limits.colorComponentValue.maxColorComponentValue =
8686 view.window.windowScene.screen.currentEDRHeadroom;
8687 info.limits.colorComponentValue.maxPotentialColorComponentValue =
8688 screen.potentialEDRHeadroom;
static QRhiResourceUpdateBatchPrivate * get(QRhiResourceUpdateBatch *b)
Combined button and popup list for selecting options.
Int aligned(Int v, Int byteAlign)
\variable QRhiVulkanQueueSubmitParams::waitSemaphoreCount
MTLPixelFormat viewFormat
MTLPixelFormat viewFormatForSampling
id< MTLTexture > viewForLevel(int level)
id< MTLTexture > perLevelViews[QRhi::MAX_MIP_LEVELS]
id< MTLBuffer > stagingBuf[QMTL_FRAMES_IN_FLIGHT]
id< MTLTexture > writeView
QMetalTextureData(QMetalTexture *t)
id< MTLTexture > samplingView
id< MTLTexture > textureForWrite() const
id< MTLTexture > textureForSampling() const
~QMetalTextureRenderTarget()
float devicePixelRatio() const override
QMetalRenderTargetData * d
QMetalTextureRenderTarget(QRhiImplementation *rhi, const QRhiTextureRenderTargetDescription &desc, Flags flags)
bool create() override
Creates the corresponding native graphics resources.
QRhiRenderPassDescriptor * newCompatibleRenderPassDescriptor() override
int sampleCount() const override
QSize pixelSize() const override
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
QMetalTexture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth, int arraySize, int sampleCount, Flags flags)
bool prepareCreate(QSize *adjustedSize=nullptr)
NativeTexture nativeTexture() override
bool create() override
Creates the corresponding native graphics resources.
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
bool createFrom(NativeTexture src) override
Similar to create(), except that no new native textures are created.
\variable QRhiIndirectDrawCommand::vertexCount
QRhiReadbackDescription desc
quint32 depthPlaneByteSize
QRhiReadbackResult * result
QRhiTexture::Format format
quint32 stencilPlaneByteSize
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
LuminanceBehavior luminanceBehavior
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h