| 1 |
/**************************************************************************/ |
| 2 |
/* metal_objects.mm */ |
| 3 |
/**************************************************************************/ |
| 4 |
/* This file is part of: */ |
| 5 |
/* GODOT ENGINE */ |
| 6 |
/* https://godotengine.org */ |
| 7 |
/**************************************************************************/ |
| 8 |
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ |
| 9 |
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ |
| 10 |
/* */ |
| 11 |
/* Permission is hereby granted, free of charge, to any person obtaining */ |
| 12 |
/* a copy of this software and associated documentation files (the */ |
| 13 |
/* "Software"), to deal in the Software without restriction, including */ |
| 14 |
/* without limitation the rights to use, copy, modify, merge, publish, */ |
| 15 |
/* distribute, sublicense, and/or sell copies of the Software, and to */ |
| 16 |
/* permit persons to whom the Software is furnished to do so, subject to */ |
| 17 |
/* the following conditions: */ |
| 18 |
/* */ |
| 19 |
/* The above copyright notice and this permission notice shall be */ |
| 20 |
/* included in all copies or substantial portions of the Software. */ |
| 21 |
/* */ |
| 22 |
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ |
| 23 |
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ |
| 24 |
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ |
| 25 |
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ |
| 26 |
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ |
| 27 |
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ |
| 28 |
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ |
| 29 |
/**************************************************************************/ |
| 30 |
|
| 31 |
/**************************************************************************/ |
| 32 |
/* */ |
| 33 |
/* Portions of this code were derived from MoltenVK. */ |
| 34 |
/* */ |
| 35 |
/* Copyright (c) 2015-2023 The Brenwill Workshop Ltd. */ |
| 36 |
/* (http://www.brenwill.com) */ |
| 37 |
/* */ |
| 38 |
/* Licensed under the Apache License, Version 2.0 (the "License"); */ |
| 39 |
/* you may not use this file except in compliance with the License. */ |
| 40 |
/* You may obtain a copy of the License at */ |
| 41 |
/* */ |
| 42 |
/* http://www.apache.org/licenses/LICENSE-2.0 */ |
| 43 |
/* */ |
| 44 |
/* Unless required by applicable law or agreed to in writing, software */ |
| 45 |
/* distributed under the License is distributed on an "AS IS" BASIS, */ |
| 46 |
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ |
| 47 |
/* implied. See the License for the specific language governing */ |
| 48 |
/* permissions and limitations under the License. */ |
| 49 |
/**************************************************************************/ |
| 50 |
|
| 51 |
#import "metal_objects.h" |
| 52 |
|
| 53 |
#import "metal_utils.h" |
| 54 |
#import "pixel_formats.h" |
| 55 |
#import "rendering_device_driver_metal.h" |
| 56 |
#import "rendering_shader_container_metal.h" |
| 57 |
|
| 58 |
#import <os/signpost.h> |
| 59 |
#import <algorithm> |
| 60 |
|
| 61 |
// We have to undefine these macros because they are defined in NSObjCRuntime.h. |
| 62 |
#undef MIN |
| 63 |
#undef MAX |
| 64 |
|
| 65 |
void MDCommandBuffer::begin_label(const char *p_label_name, const Color &p_color) { |
| 66 |
NSString *s = [[NSString alloc] initWithBytesNoCopy:(void *)p_label_name length:strlen(p_label_name) encoding:NSUTF8StringEncoding freeWhenDone:NO]; |
| 67 |
[commandBuffer pushDebugGroup:s]; |
| 68 |
} |
| 69 |
|
| 70 |
void MDCommandBuffer::end_label() { |
| 71 |
[commandBuffer popDebugGroup]; |
| 72 |
} |
| 73 |
|
| 74 |
void MDCommandBuffer::begin() { |
| 75 |
DEV_ASSERT(commandBuffer == nil && !state_begin); |
| 76 |
state_begin = true; |
| 77 |
binding_cache.clear(); |
| 78 |
} |
| 79 |
|
| 80 |
void MDCommandBuffer::end() { |
| 81 |
switch (type) { |
| 82 |
case MDCommandBufferStateType::None: |
| 83 |
return; |
| 84 |
case MDCommandBufferStateType::Render: |
| 85 |
return render_end_pass(); |
| 86 |
case MDCommandBufferStateType::Compute: |
| 87 |
return _end_compute_dispatch(); |
| 88 |
case MDCommandBufferStateType::Blit: |
| 89 |
return _end_blit(); |
| 90 |
} |
| 91 |
} |
| 92 |
|
| 93 |
void MDCommandBuffer::commit() { |
| 94 |
end(); |
| 95 |
[commandBuffer commit]; |
| 96 |
commandBuffer = nil; |
| 97 |
state_begin = false; |
| 98 |
} |
| 99 |
|
| 100 |
void MDCommandBuffer::bind_pipeline(RDD::PipelineID p_pipeline) { |
| 101 |
MDPipeline *p = (MDPipeline *)(p_pipeline.id); |
| 102 |
|
| 103 |
// End current encoder if it is a compute encoder or blit encoder, |
| 104 |
// as they do not have a defined end boundary in the RDD like render. |
| 105 |
if (type == MDCommandBufferStateType::Compute) { |
| 106 |
_end_compute_dispatch(); |
| 107 |
} else if (type == MDCommandBufferStateType::Blit) { |
| 108 |
_end_blit(); |
| 109 |
} |
| 110 |
|
| 111 |
if (p->type == MDPipelineType::Render) { |
| 112 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 113 |
MDRenderPipeline *rp = (MDRenderPipeline *)p; |
| 114 |
|
| 115 |
if (render.encoder == nil) { |
| 116 |
// This error would happen if the render pass failed. |
| 117 |
ERR_FAIL_NULL_MSG(render.desc, "Render pass descriptor is null."); |
| 118 |
|
| 119 |
// This condition occurs when there are no attachments when calling render_next_subpass() |
| 120 |
// and is due to the SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS flag. |
| 121 |
render.desc.defaultRasterSampleCount = static_cast<NSUInteger>(rp->sample_count); |
| 122 |
|
| 123 |
// NOTE(sgc): This is to test rdar://FB13605547 and will be deleted once fix is confirmed. |
| 124 |
#if 0 |
| 125 |
if (render.pipeline->sample_count == 4) { |
| 126 |
static id<MTLTexture> tex = nil; |
| 127 |
static id<MTLTexture> res_tex = nil; |
| 128 |
static dispatch_once_t onceToken; |
| 129 |
dispatch_once(&onceToken, ^{ |
| 130 |
Size2i sz = render.frameBuffer->size; |
| 131 |
MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:sz.width height:sz.height mipmapped:NO]; |
| 132 |
td.textureType = MTLTextureType2DMultisample; |
| 133 |
td.storageMode = MTLStorageModeMemoryless; |
| 134 |
td.usage = MTLTextureUsageRenderTarget; |
| 135 |
td.sampleCount = render.pipeline->sample_count; |
| 136 |
tex = [device_driver->get_device() newTextureWithDescriptor:td]; |
| 137 |
|
| 138 |
td.textureType = MTLTextureType2D; |
| 139 |
td.storageMode = MTLStorageModePrivate; |
| 140 |
td.usage = MTLTextureUsageShaderWrite; |
| 141 |
td.sampleCount = 1; |
| 142 |
res_tex = [device_driver->get_device() newTextureWithDescriptor:td]; |
| 143 |
}); |
| 144 |
render.desc.colorAttachments[0].texture = tex; |
| 145 |
render.desc.colorAttachments[0].loadAction = MTLLoadActionClear; |
| 146 |
render.desc.colorAttachments[0].storeAction = MTLStoreActionMultisampleResolve; |
| 147 |
|
| 148 |
render.desc.colorAttachments[0].resolveTexture = res_tex; |
| 149 |
} |
| 150 |
#endif |
| 151 |
render.encoder = [command_buffer() renderCommandEncoderWithDescriptor:render.desc]; |
| 152 |
} |
| 153 |
|
| 154 |
if (render.pipeline != rp) { |
| 155 |
render.dirty.set_flag((RenderState::DirtyFlag)(RenderState::DIRTY_PIPELINE | RenderState::DIRTY_RASTER)); |
| 156 |
// Mark all uniforms as dirty, as variants of a shader pipeline may have a different entry point ABI, |
| 157 |
// due to setting force_active_argument_buffer_resources = true for spirv_cross::CompilerMSL::Options. |
| 158 |
// As a result, uniform sets with the same layout will generate redundant binding warnings when |
| 159 |
// capturing a Metal frame in Xcode. |
| 160 |
// |
| 161 |
// If we don't mark as dirty, then some bindings will generate a validation error. |
| 162 |
binding_cache.clear(); |
| 163 |
render.mark_uniforms_dirty(); |
| 164 |
if (render.pipeline != nullptr && render.pipeline->depth_stencil != rp->depth_stencil) { |
| 165 |
render.dirty.set_flag(RenderState::DIRTY_DEPTH); |
| 166 |
} |
| 167 |
if (rp->raster_state.blend.enabled) { |
| 168 |
render.dirty.set_flag(RenderState::DIRTY_BLEND); |
| 169 |
} |
| 170 |
render.pipeline = rp; |
| 171 |
} |
| 172 |
} else if (p->type == MDPipelineType::Compute) { |
| 173 |
DEV_ASSERT(type == MDCommandBufferStateType::None); |
| 174 |
type = MDCommandBufferStateType::Compute; |
| 175 |
|
| 176 |
if (compute.pipeline != p) { |
| 177 |
compute.dirty.set_flag(ComputeState::DIRTY_PIPELINE); |
| 178 |
binding_cache.clear(); |
| 179 |
compute.mark_uniforms_dirty(); |
| 180 |
compute.pipeline = (MDComputePipeline *)p; |
| 181 |
} |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
void MDCommandBuffer::encode_push_constant_data(RDD::ShaderID p_shader, VectorView<uint32_t> p_data) { |
| 186 |
switch (type) { |
| 187 |
case MDCommandBufferStateType::Render: |
| 188 |
case MDCommandBufferStateType::Compute: { |
| 189 |
MDShader *shader = (MDShader *)(p_shader.id); |
| 190 |
if (shader->push_constants.binding == UINT32_MAX) { |
| 191 |
return; |
| 192 |
} |
| 193 |
push_constant_binding = shader->push_constants.binding; |
| 194 |
void const *ptr = p_data.ptr(); |
| 195 |
push_constant_data_len = p_data.size() * sizeof(uint32_t); |
| 196 |
DEV_ASSERT(push_constant_data_len <= sizeof(push_constant_data)); |
| 197 |
memcpy(push_constant_data, ptr, push_constant_data_len); |
| 198 |
if (push_constant_data_len > 0) { |
| 199 |
switch (type) { |
| 200 |
case MDCommandBufferStateType::Render: |
| 201 |
render.dirty.set_flag(RenderState::DirtyFlag::DIRTY_PUSH); |
| 202 |
break; |
| 203 |
case MDCommandBufferStateType::Compute: |
| 204 |
compute.dirty.set_flag(ComputeState::DirtyFlag::DIRTY_PUSH); |
| 205 |
break; |
| 206 |
default: |
| 207 |
break; |
| 208 |
} |
| 209 |
} |
| 210 |
} break; |
| 211 |
case MDCommandBufferStateType::Blit: |
| 212 |
case MDCommandBufferStateType::None: |
| 213 |
return; |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
id<MTLBlitCommandEncoder> MDCommandBuffer::_ensure_blit_encoder() { |
| 218 |
switch (type) { |
| 219 |
case MDCommandBufferStateType::None: |
| 220 |
break; |
| 221 |
case MDCommandBufferStateType::Render: |
| 222 |
render_end_pass(); |
| 223 |
break; |
| 224 |
case MDCommandBufferStateType::Compute: |
| 225 |
_end_compute_dispatch(); |
| 226 |
break; |
| 227 |
case MDCommandBufferStateType::Blit: |
| 228 |
return blit.encoder; |
| 229 |
} |
| 230 |
|
| 231 |
type = MDCommandBufferStateType::Blit; |
| 232 |
blit.encoder = command_buffer().blitCommandEncoder; |
| 233 |
return blit.encoder; |
| 234 |
} |
| 235 |
|
| 236 |
_FORCE_INLINE_ static MTLSize mipmapLevelSizeFromTexture(id<MTLTexture> p_tex, NSUInteger p_level) { |
| 237 |
MTLSize lvlSize; |
| 238 |
lvlSize.width = MAX(p_tex.width >> p_level, 1UL); |
| 239 |
lvlSize.height = MAX(p_tex.height >> p_level, 1UL); |
| 240 |
lvlSize.depth = MAX(p_tex.depth >> p_level, 1UL); |
| 241 |
return lvlSize; |
| 242 |
} |
| 243 |
|
| 244 |
void MDCommandBuffer::resolve_texture(RDD::TextureID p_src_texture, RDD::TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, RDD::TextureID p_dst_texture, RDD::TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap) { |
| 245 |
id<MTLTexture> src_tex = rid::get(p_src_texture); |
| 246 |
id<MTLTexture> dst_tex = rid::get(p_dst_texture); |
| 247 |
|
| 248 |
MTLRenderPassDescriptor *mtlRPD = [MTLRenderPassDescriptor renderPassDescriptor]; |
| 249 |
MTLRenderPassColorAttachmentDescriptor *mtlColorAttDesc = mtlRPD.colorAttachments[0]; |
| 250 |
mtlColorAttDesc.loadAction = MTLLoadActionLoad; |
| 251 |
mtlColorAttDesc.storeAction = MTLStoreActionMultisampleResolve; |
| 252 |
|
| 253 |
mtlColorAttDesc.texture = src_tex; |
| 254 |
mtlColorAttDesc.resolveTexture = dst_tex; |
| 255 |
mtlColorAttDesc.level = p_src_mipmap; |
| 256 |
mtlColorAttDesc.slice = p_src_layer; |
| 257 |
mtlColorAttDesc.resolveLevel = p_dst_mipmap; |
| 258 |
mtlColorAttDesc.resolveSlice = p_dst_layer; |
| 259 |
encodeRenderCommandEncoderWithDescriptor(mtlRPD, @"Resolve Image"); |
| 260 |
} |
| 261 |
|
| 262 |
void MDCommandBuffer::clear_color_texture(RDD::TextureID p_texture, RDD::TextureLayout p_texture_layout, const Color &p_color, const RDD::TextureSubresourceRange &p_subresources) { |
| 263 |
id<MTLTexture> src_tex = rid::get(p_texture); |
| 264 |
|
| 265 |
if (src_tex.parentTexture) { |
| 266 |
// Clear via the parent texture rather than the view. |
| 267 |
src_tex = src_tex.parentTexture; |
| 268 |
} |
| 269 |
|
| 270 |
PixelFormats &pf = device_driver->get_pixel_formats(); |
| 271 |
|
| 272 |
if (pf.isDepthFormat(src_tex.pixelFormat) || pf.isStencilFormat(src_tex.pixelFormat)) { |
| 273 |
ERR_FAIL_MSG("invalid: depth or stencil texture format"); |
| 274 |
} |
| 275 |
|
| 276 |
MTLRenderPassDescriptor *desc = MTLRenderPassDescriptor.renderPassDescriptor; |
| 277 |
|
| 278 |
if (p_subresources.aspect.has_flag(RDD::TEXTURE_ASPECT_COLOR_BIT)) { |
| 279 |
MTLRenderPassColorAttachmentDescriptor *caDesc = desc.colorAttachments[0]; |
| 280 |
caDesc.texture = src_tex; |
| 281 |
caDesc.loadAction = MTLLoadActionClear; |
| 282 |
caDesc.storeAction = MTLStoreActionStore; |
| 283 |
caDesc.clearColor = MTLClearColorMake(p_color.r, p_color.g, p_color.b, p_color.a); |
| 284 |
|
| 285 |
// Extract the mipmap levels that are to be updated. |
| 286 |
uint32_t mipLvlStart = p_subresources.base_mipmap; |
| 287 |
uint32_t mipLvlCnt = p_subresources.mipmap_count; |
| 288 |
uint32_t mipLvlEnd = mipLvlStart + mipLvlCnt; |
| 289 |
|
| 290 |
uint32_t levelCount = src_tex.mipmapLevelCount; |
| 291 |
|
| 292 |
// Extract the cube or array layers (slices) that are to be updated. |
| 293 |
bool is3D = src_tex.textureType == MTLTextureType3D; |
| 294 |
uint32_t layerStart = is3D ? 0 : p_subresources.base_layer; |
| 295 |
uint32_t layerCnt = p_subresources.layer_count; |
| 296 |
uint32_t layerEnd = layerStart + layerCnt; |
| 297 |
|
| 298 |
MetalFeatures const &features = device_driver->get_device_properties().features; |
| 299 |
|
| 300 |
// Iterate across mipmap levels and layers, and perform and empty render to clear each. |
| 301 |
for (uint32_t mipLvl = mipLvlStart; mipLvl < mipLvlEnd; mipLvl++) { |
| 302 |
ERR_FAIL_INDEX_MSG(mipLvl, levelCount, "mip level out of range"); |
| 303 |
|
| 304 |
caDesc.level = mipLvl; |
| 305 |
|
| 306 |
// If a 3D image, we need to get the depth for each level. |
| 307 |
if (is3D) { |
| 308 |
layerCnt = mipmapLevelSizeFromTexture(src_tex, mipLvl).depth; |
| 309 |
layerEnd = layerStart + layerCnt; |
| 310 |
} |
| 311 |
|
| 312 |
if ((features.layeredRendering && src_tex.sampleCount == 1) || features.multisampleLayeredRendering) { |
| 313 |
// We can clear all layers at once. |
| 314 |
if (is3D) { |
| 315 |
caDesc.depthPlane = layerStart; |
| 316 |
} else { |
| 317 |
caDesc.slice = layerStart; |
| 318 |
} |
| 319 |
desc.renderTargetArrayLength = layerCnt; |
| 320 |
encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image"); |
| 321 |
} else { |
| 322 |
for (uint32_t layer = layerStart; layer < layerEnd; layer++) { |
| 323 |
if (is3D) { |
| 324 |
caDesc.depthPlane = layer; |
| 325 |
} else { |
| 326 |
caDesc.slice = layer; |
| 327 |
} |
| 328 |
encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image"); |
| 329 |
} |
| 330 |
} |
| 331 |
} |
| 332 |
} |
| 333 |
} |
| 334 |
|
| 335 |
void MDCommandBuffer::clear_depth_stencil_texture(RDD::TextureID p_texture, RDD::TextureLayout p_texture_layout, float p_depth, uint8_t p_stencil, const RDD::TextureSubresourceRange &p_subresources) { |
| 336 |
id<MTLTexture> src_tex = rid::get(p_texture); |
| 337 |
|
| 338 |
if (src_tex.parentTexture) { |
| 339 |
// Clear via the parent texture rather than the view. |
| 340 |
src_tex = src_tex.parentTexture; |
| 341 |
} |
| 342 |
|
| 343 |
PixelFormats &pf = device_driver->get_pixel_formats(); |
| 344 |
|
| 345 |
bool is_depth_format = pf.isDepthFormat(src_tex.pixelFormat); |
| 346 |
bool is_stencil_format = pf.isStencilFormat(src_tex.pixelFormat); |
| 347 |
|
| 348 |
if (!is_depth_format && !is_stencil_format) { |
| 349 |
ERR_FAIL_MSG("invalid: color texture format"); |
| 350 |
} |
| 351 |
|
| 352 |
bool clear_depth = is_depth_format && p_subresources.aspect.has_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT); |
| 353 |
bool clear_stencil = is_stencil_format && p_subresources.aspect.has_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT); |
| 354 |
|
| 355 |
if (clear_depth || clear_stencil) { |
| 356 |
MTLRenderPassDescriptor *desc = MTLRenderPassDescriptor.renderPassDescriptor; |
| 357 |
|
| 358 |
MTLRenderPassDepthAttachmentDescriptor *daDesc = desc.depthAttachment; |
| 359 |
if (clear_depth) { |
| 360 |
daDesc.texture = src_tex; |
| 361 |
daDesc.loadAction = MTLLoadActionClear; |
| 362 |
daDesc.storeAction = MTLStoreActionStore; |
| 363 |
daDesc.clearDepth = p_depth; |
| 364 |
} |
| 365 |
|
| 366 |
MTLRenderPassStencilAttachmentDescriptor *saDesc = desc.stencilAttachment; |
| 367 |
if (clear_stencil) { |
| 368 |
saDesc.texture = src_tex; |
| 369 |
saDesc.loadAction = MTLLoadActionClear; |
| 370 |
saDesc.storeAction = MTLStoreActionStore; |
| 371 |
saDesc.clearStencil = p_stencil; |
| 372 |
} |
| 373 |
|
| 374 |
// Extract the mipmap levels that are to be updated. |
| 375 |
uint32_t mipLvlStart = p_subresources.base_mipmap; |
| 376 |
uint32_t mipLvlCnt = p_subresources.mipmap_count; |
| 377 |
uint32_t mipLvlEnd = mipLvlStart + mipLvlCnt; |
| 378 |
|
| 379 |
uint32_t levelCount = src_tex.mipmapLevelCount; |
| 380 |
|
| 381 |
// Extract the cube or array layers (slices) that are to be updated. |
| 382 |
bool is3D = src_tex.textureType == MTLTextureType3D; |
| 383 |
uint32_t layerStart = is3D ? 0 : p_subresources.base_layer; |
| 384 |
uint32_t layerCnt = p_subresources.layer_count; |
| 385 |
uint32_t layerEnd = layerStart + layerCnt; |
| 386 |
|
| 387 |
MetalFeatures const &features = device_driver->get_device_properties().features; |
| 388 |
|
| 389 |
// Iterate across mipmap levels and layers, and perform and empty render to clear each. |
| 390 |
for (uint32_t mipLvl = mipLvlStart; mipLvl < mipLvlEnd; mipLvl++) { |
| 391 |
ERR_FAIL_INDEX_MSG(mipLvl, levelCount, "mip level out of range"); |
| 392 |
|
| 393 |
if (clear_depth) { |
| 394 |
daDesc.level = mipLvl; |
| 395 |
} |
| 396 |
if (clear_stencil) { |
| 397 |
saDesc.level = mipLvl; |
| 398 |
} |
| 399 |
|
| 400 |
// If a 3D image, we need to get the depth for each level. |
| 401 |
if (is3D) { |
| 402 |
layerCnt = mipmapLevelSizeFromTexture(src_tex, mipLvl).depth; |
| 403 |
layerEnd = layerStart + layerCnt; |
| 404 |
} |
| 405 |
|
| 406 |
if ((features.layeredRendering && src_tex.sampleCount == 1) || features.multisampleLayeredRendering) { |
| 407 |
// We can clear all layers at once. |
| 408 |
if (is3D) { |
| 409 |
if (clear_depth) { |
| 410 |
daDesc.depthPlane = layerStart; |
| 411 |
} |
| 412 |
if (clear_stencil) { |
| 413 |
saDesc.depthPlane = layerStart; |
| 414 |
} |
| 415 |
} else { |
| 416 |
if (clear_depth) { |
| 417 |
daDesc.slice = layerStart; |
| 418 |
} |
| 419 |
if (clear_stencil) { |
| 420 |
saDesc.slice = layerStart; |
| 421 |
} |
| 422 |
} |
| 423 |
desc.renderTargetArrayLength = layerCnt; |
| 424 |
encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image"); |
| 425 |
} else { |
| 426 |
for (uint32_t layer = layerStart; layer < layerEnd; layer++) { |
| 427 |
if (is3D) { |
| 428 |
if (clear_depth) { |
| 429 |
daDesc.depthPlane = layer; |
| 430 |
} |
| 431 |
if (clear_stencil) { |
| 432 |
saDesc.depthPlane = layer; |
| 433 |
} |
| 434 |
} else { |
| 435 |
if (clear_depth) { |
| 436 |
daDesc.slice = layer; |
| 437 |
} |
| 438 |
if (clear_stencil) { |
| 439 |
saDesc.slice = layer; |
| 440 |
} |
| 441 |
} |
| 442 |
encodeRenderCommandEncoderWithDescriptor(desc, @"Clear Image"); |
| 443 |
} |
| 444 |
} |
| 445 |
} |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
void MDCommandBuffer::clear_buffer(RDD::BufferID p_buffer, uint64_t p_offset, uint64_t p_size) { |
| 450 |
id<MTLBlitCommandEncoder> blit_enc = _ensure_blit_encoder(); |
| 451 |
const RDM::BufferInfo *buffer = (const RDM::BufferInfo *)p_buffer.id; |
| 452 |
|
| 453 |
[blit_enc fillBuffer:buffer->metal_buffer |
| 454 |
range:NSMakeRange(p_offset, p_size) |
| 455 |
value:0]; |
| 456 |
} |
| 457 |
|
| 458 |
void MDCommandBuffer::copy_buffer(RDD::BufferID p_src_buffer, RDD::BufferID p_dst_buffer, VectorView<RDD::BufferCopyRegion> p_regions) { |
| 459 |
const RDM::BufferInfo *src = (const RDM::BufferInfo *)p_src_buffer.id; |
| 460 |
const RDM::BufferInfo *dst = (const RDM::BufferInfo *)p_dst_buffer.id; |
| 461 |
|
| 462 |
id<MTLBlitCommandEncoder> enc = _ensure_blit_encoder(); |
| 463 |
|
| 464 |
for (uint32_t i = 0; i < p_regions.size(); i++) { |
| 465 |
RDD::BufferCopyRegion region = p_regions[i]; |
| 466 |
[enc copyFromBuffer:src->metal_buffer |
| 467 |
sourceOffset:region.src_offset |
| 468 |
toBuffer:dst->metal_buffer |
| 469 |
destinationOffset:region.dst_offset |
| 470 |
size:region.size]; |
| 471 |
} |
| 472 |
} |
| 473 |
|
| 474 |
static MTLSize MTLSizeFromVector3i(Vector3i p_size) { |
| 475 |
return MTLSizeMake(p_size.x, p_size.y, p_size.z); |
| 476 |
} |
| 477 |
|
| 478 |
static MTLOrigin MTLOriginFromVector3i(Vector3i p_origin) { |
| 479 |
return MTLOriginMake(p_origin.x, p_origin.y, p_origin.z); |
| 480 |
} |
| 481 |
|
| 482 |
// Clamps the size so that the sum of the origin and size do not exceed the maximum size. |
| 483 |
static inline MTLSize clampMTLSize(MTLSize p_size, MTLOrigin p_origin, MTLSize p_max_size) { |
| 484 |
MTLSize clamped; |
| 485 |
clamped.width = MIN(p_size.width, p_max_size.width - p_origin.x); |
| 486 |
clamped.height = MIN(p_size.height, p_max_size.height - p_origin.y); |
| 487 |
clamped.depth = MIN(p_size.depth, p_max_size.depth - p_origin.z); |
| 488 |
return clamped; |
| 489 |
} |
| 490 |
|
| 491 |
API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) |
| 492 |
static bool isArrayTexture(MTLTextureType p_type) { |
| 493 |
return (p_type == MTLTextureType3D || |
| 494 |
p_type == MTLTextureType2DArray || |
| 495 |
p_type == MTLTextureType2DMultisampleArray || |
| 496 |
p_type == MTLTextureType1DArray); |
| 497 |
} |
| 498 |
|
| 499 |
_FORCE_INLINE_ static bool operator==(MTLSize p_a, MTLSize p_b) { |
| 500 |
return p_a.width == p_b.width && p_a.height == p_b.height && p_a.depth == p_b.depth; |
| 501 |
} |
| 502 |
|
| 503 |
void MDCommandBuffer::copy_texture(RDD::TextureID p_src_texture, RDD::TextureID p_dst_texture, VectorView<RDD::TextureCopyRegion> p_regions) { |
| 504 |
id<MTLTexture> src = rid::get(p_src_texture); |
| 505 |
id<MTLTexture> dst = rid::get(p_dst_texture); |
| 506 |
|
| 507 |
id<MTLBlitCommandEncoder> enc = _ensure_blit_encoder(); |
| 508 |
PixelFormats &pf = device_driver->get_pixel_formats(); |
| 509 |
|
| 510 |
MTLPixelFormat src_fmt = src.pixelFormat; |
| 511 |
bool src_is_compressed = pf.getFormatType(src_fmt) == MTLFormatType::Compressed; |
| 512 |
MTLPixelFormat dst_fmt = dst.pixelFormat; |
| 513 |
bool dst_is_compressed = pf.getFormatType(dst_fmt) == MTLFormatType::Compressed; |
| 514 |
|
| 515 |
// Validate copy. |
| 516 |
if (src.sampleCount != dst.sampleCount || pf.getBytesPerBlock(src_fmt) != pf.getBytesPerBlock(dst_fmt)) { |
| 517 |
ERR_FAIL_MSG("Cannot copy between incompatible pixel formats, such as formats of different pixel sizes, or between images with different sample counts."); |
| 518 |
} |
| 519 |
|
| 520 |
// If source and destination have different formats and at least one is compressed, a temporary buffer is required. |
| 521 |
bool need_tmp_buffer = (src_fmt != dst_fmt) && (src_is_compressed || dst_is_compressed); |
| 522 |
if (need_tmp_buffer) { |
| 523 |
ERR_FAIL_MSG("not implemented: copy with intermediate buffer"); |
| 524 |
} |
| 525 |
|
| 526 |
if (src_fmt != dst_fmt) { |
| 527 |
// Map the source pixel format to the dst through a texture view on the source texture. |
| 528 |
src = [src newTextureViewWithPixelFormat:dst_fmt]; |
| 529 |
} |
| 530 |
|
| 531 |
for (uint32_t i = 0; i < p_regions.size(); i++) { |
| 532 |
RDD::TextureCopyRegion region = p_regions[i]; |
| 533 |
|
| 534 |
MTLSize extent = MTLSizeFromVector3i(region.size); |
| 535 |
|
| 536 |
// If copies can be performed using direct texture-texture copying, do so. |
| 537 |
uint32_t src_level = region.src_subresources.mipmap; |
| 538 |
uint32_t src_base_layer = region.src_subresources.base_layer; |
| 539 |
MTLSize src_extent = mipmapLevelSizeFromTexture(src, src_level); |
| 540 |
uint32_t dst_level = region.dst_subresources.mipmap; |
| 541 |
uint32_t dst_base_layer = region.dst_subresources.base_layer; |
| 542 |
MTLSize dst_extent = mipmapLevelSizeFromTexture(dst, dst_level); |
| 543 |
|
| 544 |
// All layers may be copied at once, if the extent completely covers both images. |
| 545 |
if (src_extent == extent && dst_extent == extent) { |
| 546 |
[enc copyFromTexture:src |
| 547 |
sourceSlice:src_base_layer |
| 548 |
sourceLevel:src_level |
| 549 |
toTexture:dst |
| 550 |
destinationSlice:dst_base_layer |
| 551 |
destinationLevel:dst_level |
| 552 |
sliceCount:region.src_subresources.layer_count |
| 553 |
levelCount:1]; |
| 554 |
} else { |
| 555 |
MTLOrigin src_origin = MTLOriginFromVector3i(region.src_offset); |
| 556 |
MTLSize src_size = clampMTLSize(extent, src_origin, src_extent); |
| 557 |
uint32_t layer_count = 0; |
| 558 |
if ((src.textureType == MTLTextureType3D) != (dst.textureType == MTLTextureType3D)) { |
| 559 |
// In the case, the number of layers to copy is in extent.depth. Use that value, |
| 560 |
// then clamp the depth, so we don't try to copy more than Metal will allow. |
| 561 |
layer_count = extent.depth; |
| 562 |
src_size.depth = 1; |
| 563 |
} else { |
| 564 |
layer_count = region.src_subresources.layer_count; |
| 565 |
} |
| 566 |
MTLOrigin dst_origin = MTLOriginFromVector3i(region.dst_offset); |
| 567 |
|
| 568 |
for (uint32_t layer = 0; layer < layer_count; layer++) { |
| 569 |
// We can copy between a 3D and a 2D image easily. Just copy between |
| 570 |
// one slice of the 2D image and one plane of the 3D image at a time. |
| 571 |
if ((src.textureType == MTLTextureType3D) == (dst.textureType == MTLTextureType3D)) { |
| 572 |
[enc copyFromTexture:src |
| 573 |
sourceSlice:src_base_layer + layer |
| 574 |
sourceLevel:src_level |
| 575 |
sourceOrigin:src_origin |
| 576 |
sourceSize:src_size |
| 577 |
toTexture:dst |
| 578 |
destinationSlice:dst_base_layer + layer |
| 579 |
destinationLevel:dst_level |
| 580 |
destinationOrigin:dst_origin]; |
| 581 |
} else if (src.textureType == MTLTextureType3D) { |
| 582 |
[enc copyFromTexture:src |
| 583 |
sourceSlice:src_base_layer |
| 584 |
sourceLevel:src_level |
| 585 |
sourceOrigin:MTLOriginMake(src_origin.x, src_origin.y, src_origin.z + layer) |
| 586 |
sourceSize:src_size |
| 587 |
toTexture:dst |
| 588 |
destinationSlice:dst_base_layer + layer |
| 589 |
destinationLevel:dst_level |
| 590 |
destinationOrigin:dst_origin]; |
| 591 |
} else { |
| 592 |
DEV_ASSERT(dst.textureType == MTLTextureType3D); |
| 593 |
[enc copyFromTexture:src |
| 594 |
sourceSlice:src_base_layer + layer |
| 595 |
sourceLevel:src_level |
| 596 |
sourceOrigin:src_origin |
| 597 |
sourceSize:src_size |
| 598 |
toTexture:dst |
| 599 |
destinationSlice:dst_base_layer |
| 600 |
destinationLevel:dst_level |
| 601 |
destinationOrigin:MTLOriginMake(dst_origin.x, dst_origin.y, dst_origin.z + layer)]; |
| 602 |
} |
| 603 |
} |
| 604 |
} |
| 605 |
} |
| 606 |
} |
| 607 |
|
| 608 |
void MDCommandBuffer::copy_buffer_to_texture(RDD::BufferID p_src_buffer, RDD::TextureID p_dst_texture, VectorView<RDD::BufferTextureCopyRegion> p_regions) { |
| 609 |
_copy_texture_buffer(CopySource::Buffer, p_dst_texture, p_src_buffer, p_regions); |
| 610 |
} |
| 611 |
|
| 612 |
void MDCommandBuffer::copy_texture_to_buffer(RDD::TextureID p_src_texture, RDD::BufferID p_dst_buffer, VectorView<RDD::BufferTextureCopyRegion> p_regions) { |
| 613 |
_copy_texture_buffer(CopySource::Texture, p_src_texture, p_dst_buffer, p_regions); |
| 614 |
} |
| 615 |
|
| 616 |
void MDCommandBuffer::_copy_texture_buffer(CopySource p_source, |
| 617 |
RDD::TextureID p_texture, |
| 618 |
RDD::BufferID p_buffer, |
| 619 |
VectorView<RDD::BufferTextureCopyRegion> p_regions) { |
| 620 |
const RDM::BufferInfo *buffer = (const RDM::BufferInfo *)p_buffer.id; |
| 621 |
id<MTLTexture> texture = rid::get(p_texture); |
| 622 |
|
| 623 |
id<MTLBlitCommandEncoder> enc = _ensure_blit_encoder(); |
| 624 |
|
| 625 |
PixelFormats &pf = device_driver->get_pixel_formats(); |
| 626 |
MTLPixelFormat mtlPixFmt = texture.pixelFormat; |
| 627 |
|
| 628 |
MTLBlitOption options = MTLBlitOptionNone; |
| 629 |
if (pf.isPVRTCFormat(mtlPixFmt)) { |
| 630 |
options |= MTLBlitOptionRowLinearPVRTC; |
| 631 |
} |
| 632 |
|
| 633 |
for (uint32_t i = 0; i < p_regions.size(); i++) { |
| 634 |
RDD::BufferTextureCopyRegion region = p_regions[i]; |
| 635 |
|
| 636 |
uint32_t mip_level = region.texture_subresource.mipmap; |
| 637 |
MTLOrigin txt_origin = MTLOriginMake(region.texture_offset.x, region.texture_offset.y, region.texture_offset.z); |
| 638 |
MTLSize src_extent = mipmapLevelSizeFromTexture(texture, mip_level); |
| 639 |
MTLSize txt_size = clampMTLSize(MTLSizeMake(region.texture_region_size.x, region.texture_region_size.y, region.texture_region_size.z), |
| 640 |
txt_origin, |
| 641 |
src_extent); |
| 642 |
|
| 643 |
uint32_t buffImgWd = region.texture_region_size.x; |
| 644 |
uint32_t buffImgHt = region.texture_region_size.y; |
| 645 |
|
| 646 |
NSUInteger bytesPerRow = pf.getBytesPerRow(mtlPixFmt, buffImgWd); |
| 647 |
NSUInteger bytesPerImg = pf.getBytesPerLayer(mtlPixFmt, bytesPerRow, buffImgHt); |
| 648 |
|
| 649 |
MTLBlitOption blit_options = options; |
| 650 |
|
| 651 |
if (pf.isDepthFormat(mtlPixFmt) && pf.isStencilFormat(mtlPixFmt)) { |
| 652 |
// Don't reduce depths of 32-bit depth/stencil formats. |
| 653 |
if (region.texture_subresource.aspect == RDD::TEXTURE_ASPECT_DEPTH) { |
| 654 |
if (pf.getBytesPerTexel(mtlPixFmt) != 4) { |
| 655 |
bytesPerRow -= buffImgWd; |
| 656 |
bytesPerImg -= buffImgWd * buffImgHt; |
| 657 |
} |
| 658 |
blit_options |= MTLBlitOptionDepthFromDepthStencil; |
| 659 |
} else if (region.texture_subresource.aspect == RDD::TEXTURE_ASPECT_STENCIL) { |
| 660 |
// The stencil component is always 1 byte per pixel. |
| 661 |
bytesPerRow = buffImgWd; |
| 662 |
bytesPerImg = buffImgWd * buffImgHt; |
| 663 |
blit_options |= MTLBlitOptionStencilFromDepthStencil; |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
if (!isArrayTexture(texture.textureType)) { |
| 668 |
bytesPerImg = 0; |
| 669 |
} |
| 670 |
|
| 671 |
if (p_source == CopySource::Buffer) { |
| 672 |
[enc copyFromBuffer:buffer->metal_buffer |
| 673 |
sourceOffset:region.buffer_offset |
| 674 |
sourceBytesPerRow:bytesPerRow |
| 675 |
sourceBytesPerImage:bytesPerImg |
| 676 |
sourceSize:txt_size |
| 677 |
toTexture:texture |
| 678 |
destinationSlice:region.texture_subresource.layer |
| 679 |
destinationLevel:mip_level |
| 680 |
destinationOrigin:txt_origin |
| 681 |
options:blit_options]; |
| 682 |
} else { |
| 683 |
[enc copyFromTexture:texture |
| 684 |
sourceSlice:region.texture_subresource.layer |
| 685 |
sourceLevel:mip_level |
| 686 |
sourceOrigin:txt_origin |
| 687 |
sourceSize:txt_size |
| 688 |
toBuffer:buffer->metal_buffer |
| 689 |
destinationOffset:region.buffer_offset |
| 690 |
destinationBytesPerRow:bytesPerRow |
| 691 |
destinationBytesPerImage:bytesPerImg |
| 692 |
options:blit_options]; |
| 693 |
} |
| 694 |
} |
| 695 |
} |
| 696 |
|
| 697 |
void MDCommandBuffer::encodeRenderCommandEncoderWithDescriptor(MTLRenderPassDescriptor *p_desc, NSString *p_label) { |
| 698 |
switch (type) { |
| 699 |
case MDCommandBufferStateType::None: |
| 700 |
break; |
| 701 |
case MDCommandBufferStateType::Render: |
| 702 |
render_end_pass(); |
| 703 |
break; |
| 704 |
case MDCommandBufferStateType::Compute: |
| 705 |
_end_compute_dispatch(); |
| 706 |
break; |
| 707 |
case MDCommandBufferStateType::Blit: |
| 708 |
_end_blit(); |
| 709 |
break; |
| 710 |
} |
| 711 |
|
| 712 |
id<MTLRenderCommandEncoder> enc = [command_buffer() renderCommandEncoderWithDescriptor:p_desc]; |
| 713 |
if (p_label != nil) { |
| 714 |
[enc pushDebugGroup:p_label]; |
| 715 |
[enc popDebugGroup]; |
| 716 |
} |
| 717 |
[enc endEncoding]; |
| 718 |
} |
| 719 |
|
| 720 |
#pragma mark - Render Commands |
| 721 |
|
| 722 |
void MDCommandBuffer::render_bind_uniform_sets(VectorView<RDD::UniformSetID> p_uniform_sets, RDD::ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, uint32_t p_dynamic_offsets) { |
| 723 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 724 |
|
| 725 |
if (uint32_t new_size = p_first_set_index + p_set_count; render.uniform_sets.size() < new_size) { |
| 726 |
uint32_t s = render.uniform_sets.size(); |
| 727 |
render.uniform_sets.resize(new_size); |
| 728 |
// Set intermediate values to null. |
| 729 |
std::fill(&render.uniform_sets[s], render.uniform_sets.end().operator->(), nullptr); |
| 730 |
} |
| 731 |
|
| 732 |
const MDShader *shader = (const MDShader *)p_shader.id; |
| 733 |
DynamicOffsetLayout layout = shader->dynamic_offset_layout; |
| 734 |
|
| 735 |
// Clear bits for sets being rebound before OR'ing new values. |
| 736 |
// This prevents corruption when the same set is bound multiple times |
| 737 |
// with different frame indices (e.g., OPAQUE pass then ALPHA pass). |
| 738 |
for (uint32_t i = 0; i < p_set_count && render.dynamic_offsets != 0; i++) { |
| 739 |
uint32_t set_index = p_first_set_index + i; |
| 740 |
uint32_t count = layout.get_count(set_index); |
| 741 |
if (count > 0) { |
| 742 |
uint32_t shift = layout.get_offset_index_shift(set_index); |
| 743 |
uint32_t mask = ((1u << (count * 4u)) - 1u) << shift; |
| 744 |
render.dynamic_offsets &= ~mask; |
| 745 |
} |
| 746 |
} |
| 747 |
render.dynamic_offsets |= p_dynamic_offsets; |
| 748 |
|
| 749 |
for (size_t i = 0; i < p_set_count; ++i) { |
| 750 |
MDUniformSet *set = (MDUniformSet *)(p_uniform_sets[i].id); |
| 751 |
|
| 752 |
uint32_t index = p_first_set_index + i; |
| 753 |
if (render.uniform_sets[index] != set || layout.get_count(index) > 0) { |
| 754 |
render.dirty.set_flag(RenderState::DIRTY_UNIFORMS); |
| 755 |
render.uniform_set_mask |= 1ULL << index; |
| 756 |
render.uniform_sets[index] = set; |
| 757 |
} |
| 758 |
} |
| 759 |
} |
| 760 |
|
| 761 |
void MDCommandBuffer::render_clear_attachments(VectorView<RDD::AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) { |
| 762 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 763 |
|
| 764 |
const MDSubpass &subpass = render.get_subpass(); |
| 765 |
|
| 766 |
uint32_t vertex_count = p_rects.size() * 6 * subpass.view_count; |
| 767 |
simd::float4 *vertices = ALLOCA_ARRAY(simd::float4, vertex_count); |
| 768 |
simd::float4 clear_colors[ClearAttKey::ATTACHMENT_COUNT]; |
| 769 |
|
| 770 |
Size2i size = render.frameBuffer->size; |
| 771 |
Rect2i render_area = render.clip_to_render_area({ { 0, 0 }, size }); |
| 772 |
size = Size2i(render_area.position.x + render_area.size.width, render_area.position.y + render_area.size.height); |
| 773 |
_populate_vertices(vertices, size, p_rects); |
| 774 |
|
| 775 |
ClearAttKey key; |
| 776 |
key.sample_count = render.pass->get_sample_count(); |
| 777 |
if (subpass.view_count > 1) { |
| 778 |
key.enable_layered_rendering(); |
| 779 |
} |
| 780 |
|
| 781 |
float depth_value = 0; |
| 782 |
uint32_t stencil_value = 0; |
| 783 |
|
| 784 |
for (uint32_t i = 0; i < p_attachment_clears.size(); i++) { |
| 785 |
RDD::AttachmentClear const &attClear = p_attachment_clears[i]; |
| 786 |
uint32_t attachment_index; |
| 787 |
if (attClear.aspect.has_flag(RDD::TEXTURE_ASPECT_COLOR_BIT)) { |
| 788 |
attachment_index = attClear.color_attachment; |
| 789 |
} else { |
| 790 |
attachment_index = subpass.depth_stencil_reference.attachment; |
| 791 |
} |
| 792 |
|
| 793 |
MDAttachment const &mda = render.pass->attachments[attachment_index]; |
| 794 |
if (attClear.aspect.has_flag(RDD::TEXTURE_ASPECT_COLOR_BIT)) { |
| 795 |
key.set_color_format(attachment_index, mda.format); |
| 796 |
clear_colors[attachment_index] = { |
| 797 |
attClear.value.color.r, |
| 798 |
attClear.value.color.g, |
| 799 |
attClear.value.color.b, |
| 800 |
attClear.value.color.a |
| 801 |
}; |
| 802 |
} |
| 803 |
|
| 804 |
if (attClear.aspect.has_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT)) { |
| 805 |
key.set_depth_format(mda.format); |
| 806 |
depth_value = attClear.value.depth; |
| 807 |
} |
| 808 |
|
| 809 |
if (attClear.aspect.has_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT)) { |
| 810 |
key.set_stencil_format(mda.format); |
| 811 |
stencil_value = attClear.value.stencil; |
| 812 |
} |
| 813 |
} |
| 814 |
clear_colors[ClearAttKey::DEPTH_INDEX] = { |
| 815 |
depth_value, |
| 816 |
depth_value, |
| 817 |
depth_value, |
| 818 |
depth_value |
| 819 |
}; |
| 820 |
|
| 821 |
id<MTLRenderCommandEncoder> enc = render.encoder; |
| 822 |
|
| 823 |
MDResourceCache &cache = device_driver->get_resource_cache(); |
| 824 |
|
| 825 |
[enc pushDebugGroup:@"ClearAttachments"]; |
| 826 |
[enc setRenderPipelineState:cache.get_clear_render_pipeline_state(key, nil)]; |
| 827 |
[enc setDepthStencilState:cache.get_depth_stencil_state( |
| 828 |
key.is_depth_enabled(), |
| 829 |
key.is_stencil_enabled())]; |
| 830 |
[enc setStencilReferenceValue:stencil_value]; |
| 831 |
[enc setCullMode:MTLCullModeNone]; |
| 832 |
[enc setTriangleFillMode:MTLTriangleFillModeFill]; |
| 833 |
[enc setDepthBias:0 slopeScale:0 clamp:0]; |
| 834 |
[enc setViewport:{ 0, 0, (double)size.width, (double)size.height, 0.0, 1.0 }]; |
| 835 |
[enc setScissorRect:{ 0, 0, (NSUInteger)size.width, (NSUInteger)size.height }]; |
| 836 |
|
| 837 |
[enc setVertexBytes:clear_colors length:sizeof(clear_colors) atIndex:0]; |
| 838 |
[enc setFragmentBytes:clear_colors length:sizeof(clear_colors) atIndex:0]; |
| 839 |
[enc setVertexBytes:vertices length:vertex_count * sizeof(vertices[0]) atIndex:device_driver->get_metal_buffer_index_for_vertex_attribute_binding(VERT_CONTENT_BUFFER_INDEX)]; |
| 840 |
|
| 841 |
[enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:vertex_count]; |
| 842 |
[enc popDebugGroup]; |
| 843 |
|
| 844 |
render.dirty.set_flag((RenderState::DirtyFlag)(RenderState::DIRTY_PIPELINE | RenderState::DIRTY_DEPTH | RenderState::DIRTY_RASTER)); |
| 845 |
binding_cache.clear(); |
| 846 |
render.mark_uniforms_dirty({ 0 }); // Mark index 0 dirty, if there is already a binding for index 0. |
| 847 |
render.mark_viewport_dirty(); |
| 848 |
render.mark_scissors_dirty(); |
| 849 |
render.mark_vertex_dirty(); |
| 850 |
render.mark_blend_dirty(); |
| 851 |
} |
| 852 |
|
| 853 |
void MDCommandBuffer::_render_set_dirty_state() { |
| 854 |
_render_bind_uniform_sets(); |
| 855 |
|
| 856 |
if (render.dirty.has_flag(RenderState::DIRTY_PUSH)) { |
| 857 |
if (push_constant_binding != UINT32_MAX) { |
| 858 |
[render.encoder setVertexBytes:push_constant_data |
| 859 |
length:push_constant_data_len |
| 860 |
atIndex:push_constant_binding]; |
| 861 |
[render.encoder setFragmentBytes:push_constant_data |
| 862 |
length:push_constant_data_len |
| 863 |
atIndex:push_constant_binding]; |
| 864 |
} |
| 865 |
} |
| 866 |
|
| 867 |
MDSubpass const &subpass = render.get_subpass(); |
| 868 |
if (subpass.view_count > 1) { |
| 869 |
uint32_t view_range[2] = { 0, subpass.view_count }; |
| 870 |
[render.encoder setVertexBytes:view_range length:sizeof(view_range) atIndex:VIEW_MASK_BUFFER_INDEX]; |
| 871 |
[render.encoder setFragmentBytes:view_range length:sizeof(view_range) atIndex:VIEW_MASK_BUFFER_INDEX]; |
| 872 |
} |
| 873 |
|
| 874 |
if (render.dirty.has_flag(RenderState::DIRTY_PIPELINE)) { |
| 875 |
[render.encoder setRenderPipelineState:render.pipeline->state]; |
| 876 |
} |
| 877 |
|
| 878 |
if (render.dirty.has_flag(RenderState::DIRTY_VIEWPORT)) { |
| 879 |
[render.encoder setViewports:render.viewports.ptr() count:render.viewports.size()]; |
| 880 |
} |
| 881 |
|
| 882 |
if (render.dirty.has_flag(RenderState::DIRTY_DEPTH)) { |
| 883 |
[render.encoder setDepthStencilState:render.pipeline->depth_stencil]; |
| 884 |
} |
| 885 |
|
| 886 |
if (render.dirty.has_flag(RenderState::DIRTY_RASTER)) { |
| 887 |
render.pipeline->raster_state.apply(render.encoder); |
| 888 |
} |
| 889 |
|
| 890 |
if (render.dirty.has_flag(RenderState::DIRTY_SCISSOR) && !render.scissors.is_empty()) { |
| 891 |
size_t len = render.scissors.size(); |
| 892 |
MTLScissorRect *rects = ALLOCA_ARRAY(MTLScissorRect, len); |
| 893 |
for (size_t i = 0; i < len; i++) { |
| 894 |
rects[i] = render.clip_to_render_area(render.scissors[i]); |
| 895 |
} |
| 896 |
[render.encoder setScissorRects:rects count:len]; |
| 897 |
} |
| 898 |
|
| 899 |
if (render.dirty.has_flag(RenderState::DIRTY_BLEND) && render.blend_constants.has_value()) { |
| 900 |
[render.encoder setBlendColorRed:render.blend_constants->r green:render.blend_constants->g blue:render.blend_constants->b alpha:render.blend_constants->a]; |
| 901 |
} |
| 902 |
|
| 903 |
if (render.dirty.has_flag(RenderState::DIRTY_VERTEX)) { |
| 904 |
uint32_t p_binding_count = render.vertex_buffers.size(); |
| 905 |
if (p_binding_count > 0) { |
| 906 |
uint32_t first = device_driver->get_metal_buffer_index_for_vertex_attribute_binding(p_binding_count - 1); |
| 907 |
[render.encoder setVertexBuffers:render.vertex_buffers.ptr() |
| 908 |
offsets:render.vertex_offsets.ptr() |
| 909 |
withRange:NSMakeRange(first, p_binding_count)]; |
| 910 |
} |
| 911 |
} |
| 912 |
|
| 913 |
render.resource_tracker.encode(render.encoder); |
| 914 |
|
| 915 |
render.dirty.clear(); |
| 916 |
} |
| 917 |
|
| 918 |
void MDCommandBuffer::render_set_viewport(VectorView<Rect2i> p_viewports) { |
| 919 |
render.viewports.resize(p_viewports.size()); |
| 920 |
for (uint32_t i = 0; i < p_viewports.size(); i += 1) { |
| 921 |
Rect2i const &vp = p_viewports[i]; |
| 922 |
render.viewports[i] = { |
| 923 |
.originX = static_cast<double>(vp.position.x), |
| 924 |
.originY = static_cast<double>(vp.position.y), |
| 925 |
.width = static_cast<double>(vp.size.width), |
| 926 |
.height = static_cast<double>(vp.size.height), |
| 927 |
.znear = 0.0, |
| 928 |
.zfar = 1.0, |
| 929 |
}; |
| 930 |
} |
| 931 |
|
| 932 |
render.dirty.set_flag(RenderState::DIRTY_VIEWPORT); |
| 933 |
} |
| 934 |
|
| 935 |
void MDCommandBuffer::render_set_scissor(VectorView<Rect2i> p_scissors) { |
| 936 |
render.scissors.resize(p_scissors.size()); |
| 937 |
for (uint32_t i = 0; i < p_scissors.size(); i += 1) { |
| 938 |
Rect2i const &vp = p_scissors[i]; |
| 939 |
render.scissors[i] = { |
| 940 |
.x = static_cast<NSUInteger>(vp.position.x), |
| 941 |
.y = static_cast<NSUInteger>(vp.position.y), |
| 942 |
.width = static_cast<NSUInteger>(vp.size.width), |
| 943 |
.height = static_cast<NSUInteger>(vp.size.height), |
| 944 |
}; |
| 945 |
} |
| 946 |
|
| 947 |
render.dirty.set_flag(RenderState::DIRTY_SCISSOR); |
| 948 |
} |
| 949 |
|
| 950 |
void MDCommandBuffer::render_set_blend_constants(const Color &p_constants) { |
| 951 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 952 |
if (render.blend_constants != p_constants) { |
| 953 |
render.blend_constants = p_constants; |
| 954 |
render.dirty.set_flag(RenderState::DIRTY_BLEND); |
| 955 |
} |
| 956 |
} |
| 957 |
|
| 958 |
void ResourceTracker::merge_from(const ResourceUsageMap &p_from) { |
| 959 |
for (KeyValue<StageResourceUsage, ResourceVector> const &keyval : p_from) { |
| 960 |
ResourceVector *resources = _current.getptr(keyval.key); |
| 961 |
if (resources == nullptr) { |
| 962 |
resources = &_current.insert(keyval.key, ResourceVector())->value; |
| 963 |
} |
| 964 |
// Reserve space for the new resources, assuming they are all added. |
| 965 |
resources->reserve(resources->size() + keyval.value.size()); |
| 966 |
|
| 967 |
uint32_t i = 0, j = 0; |
| 968 |
MTLResourceUnsafe *resources_ptr = resources->ptr(); |
| 969 |
const MTLResourceUnsafe *keyval_ptr = keyval.value.ptr(); |
| 970 |
// 2-way merge. |
| 971 |
while (i < resources->size() && j < keyval.value.size()) { |
| 972 |
if (resources_ptr[i] < keyval_ptr[j]) { |
| 973 |
i++; |
| 974 |
} else if (resources_ptr[i] > keyval_ptr[j]) { |
| 975 |
ResourceUsageEntry *existing = nullptr; |
| 976 |
if ((existing = _previous.getptr(keyval_ptr[j])) == nullptr) { |
| 977 |
existing = &_previous.insert(keyval_ptr[j], keyval.key)->value; |
| 978 |
resources->insert(i, keyval_ptr[j]); |
| 979 |
} else { |
| 980 |
if (existing->usage != keyval.key) { |
| 981 |
existing->usage |= keyval.key; |
| 982 |
resources->insert(i, keyval_ptr[j]); |
| 983 |
} |
| 984 |
} |
| 985 |
i++; |
| 986 |
j++; |
| 987 |
} else { |
| 988 |
i++; |
| 989 |
j++; |
| 990 |
} |
| 991 |
} |
| 992 |
// Append the remaining resources. |
| 993 |
for (; j < keyval.value.size(); j++) { |
| 994 |
ResourceUsageEntry *existing = nullptr; |
| 995 |
if ((existing = _previous.getptr(keyval_ptr[j])) == nullptr) { |
| 996 |
existing = &_previous.insert(keyval_ptr[j], keyval.key)->value; |
| 997 |
resources->push_back(keyval_ptr[j]); |
| 998 |
} else { |
| 999 |
if (existing->usage != keyval.key) { |
| 1000 |
existing->usage |= keyval.key; |
| 1001 |
resources->push_back(keyval_ptr[j]); |
| 1002 |
} |
| 1003 |
} |
| 1004 |
} |
| 1005 |
} |
| 1006 |
} |
| 1007 |
|
| 1008 |
void ResourceTracker::encode(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) { |
| 1009 |
for (KeyValue<StageResourceUsage, ResourceVector> const &keyval : _current) { |
| 1010 |
if (keyval.value.is_empty()) { |
| 1011 |
continue; |
| 1012 |
} |
| 1013 |
|
| 1014 |
MTLResourceUsage vert_usage = resource_usage_for_stage(keyval.key, RDD::ShaderStage::SHADER_STAGE_VERTEX); |
| 1015 |
MTLResourceUsage frag_usage = resource_usage_for_stage(keyval.key, RDD::ShaderStage::SHADER_STAGE_FRAGMENT); |
| 1016 |
if (vert_usage == frag_usage) { |
| 1017 |
[p_enc useResources:keyval.value.ptr() count:keyval.value.size() usage:vert_usage stages:MTLRenderStageVertex | MTLRenderStageFragment]; |
| 1018 |
} else { |
| 1019 |
if (vert_usage != 0) { |
| 1020 |
[p_enc useResources:keyval.value.ptr() count:keyval.value.size() usage:vert_usage stages:MTLRenderStageVertex]; |
| 1021 |
} |
| 1022 |
if (frag_usage != 0) { |
| 1023 |
[p_enc useResources:keyval.value.ptr() count:keyval.value.size() usage:frag_usage stages:MTLRenderStageFragment]; |
| 1024 |
} |
| 1025 |
} |
| 1026 |
} |
| 1027 |
|
| 1028 |
// Keep the keys for now and clear the vectors to reduce churn. |
| 1029 |
for (KeyValue<StageResourceUsage, ResourceVector> &v : _current) { |
| 1030 |
v.value.clear(); |
| 1031 |
} |
| 1032 |
} |
| 1033 |
|
| 1034 |
void ResourceTracker::encode(id<MTLComputeCommandEncoder> __unsafe_unretained p_enc) { |
| 1035 |
for (KeyValue<StageResourceUsage, ResourceVector> const &keyval : _current) { |
| 1036 |
if (keyval.value.is_empty()) { |
| 1037 |
continue; |
| 1038 |
} |
| 1039 |
MTLResourceUsage usage = resource_usage_for_stage(keyval.key, RDD::ShaderStage::SHADER_STAGE_COMPUTE); |
| 1040 |
if (usage != 0) { |
| 1041 |
[p_enc useResources:keyval.value.ptr() count:keyval.value.size() usage:usage]; |
| 1042 |
} |
| 1043 |
} |
| 1044 |
|
| 1045 |
// Keep the keys for now and clear the vectors to reduce churn. |
| 1046 |
for (KeyValue<StageResourceUsage, ResourceVector> &v : _current) { |
| 1047 |
v.value.clear(); |
| 1048 |
} |
| 1049 |
} |
| 1050 |
|
| 1051 |
void ResourceTracker::reset() { |
| 1052 |
// Keep the keys for now, as they are likely to be used repeatedly. |
| 1053 |
for (KeyValue<MTLResourceUnsafe, ResourceUsageEntry> &v : _previous) { |
| 1054 |
if (v.value.usage == ResourceUnused) { |
| 1055 |
v.value.unused++; |
| 1056 |
if (v.value.unused >= RESOURCE_UNUSED_CLEANUP_COUNT) { |
| 1057 |
_scratch.push_back(v.key); |
| 1058 |
} |
| 1059 |
} else { |
| 1060 |
v.value = ResourceUnused; |
| 1061 |
v.value.unused = 0; |
| 1062 |
} |
| 1063 |
} |
| 1064 |
|
| 1065 |
// Clear up resources that weren't used for the last pass. |
| 1066 |
for (const MTLResourceUnsafe &res : _scratch) { |
| 1067 |
_previous.erase(res); |
| 1068 |
} |
| 1069 |
_scratch.clear(); |
| 1070 |
} |
| 1071 |
|
| 1072 |
void MDCommandBuffer::_render_bind_uniform_sets() { |
| 1073 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 1074 |
if (!render.dirty.has_flag(RenderState::DIRTY_UNIFORMS)) { |
| 1075 |
return; |
| 1076 |
} |
| 1077 |
|
| 1078 |
render.dirty.clear_flag(RenderState::DIRTY_UNIFORMS); |
| 1079 |
uint64_t set_uniforms = render.uniform_set_mask; |
| 1080 |
render.uniform_set_mask = 0; |
| 1081 |
|
| 1082 |
MDRenderShader *shader = render.pipeline->shader; |
| 1083 |
const uint32_t dynamic_offsets = render.dynamic_offsets; |
| 1084 |
|
| 1085 |
while (set_uniforms != 0) { |
| 1086 |
// Find the index of the next set bit. |
| 1087 |
uint32_t index = (uint32_t)__builtin_ctzll(set_uniforms); |
| 1088 |
// Clear the set bit. |
| 1089 |
set_uniforms &= (set_uniforms - 1); |
| 1090 |
MDUniformSet *set = render.uniform_sets[index]; |
| 1091 |
if (set == nullptr || index >= (uint32_t)shader->sets.size()) { |
| 1092 |
continue; |
| 1093 |
} |
| 1094 |
if (shader->uses_argument_buffers) { |
| 1095 |
set->bind_uniforms_argument_buffers(shader, render, index, dynamic_offsets, device_driver->frame_index(), device_driver->frame_count()); |
| 1096 |
} else { |
| 1097 |
DirectEncoder de(render.encoder, binding_cache); |
| 1098 |
set->bind_uniforms_direct(shader, de, index, dynamic_offsets); |
| 1099 |
} |
| 1100 |
} |
| 1101 |
} |
| 1102 |
|
| 1103 |
void MDCommandBuffer::_populate_vertices(simd::float4 *p_vertices, Size2i p_fb_size, VectorView<Rect2i> p_rects) { |
| 1104 |
uint32_t idx = 0; |
| 1105 |
for (uint32_t i = 0; i < p_rects.size(); i++) { |
| 1106 |
Rect2i const &rect = p_rects[i]; |
| 1107 |
idx = _populate_vertices(p_vertices, idx, rect, p_fb_size); |
| 1108 |
} |
| 1109 |
} |
| 1110 |
|
| 1111 |
uint32_t MDCommandBuffer::_populate_vertices(simd::float4 *p_vertices, uint32_t p_index, Rect2i const &p_rect, Size2i p_fb_size) { |
| 1112 |
// Determine the positions of the four edges of the |
| 1113 |
// clear rectangle as a fraction of the attachment size. |
| 1114 |
float leftPos = (float)(p_rect.position.x) / (float)p_fb_size.width; |
| 1115 |
float rightPos = (float)(p_rect.size.width) / (float)p_fb_size.width + leftPos; |
| 1116 |
float bottomPos = (float)(p_rect.position.y) / (float)p_fb_size.height; |
| 1117 |
float topPos = (float)(p_rect.size.height) / (float)p_fb_size.height + bottomPos; |
| 1118 |
|
| 1119 |
// Transform to clip-space coordinates, which are bounded by (-1.0 < p < 1.0) in clip-space. |
| 1120 |
leftPos = (leftPos * 2.0f) - 1.0f; |
| 1121 |
rightPos = (rightPos * 2.0f) - 1.0f; |
| 1122 |
bottomPos = (bottomPos * 2.0f) - 1.0f; |
| 1123 |
topPos = (topPos * 2.0f) - 1.0f; |
| 1124 |
|
| 1125 |
simd::float4 vtx; |
| 1126 |
|
| 1127 |
uint32_t idx = p_index; |
| 1128 |
uint32_t endLayer = render.get_subpass().view_count; |
| 1129 |
|
| 1130 |
for (uint32_t layer = 0; layer < endLayer; layer++) { |
| 1131 |
vtx.z = 0.0; |
| 1132 |
vtx.w = (float)layer; |
| 1133 |
|
| 1134 |
// Top left vertex - First triangle. |
| 1135 |
vtx.y = topPos; |
| 1136 |
vtx.x = leftPos; |
| 1137 |
p_vertices[idx++] = vtx; |
| 1138 |
|
| 1139 |
// Bottom left vertex. |
| 1140 |
vtx.y = bottomPos; |
| 1141 |
vtx.x = leftPos; |
| 1142 |
p_vertices[idx++] = vtx; |
| 1143 |
|
| 1144 |
// Bottom right vertex. |
| 1145 |
vtx.y = bottomPos; |
| 1146 |
vtx.x = rightPos; |
| 1147 |
p_vertices[idx++] = vtx; |
| 1148 |
|
| 1149 |
// Bottom right vertex - Second triangle. |
| 1150 |
p_vertices[idx++] = vtx; |
| 1151 |
|
| 1152 |
// Top right vertex. |
| 1153 |
vtx.y = topPos; |
| 1154 |
vtx.x = rightPos; |
| 1155 |
p_vertices[idx++] = vtx; |
| 1156 |
|
| 1157 |
// Top left vertex. |
| 1158 |
vtx.y = topPos; |
| 1159 |
vtx.x = leftPos; |
| 1160 |
p_vertices[idx++] = vtx; |
| 1161 |
} |
| 1162 |
|
| 1163 |
return idx; |
| 1164 |
} |
| 1165 |
|
| 1166 |
void MDCommandBuffer::render_begin_pass(RDD::RenderPassID p_render_pass, RDD::FramebufferID p_frameBuffer, RDD::CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView<RDD::RenderPassClearValue> p_clear_values) { |
| 1167 |
DEV_ASSERT(command_buffer() != nil); |
| 1168 |
end(); |
| 1169 |
|
| 1170 |
MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id); |
| 1171 |
MDFrameBuffer *fb = (MDFrameBuffer *)(p_frameBuffer.id); |
| 1172 |
|
| 1173 |
type = MDCommandBufferStateType::Render; |
| 1174 |
render.pass = pass; |
| 1175 |
render.current_subpass = UINT32_MAX; |
| 1176 |
render.render_area = p_rect; |
| 1177 |
render.clear_values.resize(p_clear_values.size()); |
| 1178 |
for (uint32_t i = 0; i < p_clear_values.size(); i++) { |
| 1179 |
render.clear_values[i] = p_clear_values[i]; |
| 1180 |
} |
| 1181 |
render.is_rendering_entire_area = (p_rect.position == Point2i(0, 0)) && p_rect.size == fb->size; |
| 1182 |
render.frameBuffer = fb; |
| 1183 |
render_next_subpass(); |
| 1184 |
} |
| 1185 |
|
| 1186 |
void MDCommandBuffer::_end_render_pass() { |
| 1187 |
MDFrameBuffer const &fb_info = *render.frameBuffer; |
| 1188 |
MDSubpass const &subpass = render.get_subpass(); |
| 1189 |
|
| 1190 |
PixelFormats &pf = device_driver->get_pixel_formats(); |
| 1191 |
|
| 1192 |
for (uint32_t i = 0; i < subpass.resolve_references.size(); i++) { |
| 1193 |
uint32_t color_index = subpass.color_references[i].attachment; |
| 1194 |
uint32_t resolve_index = subpass.resolve_references[i].attachment; |
| 1195 |
DEV_ASSERT((color_index == RDD::AttachmentReference::UNUSED) == (resolve_index == RDD::AttachmentReference::UNUSED)); |
| 1196 |
if (color_index == RDD::AttachmentReference::UNUSED || !fb_info.has_texture(color_index)) { |
| 1197 |
continue; |
| 1198 |
} |
| 1199 |
|
| 1200 |
id<MTLTexture> resolve_tex = fb_info.get_texture(resolve_index); |
| 1201 |
|
| 1202 |
CRASH_COND_MSG(!flags::all(pf.getCapabilities(resolve_tex.pixelFormat), kMTLFmtCapsResolve), "not implemented: unresolvable texture types"); |
| 1203 |
// see: https://github.com/KhronosGroup/MoltenVK/blob/d20d13fe2735adb845636a81522df1b9d89c0fba/MoltenVK/MoltenVK/GPUObjects/MVKRenderPass.mm#L407 |
| 1204 |
} |
| 1205 |
|
| 1206 |
render.end_encoding(); |
| 1207 |
} |
| 1208 |
|
| 1209 |
void MDCommandBuffer::_render_clear_render_area() { |
| 1210 |
MDRenderPass const &pass = *render.pass; |
| 1211 |
MDSubpass const &subpass = render.get_subpass(); |
| 1212 |
|
| 1213 |
uint32_t ds_index = subpass.depth_stencil_reference.attachment; |
| 1214 |
bool clear_depth = (ds_index != RDD::AttachmentReference::UNUSED && pass.attachments[ds_index].shouldClear(subpass, false)); |
| 1215 |
bool clear_stencil = (ds_index != RDD::AttachmentReference::UNUSED && pass.attachments[ds_index].shouldClear(subpass, true)); |
| 1216 |
|
| 1217 |
uint32_t color_count = subpass.color_references.size(); |
| 1218 |
uint32_t clears_size = color_count + (clear_depth || clear_stencil ? 1 : 0); |
| 1219 |
if (clears_size == 0) { |
| 1220 |
return; |
| 1221 |
} |
| 1222 |
|
| 1223 |
RDD::AttachmentClear *clears = ALLOCA_ARRAY(RDD::AttachmentClear, clears_size); |
| 1224 |
uint32_t clears_count = 0; |
| 1225 |
|
| 1226 |
for (uint32_t i = 0; i < color_count; i++) { |
| 1227 |
uint32_t idx = subpass.color_references[i].attachment; |
| 1228 |
if (idx != RDD::AttachmentReference::UNUSED && pass.attachments[idx].shouldClear(subpass, false)) { |
| 1229 |
clears[clears_count++] = { .aspect = RDD::TEXTURE_ASPECT_COLOR_BIT, .color_attachment = idx, .value = render.clear_values[idx] }; |
| 1230 |
} |
| 1231 |
} |
| 1232 |
|
| 1233 |
if (clear_depth || clear_stencil) { |
| 1234 |
MDAttachment const &attachment = pass.attachments[ds_index]; |
| 1235 |
BitField<RDD::TextureAspectBits> bits = {}; |
| 1236 |
if (clear_depth && attachment.type & MDAttachmentType::Depth) { |
| 1237 |
bits.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT); |
| 1238 |
} |
| 1239 |
if (clear_stencil && attachment.type & MDAttachmentType::Stencil) { |
| 1240 |
bits.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT); |
| 1241 |
} |
| 1242 |
|
| 1243 |
clears[clears_count++] = { .aspect = bits, .color_attachment = ds_index, .value = render.clear_values[ds_index] }; |
| 1244 |
} |
| 1245 |
|
| 1246 |
if (clears_count == 0) { |
| 1247 |
return; |
| 1248 |
} |
| 1249 |
|
| 1250 |
render_clear_attachments(VectorView(clears, clears_count), { render.render_area }); |
| 1251 |
} |
| 1252 |
|
| 1253 |
void MDCommandBuffer::render_next_subpass() { |
| 1254 |
DEV_ASSERT(command_buffer() != nil); |
| 1255 |
|
| 1256 |
if (render.current_subpass == UINT32_MAX) { |
| 1257 |
render.current_subpass = 0; |
| 1258 |
} else { |
| 1259 |
_end_render_pass(); |
| 1260 |
render.current_subpass++; |
| 1261 |
} |
| 1262 |
|
| 1263 |
MDFrameBuffer const &fb = *render.frameBuffer; |
| 1264 |
MDRenderPass const &pass = *render.pass; |
| 1265 |
MDSubpass const &subpass = render.get_subpass(); |
| 1266 |
|
| 1267 |
MTLRenderPassDescriptor *desc = MTLRenderPassDescriptor.renderPassDescriptor; |
| 1268 |
|
| 1269 |
if (subpass.view_count > 1) { |
| 1270 |
desc.renderTargetArrayLength = subpass.view_count; |
| 1271 |
} |
| 1272 |
|
| 1273 |
PixelFormats &pf = device_driver->get_pixel_formats(); |
| 1274 |
|
| 1275 |
uint32_t attachmentCount = 0; |
| 1276 |
for (uint32_t i = 0; i < subpass.color_references.size(); i++) { |
| 1277 |
uint32_t idx = subpass.color_references[i].attachment; |
| 1278 |
if (idx == RDD::AttachmentReference::UNUSED) { |
| 1279 |
continue; |
| 1280 |
} |
| 1281 |
|
| 1282 |
attachmentCount += 1; |
| 1283 |
MTLRenderPassColorAttachmentDescriptor *ca = desc.colorAttachments[i]; |
| 1284 |
|
| 1285 |
uint32_t resolveIdx = subpass.resolve_references.is_empty() ? RDD::AttachmentReference::UNUSED : subpass.resolve_references[i].attachment; |
| 1286 |
bool has_resolve = resolveIdx != RDD::AttachmentReference::UNUSED; |
| 1287 |
bool can_resolve = true; |
| 1288 |
if (resolveIdx != RDD::AttachmentReference::UNUSED) { |
| 1289 |
id<MTLTexture> resolve_tex = fb.get_texture(resolveIdx); |
| 1290 |
can_resolve = flags::all(pf.getCapabilities(resolve_tex.pixelFormat), kMTLFmtCapsResolve); |
| 1291 |
if (can_resolve) { |
| 1292 |
ca.resolveTexture = resolve_tex; |
| 1293 |
} else { |
| 1294 |
CRASH_NOW_MSG("unimplemented: using a texture format that is not supported for resolve"); |
| 1295 |
} |
| 1296 |
} |
| 1297 |
|
| 1298 |
MDAttachment const &attachment = pass.attachments[idx]; |
| 1299 |
|
| 1300 |
id<MTLTexture> tex = fb.get_texture(idx); |
| 1301 |
ERR_FAIL_NULL_MSG(tex, "Frame buffer color texture is null."); |
| 1302 |
|
| 1303 |
if ((attachment.type & MDAttachmentType::Color)) { |
| 1304 |
if (attachment.configureDescriptor(ca, pf, subpass, tex, render.is_rendering_entire_area, has_resolve, can_resolve, false)) { |
| 1305 |
Color clearColor = render.clear_values[idx].color; |
| 1306 |
ca.clearColor = MTLClearColorMake(clearColor.r, clearColor.g, clearColor.b, clearColor.a); |
| 1307 |
} |
| 1308 |
} |
| 1309 |
} |
| 1310 |
|
| 1311 |
if (subpass.depth_stencil_reference.attachment != RDD::AttachmentReference::UNUSED) { |
| 1312 |
attachmentCount += 1; |
| 1313 |
uint32_t idx = subpass.depth_stencil_reference.attachment; |
| 1314 |
MDAttachment const &attachment = pass.attachments[idx]; |
| 1315 |
id<MTLTexture> tex = fb.get_texture(idx); |
| 1316 |
ERR_FAIL_NULL_MSG(tex, "Frame buffer depth / stencil texture is null."); |
| 1317 |
if (attachment.type & MDAttachmentType::Depth) { |
| 1318 |
MTLRenderPassDepthAttachmentDescriptor *da = desc.depthAttachment; |
| 1319 |
if (attachment.configureDescriptor(da, pf, subpass, tex, render.is_rendering_entire_area, false, false, false)) { |
| 1320 |
da.clearDepth = render.clear_values[idx].depth; |
| 1321 |
} |
| 1322 |
} |
| 1323 |
|
| 1324 |
if (attachment.type & MDAttachmentType::Stencil) { |
| 1325 |
MTLRenderPassStencilAttachmentDescriptor *sa = desc.stencilAttachment; |
| 1326 |
if (attachment.configureDescriptor(sa, pf, subpass, tex, render.is_rendering_entire_area, false, false, true)) { |
| 1327 |
sa.clearStencil = render.clear_values[idx].stencil; |
| 1328 |
} |
| 1329 |
} |
| 1330 |
} |
| 1331 |
|
| 1332 |
desc.renderTargetWidth = MAX((NSUInteger)MIN(render.render_area.position.x + render.render_area.size.width, fb.size.width), 1u); |
| 1333 |
desc.renderTargetHeight = MAX((NSUInteger)MIN(render.render_area.position.y + render.render_area.size.height, fb.size.height), 1u); |
| 1334 |
|
| 1335 |
if (attachmentCount == 0) { |
| 1336 |
// If there are no attachments, delay the creation of the encoder, |
| 1337 |
// so we can use a matching sample count for the pipeline, by setting |
| 1338 |
// the defaultRasterSampleCount from the pipeline's sample count. |
| 1339 |
render.desc = desc; |
| 1340 |
} else { |
| 1341 |
render.encoder = [command_buffer() renderCommandEncoderWithDescriptor:desc]; |
| 1342 |
|
| 1343 |
if (!render.is_rendering_entire_area) { |
| 1344 |
_render_clear_render_area(); |
| 1345 |
} |
| 1346 |
// With a new encoder, all state is dirty. |
| 1347 |
render.dirty.set_flag(RenderState::DIRTY_ALL); |
| 1348 |
} |
| 1349 |
} |
| 1350 |
|
| 1351 |
void MDCommandBuffer::render_draw(uint32_t p_vertex_count, |
| 1352 |
uint32_t p_instance_count, |
| 1353 |
uint32_t p_base_vertex, |
| 1354 |
uint32_t p_first_instance) { |
| 1355 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 1356 |
ERR_FAIL_NULL_MSG(render.pipeline, "No pipeline set for render command buffer."); |
| 1357 |
|
| 1358 |
_render_set_dirty_state(); |
| 1359 |
|
| 1360 |
MDSubpass const &subpass = render.get_subpass(); |
| 1361 |
if (subpass.view_count > 1) { |
| 1362 |
p_instance_count *= subpass.view_count; |
| 1363 |
} |
| 1364 |
|
| 1365 |
DEV_ASSERT(render.dirty == 0); |
| 1366 |
|
| 1367 |
id<MTLRenderCommandEncoder> enc = render.encoder; |
| 1368 |
|
| 1369 |
[enc drawPrimitives:render.pipeline->raster_state.render_primitive |
| 1370 |
vertexStart:p_base_vertex |
| 1371 |
vertexCount:p_vertex_count |
| 1372 |
instanceCount:p_instance_count |
| 1373 |
baseInstance:p_first_instance]; |
| 1374 |
} |
| 1375 |
|
| 1376 |
void MDCommandBuffer::render_bind_vertex_buffers(uint32_t p_binding_count, const RDD::BufferID *p_buffers, const uint64_t *p_offsets, uint64_t p_dynamic_offsets) { |
| 1377 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 1378 |
|
| 1379 |
render.vertex_buffers.resize(p_binding_count); |
| 1380 |
render.vertex_offsets.resize(p_binding_count); |
| 1381 |
|
| 1382 |
// Are the existing buffer bindings the same? |
| 1383 |
bool same = true; |
| 1384 |
|
| 1385 |
// Reverse the buffers, as their bindings are assigned in descending order. |
| 1386 |
for (uint32_t i = 0; i < p_binding_count; i += 1) { |
| 1387 |
const RenderingDeviceDriverMetal::BufferInfo *buf_info = (const RenderingDeviceDriverMetal::BufferInfo *)p_buffers[p_binding_count - i - 1].id; |
| 1388 |
|
| 1389 |
NSUInteger dynamic_offset = 0; |
| 1390 |
if (buf_info->is_dynamic()) { |
| 1391 |
const MetalBufferDynamicInfo *dyn_buf = (const MetalBufferDynamicInfo *)buf_info; |
| 1392 |
uint64_t frame_idx = p_dynamic_offsets & 0x3; |
| 1393 |
p_dynamic_offsets >>= 2; |
| 1394 |
dynamic_offset = frame_idx * dyn_buf->size_bytes; |
| 1395 |
} |
| 1396 |
if (render.vertex_buffers[i] != buf_info->metal_buffer) { |
| 1397 |
render.vertex_buffers[i] = buf_info->metal_buffer; |
| 1398 |
same = false; |
| 1399 |
} |
| 1400 |
|
| 1401 |
render.vertex_offsets[i] = dynamic_offset + p_offsets[p_binding_count - i - 1]; |
| 1402 |
} |
| 1403 |
|
| 1404 |
if (render.encoder) { |
| 1405 |
uint32_t first = device_driver->get_metal_buffer_index_for_vertex_attribute_binding(p_binding_count - 1); |
| 1406 |
if (same) { |
| 1407 |
NSUInteger *offset_ptr = render.vertex_offsets.ptr(); |
| 1408 |
for (uint32_t i = first; i < first + p_binding_count; i++) { |
| 1409 |
[render.encoder setVertexBufferOffset:*offset_ptr atIndex:i]; |
| 1410 |
offset_ptr++; |
| 1411 |
} |
| 1412 |
} else { |
| 1413 |
[render.encoder setVertexBuffers:render.vertex_buffers.ptr() |
| 1414 |
offsets:render.vertex_offsets.ptr() |
| 1415 |
withRange:NSMakeRange(first, p_binding_count)]; |
| 1416 |
} |
| 1417 |
render.dirty.clear_flag(RenderState::DIRTY_VERTEX); |
| 1418 |
} else { |
| 1419 |
render.dirty.set_flag(RenderState::DIRTY_VERTEX); |
| 1420 |
} |
| 1421 |
} |
| 1422 |
|
| 1423 |
void MDCommandBuffer::render_bind_index_buffer(RDD::BufferID p_buffer, RDD::IndexBufferFormat p_format, uint64_t p_offset) { |
| 1424 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 1425 |
|
| 1426 |
const RenderingDeviceDriverMetal::BufferInfo *buffer = (const RenderingDeviceDriverMetal::BufferInfo *)p_buffer.id; |
| 1427 |
|
| 1428 |
render.index_buffer = buffer->metal_buffer; |
| 1429 |
render.index_type = p_format == RDD::IndexBufferFormat::INDEX_BUFFER_FORMAT_UINT16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32; |
| 1430 |
render.index_offset = p_offset; |
| 1431 |
} |
| 1432 |
|
| 1433 |
void MDCommandBuffer::render_draw_indexed(uint32_t p_index_count, |
| 1434 |
uint32_t p_instance_count, |
| 1435 |
uint32_t p_first_index, |
| 1436 |
int32_t p_vertex_offset, |
| 1437 |
uint32_t p_first_instance) { |
| 1438 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 1439 |
ERR_FAIL_NULL_MSG(render.pipeline, "No pipeline set for render command buffer."); |
| 1440 |
|
| 1441 |
_render_set_dirty_state(); |
| 1442 |
|
| 1443 |
MDSubpass const &subpass = render.get_subpass(); |
| 1444 |
if (subpass.view_count > 1) { |
| 1445 |
p_instance_count *= subpass.view_count; |
| 1446 |
} |
| 1447 |
|
| 1448 |
id<MTLRenderCommandEncoder> enc = render.encoder; |
| 1449 |
|
| 1450 |
uint32_t index_offset = render.index_offset; |
| 1451 |
index_offset += p_first_index * (render.index_type == MTLIndexTypeUInt16 ? sizeof(uint16_t) : sizeof(uint32_t)); |
| 1452 |
|
| 1453 |
[enc drawIndexedPrimitives:render.pipeline->raster_state.render_primitive |
| 1454 |
indexCount:p_index_count |
| 1455 |
indexType:render.index_type |
| 1456 |
indexBuffer:render.index_buffer |
| 1457 |
indexBufferOffset:index_offset |
| 1458 |
instanceCount:p_instance_count |
| 1459 |
baseVertex:p_vertex_offset |
| 1460 |
baseInstance:p_first_instance]; |
| 1461 |
} |
| 1462 |
|
| 1463 |
void MDCommandBuffer::render_draw_indexed_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) { |
| 1464 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 1465 |
ERR_FAIL_NULL_MSG(render.pipeline, "No pipeline set for render command buffer."); |
| 1466 |
|
| 1467 |
_render_set_dirty_state(); |
| 1468 |
|
| 1469 |
id<MTLRenderCommandEncoder> enc = render.encoder; |
| 1470 |
|
| 1471 |
const RenderingDeviceDriverMetal::BufferInfo *indirect_buffer = (const RenderingDeviceDriverMetal::BufferInfo *)p_indirect_buffer.id; |
| 1472 |
NSUInteger indirect_offset = p_offset; |
| 1473 |
|
| 1474 |
for (uint32_t i = 0; i < p_draw_count; i++) { |
| 1475 |
[enc drawIndexedPrimitives:render.pipeline->raster_state.render_primitive |
| 1476 |
indexType:render.index_type |
| 1477 |
indexBuffer:render.index_buffer |
| 1478 |
indexBufferOffset:0 |
| 1479 |
indirectBuffer:indirect_buffer->metal_buffer |
| 1480 |
indirectBufferOffset:indirect_offset]; |
| 1481 |
indirect_offset += p_stride; |
| 1482 |
} |
| 1483 |
} |
| 1484 |
|
| 1485 |
void MDCommandBuffer::render_draw_indexed_indirect_count(RDD::BufferID p_indirect_buffer, uint64_t p_offset, RDD::BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) { |
| 1486 |
ERR_FAIL_MSG("not implemented"); |
| 1487 |
} |
| 1488 |
|
| 1489 |
void MDCommandBuffer::render_draw_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) { |
| 1490 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 1491 |
ERR_FAIL_NULL_MSG(render.pipeline, "No pipeline set for render command buffer."); |
| 1492 |
|
| 1493 |
_render_set_dirty_state(); |
| 1494 |
|
| 1495 |
id<MTLRenderCommandEncoder> enc = render.encoder; |
| 1496 |
|
| 1497 |
const RenderingDeviceDriverMetal::BufferInfo *indirect_buffer = (const RenderingDeviceDriverMetal::BufferInfo *)p_indirect_buffer.id; |
| 1498 |
NSUInteger indirect_offset = p_offset; |
| 1499 |
|
| 1500 |
for (uint32_t i = 0; i < p_draw_count; i++) { |
| 1501 |
[enc drawPrimitives:render.pipeline->raster_state.render_primitive |
| 1502 |
indirectBuffer:indirect_buffer->metal_buffer |
| 1503 |
indirectBufferOffset:indirect_offset]; |
| 1504 |
indirect_offset += p_stride; |
| 1505 |
} |
| 1506 |
} |
| 1507 |
|
| 1508 |
void MDCommandBuffer::render_draw_indirect_count(RDD::BufferID p_indirect_buffer, uint64_t p_offset, RDD::BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) { |
| 1509 |
ERR_FAIL_MSG("not implemented"); |
| 1510 |
} |
| 1511 |
|
| 1512 |
void MDCommandBuffer::render_end_pass() { |
| 1513 |
DEV_ASSERT(type == MDCommandBufferStateType::Render); |
| 1514 |
|
| 1515 |
render.end_encoding(); |
| 1516 |
render.reset(); |
| 1517 |
reset(); |
| 1518 |
} |
| 1519 |
|
| 1520 |
#pragma mark - RenderState |
| 1521 |
|
| 1522 |
void MDCommandBuffer::RenderState::reset() { |
| 1523 |
pass = nil; |
| 1524 |
frameBuffer = nil; |
| 1525 |
pipeline = nil; |
| 1526 |
current_subpass = UINT32_MAX; |
| 1527 |
render_area = {}; |
| 1528 |
is_rendering_entire_area = false; |
| 1529 |
desc = nil; |
| 1530 |
encoder = nil; |
| 1531 |
index_buffer = nil; |
| 1532 |
index_type = MTLIndexTypeUInt16; |
| 1533 |
dirty = DIRTY_NONE; |
| 1534 |
uniform_sets.clear(); |
| 1535 |
dynamic_offsets = 0; |
| 1536 |
uniform_set_mask = 0; |
| 1537 |
clear_values.clear(); |
| 1538 |
viewports.clear(); |
| 1539 |
scissors.clear(); |
| 1540 |
blend_constants.reset(); |
| 1541 |
bzero(vertex_buffers.ptr(), sizeof(id<MTLBuffer> __unsafe_unretained) * vertex_buffers.size()); |
| 1542 |
vertex_buffers.clear(); |
| 1543 |
bzero(vertex_offsets.ptr(), sizeof(NSUInteger) * vertex_offsets.size()); |
| 1544 |
vertex_offsets.clear(); |
| 1545 |
resource_tracker.reset(); |
| 1546 |
} |
| 1547 |
|
| 1548 |
void MDCommandBuffer::RenderState::end_encoding() { |
| 1549 |
if (encoder == nil) { |
| 1550 |
return; |
| 1551 |
} |
| 1552 |
|
| 1553 |
[encoder endEncoding]; |
| 1554 |
encoder = nil; |
| 1555 |
} |
| 1556 |
|
| 1557 |
#pragma mark - ComputeState |
| 1558 |
|
| 1559 |
void MDCommandBuffer::ComputeState::end_encoding() { |
| 1560 |
if (encoder == nil) { |
| 1561 |
return; |
| 1562 |
} |
| 1563 |
|
| 1564 |
[encoder endEncoding]; |
| 1565 |
encoder = nil; |
| 1566 |
} |
| 1567 |
|
| 1568 |
#pragma mark - Compute |
| 1569 |
|
| 1570 |
void MDCommandBuffer::_compute_set_dirty_state() { |
| 1571 |
if (compute.dirty.has_flag(ComputeState::DIRTY_PIPELINE)) { |
| 1572 |
compute.encoder = [command_buffer() computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent]; |
| 1573 |
[compute.encoder setComputePipelineState:compute.pipeline->state]; |
| 1574 |
} |
| 1575 |
|
| 1576 |
_compute_bind_uniform_sets(); |
| 1577 |
|
| 1578 |
if (compute.dirty.has_flag(ComputeState::DIRTY_PUSH)) { |
| 1579 |
if (push_constant_binding != UINT32_MAX) { |
| 1580 |
[compute.encoder setBytes:push_constant_data |
| 1581 |
length:push_constant_data_len |
| 1582 |
atIndex:push_constant_binding]; |
| 1583 |
} |
| 1584 |
} |
| 1585 |
|
| 1586 |
compute.resource_tracker.encode(compute.encoder); |
| 1587 |
|
| 1588 |
compute.dirty.clear(); |
| 1589 |
} |
| 1590 |
|
| 1591 |
void MDCommandBuffer::_compute_bind_uniform_sets() { |
| 1592 |
DEV_ASSERT(type == MDCommandBufferStateType::Compute); |
| 1593 |
if (!compute.dirty.has_flag(ComputeState::DIRTY_UNIFORMS)) { |
| 1594 |
return; |
| 1595 |
} |
| 1596 |
|
| 1597 |
compute.dirty.clear_flag(ComputeState::DIRTY_UNIFORMS); |
| 1598 |
uint64_t set_uniforms = compute.uniform_set_mask; |
| 1599 |
compute.uniform_set_mask = 0; |
| 1600 |
|
| 1601 |
MDComputeShader *shader = compute.pipeline->shader; |
| 1602 |
const uint32_t dynamic_offsets = compute.dynamic_offsets; |
| 1603 |
|
| 1604 |
while (set_uniforms != 0) { |
| 1605 |
// Find the index of the next set bit. |
| 1606 |
uint32_t index = (uint32_t)__builtin_ctzll(set_uniforms); |
| 1607 |
// Clear the set bit. |
| 1608 |
set_uniforms &= (set_uniforms - 1); |
| 1609 |
MDUniformSet *set = compute.uniform_sets[index]; |
| 1610 |
if (set == nullptr || index >= (uint32_t)shader->sets.size()) { |
| 1611 |
continue; |
| 1612 |
} |
| 1613 |
if (shader->uses_argument_buffers) { |
| 1614 |
set->bind_uniforms_argument_buffers(shader, compute, index, dynamic_offsets, device_driver->frame_index(), device_driver->frame_count()); |
| 1615 |
} else { |
| 1616 |
DirectEncoder de(compute.encoder, binding_cache); |
| 1617 |
set->bind_uniforms_direct(shader, de, index, dynamic_offsets); |
| 1618 |
} |
| 1619 |
} |
| 1620 |
} |
| 1621 |
|
| 1622 |
void MDCommandBuffer::ComputeState::reset() { |
| 1623 |
pipeline = nil; |
| 1624 |
encoder = nil; |
| 1625 |
dirty = DIRTY_NONE; |
| 1626 |
uniform_sets.clear(); |
| 1627 |
dynamic_offsets = 0; |
| 1628 |
uniform_set_mask = 0; |
| 1629 |
resource_tracker.reset(); |
| 1630 |
} |
| 1631 |
|
| 1632 |
void MDCommandBuffer::compute_bind_uniform_sets(VectorView<RDD::UniformSetID> p_uniform_sets, RDD::ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, uint32_t p_dynamic_offsets) { |
| 1633 |
DEV_ASSERT(type == MDCommandBufferStateType::Compute); |
| 1634 |
|
| 1635 |
if (uint32_t new_size = p_first_set_index + p_set_count; compute.uniform_sets.size() < new_size) { |
| 1636 |
uint32_t s = compute.uniform_sets.size(); |
| 1637 |
compute.uniform_sets.resize(new_size); |
| 1638 |
// Set intermediate values to null. |
| 1639 |
std::fill(&compute.uniform_sets[s], compute.uniform_sets.end().operator->(), nullptr); |
| 1640 |
} |
| 1641 |
|
| 1642 |
const MDShader *shader = (const MDShader *)p_shader.id; |
| 1643 |
DynamicOffsetLayout layout = shader->dynamic_offset_layout; |
| 1644 |
|
| 1645 |
// Clear bits for sets being rebound before OR'ing new values. |
| 1646 |
// This prevents corruption when the same set is bound multiple times |
| 1647 |
// with different frame indices. |
| 1648 |
for (uint32_t i = 0; i < p_set_count && compute.dynamic_offsets != 0; i++) { |
| 1649 |
uint32_t set_index = p_first_set_index + i; |
| 1650 |
uint32_t count = layout.get_count(set_index); |
| 1651 |
if (count > 0) { |
| 1652 |
uint32_t shift = layout.get_offset_index_shift(set_index); |
| 1653 |
uint32_t mask = ((1u << (count * 4u)) - 1u) << shift; |
| 1654 |
compute.dynamic_offsets &= ~mask; |
| 1655 |
} |
| 1656 |
} |
| 1657 |
compute.dynamic_offsets |= p_dynamic_offsets; |
| 1658 |
|
| 1659 |
for (size_t i = 0; i < p_set_count; ++i) { |
| 1660 |
MDUniformSet *set = (MDUniformSet *)(p_uniform_sets[i].id); |
| 1661 |
|
| 1662 |
uint32_t index = p_first_set_index + i; |
| 1663 |
if (compute.uniform_sets[index] != set || layout.get_count(index) > 0) { |
| 1664 |
compute.dirty.set_flag(ComputeState::DIRTY_UNIFORMS); |
| 1665 |
compute.uniform_set_mask |= 1ULL << index; |
| 1666 |
compute.uniform_sets[index] = set; |
| 1667 |
} |
| 1668 |
} |
| 1669 |
} |
| 1670 |
|
| 1671 |
void MDCommandBuffer::compute_dispatch(uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) { |
| 1672 |
DEV_ASSERT(type == MDCommandBufferStateType::Compute); |
| 1673 |
|
| 1674 |
_compute_set_dirty_state(); |
| 1675 |
|
| 1676 |
MTLRegion region = MTLRegionMake3D(0, 0, 0, p_x_groups, p_y_groups, p_z_groups); |
| 1677 |
|
| 1678 |
id<MTLComputeCommandEncoder> enc = compute.encoder; |
| 1679 |
[enc dispatchThreadgroups:region.size threadsPerThreadgroup:compute.pipeline->compute_state.local]; |
| 1680 |
} |
| 1681 |
|
| 1682 |
void MDCommandBuffer::compute_dispatch_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset) { |
| 1683 |
DEV_ASSERT(type == MDCommandBufferStateType::Compute); |
| 1684 |
|
| 1685 |
_compute_set_dirty_state(); |
| 1686 |
|
| 1687 |
const RenderingDeviceDriverMetal::BufferInfo *indirectBuffer = (const RenderingDeviceDriverMetal::BufferInfo *)p_indirect_buffer.id; |
| 1688 |
|
| 1689 |
id<MTLComputeCommandEncoder> enc = compute.encoder; |
| 1690 |
[enc dispatchThreadgroupsWithIndirectBuffer:indirectBuffer->metal_buffer indirectBufferOffset:p_offset threadsPerThreadgroup:compute.pipeline->compute_state.local]; |
| 1691 |
} |
| 1692 |
|
| 1693 |
void MDCommandBuffer::reset() { |
| 1694 |
push_constant_data_len = 0; |
| 1695 |
type = MDCommandBufferStateType::None; |
| 1696 |
} |
| 1697 |
|
| 1698 |
void MDCommandBuffer::_end_compute_dispatch() { |
| 1699 |
DEV_ASSERT(type == MDCommandBufferStateType::Compute); |
| 1700 |
|
| 1701 |
compute.end_encoding(); |
| 1702 |
compute.reset(); |
| 1703 |
reset(); |
| 1704 |
} |
| 1705 |
|
| 1706 |
void MDCommandBuffer::_end_blit() { |
| 1707 |
DEV_ASSERT(type == MDCommandBufferStateType::Blit); |
| 1708 |
|
| 1709 |
[blit.encoder endEncoding]; |
| 1710 |
blit.reset(); |
| 1711 |
reset(); |
| 1712 |
} |
| 1713 |
|
| 1714 |
MDComputeShader::MDComputeShader(CharString p_name, |
| 1715 |
Vector<UniformSet> p_sets, |
| 1716 |
bool p_uses_argument_buffers, |
| 1717 |
MDLibrary *p_kernel) : |
| 1718 |
MDShader(p_name, p_sets, p_uses_argument_buffers), kernel(p_kernel) { |
| 1719 |
} |
| 1720 |
|
| 1721 |
MDRenderShader::MDRenderShader(CharString p_name, |
| 1722 |
Vector<UniformSet> p_sets, |
| 1723 |
bool p_needs_view_mask_buffer, |
| 1724 |
bool p_uses_argument_buffers, |
| 1725 |
MDLibrary *_Nonnull p_vert, MDLibrary *_Nonnull p_frag) : |
| 1726 |
MDShader(p_name, p_sets, p_uses_argument_buffers), |
| 1727 |
needs_view_mask_buffer(p_needs_view_mask_buffer), |
| 1728 |
vert(p_vert), |
| 1729 |
frag(p_frag) { |
| 1730 |
} |
| 1731 |
|
| 1732 |
void DirectEncoder::set(__unsafe_unretained id<MTLTexture> *p_textures, NSRange p_range) { |
| 1733 |
if (cache.update(p_range, p_textures)) { |
| 1734 |
switch (mode) { |
| 1735 |
case RENDER: { |
| 1736 |
id<MTLRenderCommandEncoder> __unsafe_unretained enc = (id<MTLRenderCommandEncoder>)encoder; |
| 1737 |
[enc setVertexTextures:p_textures withRange:p_range]; |
| 1738 |
[enc setFragmentTextures:p_textures withRange:p_range]; |
| 1739 |
} break; |
| 1740 |
case COMPUTE: { |
| 1741 |
id<MTLComputeCommandEncoder> __unsafe_unretained enc = (id<MTLComputeCommandEncoder>)encoder; |
| 1742 |
[enc setTextures:p_textures withRange:p_range]; |
| 1743 |
} break; |
| 1744 |
} |
| 1745 |
} |
| 1746 |
} |
| 1747 |
|
| 1748 |
void DirectEncoder::set(__unsafe_unretained id<MTLBuffer> *p_buffers, const NSUInteger *p_offsets, NSRange p_range) { |
| 1749 |
if (cache.update(p_range, p_buffers, p_offsets)) { |
| 1750 |
switch (mode) { |
| 1751 |
case RENDER: { |
| 1752 |
id<MTLRenderCommandEncoder> __unsafe_unretained enc = (id<MTLRenderCommandEncoder>)encoder; |
| 1753 |
[enc setVertexBuffers:p_buffers offsets:p_offsets withRange:p_range]; |
| 1754 |
[enc setFragmentBuffers:p_buffers offsets:p_offsets withRange:p_range]; |
| 1755 |
} break; |
| 1756 |
case COMPUTE: { |
| 1757 |
id<MTLComputeCommandEncoder> __unsafe_unretained enc = (id<MTLComputeCommandEncoder>)encoder; |
| 1758 |
[enc setBuffers:p_buffers offsets:p_offsets withRange:p_range]; |
| 1759 |
} break; |
| 1760 |
} |
| 1761 |
} |
| 1762 |
} |
| 1763 |
|
| 1764 |
void DirectEncoder::set(id<MTLBuffer> __unsafe_unretained p_buffer, const NSUInteger p_offset, uint32_t p_index) { |
| 1765 |
if (cache.update(p_buffer, p_offset, p_index)) { |
| 1766 |
switch (mode) { |
| 1767 |
case RENDER: { |
| 1768 |
id<MTLRenderCommandEncoder> __unsafe_unretained enc = (id<MTLRenderCommandEncoder>)encoder; |
| 1769 |
[enc setVertexBuffer:p_buffer offset:p_offset atIndex:p_index]; |
| 1770 |
[enc setFragmentBuffer:p_buffer offset:p_offset atIndex:p_index]; |
| 1771 |
} break; |
| 1772 |
case COMPUTE: { |
| 1773 |
id<MTLComputeCommandEncoder> __unsafe_unretained enc = (id<MTLComputeCommandEncoder>)encoder; |
| 1774 |
[enc setBuffer:p_buffer offset:p_offset atIndex:p_index]; |
| 1775 |
} break; |
| 1776 |
} |
| 1777 |
} |
| 1778 |
} |
| 1779 |
|
| 1780 |
void DirectEncoder::set(__unsafe_unretained id<MTLSamplerState> *p_samplers, NSRange p_range) { |
| 1781 |
if (cache.update(p_range, p_samplers)) { |
| 1782 |
switch (mode) { |
| 1783 |
case RENDER: { |
| 1784 |
id<MTLRenderCommandEncoder> __unsafe_unretained enc = (id<MTLRenderCommandEncoder>)encoder; |
| 1785 |
[enc setVertexSamplerStates:p_samplers withRange:p_range]; |
| 1786 |
[enc setFragmentSamplerStates:p_samplers withRange:p_range]; |
| 1787 |
} break; |
| 1788 |
case COMPUTE: { |
| 1789 |
id<MTLComputeCommandEncoder> __unsafe_unretained enc = (id<MTLComputeCommandEncoder>)encoder; |
| 1790 |
[enc setSamplerStates:p_samplers withRange:p_range]; |
| 1791 |
} break; |
| 1792 |
} |
| 1793 |
} |
| 1794 |
} |
| 1795 |
|
| 1796 |
void MDUniformSet::bind_uniforms_argument_buffers(MDShader *p_shader, MDCommandBuffer::RenderState &p_state, uint32_t p_set_index, uint32_t p_dynamic_offsets, uint32_t p_frame_idx, uint32_t p_frame_count) { |
| 1797 |
DEV_ASSERT(p_shader->uses_argument_buffers); |
| 1798 |
DEV_ASSERT(p_state.encoder != nil); |
| 1799 |
DEV_ASSERT(p_shader->dynamic_offset_layout.is_empty()); // Argument buffers do not support dynamic offsets. |
| 1800 |
|
| 1801 |
id<MTLRenderCommandEncoder> __unsafe_unretained enc = p_state.encoder; |
| 1802 |
|
| 1803 |
p_state.resource_tracker.merge_from(usage_to_resources); |
| 1804 |
|
| 1805 |
[enc setVertexBuffer:arg_buffer |
| 1806 |
offset:0 |
| 1807 |
atIndex:p_set_index]; |
| 1808 |
[enc setFragmentBuffer:arg_buffer offset:0 atIndex:p_set_index]; |
| 1809 |
} |
| 1810 |
|
| 1811 |
void MDUniformSet::bind_uniforms_direct(MDShader *p_shader, DirectEncoder p_enc, uint32_t p_set_index, uint32_t p_dynamic_offsets) { |
| 1812 |
DEV_ASSERT(!p_shader->uses_argument_buffers); |
| 1813 |
|
| 1814 |
UniformSet const &set = p_shader->sets[p_set_index]; |
| 1815 |
DynamicOffsetLayout layout = p_shader->dynamic_offset_layout; |
| 1816 |
uint32_t dynamic_index = 0; |
| 1817 |
|
| 1818 |
for (uint32_t i = 0; i < MIN(uniforms.size(), set.uniforms.size()); i++) { |
| 1819 |
RDD::BoundUniform const &uniform = uniforms[i]; |
| 1820 |
const UniformInfo &ui = set.uniforms[i]; |
| 1821 |
const UniformInfo::Indexes &indexes = ui.slot; |
| 1822 |
|
| 1823 |
uint32_t frame_idx; |
| 1824 |
if (uniform.is_dynamic()) { |
| 1825 |
uint32_t shift = layout.get_offset_index_shift(p_set_index, dynamic_index); |
| 1826 |
dynamic_index++; |
| 1827 |
frame_idx = (p_dynamic_offsets >> shift) & 0xf; |
| 1828 |
} else { |
| 1829 |
frame_idx = 0; |
| 1830 |
} |
| 1831 |
|
| 1832 |
switch (uniform.type) { |
| 1833 |
case RDD::UNIFORM_TYPE_SAMPLER: { |
| 1834 |
size_t count = uniform.ids.size(); |
| 1835 |
id<MTLSamplerState> __unsafe_unretained *objects = ALLOCA_ARRAY(id<MTLSamplerState> __unsafe_unretained, count); |
| 1836 |
for (size_t j = 0; j < count; j += 1) { |
| 1837 |
objects[j] = rid::get(uniform.ids[j].id); |
| 1838 |
} |
| 1839 |
NSRange sampler_range = NSMakeRange(indexes.sampler, count); |
| 1840 |
p_enc.set(objects, sampler_range); |
| 1841 |
} break; |
| 1842 |
case RDD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: { |
| 1843 |
size_t count = uniform.ids.size() / 2; |
| 1844 |
id<MTLTexture> __unsafe_unretained *textures = ALLOCA_ARRAY(id<MTLTexture> __unsafe_unretained, count); |
| 1845 |
id<MTLSamplerState> __unsafe_unretained *samplers = ALLOCA_ARRAY(id<MTLSamplerState> __unsafe_unretained, count); |
| 1846 |
for (uint32_t j = 0; j < count; j += 1) { |
| 1847 |
id<MTLSamplerState> sampler = rid::get(uniform.ids[j * 2 + 0]); |
| 1848 |
id<MTLTexture> texture = rid::get(uniform.ids[j * 2 + 1]); |
| 1849 |
samplers[j] = sampler; |
| 1850 |
textures[j] = texture; |
| 1851 |
} |
| 1852 |
NSRange sampler_range = NSMakeRange(indexes.sampler, count); |
| 1853 |
NSRange texture_range = NSMakeRange(indexes.texture, count); |
| 1854 |
p_enc.set(samplers, sampler_range); |
| 1855 |
p_enc.set(textures, texture_range); |
| 1856 |
} break; |
| 1857 |
case RDD::UNIFORM_TYPE_TEXTURE: { |
| 1858 |
size_t count = uniform.ids.size(); |
| 1859 |
id<MTLTexture> __unsafe_unretained *objects = ALLOCA_ARRAY(id<MTLTexture> __unsafe_unretained, count); |
| 1860 |
for (size_t j = 0; j < count; j += 1) { |
| 1861 |
id<MTLTexture> obj = rid::get(uniform.ids[j]); |
| 1862 |
objects[j] = obj; |
| 1863 |
} |
| 1864 |
NSRange texture_range = NSMakeRange(indexes.texture, count); |
| 1865 |
p_enc.set(objects, texture_range); |
| 1866 |
} break; |
| 1867 |
case RDD::UNIFORM_TYPE_IMAGE: { |
| 1868 |
size_t count = uniform.ids.size(); |
| 1869 |
id<MTLTexture> __unsafe_unretained *objects = ALLOCA_ARRAY(id<MTLTexture> __unsafe_unretained, count); |
| 1870 |
for (size_t j = 0; j < count; j += 1) { |
| 1871 |
id<MTLTexture> obj = rid::get(uniform.ids[j]); |
| 1872 |
objects[j] = obj; |
| 1873 |
} |
| 1874 |
NSRange texture_range = NSMakeRange(indexes.texture, count); |
| 1875 |
p_enc.set(objects, texture_range); |
| 1876 |
|
| 1877 |
if (indexes.buffer != UINT32_MAX) { |
| 1878 |
// Emulated atomic image access. |
| 1879 |
id<MTLBuffer> __unsafe_unretained *bufs = ALLOCA_ARRAY(id<MTLBuffer> __unsafe_unretained, count); |
| 1880 |
for (size_t j = 0; j < count; j += 1) { |
| 1881 |
id<MTLTexture> obj = rid::get(uniform.ids[j]); |
| 1882 |
id<MTLTexture> tex = obj.parentTexture ? obj.parentTexture : obj; |
| 1883 |
id<MTLBuffer> buf = tex.buffer; |
| 1884 |
bufs[j] = buf; |
| 1885 |
} |
| 1886 |
NSUInteger *offs = ALLOCA_ARRAY(NSUInteger, count); |
| 1887 |
bzero(offs, sizeof(NSUInteger) * count); |
| 1888 |
NSRange buffer_range = NSMakeRange(indexes.buffer, count); |
| 1889 |
p_enc.set(bufs, offs, buffer_range); |
| 1890 |
} |
| 1891 |
} break; |
| 1892 |
case RDD::UNIFORM_TYPE_TEXTURE_BUFFER: { |
| 1893 |
ERR_PRINT("not implemented: UNIFORM_TYPE_TEXTURE_BUFFER"); |
| 1894 |
} break; |
| 1895 |
case RDD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: { |
| 1896 |
ERR_PRINT("not implemented: UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER"); |
| 1897 |
} break; |
| 1898 |
case RDD::UNIFORM_TYPE_IMAGE_BUFFER: { |
| 1899 |
CRASH_NOW_MSG("not implemented: UNIFORM_TYPE_IMAGE_BUFFER"); |
| 1900 |
} break; |
| 1901 |
case RDD::UNIFORM_TYPE_UNIFORM_BUFFER: |
| 1902 |
case RDD::UNIFORM_TYPE_STORAGE_BUFFER: { |
| 1903 |
const RDM::BufferInfo *buf_info = (const RDM::BufferInfo *)uniform.ids[0].id; |
| 1904 |
p_enc.set(buf_info->metal_buffer, 0, indexes.buffer); |
| 1905 |
} break; |
| 1906 |
case RDD::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC: |
| 1907 |
case RDD::UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC: { |
| 1908 |
const MetalBufferDynamicInfo *buf_info = (const MetalBufferDynamicInfo *)uniform.ids[0].id; |
| 1909 |
p_enc.set(buf_info->metal_buffer, frame_idx * buf_info->size_bytes, indexes.buffer); |
| 1910 |
} break; |
| 1911 |
case RDD::UNIFORM_TYPE_INPUT_ATTACHMENT: { |
| 1912 |
size_t count = uniform.ids.size(); |
| 1913 |
id<MTLTexture> __unsafe_unretained *objects = ALLOCA_ARRAY(id<MTLTexture> __unsafe_unretained, count); |
| 1914 |
for (size_t j = 0; j < count; j += 1) { |
| 1915 |
id<MTLTexture> obj = rid::get(uniform.ids[j]); |
| 1916 |
objects[j] = obj; |
| 1917 |
} |
| 1918 |
NSRange texture_range = NSMakeRange(indexes.texture, count); |
| 1919 |
p_enc.set(objects, texture_range); |
| 1920 |
} break; |
| 1921 |
default: { |
| 1922 |
DEV_ASSERT(false); |
| 1923 |
} |
| 1924 |
} |
| 1925 |
} |
| 1926 |
} |
| 1927 |
|
| 1928 |
void MDUniformSet::bind_uniforms_argument_buffers(MDShader *p_shader, MDCommandBuffer::ComputeState &p_state, uint32_t p_set_index, uint32_t p_dynamic_offsets, uint32_t p_frame_idx, uint32_t p_frame_count) { |
| 1929 |
DEV_ASSERT(p_shader->uses_argument_buffers); |
| 1930 |
DEV_ASSERT(p_state.encoder != nil); |
| 1931 |
|
| 1932 |
id<MTLComputeCommandEncoder> enc = p_state.encoder; |
| 1933 |
|
| 1934 |
p_state.resource_tracker.merge_from(usage_to_resources); |
| 1935 |
[enc setBuffer:arg_buffer |
| 1936 |
offset:0 |
| 1937 |
atIndex:p_set_index]; |
| 1938 |
} |
| 1939 |
|
| 1940 |
MTLFmtCaps MDSubpass::getRequiredFmtCapsForAttachmentAt(uint32_t p_index) const { |
| 1941 |
MTLFmtCaps caps = kMTLFmtCapsNone; |
| 1942 |
|
| 1943 |
for (RDD::AttachmentReference const &ar : input_references) { |
| 1944 |
if (ar.attachment == p_index) { |
| 1945 |
flags::set(caps, kMTLFmtCapsRead); |
| 1946 |
break; |
| 1947 |
} |
| 1948 |
} |
| 1949 |
|
| 1950 |
for (RDD::AttachmentReference const &ar : color_references) { |
| 1951 |
if (ar.attachment == p_index) { |
| 1952 |
flags::set(caps, kMTLFmtCapsColorAtt); |
| 1953 |
break; |
| 1954 |
} |
| 1955 |
} |
| 1956 |
|
| 1957 |
for (RDD::AttachmentReference const &ar : resolve_references) { |
| 1958 |
if (ar.attachment == p_index) { |
| 1959 |
flags::set(caps, kMTLFmtCapsResolve); |
| 1960 |
break; |
| 1961 |
} |
| 1962 |
} |
| 1963 |
|
| 1964 |
if (depth_stencil_reference.attachment == p_index) { |
| 1965 |
flags::set(caps, kMTLFmtCapsDSAtt); |
| 1966 |
} |
| 1967 |
|
| 1968 |
return caps; |
| 1969 |
} |
| 1970 |
|
| 1971 |
void MDAttachment::linkToSubpass(const MDRenderPass &p_pass) { |
| 1972 |
firstUseSubpassIndex = UINT32_MAX; |
| 1973 |
lastUseSubpassIndex = 0; |
| 1974 |
|
| 1975 |
for (MDSubpass const &subpass : p_pass.subpasses) { |
| 1976 |
MTLFmtCaps reqCaps = subpass.getRequiredFmtCapsForAttachmentAt(index); |
| 1977 |
if (reqCaps) { |
| 1978 |
firstUseSubpassIndex = MIN(subpass.subpass_index, firstUseSubpassIndex); |
| 1979 |
lastUseSubpassIndex = MAX(subpass.subpass_index, lastUseSubpassIndex); |
| 1980 |
} |
| 1981 |
} |
| 1982 |
} |
| 1983 |
|
| 1984 |
MTLStoreAction MDAttachment::getMTLStoreAction(MDSubpass const &p_subpass, |
| 1985 |
bool p_is_rendering_entire_area, |
| 1986 |
bool p_has_resolve, |
| 1987 |
bool p_can_resolve, |
| 1988 |
bool p_is_stencil) const { |
| 1989 |
if (!p_is_rendering_entire_area || !isLastUseOf(p_subpass)) { |
| 1990 |
return p_has_resolve && p_can_resolve ? MTLStoreActionStoreAndMultisampleResolve : MTLStoreActionStore; |
| 1991 |
} |
| 1992 |
|
| 1993 |
switch (p_is_stencil ? stencilStoreAction : storeAction) { |
| 1994 |
case MTLStoreActionStore: |
| 1995 |
return p_has_resolve && p_can_resolve ? MTLStoreActionStoreAndMultisampleResolve : MTLStoreActionStore; |
| 1996 |
case MTLStoreActionDontCare: |
| 1997 |
return p_has_resolve ? (p_can_resolve ? MTLStoreActionMultisampleResolve : MTLStoreActionStore) : MTLStoreActionDontCare; |
| 1998 |
|
| 1999 |
default: |
| 2000 |
return MTLStoreActionStore; |
| 2001 |
} |
| 2002 |
} |
| 2003 |
|
| 2004 |
bool MDAttachment::configureDescriptor(MTLRenderPassAttachmentDescriptor *p_desc, |
| 2005 |
PixelFormats &p_pf, |
| 2006 |
MDSubpass const &p_subpass, |
| 2007 |
id<MTLTexture> p_attachment, |
| 2008 |
bool p_is_rendering_entire_area, |
| 2009 |
bool p_has_resolve, |
| 2010 |
bool p_can_resolve, |
| 2011 |
bool p_is_stencil) const { |
| 2012 |
p_desc.texture = p_attachment; |
| 2013 |
|
| 2014 |
MTLLoadAction load; |
| 2015 |
if (!p_is_rendering_entire_area || !isFirstUseOf(p_subpass)) { |
| 2016 |
load = MTLLoadActionLoad; |
| 2017 |
} else { |
| 2018 |
load = p_is_stencil ? stencilLoadAction : loadAction; |
| 2019 |
} |
| 2020 |
|
| 2021 |
p_desc.loadAction = load; |
| 2022 |
|
| 2023 |
MTLPixelFormat mtlFmt = p_attachment.pixelFormat; |
| 2024 |
bool isDepthFormat = p_pf.isDepthFormat(mtlFmt); |
| 2025 |
bool isStencilFormat = p_pf.isStencilFormat(mtlFmt); |
| 2026 |
if (isStencilFormat && !p_is_stencil && !isDepthFormat) { |
| 2027 |
p_desc.storeAction = MTLStoreActionDontCare; |
| 2028 |
} else { |
| 2029 |
p_desc.storeAction = getMTLStoreAction(p_subpass, p_is_rendering_entire_area, p_has_resolve, p_can_resolve, p_is_stencil); |
| 2030 |
} |
| 2031 |
|
| 2032 |
return load == MTLLoadActionClear; |
| 2033 |
} |
| 2034 |
|
| 2035 |
bool MDAttachment::shouldClear(const MDSubpass &p_subpass, bool p_is_stencil) const { |
| 2036 |
// If the subpass is not the first subpass to use this attachment, don't clear this attachment. |
| 2037 |
if (p_subpass.subpass_index != firstUseSubpassIndex) { |
| 2038 |
return false; |
| 2039 |
} |
| 2040 |
return (p_is_stencil ? stencilLoadAction : loadAction) == MTLLoadActionClear; |
| 2041 |
} |
| 2042 |
|
| 2043 |
MDRenderPass::MDRenderPass(Vector<MDAttachment> &p_attachments, Vector<MDSubpass> &p_subpasses) : |
| 2044 |
attachments(p_attachments), subpasses(p_subpasses) { |
| 2045 |
for (MDAttachment &att : attachments) { |
| 2046 |
att.linkToSubpass(*this); |
| 2047 |
} |
| 2048 |
} |
| 2049 |
|
| 2050 |
#pragma mark - Resource Factory |
| 2051 |
|
| 2052 |
id<MTLFunction> MDResourceFactory::new_func(NSString *p_source, NSString *p_name, NSError **p_error) { |
| 2053 |
@autoreleasepool { |
| 2054 |
NSError *err = nil; |
| 2055 |
MTLCompileOptions *options = [MTLCompileOptions new]; |
| 2056 |
id<MTLDevice> device = device_driver->get_device(); |
| 2057 |
id<MTLLibrary> mtlLib = [device newLibraryWithSource:p_source |
| 2058 |
options:options |
| 2059 |
error:&err]; |
| 2060 |
if (err) { |
| 2061 |
if (p_error != nil) { |
| 2062 |
*p_error = err; |
| 2063 |
} |
| 2064 |
} |
| 2065 |
return [mtlLib newFunctionWithName:p_name]; |
| 2066 |
} |
| 2067 |
} |
| 2068 |
|
| 2069 |
id<MTLFunction> MDResourceFactory::new_clear_vert_func(ClearAttKey &p_key) { |
| 2070 |
@autoreleasepool { |
| 2071 |
NSString *msl = [NSString stringWithFormat:@R"( |
| 2072 |
#include <metal_stdlib> |
| 2073 |
using namespace metal; |
| 2074 |
|
| 2075 |
typedef struct { |
| 2076 |
float4 a_position [[attribute(0)]]; |
| 2077 |
} AttributesPos; |
| 2078 |
|
| 2079 |
typedef struct { |
| 2080 |
float4 colors[9]; |
| 2081 |
} ClearColorsIn; |
| 2082 |
|
| 2083 |
typedef struct { |
| 2084 |
float4 v_position [[position]]; |
| 2085 |
uint layer%s; |
| 2086 |
} VaryingsPos; |
| 2087 |
|
| 2088 |
vertex VaryingsPos vertClear(AttributesPos attributes [[stage_in]], constant ClearColorsIn& ccIn [[buffer(0)]]) { |
| 2089 |
VaryingsPos varyings; |
| 2090 |
varyings.v_position = float4(attributes.a_position.x, -attributes.a_position.y, ccIn.colors[%d].r, 1.0); |
| 2091 |
varyings.layer = uint(attributes.a_position.w); |
| 2092 |
return varyings; |
| 2093 |
} |
| 2094 |
)", p_key.is_layered_rendering_enabled() ? " [[render_target_array_index]]" : "", ClearAttKey::DEPTH_INDEX]; |
| 2095 |
|
| 2096 |
return new_func(msl, @"vertClear", nil); |
| 2097 |
} |
| 2098 |
} |
| 2099 |
|
| 2100 |
id<MTLFunction> MDResourceFactory::new_clear_frag_func(ClearAttKey &p_key) { |
| 2101 |
@autoreleasepool { |
| 2102 |
NSMutableString *msl = [NSMutableString stringWithCapacity:2048]; |
| 2103 |
|
| 2104 |
[msl appendFormat:@R"( |
| 2105 |
#include <metal_stdlib> |
| 2106 |
using namespace metal; |
| 2107 |
|
| 2108 |
typedef struct { |
| 2109 |
float4 v_position [[position]]; |
| 2110 |
} VaryingsPos; |
| 2111 |
|
| 2112 |
typedef struct { |
| 2113 |
float4 colors[9]; |
| 2114 |
} ClearColorsIn; |
| 2115 |
|
| 2116 |
typedef struct { |
| 2117 |
)"]; |
| 2118 |
|
| 2119 |
for (uint32_t caIdx = 0; caIdx < ClearAttKey::COLOR_COUNT; caIdx++) { |
| 2120 |
if (p_key.is_enabled(caIdx)) { |
| 2121 |
NSString *typeStr = get_format_type_string((MTLPixelFormat)p_key.pixel_formats[caIdx]); |
| 2122 |
[msl appendFormat:@" %@4 color%u [[color(%u)]];\n", typeStr, caIdx, caIdx]; |
| 2123 |
} |
| 2124 |
} |
| 2125 |
[msl appendFormat:@R"(} ClearColorsOut; |
| 2126 |
|
| 2127 |
fragment ClearColorsOut fragClear(VaryingsPos varyings [[stage_in]], constant ClearColorsIn& ccIn [[buffer(0)]]) { |
| 2128 |
|
| 2129 |
ClearColorsOut ccOut; |
| 2130 |
)"]; |
| 2131 |
for (uint32_t caIdx = 0; caIdx < ClearAttKey::COLOR_COUNT; caIdx++) { |
| 2132 |
if (p_key.is_enabled(caIdx)) { |
| 2133 |
NSString *typeStr = get_format_type_string((MTLPixelFormat)p_key.pixel_formats[caIdx]); |
| 2134 |
[msl appendFormat:@" ccOut.color%u = %@4(ccIn.colors[%u]);\n", caIdx, typeStr, caIdx]; |
| 2135 |
} |
| 2136 |
} |
| 2137 |
[msl appendString:@R"( return ccOut; |
| 2138 |
})"]; |
| 2139 |
|
| 2140 |
return new_func(msl, @"fragClear", nil); |
| 2141 |
} |
| 2142 |
} |
| 2143 |
|
| 2144 |
NSString *MDResourceFactory::get_format_type_string(MTLPixelFormat p_fmt) { |
| 2145 |
switch (device_driver->get_pixel_formats().getFormatType(p_fmt)) { |
| 2146 |
case MTLFormatType::ColorInt8: |
| 2147 |
case MTLFormatType::ColorInt16: |
| 2148 |
return @"short"; |
| 2149 |
case MTLFormatType::ColorUInt8: |
| 2150 |
case MTLFormatType::ColorUInt16: |
| 2151 |
return @"ushort"; |
| 2152 |
case MTLFormatType::ColorInt32: |
| 2153 |
return @"int"; |
| 2154 |
case MTLFormatType::ColorUInt32: |
| 2155 |
return @"uint"; |
| 2156 |
case MTLFormatType::ColorHalf: |
| 2157 |
return @"half"; |
| 2158 |
case MTLFormatType::ColorFloat: |
| 2159 |
case MTLFormatType::DepthStencil: |
| 2160 |
case MTLFormatType::Compressed: |
| 2161 |
return @"float"; |
| 2162 |
case MTLFormatType::None: |
| 2163 |
return @"unexpected_MTLPixelFormatInvalid"; |
| 2164 |
} |
| 2165 |
} |
| 2166 |
|
| 2167 |
id<MTLDepthStencilState> MDResourceFactory::new_depth_stencil_state(bool p_use_depth, bool p_use_stencil) { |
| 2168 |
MTLDepthStencilDescriptor *dsDesc = [MTLDepthStencilDescriptor new]; |
| 2169 |
dsDesc.depthCompareFunction = MTLCompareFunctionAlways; |
| 2170 |
dsDesc.depthWriteEnabled = p_use_depth; |
| 2171 |
|
| 2172 |
if (p_use_stencil) { |
| 2173 |
MTLStencilDescriptor *sDesc = [MTLStencilDescriptor new]; |
| 2174 |
sDesc.stencilCompareFunction = MTLCompareFunctionAlways; |
| 2175 |
sDesc.stencilFailureOperation = MTLStencilOperationReplace; |
| 2176 |
sDesc.depthFailureOperation = MTLStencilOperationReplace; |
| 2177 |
sDesc.depthStencilPassOperation = MTLStencilOperationReplace; |
| 2178 |
|
| 2179 |
dsDesc.frontFaceStencil = sDesc; |
| 2180 |
dsDesc.backFaceStencil = sDesc; |
| 2181 |
} else { |
| 2182 |
dsDesc.frontFaceStencil = nil; |
| 2183 |
dsDesc.backFaceStencil = nil; |
| 2184 |
} |
| 2185 |
|
| 2186 |
return [device_driver->get_device() newDepthStencilStateWithDescriptor:dsDesc]; |
| 2187 |
} |
| 2188 |
|
| 2189 |
id<MTLRenderPipelineState> MDResourceFactory::new_clear_pipeline_state(ClearAttKey &p_key, NSError **p_error) { |
| 2190 |
PixelFormats &pixFmts = device_driver->get_pixel_formats(); |
| 2191 |
|
| 2192 |
id<MTLFunction> vtxFunc = new_clear_vert_func(p_key); |
| 2193 |
id<MTLFunction> fragFunc = new_clear_frag_func(p_key); |
| 2194 |
MTLRenderPipelineDescriptor *plDesc = [MTLRenderPipelineDescriptor new]; |
| 2195 |
plDesc.label = @"ClearRenderAttachments"; |
| 2196 |
plDesc.vertexFunction = vtxFunc; |
| 2197 |
plDesc.fragmentFunction = fragFunc; |
| 2198 |
plDesc.rasterSampleCount = p_key.sample_count; |
| 2199 |
plDesc.inputPrimitiveTopology = MTLPrimitiveTopologyClassTriangle; |
| 2200 |
|
| 2201 |
for (uint32_t caIdx = 0; caIdx < ClearAttKey::COLOR_COUNT; caIdx++) { |
| 2202 |
MTLRenderPipelineColorAttachmentDescriptor *colorDesc = plDesc.colorAttachments[caIdx]; |
| 2203 |
colorDesc.pixelFormat = (MTLPixelFormat)p_key.pixel_formats[caIdx]; |
| 2204 |
colorDesc.writeMask = p_key.is_enabled(caIdx) ? MTLColorWriteMaskAll : MTLColorWriteMaskNone; |
| 2205 |
} |
| 2206 |
|
| 2207 |
MTLPixelFormat mtlDepthFormat = p_key.depth_format(); |
| 2208 |
if (pixFmts.isDepthFormat(mtlDepthFormat)) { |
| 2209 |
plDesc.depthAttachmentPixelFormat = mtlDepthFormat; |
| 2210 |
} |
| 2211 |
|
| 2212 |
MTLPixelFormat mtlStencilFormat = p_key.stencil_format(); |
| 2213 |
if (pixFmts.isStencilFormat(mtlStencilFormat)) { |
| 2214 |
plDesc.stencilAttachmentPixelFormat = mtlStencilFormat; |
| 2215 |
} |
| 2216 |
|
| 2217 |
MTLVertexDescriptor *vtxDesc = plDesc.vertexDescriptor; |
| 2218 |
|
| 2219 |
// Vertex attribute descriptors. |
| 2220 |
MTLVertexAttributeDescriptorArray *vaDescArray = vtxDesc.attributes; |
| 2221 |
MTLVertexAttributeDescriptor *vaDesc; |
| 2222 |
NSUInteger vtxBuffIdx = device_driver->get_metal_buffer_index_for_vertex_attribute_binding(VERT_CONTENT_BUFFER_INDEX); |
| 2223 |
NSUInteger vtxStride = 0; |
| 2224 |
|
| 2225 |
// Vertex location. |
| 2226 |
vaDesc = vaDescArray[0]; |
| 2227 |
vaDesc.format = MTLVertexFormatFloat4; |
| 2228 |
vaDesc.bufferIndex = vtxBuffIdx; |
| 2229 |
vaDesc.offset = vtxStride; |
| 2230 |
vtxStride += sizeof(simd::float4); |
| 2231 |
|
| 2232 |
// Vertex attribute buffer. |
| 2233 |
MTLVertexBufferLayoutDescriptorArray *vbDescArray = vtxDesc.layouts; |
| 2234 |
MTLVertexBufferLayoutDescriptor *vbDesc = vbDescArray[vtxBuffIdx]; |
| 2235 |
vbDesc.stepFunction = MTLVertexStepFunctionPerVertex; |
| 2236 |
vbDesc.stepRate = 1; |
| 2237 |
vbDesc.stride = vtxStride; |
| 2238 |
|
| 2239 |
return [device_driver->get_device() newRenderPipelineStateWithDescriptor:plDesc error:p_error]; |
| 2240 |
} |
| 2241 |
|
| 2242 |
id<MTLRenderPipelineState> MDResourceCache::get_clear_render_pipeline_state(ClearAttKey &p_key, NSError **p_error) { |
| 2243 |
HashMap::ConstIterator it = clear_states.find(p_key); |
| 2244 |
if (it != clear_states.end()) { |
| 2245 |
return it->value; |
| 2246 |
} |
| 2247 |
|
| 2248 |
id<MTLRenderPipelineState> state = resource_factory->new_clear_pipeline_state(p_key, p_error); |
| 2249 |
clear_states[p_key] = state; |
| 2250 |
return state; |
| 2251 |
} |
| 2252 |
|
| 2253 |
id<MTLDepthStencilState> MDResourceCache::get_depth_stencil_state(bool p_use_depth, bool p_use_stencil) { |
| 2254 |
id<MTLDepthStencilState> __strong *val; |
| 2255 |
if (p_use_depth && p_use_stencil) { |
| 2256 |
val = &clear_depth_stencil_state.all; |
| 2257 |
} else if (p_use_depth) { |
| 2258 |
val = &clear_depth_stencil_state.depth_only; |
| 2259 |
} else if (p_use_stencil) { |
| 2260 |
val = &clear_depth_stencil_state.stencil_only; |
| 2261 |
} else { |
| 2262 |
val = &clear_depth_stencil_state.none; |
| 2263 |
} |
| 2264 |
DEV_ASSERT(val != nullptr); |
| 2265 |
|
| 2266 |
if (*val == nil) { |
| 2267 |
*val = resource_factory->new_depth_stencil_state(p_use_depth, p_use_stencil); |
| 2268 |
} |
| 2269 |
return *val; |
| 2270 |
} |
| 2271 |
|
| 2272 |
static const char *SHADER_STAGE_NAMES[] = { |
| 2273 |
"vert", // [RD::SHADER_STAGE_VERTEX] |
| 2274 |
"frag", // [RD::SHADER_STAGE_FRAGMENT] |
| 2275 |
"tess_ctrl", // [RD::SHADER_STAGE_TESSELATION_CONTROL] |
| 2276 |
"tess_eval", // [RD::SHADER_STAGE_TESSELATION_EVALUATION] |
| 2277 |
"comp", // [RD::SHADER_STAGE_COMPUTE] |
| 2278 |
}; |
| 2279 |
|
| 2280 |
void ShaderCacheEntry::notify_free() const { |
| 2281 |
owner.shader_cache_free_entry(key); |
| 2282 |
} |
| 2283 |
|
| 2284 |
@interface MDLibrary () |
| 2285 |
- (instancetype)initWithCacheEntry:(ShaderCacheEntry *)entry |
| 2286 |
#ifdef DEV_ENABLED |
| 2287 |
source:(NSString *)source; |
| 2288 |
#endif |
| 2289 |
; |
| 2290 |
@end |
| 2291 |
|
| 2292 |
/// Loads the MTLLibrary when the library is first accessed. |
| 2293 |
@interface MDLazyLibrary : MDLibrary { |
| 2294 |
id<MTLLibrary> _library; |
| 2295 |
NSError *_error; |
| 2296 |
std::shared_mutex _mu; |
| 2297 |
bool _loaded; |
| 2298 |
id<MTLDevice> _device; |
| 2299 |
NSString *_source; |
| 2300 |
MTLCompileOptions *_options; |
| 2301 |
} |
| 2302 |
- (instancetype)initWithCacheEntry:(ShaderCacheEntry *)entry |
| 2303 |
device:(id<MTLDevice>)device |
| 2304 |
source:(NSString *)source |
| 2305 |
options:(MTLCompileOptions *)options; |
| 2306 |
@end |
| 2307 |
|
| 2308 |
/// Loads the MTLLibrary immediately on initialization, using an asynchronous API. |
| 2309 |
@interface MDImmediateLibrary : MDLibrary { |
| 2310 |
id<MTLLibrary> _library; |
| 2311 |
NSError *_error; |
| 2312 |
std::mutex _cv_mutex; |
| 2313 |
std::condition_variable _cv; |
| 2314 |
std::atomic<bool> _complete; |
| 2315 |
bool _ready; |
| 2316 |
} |
| 2317 |
- (instancetype)initWithCacheEntry:(ShaderCacheEntry *)entry |
| 2318 |
device:(id<MTLDevice>)device |
| 2319 |
source:(NSString *)source |
| 2320 |
options:(MTLCompileOptions *)options; |
| 2321 |
@end |
| 2322 |
|
| 2323 |
@interface MDBinaryLibrary : MDLibrary { |
| 2324 |
id<MTLLibrary> _library; |
| 2325 |
NSError *_error; |
| 2326 |
} |
| 2327 |
- (instancetype)initWithCacheEntry:(ShaderCacheEntry *)entry |
| 2328 |
device:(id<MTLDevice>)device |
| 2329 |
#ifdef DEV_ENABLED |
| 2330 |
source:(NSString *)source |
| 2331 |
#endif |
| 2332 |
data:(dispatch_data_t)data; |
| 2333 |
@end |
| 2334 |
|
| 2335 |
@implementation MDLibrary |
| 2336 |
|
| 2337 |
+ (instancetype)newLibraryWithCacheEntry:(ShaderCacheEntry *)entry |
| 2338 |
device:(id<MTLDevice>)device |
| 2339 |
source:(NSString *)source |
| 2340 |
options:(MTLCompileOptions *)options |
| 2341 |
strategy:(ShaderLoadStrategy)strategy { |
| 2342 |
switch (strategy) { |
| 2343 |
case ShaderLoadStrategy::IMMEDIATE: |
| 2344 |
[[fallthrough]]; |
| 2345 |
default: |
| 2346 |
return [[MDImmediateLibrary alloc] initWithCacheEntry:entry device:device source:source options:options]; |
| 2347 |
case ShaderLoadStrategy::LAZY: |
| 2348 |
return [[MDLazyLibrary alloc] initWithCacheEntry:entry device:device source:source options:options]; |
| 2349 |
} |
| 2350 |
} |
| 2351 |
|
| 2352 |
+ (instancetype)newLibraryWithCacheEntry:(ShaderCacheEntry *)entry |
| 2353 |
device:(id<MTLDevice>)device |
| 2354 |
#ifdef DEV_ENABLED |
| 2355 |
source:(NSString *)source |
| 2356 |
#endif |
| 2357 |
data:(dispatch_data_t)data { |
| 2358 |
return [[MDBinaryLibrary alloc] initWithCacheEntry:entry |
| 2359 |
device:device |
| 2360 |
#ifdef DEV_ENABLED |
| 2361 |
source:source |
| 2362 |
#endif |
| 2363 |
data:data]; |
| 2364 |
} |
| 2365 |
|
| 2366 |
#ifdef DEV_ENABLED |
| 2367 |
- (NSString *)originalSource { |
| 2368 |
return _original_source; |
| 2369 |
} |
| 2370 |
#endif |
| 2371 |
|
| 2372 |
- (id<MTLLibrary>)library { |
| 2373 |
CRASH_NOW_MSG("Not implemented"); |
| 2374 |
return nil; |
| 2375 |
} |
| 2376 |
|
| 2377 |
- (NSError *)error { |
| 2378 |
CRASH_NOW_MSG("Not implemented"); |
| 2379 |
return nil; |
| 2380 |
} |
| 2381 |
|
| 2382 |
- (void)setLabel:(NSString *)label { |
| 2383 |
} |
| 2384 |
|
| 2385 |
- (instancetype)initWithCacheEntry:(ShaderCacheEntry *)entry |
| 2386 |
#ifdef DEV_ENABLED |
| 2387 |
source:(NSString *)source |
| 2388 |
#endif |
| 2389 |
{ |
| 2390 |
self = [super init]; |
| 2391 |
_entry = entry; |
| 2392 |
_entry->library = self; |
| 2393 |
#ifdef DEV_ENABLED |
| 2394 |
_original_source = source; |
| 2395 |
#endif |
| 2396 |
return self; |
| 2397 |
} |
| 2398 |
|
| 2399 |
- (void)dealloc { |
| 2400 |
_entry->notify_free(); |
| 2401 |
} |
| 2402 |
|
| 2403 |
@end |
| 2404 |
|
| 2405 |
@implementation MDImmediateLibrary |
| 2406 |
|
| 2407 |
- (instancetype)initWithCacheEntry:(ShaderCacheEntry *)entry |
| 2408 |
device:(id<MTLDevice>)device |
| 2409 |
source:(NSString *)source |
| 2410 |
options:(MTLCompileOptions *)options { |
| 2411 |
self = [super initWithCacheEntry:entry |
| 2412 |
#ifdef DEV_ENABLED |
| 2413 |
source:source |
| 2414 |
#endif |
| 2415 |
]; |
| 2416 |
_complete = false; |
| 2417 |
_ready = false; |
| 2418 |
|
| 2419 |
__block os_signpost_id_t compile_id = (os_signpost_id_t)(uintptr_t)self; |
| 2420 |
os_signpost_interval_begin(LOG_INTERVALS, compile_id, "shader_compile", |
| 2421 |
"shader_name=%{public}s stage=%{public}s hash=%X", |
| 2422 |
entry->name.get_data(), SHADER_STAGE_NAMES[entry->stage], entry->key.short_sha()); |
| 2423 |
|
| 2424 |
[device newLibraryWithSource:source |
| 2425 |
options:options |
| 2426 |
completionHandler:^(id<MTLLibrary> library, NSError *error) { |
| 2427 |
os_signpost_interval_end(LOG_INTERVALS, compile_id, "shader_compile"); |
| 2428 |
self->_library = library; |
| 2429 |
self->_error = error; |
| 2430 |
if (error) { |
| 2431 |
ERR_PRINT(vformat(U"Error compiling shader %s: %s", entry->name.get_data(), error.localizedDescription.UTF8String)); |
| 2432 |
} |
| 2433 |
|
| 2434 |
{ |
| 2435 |
std::lock_guard<std::mutex> lock(self->_cv_mutex); |
| 2436 |
_ready = true; |
| 2437 |
} |
| 2438 |
_cv.notify_all(); |
| 2439 |
_complete = true; |
| 2440 |
}]; |
| 2441 |
return self; |
| 2442 |
} |
| 2443 |
|
| 2444 |
- (id<MTLLibrary>)library { |
| 2445 |
if (!_complete) { |
| 2446 |
std::unique_lock<std::mutex> lock(_cv_mutex); |
| 2447 |
_cv.wait(lock, [&] { return _ready; }); |
| 2448 |
} |
| 2449 |
return _library; |
| 2450 |
} |
| 2451 |
|
| 2452 |
- (NSError *)error { |
| 2453 |
if (!_complete) { |
| 2454 |
std::unique_lock<std::mutex> lock(_cv_mutex); |
| 2455 |
_cv.wait(lock, [&] { return _ready; }); |
| 2456 |
} |
| 2457 |
return _error; |
| 2458 |
} |
| 2459 |
|
| 2460 |
@end |
| 2461 |
|
| 2462 |
@implementation MDLazyLibrary |
| 2463 |
- (instancetype)initWithCacheEntry:(ShaderCacheEntry *)entry |
| 2464 |
device:(id<MTLDevice>)device |
| 2465 |
source:(NSString *)source |
| 2466 |
options:(MTLCompileOptions *)options { |
| 2467 |
self = [super initWithCacheEntry:entry |
| 2468 |
#ifdef DEV_ENABLED |
| 2469 |
source:source |
| 2470 |
#endif |
| 2471 |
]; |
| 2472 |
_device = device; |
| 2473 |
_source = source; |
| 2474 |
_options = options; |
| 2475 |
|
| 2476 |
return self; |
| 2477 |
} |
| 2478 |
|
| 2479 |
- (void)load { |
| 2480 |
{ |
| 2481 |
std::shared_lock<std::shared_mutex> lock(_mu); |
| 2482 |
if (_loaded) { |
| 2483 |
return; |
| 2484 |
} |
| 2485 |
} |
| 2486 |
|
| 2487 |
std::unique_lock<std::shared_mutex> lock(_mu); |
| 2488 |
if (_loaded) { |
| 2489 |
return; |
| 2490 |
} |
| 2491 |
|
| 2492 |
__block os_signpost_id_t compile_id = (os_signpost_id_t)(uintptr_t)self; |
| 2493 |
os_signpost_interval_begin(LOG_INTERVALS, compile_id, "shader_compile", |
| 2494 |
"shader_name=%{public}s stage=%{public}s hash=%X", |
| 2495 |
_entry->name.get_data(), SHADER_STAGE_NAMES[_entry->stage], _entry->key.short_sha()); |
| 2496 |
NSError *error; |
| 2497 |
_library = [_device newLibraryWithSource:_source options:_options error:&error]; |
| 2498 |
os_signpost_interval_end(LOG_INTERVALS, compile_id, "shader_compile"); |
| 2499 |
_device = nil; |
| 2500 |
_source = nil; |
| 2501 |
_options = nil; |
| 2502 |
_loaded = true; |
| 2503 |
} |
| 2504 |
|
| 2505 |
- (id<MTLLibrary>)library { |
| 2506 |
[self load]; |
| 2507 |
return _library; |
| 2508 |
} |
| 2509 |
|
| 2510 |
- (NSError *)error { |
| 2511 |
[self load]; |
| 2512 |
return _error; |
| 2513 |
} |
| 2514 |
|
| 2515 |
@end |
| 2516 |
|
| 2517 |
@implementation MDBinaryLibrary |
| 2518 |
|
| 2519 |
- (instancetype)initWithCacheEntry:(ShaderCacheEntry *)entry |
| 2520 |
device:(id<MTLDevice>)device |
| 2521 |
#ifdef DEV_ENABLED |
| 2522 |
source:(NSString *)source |
| 2523 |
#endif |
| 2524 |
data:(dispatch_data_t)data { |
| 2525 |
self = [super initWithCacheEntry:entry |
| 2526 |
#ifdef DEV_ENABLED |
| 2527 |
source:source |
| 2528 |
#endif |
| 2529 |
]; |
| 2530 |
NSError *error = nil; |
| 2531 |
_library = [device newLibraryWithData:data error:&error]; |
| 2532 |
if (error != nil) { |
| 2533 |
_error = error; |
| 2534 |
NSString *desc = [error description]; |
| 2535 |
ERR_PRINT(vformat("Unable to load shader library: %s", desc.UTF8String)); |
| 2536 |
} |
| 2537 |
return self; |
| 2538 |
} |
| 2539 |
|
| 2540 |
- (id<MTLLibrary>)library { |
| 2541 |
return _library; |
| 2542 |
} |
| 2543 |
|
| 2544 |
- (NSError *)error { |
| 2545 |
return _error; |
| 2546 |
} |
| 2547 |
|
| 2548 |
@end |