diff --git a/agdk/agdktunnel/app/src/main/cpp/CMakeLists.txt b/agdk/agdktunnel/app/src/main/cpp/CMakeLists.txt index d2059fdb..deb5c958 100644 --- a/agdk/agdktunnel/app/src/main/cpp/CMakeLists.txt +++ b/agdk/agdktunnel/app/src/main/cpp/CMakeLists.txt @@ -94,6 +94,7 @@ set(SIMPLE_RENDERER_SRCS ${SIMPLE_RENDERER_DIR}/renderer_resources.cpp ${SIMPLE_RENDERER_DIR}/renderer_shader_program_gles.cpp ${SIMPLE_RENDERER_DIR}/renderer_shader_program_vk.cpp + ${SIMPLE_RENDERER_DIR}/renderer_texture.cpp ${SIMPLE_RENDERER_DIR}/renderer_texture_gles.cpp ${SIMPLE_RENDERER_DIR}/renderer_texture_vk.cpp ${SIMPLE_RENDERER_DIR}/renderer_uniform_buffer.cpp diff --git a/agdk/common/simple_renderer/renderer_texture.cpp b/agdk/common/simple_renderer/renderer_texture.cpp new file mode 100644 index 00000000..53a2a1aa --- /dev/null +++ b/agdk/common/simple_renderer/renderer_texture.cpp @@ -0,0 +1,136 @@ +/* + * Copyright 2023 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "renderer_texture.h" +#include +#include "renderer_debug.h" + +namespace simple_renderer { + +// ASTC block dimensions, indexed from kTextureCompression_ASTC_LDR_4x4 +static constexpr uint32_t kASTCBlockSizes[][2] = { + {4, 4}, {5, 4}, {5, 5}, {6, 5}, {6, 6}, {8, 5}, {8, 6}, {8, 8}, + {10, 5}, {10, 6}, {10, 8}, {10, 10}, {12, 10}, {12, 12} +}; + +static bool IsASTC(const Texture::TextureCompressionType compression) { + return compression >= Texture::kTextureCompression_ASTC_LDR_4x4 && + compression <= Texture::kTextureCompression_ASTC_LDR_12x12; +} + +static bool IsETC2(const Texture::TextureCompressionType compression) { + return compression >= Texture::kTextureCompression_ETC2_RGB8 && + compression <= Texture::kTextureCompression_ETC2_SRGB8_ALPHA8_EAC; +} + +// Sizes are computed in 64 bits: width + block - 1 can overflow 32 bits, and so can the +// byte count (size_t is 32 bits on 32-bit ABIs) +uint64_t Texture::GetRequiredMipSize(const TextureFormat format, + const TextureCompressionType compression, + const uint32_t width, const uint32_t height) { + const uint64_t w = width; + const uint64_t h = height; + switch (format) { + case kTextureFormat_RGBA_8888: + return w * h * 4; + case kTextureFormat_RGB_888: + return w * h * 3; + case kTextureFormat_ASTC: { + if (!IsASTC(compression)) { + return 0; + } + // Every ASTC block is 16 bytes, partial blocks at the edges are whole blocks + const uint32_t* block = kASTCBlockSizes[compression - kTextureCompression_ASTC_LDR_4x4]; + return ((w + block[0] - 1) / block[0]) * ((h + block[1] - 1) / block[1]) * 16; + } + case kTextureFormat_ETC2: { + if (!IsETC2(compression)) { + return 0; + } + // 4x4 blocks: 16 bytes with EAC alpha, 8 bytes otherwise + const uint64_t block_bytes = + (compression == kTextureCompression_ETC2_RGBA8_EAC || + compression == kTextureCompression_ETC2_SRGB8_ALPHA8_EAC) ? 16 : 8; + return ((w + 3) / 4) * ((h + 3) / 4) * block_bytes; + } + default: + return 0; + } +} + +bool Texture::ValidateCreationParams(const TextureCreationParams& params) { + if (params.format >= kTextureFormat_Count || + params.compression_type >= kTextureCompression_Count || + params.min_filter >= kMinFilter_Count || params.mag_filter >= kMagFilter_Count || + params.wrap_s >= kWrapS_Count || params.wrap_t >= kWrapT_Count) { + RENDERER_ERROR("Texture: invalid format/compression/filter/wrap enum"); + return false; + } + if (params.base_width == 0 || params.base_height == 0 || params.mip_count == 0 || + params.texture_data == nullptr || params.texture_sizes == nullptr) { + RENDERER_ERROR("Texture: missing size or data (%ux%u, %u mips)", params.base_width, + params.base_height, params.mip_count); + return false; + } + if (params.mip_count > kMaxMipCount) { + RENDERER_ERROR("Texture: %u mips, the maximum is %u", params.mip_count, kMaxMipCount); + return false; + } + if ((params.format == kTextureFormat_RGBA_8888 || params.format == kTextureFormat_RGB_888) && + params.compression_type != kTextureCompression_None) { + RENDERER_ERROR("Texture: uncompressed texture with compression %u", + params.compression_type); + return false; + } + if (params.format == kTextureFormat_ASTC && !IsASTC(params.compression_type)) { + RENDERER_ERROR("Texture: ASTC texture with non-ASTC compression %u", + params.compression_type); + return false; + } + if (params.format == kTextureFormat_ETC2 && !IsETC2(params.compression_type)) { + RENDERER_ERROR("Texture: ETC2 texture with non-ETC2 compression %u", + params.compression_type); + return false; + } + // A full mip chain ends at 1x1 + uint32_t full_chain = 1; + for (uint32_t size = std::max(params.base_width, params.base_height); size > 1; size >>= 1) { + ++full_chain; + } + if (params.mip_count > full_chain) { + RENDERER_ERROR("Texture: %u mips for %ux%u, a full chain is %u", params.mip_count, + params.base_width, params.base_height, full_chain); + return false; + } + // Uploads read the required byte count for each level, whatever size is passed in, so + // make sure that much data is there + uint32_t width = params.base_width; + uint32_t height = params.base_height; + for (uint32_t level = 0; level < params.mip_count; ++level) { + const uint64_t required = GetRequiredMipSize(params.format, params.compression_type, + width, height); + if (params.texture_sizes[level] < required) { + RENDERER_ERROR("Texture: mip %u has %u bytes, needs %llu", level, + params.texture_sizes[level], static_cast(required)); + return false; + } + width = (width > 1) ? (width >> 1) : 1; + height = (height > 1) ? (height >> 1) : 1; + } + return true; +} + +} // namespace simple_renderer diff --git a/agdk/common/simple_renderer/renderer_texture.h b/agdk/common/simple_renderer/renderer_texture.h index 8fbb4ec3..0c4d71d6 100644 --- a/agdk/common/simple_renderer/renderer_texture.h +++ b/agdk/common/simple_renderer/renderer_texture.h @@ -245,20 +245,42 @@ class Texture { */ virtual ~Texture() {} + /** + * @brief Check that texture creation parameters are usable: enums in range, a + * compression type that matches the format (`kTextureCompression_None` for uncompressed + * formats), nonzero dimensions, between 1 and `kMaxMipCount` mip levels and no more than + * a full mip chain, and enough data for each level. Logs the problem if not. + * @param params The creation parameters + * @return true if the parameters are valid + */ + static bool ValidateCreationParams(const TextureCreationParams& params); + + /** + * @brief Get the number of bytes of texel data a mip level of the given size needs. + * @return The required byte count, or 0 for an invalid format/compression combination. + */ + static uint64_t GetRequiredMipSize(TextureFormat format, TextureCompressionType compression, + uint32_t width, uint32_t height); + protected: + /** @brief Maximum number of mip levels a texture can have */ + static constexpr uint32_t kMaxMipCount = 16; + + /** + * @brief Whether the creation parameters passed validation. If not, the texture has no + * mip levels and subclasses must not create any API objects. + */ + bool HasValidCreationParams() const { return valid_creation_params_; } + Texture(const TextureCreationParams& params) : texture_format_(params.format), texture_compression_type_(params.compression_type), texture_base_width_(params.base_width), texture_base_height_(params.base_height), texture_debug_name_("noname)") { - texture_mip_count_ = params.mip_count; - if (params.mip_count > kMaxMipCount) { - texture_mip_count_ = kMaxMipCount; - } - if (params.texture_sizes == nullptr) { - texture_mip_count_ = 0; - } + valid_creation_params_ = ValidateCreationParams(params); + // An invalid texture reports no mip levels (and no level sizes) + texture_mip_count_ = valid_creation_params_ ? params.mip_count : 0; uint32_t i = 0; while (i < texture_mip_count_) { texture_sizes_[i] = params.texture_sizes[i]; @@ -274,19 +296,20 @@ class Texture { Texture() : texture_format_(kTextureFormat_Count), texture_compression_type_(kTextureCompression_Count), - texture_mip_count_(0) { + texture_mip_count_(0), + valid_creation_params_(false) { for (uint32_t i = 0; i < kMaxMipCount; ++i) { texture_sizes_[i] = 0; } } - static constexpr uint32_t kMaxMipCount = 16; TextureFormat texture_format_; TextureCompressionType texture_compression_type_; uint32_t texture_base_width_; uint32_t texture_base_height_; uint32_t texture_mip_count_; size_t texture_sizes_[kMaxMipCount]; + bool valid_creation_params_; std::string texture_debug_name_; }; diff --git a/agdk/common/simple_renderer/renderer_texture_gles.cpp b/agdk/common/simple_renderer/renderer_texture_gles.cpp index a310ed2f..642eadbb 100644 --- a/agdk/common/simple_renderer/renderer_texture_gles.cpp +++ b/agdk/common/simple_renderer/renderer_texture_gles.cpp @@ -84,68 +84,17 @@ static constexpr GLint kGLWrapT[Texture::kWrapT_Count] = { GL_MIRRORED_REPEAT }; -// Returns true if the creation parameters are usable: enums in range, the compression type -// matches a compressed format, and every mip level has data of a plausible size -static bool ValidateTextureParams(const Texture::TextureCreationParams& params, - const uint32_t mip_count) { - if (params.format >= Texture::kTextureFormat_Count || - params.min_filter >= Texture::kMinFilter_Count || - params.mag_filter >= Texture::kMagFilter_Count || - params.wrap_s >= Texture::kWrapS_Count || params.wrap_t >= Texture::kWrapT_Count) { - RENDERER_ERROR("TextureGLES: invalid format/filter/wrap enum"); - return false; - } - if (params.base_width == 0 || params.base_height == 0 || mip_count == 0 || - params.texture_data == nullptr || params.texture_sizes == nullptr) { - RENDERER_ERROR("TextureGLES: missing size or data (%ux%u, %u mips)", params.base_width, - params.base_height, params.mip_count); - return false; - } - if (params.format == Texture::kTextureFormat_ASTC && - !(params.compression_type >= Texture::kTextureCompression_ASTC_LDR_4x4 && - params.compression_type <= Texture::kTextureCompression_ASTC_LDR_12x12)) { - RENDERER_ERROR("TextureGLES: ASTC texture with non-ASTC compression %u", - params.compression_type); - return false; - } - if (params.format == Texture::kTextureFormat_ETC2 && - !(params.compression_type >= Texture::kTextureCompression_ETC2_RGB8 && - params.compression_type <= Texture::kTextureCompression_ETC2_SRGB8_ALPHA8_EAC)) { - RENDERER_ERROR("TextureGLES: ETC2 texture with non-ETC2 compression %u", - params.compression_type); - return false; - } - // glTexImage2D reads width * height * bytes per pixel for each uncompressed level, - // regardless of the size passed in, so make sure that much data is there - if (params.format == Texture::kTextureFormat_RGBA_8888 || - params.format == Texture::kTextureFormat_RGB_888) { - const size_t bytes_per_pixel = (params.format == Texture::kTextureFormat_RGBA_8888) ? 4 : 3; - size_t width = params.base_width; - size_t height = params.base_height; - for (uint32_t level = 0; level < mip_count; ++level) { - if (params.texture_sizes[level] < width * height * bytes_per_pixel) { - RENDERER_ERROR("TextureGLES: mip %u has %u bytes, needs %zu", level, - params.texture_sizes[level], width * height * bytes_per_pixel); - return false; - } - width = (width > 1) ? (width >> 1) : 1; - height = (height > 1) ? (height >> 1) : 1; - } - } - return true; -} - TextureGLES::TextureGLES(const Texture::TextureCreationParams& params) : Texture(params) { texture_object_ = 0; - // Use the base class mip count, which is clamped to the supported maximum - const uint32_t mip_count = GetMipCount(); - const bool valid_params = ValidateTextureParams(params, mip_count); + // The base class validated the parameters; an invalid texture has no mip levels + const bool valid_params = HasValidCreationParams(); RENDERER_ASSERT(valid_params); if (!valid_params) { // Leave texture_object_ as 0; binding it unbinds any texture return; } + const uint32_t mip_count = GetMipCount(); // Don't disturb the caller's texture binding or pixel unpack state GLint previous_texture = 0; diff --git a/agdk/common/simple_renderer/renderer_texture_vk.cpp b/agdk/common/simple_renderer/renderer_texture_vk.cpp index 5bb6c57b..76403699 100644 --- a/agdk/common/simple_renderer/renderer_texture_vk.cpp +++ b/agdk/common/simple_renderer/renderer_texture_vk.cpp @@ -20,22 +20,24 @@ namespace simple_renderer { +// Mipmap mode for each min filter (the min filter itself is in kVkMinFilters). The non-mip +// filters only sample level 0, see the sampler's maxLod. static constexpr VkSamplerMipmapMode kVkMipmapMode[Texture::kMinFilter_Count] = { - VK_SAMPLER_MIPMAP_MODE_NEAREST, - VK_SAMPLER_MIPMAP_MODE_LINEAR, - VK_SAMPLER_MIPMAP_MODE_NEAREST, - VK_SAMPLER_MIPMAP_MODE_LINEAR, - VK_SAMPLER_MIPMAP_MODE_NEAREST, - VK_SAMPLER_MIPMAP_MODE_LINEAR + VK_SAMPLER_MIPMAP_MODE_NEAREST, // kMinFilter_Nearest + VK_SAMPLER_MIPMAP_MODE_NEAREST, // kMinFilter_Linear + VK_SAMPLER_MIPMAP_MODE_NEAREST, // kMinFilter_Nearest_Mipmap_Nearest + VK_SAMPLER_MIPMAP_MODE_NEAREST, // kMinFilter_Linear_Mipmap_Nearest + VK_SAMPLER_MIPMAP_MODE_LINEAR, // kMinFilter_Nearest_Mipmap_Linear + VK_SAMPLER_MIPMAP_MODE_LINEAR // kMinFilter_Linear_Mipmap_Linear }; static constexpr VkFilter kVkMinFilters[Texture::kMinFilter_Count] = { - VK_FILTER_NEAREST, - VK_FILTER_LINEAR, - VK_FILTER_NEAREST, - VK_FILTER_LINEAR, - VK_FILTER_NEAREST, - VK_FILTER_LINEAR, + VK_FILTER_NEAREST, // kMinFilter_Nearest + VK_FILTER_LINEAR, // kMinFilter_Linear + VK_FILTER_NEAREST, // kMinFilter_Nearest_Mipmap_Nearest + VK_FILTER_LINEAR, // kMinFilter_Linear_Mipmap_Nearest + VK_FILTER_NEAREST, // kMinFilter_Nearest_Mipmap_Linear + VK_FILTER_LINEAR, // kMinFilter_Linear_Mipmap_Linear }; static constexpr VkFilter kVkMagFilters[Texture::kMagFilter_Count] = { @@ -55,64 +57,82 @@ static constexpr VkSamplerAddressMode kVkWrapT[Texture::kWrapT_Count] = { VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT }; +// ASTC formats, indexed from kTextureCompression_ASTC_LDR_4x4 +static constexpr VkFormat kVkASTCFormats[] = { + VK_FORMAT_ASTC_4x4_UNORM_BLOCK, + VK_FORMAT_ASTC_5x4_UNORM_BLOCK, + VK_FORMAT_ASTC_5x5_UNORM_BLOCK, + VK_FORMAT_ASTC_6x5_UNORM_BLOCK, + VK_FORMAT_ASTC_6x6_UNORM_BLOCK, + VK_FORMAT_ASTC_8x5_UNORM_BLOCK, + VK_FORMAT_ASTC_8x6_UNORM_BLOCK, + VK_FORMAT_ASTC_8x8_UNORM_BLOCK, + VK_FORMAT_ASTC_10x5_UNORM_BLOCK, + VK_FORMAT_ASTC_10x6_UNORM_BLOCK, + VK_FORMAT_ASTC_10x8_UNORM_BLOCK, + VK_FORMAT_ASTC_10x10_UNORM_BLOCK, + VK_FORMAT_ASTC_12x10_UNORM_BLOCK, + VK_FORMAT_ASTC_12x12_UNORM_BLOCK +}; + +// ETC2 formats, indexed from kTextureCompression_ETC2_RGB8 +static constexpr VkFormat kVkETC2Formats[] = { + VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK, + VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK, + VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK, + VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK, + VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK, + VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK +}; + +// Only called with validated parameters (see Texture::ValidateCreationParams) static VkFormat GetTextureVkFormat(const Texture::TextureCreationParams& params) { - VkFormat texture_format = VK_FORMAT_R8G8B8A8_UNORM; - if (params.format == Texture::kTextureFormat_RGB_888) { - texture_format = VK_FORMAT_R8G8B8_UNORM; - } else if (params.format == Texture::kTextureFormat_ASTC) { - switch (params.compression_type) { - case Texture::kTextureCompression_ASTC_LDR_4x4: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_5x4: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_5x5: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_6x5: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_6x6: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_8x5: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_8x6: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_8x8: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_10x5: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_10x6: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_10x8: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_10x10: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_12x10: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - case Texture::kTextureCompression_ASTC_LDR_12x12: - texture_format = VK_FORMAT_ASTC_4x4_UNORM_BLOCK; break; - default: - RENDERER_ASSERT(false); - break; - } - } else if (params.format == Texture::kTextureFormat_ETC2) { - switch (params.compression_type) { - case Texture::kTextureCompression_ETC2_RGB8: - texture_format = VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK; break; - case Texture::kTextureCompression_ETC2_SRGB8: - texture_format = VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK; break; - case Texture::kTextureCompression_ETC2_RGB8_PUNCH_ALPHA1: - texture_format = VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK; break; - case Texture::kTextureCompression_ETC2_SRGB8_PUNCH_ALPHA1: - texture_format = VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK; break; - case Texture::kTextureCompression_ETC2_RGBA8_EAC: - texture_format = VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK; break; - case Texture::kTextureCompression_ETC2_SRGB8_ALPHA8_EAC: - texture_format = VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK; break; - default: - RENDERER_ASSERT(false); - break; - } + switch (params.format) { + case Texture::kTextureFormat_RGBA_8888: + return VK_FORMAT_R8G8B8A8_UNORM; + case Texture::kTextureFormat_RGB_888: + return VK_FORMAT_R8G8B8_UNORM; + case Texture::kTextureFormat_ASTC: + return kVkASTCFormats[params.compression_type - Texture::kTextureCompression_ASTC_LDR_4x4]; + case Texture::kTextureFormat_ETC2: + return kVkETC2Formats[params.compression_type - Texture::kTextureCompression_ETC2_RGB8]; + default: + return VK_FORMAT_UNDEFINED; } - return texture_format; +} + +static bool IsFormatSampleable(VkPhysicalDevice physical_device, const VkFormat format) { + VkFormatProperties properties{}; + vkGetPhysicalDeviceFormatProperties(physical_device, format, &properties); + constexpr VkFormatFeatureFlags kRequired = + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT; + return (properties.optimalTilingFeatures & kRequired) == kRequired; +} + +static constexpr VkImageUsageFlags kTextureImageUsage = + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + +// Check the image size and mip count against the device's limits for the format +static bool IsImageSupported(VkPhysicalDevice physical_device, const VkFormat format, + const uint32_t width, const uint32_t height, + const uint32_t mip_count) { + VkImageFormatProperties properties{}; + const VkResult result = vkGetPhysicalDeviceImageFormatProperties( + physical_device, format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, kTextureImageUsage, + 0, &properties); + if (result != VK_SUCCESS) { + RENDERER_ERROR("TextureVk: format %d not supported for textures (%d)", format, result); + return false; + } + if (width > properties.maxExtent.width || height > properties.maxExtent.height || + mip_count > properties.maxMipLevels) { + RENDERER_ERROR("TextureVk: %ux%u with %u mips exceeds the format %d limit of %ux%u " + "with %u mips", width, height, mip_count, format, + properties.maxExtent.width, properties.maxExtent.height, + properties.maxMipLevels); + return false; + } + return true; } TextureVk::TextureVk(const Texture::TextureCreationParams& params) @@ -121,16 +141,61 @@ TextureVk::TextureVk(const Texture::TextureCreationParams& params) , image_view_(VK_NULL_HANDLE) , image_alloc_(VK_NULL_HANDLE) , sampler_(VK_NULL_HANDLE) { + // The base class validated the parameters; an invalid texture has no mip levels + const bool valid_params = HasValidCreationParams(); + RENDERER_ASSERT(valid_params); + if (!valid_params) { + // Leave the texture empty (null image view and sampler) + return; + } + const uint32_t mip_count = GetMipCount(); RendererVk &renderer = RendererVk::GetInstanceVk(); VmaAllocator allocator = renderer.GetAllocator(); - const VkFormat texture_format = GetTextureVkFormat(params); + VkFormat texture_format = GetTextureVkFormat(params); + // R8G8B8 is often not sampleable (e.g. not on PowerVR), store it as RGBA8 instead + const bool expand_rgb_to_rgba = (texture_format == VK_FORMAT_R8G8B8_UNORM && + !IsFormatSampleable(renderer.GetPhysicalDevice(), texture_format)); + if (expand_rgb_to_rgba) { + texture_format = VK_FORMAT_R8G8B8A8_UNORM; + } + // Valid parameters the device can't handle (e.g. a compressed format it doesn't support, + // or a size over its limits) are reported, and leave the texture empty. Check before + // staging anything. + if (!IsFormatSampleable(renderer.GetPhysicalDevice(), texture_format)) { + RENDERER_ERROR("TextureVk: format %d can't be sampled on this device", texture_format); + return; + } + if (!IsImageSupported(renderer.GetPhysicalDevice(), texture_format, params.base_width, + params.base_height, mip_count)) { + return; + } + + // Lay out every mip level in the staging buffer, tightly packed. Each level only takes + // the bytes it needs, which keeps every level offset a multiple of the texel block size. + const TextureFormat staging_format = expand_rgb_to_rgba ? kTextureFormat_RGBA_8888 : + params.format; + VkBufferImageCopy copy_regions[kMaxMipCount] = {}; + VkDeviceSize staging_size = 0; + uint32_t width = params.base_width; + uint32_t height = params.base_height; + for (uint32_t level = 0; level < mip_count; ++level) { + VkBufferImageCopy ®ion = copy_regions[level]; + region.bufferOffset = staging_size; + region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + region.imageSubresource.mipLevel = level; + region.imageSubresource.layerCount = 1; + region.imageExtent = {width, height, 1}; + staging_size += GetRequiredMipSize(staging_format, params.compression_type, width, height); + width = (width > 1) ? (width >> 1) : 1; + height = (height > 1) ? (height >> 1) : 1; + } // Create a staging buffer for the texture data - VkBufferCreateInfo create_info = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - // TODO: only supports one mip level right now - create_info.size = params.texture_sizes[0]; + VkBufferCreateInfo create_info{}; + create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + create_info.size = staging_size; create_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; VmaAllocationCreateInfo staging_create_info = {}; staging_create_info.usage = VMA_MEMORY_USAGE_AUTO; @@ -142,21 +207,53 @@ TextureVk::TextureVk(const Texture::TextureCreationParams& params) const VkResult staging_alloc_result = vmaCreateBuffer(allocator, &create_info, &staging_create_info, &staging_buffer, &staging_alloc, &staging_info); - RENDERER_CHECK_VK(staging_alloc_result, "vmaCreateBuffer (staging)"); + if (!RENDERER_CHECK_VK(staging_alloc_result, "vmaCreateBuffer (staging)")) { + return; + } RENDERER_ASSERT(staging_info.pMappedData != nullptr); - memcpy(staging_info.pMappedData, params.texture_data, params.texture_sizes[0]); + if (staging_info.pMappedData == nullptr) { + vmaDestroyBuffer(allocator, staging_buffer, staging_alloc); + return; + } + + // Copy each level's data (texture_sizes[level] bytes apart in the source) to its + // staging offset, expanding RGB to RGBA if needed + const uint8_t* source = static_cast(params.texture_data); + uint8_t* staging = static_cast(staging_info.pMappedData); + for (uint32_t level = 0; level < mip_count; ++level) { + const VkBufferImageCopy ®ion = copy_regions[level]; + uint8_t* destination = staging + region.bufferOffset; + const size_t pixel_count = static_cast(region.imageExtent.width) * + region.imageExtent.height; + if (expand_rgb_to_rgba) { + for (size_t pixel = 0; pixel < pixel_count; ++pixel) { + destination[pixel * 4 + 0] = source[pixel * 3 + 0]; + destination[pixel * 4 + 1] = source[pixel * 3 + 1]; + destination[pixel * 4 + 2] = source[pixel * 3 + 2]; + destination[pixel * 4 + 3] = 255; + } + } else { + // At most texture_sizes[level] bytes (validated), so it fits in size_t + memcpy(destination, source, + static_cast(GetRequiredMipSize(params.format, params.compression_type, + region.imageExtent.width, + region.imageExtent.height))); + } + source += params.texture_sizes[level]; + } - VkImageCreateInfo image_create_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; + VkImageCreateInfo image_create_info{}; + image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_create_info.imageType = VK_IMAGE_TYPE_2D; image_create_info.extent.width = params.base_width; image_create_info.extent.height = params.base_height; image_create_info.extent.depth = 1; - image_create_info.mipLevels = 1; + image_create_info.mipLevels = mip_count; image_create_info.arrayLayers = 1; image_create_info.format = texture_format; image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.usage = kTextureImageUsage; image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; image_create_info.flags = 0; @@ -167,17 +264,24 @@ TextureVk::TextureVk(const Texture::TextureCreationParams& params) const VkResult image_alloc_result = vmaCreateImage(allocator, &image_create_info, &image_alloc_create_info, &image_, &image_alloc_, nullptr); - RENDERER_CHECK_VK(image_alloc_result, "vmaCreateImage"); + if (!RENDERER_CHECK_VK(image_alloc_result, "vmaCreateImage")) { + image_ = VK_NULL_HANDLE; + image_alloc_ = VK_NULL_HANDLE; + vmaDestroyBuffer(allocator, staging_buffer, staging_alloc); + return; + } VkCommandBuffer command_buffer = renderer.BeginStagingCommandBuffer(); - // Copy and translate the image data from the staging buffer to the final GPU memory and format - VkImageMemoryBarrier image_memory_barrier = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER }; + // Copy and translate the image data from the staging buffer to the final GPU memory and + // format, for all mip levels + VkImageMemoryBarrier image_memory_barrier{}; + image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; image_memory_barrier.subresourceRange.baseMipLevel = 0; - image_memory_barrier.subresourceRange.levelCount = 1; + image_memory_barrier.subresourceRange.levelCount = mip_count; image_memory_barrier.subresourceRange.baseArrayLayer = 0; image_memory_barrier.subresourceRange.layerCount = 1; image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; @@ -190,19 +294,11 @@ TextureVk::TextureVk(const Texture::TextureCreationParams& params) VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); - VkBufferImageCopy copy_region = {}; - copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copy_region.imageSubresource.layerCount = 1; - copy_region.imageExtent.width = params.base_width; - copy_region.imageExtent.height = params.base_height; - copy_region.imageExtent.depth = 1; - vkCmdCopyBufferToImage(command_buffer, staging_buffer, image_, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mip_count, copy_regions); image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - image_memory_barrier.image = image_; image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; @@ -212,21 +308,34 @@ TextureVk::TextureVk(const Texture::TextureCreationParams& params) renderer.EndStagingCommandBuffer(); vmaDestroyBuffer(allocator, staging_buffer, staging_alloc); - // Create the ImageView for the new Image - VkImageViewCreateInfo view_create_info = {VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + // Create the ImageView for the new Image, covering all mip levels + VkImageViewCreateInfo view_create_info{}; + view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; view_create_info.image = image_; view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D; view_create_info.format = texture_format; view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view_create_info.subresourceRange.baseMipLevel = 0; - view_create_info.subresourceRange.levelCount = 1; + view_create_info.subresourceRange.levelCount = mip_count; view_create_info.subresourceRange.baseArrayLayer = 0; view_create_info.subresourceRange.layerCount = 1; - const VkResult create_view_result = vkCreateImageView(renderer.GetDevice(), &view_create_info, - nullptr, &image_view_); - RENDERER_CHECK_VK(create_view_result, "vkCreateImageView"); + const VkResult create_view_result = vkCreateImageView(renderer.GetDevice(), &view_create_info, + nullptr, &image_view_); + if (!RENDERER_CHECK_VK(create_view_result, "vkCreateImageView")) { + // Leave the texture empty rather than holding an image nothing can sample + image_view_ = VK_NULL_HANDLE; + vmaDestroyImage(allocator, image_, image_alloc_); + image_ = VK_NULL_HANDLE; + image_alloc_ = VK_NULL_HANDLE; + return; + } - VkSamplerCreateInfo sampler_create_info = {VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; + // The non-mipmapped min filters (as in GLES) only sample level 0: a maxLod of 0.25 + // keeps the magnification/minification switch while clamping to the base level + const bool mipmapped_filter = !(params.min_filter == kMinFilter_Nearest || + params.min_filter == kMinFilter_Linear); + VkSamplerCreateInfo sampler_create_info{}; + sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; sampler_create_info.magFilter = kVkMagFilters[params.mag_filter]; sampler_create_info.minFilter = kVkMinFilters[params.min_filter]; sampler_create_info.addressModeU = kVkWrapS[params.wrap_s]; @@ -241,11 +350,18 @@ TextureVk::TextureVk(const Texture::TextureCreationParams& params) sampler_create_info.mipmapMode = kVkMipmapMode[params.min_filter]; sampler_create_info.mipLodBias = 0.f; sampler_create_info.minLod = 0.f; - sampler_create_info.maxLod = FLT_MAX; + sampler_create_info.maxLod = mipmapped_filter ? VK_LOD_CLAMP_NONE : 0.25f; const VkResult sampler_result = vkCreateSampler(renderer.GetDevice(), &sampler_create_info, nullptr, &sampler_); - RENDERER_CHECK_VK(sampler_result, "vkCreateSampler"); - + if (!RENDERER_CHECK_VK(sampler_result, "vkCreateSampler")) { + // A combined image sampler needs both, so leave the texture empty + sampler_ = VK_NULL_HANDLE; + vkDestroyImageView(renderer.GetDevice(), image_view_, nullptr); + image_view_ = VK_NULL_HANDLE; + vmaDestroyImage(allocator, image_, image_alloc_); + image_ = VK_NULL_HANDLE; + image_alloc_ = VK_NULL_HANDLE; + } } TextureVk::~TextureVk() { diff --git a/agdk/common/simple_renderer/renderer_vk.cpp b/agdk/common/simple_renderer/renderer_vk.cpp index 69eaeb7f..4e1b248d 100644 --- a/agdk/common/simple_renderer/renderer_vk.cpp +++ b/agdk/common/simple_renderer/renderer_vk.cpp @@ -44,7 +44,9 @@ RendererVk::RendererVk() : descriptor_pools_(), descriptor_set_layouts_(), descriptor_set_vertex_table_(VertexBuffer::kVertexFormat_Count), - texture_descriptor_frame_cache_(kMaxSamplerDescriptors) { + texture_descriptor_frame_cache_() { + // Reserve space up front; the cache starts empty each frame + texture_descriptor_frame_cache_.reserve(kMaxSamplerDescriptors); DisplayManager& display_manager = DisplayManager::GetInstance(); const GraphicsAPIFeatures& api_features = display_manager.GetGraphicsAPIFeatures(); display_manager.GetGraphicsAPIResourcesVk(vk_); @@ -101,11 +103,14 @@ void RendererVk::PrepareShutdown() { bool RendererVk::GetFeatureAvailable(const RendererFeature feature) { bool supported = false; switch (feature) { - case Renderer::kFeature_ASTC: - // Android Baseline Profile requires ASTC support, we wouldn't have - // initialized RendererVk without it - supported = true; + case Renderer::kFeature_ASTC: { + // Required by the Android Baseline Profile, but that isn't enforced at + // initialization, so ask the device + VkPhysicalDeviceFeatures device_features{}; + vkGetPhysicalDeviceFeatures(vk_.physical_device, &device_features); + supported = (device_features.textureCompressionASTC_LDR == VK_TRUE); break; + } default: break; } @@ -189,8 +194,7 @@ void RendererVk::EndFrame() { active_frame_pool_ = VK_NULL_HANDLE; texture_descriptor_frame_cache_.clear(); - bound_descriptor_set_ = VK_NULL_HANDLE; - bound_image_view_ = VK_NULL_HANDLE; + ResetBoundDescriptorSet(); } void RendererVk::SwapchainRecreated() { @@ -202,14 +206,25 @@ void RendererVk::SwapchainRecreated() { } } -void RendererVk::Draw(const uint32_t vertex_count, const uint32_t first_vertex) { - RenderStateVk& state = *(static_cast(render_state_.get())); - if (dirty_descriptor_set_) { +void RendererVk::ResetBoundDescriptorSet() { + // Nothing pending either: a bind of a null set is invalid + bound_descriptor_set_ = VK_NULL_HANDLE; + bound_image_view_ = VK_NULL_HANDLE; + dirty_descriptor_set_ = false; +} + +void RendererVk::BindDirtyDescriptorSet(const RenderStateVk& state) { + if (dirty_descriptor_set_ && bound_descriptor_set_ != VK_NULL_HANDLE) { vkCmdBindDescriptorSets(render_command_buffer_, VK_PIPELINE_BIND_POINT_GRAPHICS, state.GetPipelineLayout(), 0, 1, &bound_descriptor_set_, 0, nullptr); - dirty_descriptor_set_ = false; } + dirty_descriptor_set_ = false; +} + +void RendererVk::Draw(const uint32_t vertex_count, const uint32_t first_vertex) { + RenderStateVk& state = *(static_cast(render_state_.get())); + BindDirtyDescriptorSet(state); // Update any uniform data that might have changed between draw calls state.UpdateUniformData(render_command_buffer_, true); @@ -219,12 +234,7 @@ void RendererVk::Draw(const uint32_t vertex_count, const uint32_t first_vertex) void RendererVk::DrawIndexed(const uint32_t index_count, const uint32_t first_index) { RenderStateVk& state = *(static_cast(render_state_.get())); - if (dirty_descriptor_set_) { - vkCmdBindDescriptorSets(render_command_buffer_, VK_PIPELINE_BIND_POINT_GRAPHICS, - state.GetPipelineLayout(), 0, 1, &bound_descriptor_set_, - 0, nullptr); - dirty_descriptor_set_ = false; - } + BindDirtyDescriptorSet(state); // Update any uniform data that might have changed between draw calls state.UpdateUniformData(render_command_buffer_, true); @@ -241,6 +251,8 @@ void RendererVk::SetRenderPass(std::shared_ptr render_pass) { } render_pass_ = render_pass; render_state_ = nullptr; + // The next render state binds its own descriptor set + ResetBoundDescriptorSet(); new_render_pass->BeginRenderPass(); } } @@ -250,8 +262,8 @@ void RendererVk::SetRenderState(std::shared_ptr render_state) { render_state_ = render_state; RenderStateVk& state = *(static_cast(render_state_.get())); vkCmdBindPipeline(render_command_buffer_, VK_PIPELINE_BIND_POINT_GRAPHICS, state.GetPipeline()); - bound_descriptor_set_ = VK_NULL_HANDLE; - bound_image_view_ = VK_NULL_HANDLE; + // Textures are bound again for the new state (its descriptor set layout may differ) + ResetBoundDescriptorSet(); } } @@ -269,20 +281,39 @@ void RendererVk::BindVertexBuffer(std::shared_ptr vertex_buffer) { } void RendererVk::BindTexture(std::shared_ptr texture) { - if (texture.get() == nullptr) { - bound_descriptor_set_ = VK_NULL_HANDLE; - bound_image_view_ = VK_NULL_HANDLE; - dirty_descriptor_set_ = true; + const TextureVk* texture_vk = static_cast(texture.get()); + if (texture_vk == nullptr || texture_vk->GetImageView() == VK_NULL_HANDLE || + texture_vk->GetSampler() == VK_NULL_HANDLE) { + // Nothing to bind (no texture, or one that failed to create). A null descriptor set + // can't be bound, so drop any pending bind; the last bound set stays bound. + ResetBoundDescriptorSet(); + return; } - TextureVk& texture_vk = *(static_cast(texture.get())); - const VkImageView texture_image_view = texture_vk.GetImageView(); + const VkImageView texture_image_view = texture_vk->GetImageView(); if (texture_image_view == bound_image_view_) { return; } - bound_image_view_ = texture_image_view; + RENDERER_ASSERT(render_state_ != nullptr); + if (render_state_ == nullptr) { + // The descriptor set layout comes from the render state + return; + } + + // Only textured vertex formats (P3T2, P3T2C4) have a sampler binding in their descriptor + // set layout; for the others there is nothing to bind the texture to + RenderStateVk& state = *(static_cast(render_state_.get())); + const VkDescriptorSetLayout layout = state.GetDescriptorSetLayout(); + const VkDescriptorSetLayout textured_layout = + descriptor_set_vertex_table_[VertexBuffer::kVertexFormat_P3T2]; + if (layout == VK_NULL_HANDLE || layout != textured_layout) { + return; + } + + // Descriptor sets are cached per frame by texture and layout for (const TextureDescriptorFrameCache& cache : texture_descriptor_frame_cache_) { - if (cache.texture_image_view == texture_image_view) { + if (cache.texture_image_view == texture_image_view && cache.layout == layout) { + bound_image_view_ = texture_image_view; bound_descriptor_set_ = cache.descriptor_set; dirty_descriptor_set_ = true; return; @@ -291,26 +322,27 @@ void RendererVk::BindTexture(std::shared_ptr texture) { // Create a new descriptor/descriptor set for this texture for this frame and // write the descriptor data - RenderStateVk& state = *(static_cast(render_state_.get())); - - VkDescriptorSetLayout descriptor_set_layouts[] = {state.GetDescriptorSetLayout() }; + VkDescriptorSetLayout descriptor_set_layouts[] = {layout}; VkDescriptorSetAllocateInfo descriptor_set_info = {}; descriptor_set_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; descriptor_set_info.descriptorPool = active_frame_pool_; descriptor_set_info.descriptorSetCount = 1; descriptor_set_info.pSetLayouts = descriptor_set_layouts; + VkDescriptorSet descriptor_set = VK_NULL_HANDLE; const VkResult allocate_result = vkAllocateDescriptorSets(vk_.device, &descriptor_set_info, - &bound_descriptor_set_); - RENDERER_CHECK_VK(allocate_result, "vkAllocateDescriptorSets"); + &descriptor_set); + if (!RENDERER_CHECK_VK(allocate_result, "vkAllocateDescriptorSets")) { + return; + } VkDescriptorImageInfo descriptor_image_info = {}; descriptor_image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - descriptor_image_info.imageView = texture_vk.GetImageView(); - descriptor_image_info.sampler = texture_vk.GetSampler(); + descriptor_image_info.imageView = texture_image_view; + descriptor_image_info.sampler = texture_vk->GetSampler(); VkWriteDescriptorSet write_descriptor_set = {}; write_descriptor_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - write_descriptor_set.dstSet = bound_descriptor_set_; + write_descriptor_set.dstSet = descriptor_set; write_descriptor_set.dstBinding = 1; write_descriptor_set.dstArrayElement = 0; write_descriptor_set.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; @@ -318,10 +350,11 @@ void RendererVk::BindTexture(std::shared_ptr texture) { write_descriptor_set.pImageInfo = &descriptor_image_info; vkUpdateDescriptorSets(vk_.device, 1, &write_descriptor_set, 0, nullptr); + bound_image_view_ = texture_image_view; + bound_descriptor_set_ = descriptor_set; dirty_descriptor_set_ = true; - texture_descriptor_frame_cache_.push_back( - {texture_vk.GetImageView(), bound_descriptor_set_}); + texture_descriptor_frame_cache_.push_back({texture_image_view, layout, descriptor_set}); } std::shared_ptr RendererVk::CreateIndexBuffer( diff --git a/agdk/common/simple_renderer/renderer_vk.h b/agdk/common/simple_renderer/renderer_vk.h index 61778bb3..19e469c6 100644 --- a/agdk/common/simple_renderer/renderer_vk.h +++ b/agdk/common/simple_renderer/renderer_vk.h @@ -25,6 +25,8 @@ namespace simple_renderer { +class RenderStateVk; + /* struct RendererVkResources { VkDevice device = VK_NULL_HANDLE; @@ -141,6 +143,7 @@ class RendererVk : public Renderer { // (samplers are baked into our texture class) struct TextureDescriptorFrameCache { VkImageView texture_image_view; + VkDescriptorSetLayout layout; VkDescriptorSet descriptor_set; }; @@ -152,6 +155,12 @@ class RendererVk : public Renderer { void CreateDescriptorPools(); + // Forget the bound texture descriptor set, including a pending (not yet drawn) bind + void ResetBoundDescriptorSet(); + + // Bind the pending texture descriptor set, if there is one, before a draw + void BindDirtyDescriptorSet(const RenderStateVk& state); + RendererResources resources_; std::shared_ptr render_pass_;