Browse Source

Merge pull request #99905 from stuartcarnie/fix_external_texture

Metal: Ensure `texture_create_from_extension` returns correct pixel format
Thaddeus Crews 9 months ago
parent
commit
70dae45dd0
1 changed files with 19 additions and 5 deletions
  1. 19 5
      drivers/metal/rendering_device_driver_metal.mm

+ 19 - 5
drivers/metal/rendering_device_driver_metal.mm

@@ -358,11 +358,25 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create(const TextureFormat &p
 }
 
 RDD::TextureID RenderingDeviceDriverMetal::texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil) {
-	id<MTLTexture> obj = (__bridge id<MTLTexture>)(void *)(uintptr_t)p_native_texture;
-
-	// We only need to create a RDD::TextureID for an existing, natively-provided texture.
-
-	return rid::make(obj);
+	id<MTLTexture> res = (__bridge id<MTLTexture>)(void *)(uintptr_t)p_native_texture;
+
+	// If the requested format is different, we need to create a view.
+	MTLPixelFormat format = pixel_formats->getMTLPixelFormat(p_format);
+	if (res.pixelFormat != format) {
+		MTLTextureSwizzleChannels swizzle = MTLTextureSwizzleChannelsMake(
+				MTLTextureSwizzleRed,
+				MTLTextureSwizzleGreen,
+				MTLTextureSwizzleBlue,
+				MTLTextureSwizzleAlpha);
+		res = [res newTextureViewWithPixelFormat:format
+									 textureType:res.textureType
+										  levels:NSMakeRange(0, res.mipmapLevelCount)
+										  slices:NSMakeRange(0, p_array_layers)
+										 swizzle:swizzle];
+		ERR_FAIL_NULL_V_MSG(res, TextureID(), "Unable to create texture view.");
+	}
+
+	return rid::make(res);
 }
 
 RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared(TextureID p_original_texture, const TextureView &p_view) {