From a3fa7ccd3394e18c02b9d3697b1a9c853df049e5 Mon Sep 17 00:00:00 2001 From: dan sinclair Date: Thu, 9 Jan 2025 08:44:16 -0500 Subject: [PATCH] Insert Braces around single line ifs. (#1077) Add the `InsertBraces: true` flag for clang-format and re-run the formatter. This forces brackets around all of the single line entries which did not previously have them. --- .clang-format | 2 + include/amber/amber.h | 2 +- samples/amber.cc | 33 +- samples/android_helper.cc | 3 +- samples/config_helper.cc | 3 +- samples/config_helper_dawn.cc | 3 +- samples/config_helper_vulkan.cc | 154 +- samples/image_diff.cc | 10 +- samples/png.cc | 3 +- samples/ppm.cc | 3 +- src/acceleration_structure.h | 3 +- src/amber.cc | 52 +- src/amberscript/parser.cc | 2031 ++++++++++++++------- src/amberscript/parser_blend_test.cc | 12 +- src/amberscript/parser_raytracing_test.cc | 4 +- src/buffer.cc | 89 +- src/buffer.h | 9 +- src/buffer_test.cc | 30 +- src/command_data.cc | 149 +- src/dawn/engine_dawn.cc | 153 +- src/descriptor_set_and_binding_parser.cc | 15 +- src/dxc_helper.cc | 3 +- src/dxc_helper.h | 2 +- src/executor.cc | 69 +- src/executor_test.cc | 33 +- src/float16_helper.cc | 3 +- src/format.cc | 82 +- src/format.h | 6 +- src/format_test.cc | 3 +- src/pipeline.cc | 119 +- src/pipeline.h | 17 +- src/pipeline_test.cc | 6 +- src/recipe.cc | 9 +- src/script.cc | 8 +- src/script.h | 30 +- src/shader_compiler.cc | 68 +- src/tokenizer.cc | 21 +- src/type.cc | 6 +- src/type.h | 45 +- src/type_parser.cc | 479 +++-- src/verifier.cc | 51 +- src/verifier_test.cc | 3 +- src/vkscript/command_parser.cc | 820 +++++---- src/vkscript/command_parser_test.cc | 16 +- src/vkscript/datum_type_parser.cc | 61 +- src/vkscript/datum_type_parser_test.cc | 9 +- src/vkscript/parser.cc | 102 +- src/vkscript/section_parser.cc | 36 +- src/vulkan/blas.cc | 20 +- src/vulkan/blas.h | 2 +- src/vulkan/buffer_backed_descriptor.cc | 3 +- src/vulkan/buffer_descriptor.cc | 6 +- src/vulkan/command_buffer.cc | 18 +- src/vulkan/command_pool.cc | 3 +- src/vulkan/compute_pipeline.cc | 24 +- src/vulkan/device.cc | 239 ++- src/vulkan/engine_vulkan.cc | 141 +- src/vulkan/frame_buffer.cc | 48 +- src/vulkan/graphics_pipeline.cc | 66 +- src/vulkan/image_descriptor.cc | 9 +- src/vulkan/index_buffer.cc | 18 +- src/vulkan/pipeline.cc | 99 +- src/vulkan/push_constant.cc | 15 +- src/vulkan/raytracing_pipeline.cc | 45 +- src/vulkan/resource.cc | 24 +- src/vulkan/sampler_descriptor.cc | 3 +- src/vulkan/sbt.cc | 14 +- src/vulkan/tlas.cc | 22 +- src/vulkan/tlas_descriptor.cc | 3 +- src/vulkan/transfer_buffer.cc | 9 +- src/vulkan/transfer_image.cc | 42 +- src/vulkan/vertex_buffer.cc | 9 +- 72 files changed, 3693 insertions(+), 2059 deletions(-) diff --git a/.clang-format b/.clang-format index 2fb833a5d..2d6842909 100644 --- a/.clang-format +++ b/.clang-format @@ -1,2 +1,4 @@ # http://clang.llvm.org/docs/ClangFormatStyleOptions.html BasedOnStyle: Chromium + +InsertBraces: true diff --git a/include/amber/amber.h b/include/amber/amber.h index fafc49bf4..ecc3a9071 100644 --- a/include/amber/amber.h +++ b/include/amber/amber.h @@ -106,7 +106,7 @@ class Delegate { std::vector* buffer) const = 0; /// Mechanism for gathering timing from 'TIME_EXECUTION' - virtual void ReportExecutionTiming(double){} + virtual void ReportExecutionTiming(double) {} }; /// Stores configuration options for Amber. diff --git a/samples/amber.cc b/samples/amber.cc index 15baaa24e..8d2d7d9db 100644 --- a/samples/amber.cc +++ b/samples/amber.cc @@ -394,8 +394,9 @@ class SampleDelegate : public amber::Delegate { #endif // AMBER_ENABLE_LODEPNG } else { auto data = ReadFile(path_ + file_name); - if (data.empty()) + if (data.empty()) { return amber::Result("Failed to load buffer data " + file_name); + } for (auto d : data) { amber::Value v; @@ -413,8 +414,9 @@ class SampleDelegate : public amber::Delegate { amber::Result LoadFile(const std::string file_name, std::vector* buffer) const override { *buffer = ReadFile(path_ + file_name); - if (buffer->empty()) + if (buffer->empty()) { return amber::Result("Failed to load file " + file_name); + } return {}; } @@ -433,8 +435,9 @@ std::string disassemble(const std::string& env, spv_target_env target_env = SPV_ENV_UNIVERSAL_1_0; if (!env.empty()) { - if (!spvParseTargetEnv(env.c_str(), &target_env)) + if (!spvParseTargetEnv(env.c_str(), &target_env)) { return ""; + } } auto msg_consumer = [&spv_errors](spv_message_level_t level, const char*, @@ -539,8 +542,9 @@ int main(int argc, const char** argv) { continue; } - if (options.fence_timeout > -1) + if (options.fence_timeout > -1) { recipe->SetFenceTimeout(static_cast(options.fence_timeout)); + } recipe->SetPipelineRuntimeLayerEnabled( options.enable_pipeline_runtime_layer); @@ -550,15 +554,19 @@ int main(int argc, const char** argv) { recipe_data.back().recipe = std::move(recipe); } - if (options.parse_only) + if (options.parse_only) { return 0; + } - if (options.log_graphics_calls) + if (options.log_graphics_calls) { delegate.SetLogGraphicsCalls(true); - if (options.log_graphics_calls_time) + } + if (options.log_graphics_calls_time) { delegate.SetLogGraphicsCallsTime(true); - if (options.log_execute_calls) + } + if (options.log_execute_calls) { delegate.SetLogExecuteCalls(true); + } amber::Options amber_options; amber_options.engine = options.engine; @@ -628,8 +636,9 @@ int main(int argc, const char** argv) { } // Use default frame buffer name when not specified. - while (options.image_filenames.size() > options.fb_names.size()) + while (options.image_filenames.size() > options.fb_names.size()) { options.fb_names.push_back(kGeneratedColorBuffer); + } for (const auto& fb_name : options.fb_names) { amber::BufferInfo buffer_info; @@ -773,8 +782,9 @@ int main(int argc, const char** argv) { for (size_t i = 0; i < values.size(); ++i) { buffer_file << " " << std::setfill('0') << std::setw(2) << std::hex << values[i].AsUint32(); - if (i % 16 == 15) + if (i % 16 == 15) { buffer_file << std::endl; + } } buffer_file << std::endl; } @@ -787,8 +797,9 @@ int main(int argc, const char** argv) { if (!failures.empty()) { std::cout << "\nSummary of Failures:" << std::endl; - for (const auto& failure : failures) + for (const auto& failure : failures) { std::cout << " " << failure << std::endl; + } } std::cout << "\nSummary: " diff --git a/samples/android_helper.cc b/samples/android_helper.cc index 7da69ad61..9913a79ca 100644 --- a/samples/android_helper.cc +++ b/samples/android_helper.cc @@ -54,8 +54,9 @@ extern "C" JNIEXPORT JNICALL int Java_com_google_amber_Amber_androidHelper( std::vector argv; - for (const std::string& arg : argv_string) + for (const std::string& arg : argv_string) { argv.push_back(arg.c_str()); + } return android_main(static_cast(argv.size()), argv.data()); } diff --git a/samples/config_helper.cc b/samples/config_helper.cc index b6d7c47fa..3dcfa38c8 100644 --- a/samples/config_helper.cc +++ b/samples/config_helper.cc @@ -65,8 +65,9 @@ amber::Result ConfigHelper::CreateConfig( #endif // AMBER_ENGINE_DAWN } - if (!impl_) + if (!impl_) { return amber::Result("Unable to create config helper"); + } return impl_->CreateConfig( engine_major, engine_minor, selected_device, required_features, diff --git a/samples/config_helper_dawn.cc b/samples/config_helper_dawn.cc index 8ed7ac1cd..bdf42b80f 100644 --- a/samples/config_helper_dawn.cc +++ b/samples/config_helper_dawn.cc @@ -76,8 +76,9 @@ amber::Result ConfigHelperDawn::CreateConfig( } } - if (!dawn_device_) + if (!dawn_device_) { return amber::Result("could not find Vulkan or Metal backend for Dawn"); + } backendProcs.deviceSetUncapturedErrorCallback(dawn_device_.Get(), PrintDeviceError, nullptr); diff --git a/samples/config_helper_vulkan.cc b/samples/config_helper_vulkan.cc index 25cf42ce8..f7b51c2d1 100644 --- a/samples/config_helper_vulkan.cc +++ b/samples/config_helper_vulkan.cc @@ -334,12 +334,14 @@ bool AreAllValidationLayersSupported() { required_layer_set.erase(property.layerName); } - if (required_layer_set.empty()) + if (required_layer_set.empty()) { return true; + } std::string missing_layers; - for (const auto& missing_layer : required_layer_set) + for (const auto& missing_layer : required_layer_set) { missing_layers = missing_layers + missing_layer + ",\n\t\t"; + } LogError("Vulkan: missing validation layers:\n\t\t" + missing_layers); return true; } @@ -361,8 +363,9 @@ bool AreAllValidationExtensionsSupported() { } for (const auto& ext : extension_properties) { - if (!strcmp(kExtensionForValidationLayer, ext.extensionName)) + if (!strcmp(kExtensionForValidationLayer, ext.extensionName)) { return true; + } } } @@ -608,8 +611,9 @@ std::vector GetAvailableInstanceExtensions() { return available_extensions; } - if (available_extension_count == 0) + if (available_extension_count == 0) { return available_extensions; + } available_extension_properties.resize(available_extension_count); if (vkEnumerateInstanceExtensionProperties( @@ -618,8 +622,9 @@ std::vector GetAvailableInstanceExtensions() { return available_extensions; } - for (const auto& property : available_extension_properties) + for (const auto& property : available_extension_properties) { available_extensions.push_back(property.extensionName); + } return available_extensions; } @@ -637,8 +642,9 @@ std::vector GetAvailableDeviceExtensions( return available_extensions; } - if (available_extension_count == 0) + if (available_extension_count == 0) { return available_extensions; + } available_extension_properties.resize(available_extension_count); if (vkEnumerateDeviceExtensionProperties( @@ -647,8 +653,9 @@ std::vector GetAvailableDeviceExtensions( return available_extensions; } - for (const auto& property : available_extension_properties) + for (const auto& property : available_extension_properties) { available_extensions.push_back(property.extensionName); + } return available_extensions; } @@ -658,8 +665,9 @@ std::vector GetAvailableDeviceExtensions( bool AreAllExtensionsSupported( const std::vector& available_extensions, const std::vector& required_extensions) { - if (required_extensions.empty()) + if (required_extensions.empty()) { return true; + } std::set required_extension_set(required_extensions.begin(), required_extensions.end()); @@ -721,8 +729,9 @@ std::string stageFlagBitsToNames(const VkShaderStageFlags bits) { bool addSeparator = false; for (const auto& stage : stages) { if ((bits & stage.first) != 0) { - if (addSeparator) + if (addSeparator) { result << ", "; + } result << stage.second; addSeparator = true; } @@ -753,8 +762,9 @@ ConfigHelperVulkan::ConfigHelperVulkan() VkPhysicalDeviceDescriptorIndexingFeatures()) {} ConfigHelperVulkan::~ConfigHelperVulkan() { - if (vulkan_device_) + if (vulkan_device_) { vkDestroyDevice(vulkan_device_, nullptr); + } if (vulkan_callback_) { auto vkDestroyDebugReportCallbackEXT = @@ -767,8 +777,9 @@ ConfigHelperVulkan::~ConfigHelperVulkan() { } } - if (vulkan_instance_) + if (vulkan_instance_) { vkDestroyInstance(vulkan_instance_, nullptr); + } } amber::Result ConfigHelperVulkan::CreateVulkanInstance( @@ -792,8 +803,9 @@ amber::Result ConfigHelperVulkan::CreateVulkanInstance( std::vector layer_names; if (!disable_validation_layer) { - if (!AreAllValidationLayersSupported()) + if (!AreAllValidationLayersSupported()) { return amber::Result("Sample: not all validation layers are supported"); + } if (!AreAllValidationExtensionsSupported()) { return amber::Result( "Sample: extensions of validation layers are not supported"); @@ -829,8 +841,9 @@ amber::Result ConfigHelperVulkan::CreateVulkanInstance( // Determine if VkPhysicalDeviceProperties2KHR should be used for (auto& ext : required_extensions) { - if (ext == "VK_KHR_get_physical_device_properties2") + if (ext == "VK_KHR_get_physical_device_properties2") { supports_get_physical_device_properties2_ = true; + } } std::vector required_extensions_in_char; @@ -864,8 +877,9 @@ amber::Result ConfigHelperVulkan::CreateDebugReportCallback() { reinterpret_cast( vkGetInstanceProcAddr(vulkan_instance_, "vkCreateDebugReportCallbackEXT")); - if (!vkCreateDebugReportCallbackEXT) + if (!vkCreateDebugReportCallbackEXT) { return amber::Result("Sample: vkCreateDebugReportCallbackEXT is nullptr"); + } if (vkCreateDebugReportCallbackEXT(vulkan_instance_, &info, nullptr, &vulkan_callback_) != VK_SUCCESS) { @@ -884,34 +898,35 @@ amber::Result ConfigHelperVulkan::CheckVulkanPhysicalDeviceRequirements( return amber::Result("Device does not support all required extensions"); } for (const auto& ext : available_device_extensions_) { - if (ext == "VK_KHR_shader_float16_int8") + if (ext == "VK_KHR_shader_float16_int8") { supports_shader_float16_int8_ = true; - else if (ext == "VK_KHR_8bit_storage") + } else if (ext == "VK_KHR_8bit_storage") { supports_shader_8bit_storage_ = true; - else if (ext == "VK_KHR_16bit_storage") + } else if (ext == "VK_KHR_16bit_storage") { supports_shader_16bit_storage_ = true; - else if (ext == "VK_EXT_subgroup_size_control") + } else if (ext == "VK_EXT_subgroup_size_control") { supports_subgroup_size_control_ = true; - else if (ext == "VK_EXT_depth_clamp_zero_one") + } else if (ext == "VK_EXT_depth_clamp_zero_one") { supports_depth_clamp_zero_one_ = true; - else if (ext == "VK_KHR_shader_subgroup_extended_types") + } else if (ext == "VK_KHR_shader_subgroup_extended_types") { supports_shader_subgroup_extended_types_ = true; - else if (ext == "VK_KHR_variable_pointers") + } else if (ext == "VK_KHR_variable_pointers") { supports_variable_pointers_ = true; - else if (ext == "VK_KHR_acceleration_structure") + } else if (ext == "VK_KHR_acceleration_structure") { supports_acceleration_structure_ = true; - else if (ext == "VK_KHR_buffer_device_address") + } else if (ext == "VK_KHR_buffer_device_address") { supports_buffer_device_address_ = true; - else if (ext == "VK_KHR_ray_tracing_pipeline") + } else if (ext == "VK_KHR_ray_tracing_pipeline") { supports_ray_tracing_pipeline_ = true; - else if (ext == VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME) + } else if (ext == VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME) { supports_descriptor_indexing_ = true; - else if (ext == VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME) + } else if (ext == VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME) { supports_deferred_host_operations_ = true; - else if (ext == VK_KHR_SPIRV_1_4_EXTENSION_NAME) + } else if (ext == VK_KHR_SPIRV_1_4_EXTENSION_NAME) { supports_spirv_1_4_ = true; - else if (ext == VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME) + } else if (ext == VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME) { supports_shader_float_controls_ = true; + } } VkPhysicalDeviceFeatures required_vulkan_features = @@ -922,8 +937,8 @@ amber::Result ConfigHelperVulkan::CheckVulkanPhysicalDeviceRequirements( shader_subgroup_extended_types_features = {}; VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features = {}; - VkPhysicalDeviceDepthClampZeroOneFeaturesEXT - depth_clamp_zero_one_features = {}; + VkPhysicalDeviceDepthClampZeroOneFeaturesEXT depth_clamp_zero_one_features = + {}; VkPhysicalDeviceVariablePointerFeaturesKHR variable_pointers_features = {}; VkPhysicalDeviceFloat16Int8FeaturesKHR float16_int8_features = {}; VkPhysicalDevice8BitStorageFeaturesKHR storage_8bit_features = {}; @@ -1082,14 +1097,16 @@ amber::Result ConfigHelperVulkan::CheckVulkanPhysicalDeviceRequirements( amber::Result r = NamesToVulkanFeatures(required_features1, &required_vulkan_features); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { amber::Result r = NamesToVulkanFeatures(required_features, &required_vulkan_features); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } vkGetPhysicalDeviceFeatures(physical_device, &available_features_); } @@ -1132,16 +1149,18 @@ amber::Result ConfigHelperVulkan::ChooseVulkanPhysicalDevice( } amber::Result r = CheckVulkanPhysicalDeviceRequirements( physical_devices[deviceID], required_features, required_extensions); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } vulkan_physical_device_ = physical_devices[deviceID]; return {}; } else { for (uint32_t i = 0; i < count; ++i) { amber::Result r = CheckVulkanPhysicalDeviceRequirements( physical_devices[i], required_features, required_extensions); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { continue; + } vulkan_physical_device_ = physical_devices[i]; return {}; } @@ -1149,10 +1168,12 @@ amber::Result ConfigHelperVulkan::ChooseVulkanPhysicalDevice( std::ostringstream out; out << "Unable to find Vulkan device supporting:" << std::endl; - for (const auto& str : required_features) + for (const auto& str : required_features) { out << " " << str << std::endl; - for (const auto& str : required_extensions) + } + for (const auto& str : required_extensions) { out << " " << str << std::endl; + } return amber::Result(out.str()); } @@ -1173,9 +1194,10 @@ amber::Result ConfigHelperVulkan::CreateVulkanDevice( info.pQueueCreateInfos = &queue_info; info.queueCreateInfoCount = 1; - if (supports_get_physical_device_properties2_) + if (supports_get_physical_device_properties2_) { return CreateDeviceWithFeatures2(required_features, required_extensions, &info); + } return CreateDeviceWithFeatures1(required_features, required_extensions, &info); } @@ -1198,8 +1220,9 @@ amber::Result ConfigHelperVulkan::CreateDeviceWithFeatures1( VkPhysicalDeviceFeatures(); amber::Result r = NamesToVulkanFeatures(required_features, &required_vulkan_features); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } info->pEnabledFeatures = &required_vulkan_features; return DoCreateDevice(info); @@ -1318,51 +1341,53 @@ amber::Result ConfigHelperVulkan::CreateDeviceWithFeatures2( continue; } - if (feature == kVariablePointers) + if (feature == kVariablePointers) { variable_pointers_feature_.variablePointers = VK_TRUE; - else if (feature == kVariablePointersStorageBuffer) + } else if (feature == kVariablePointersStorageBuffer) { variable_pointers_feature_.variablePointersStorageBuffer = VK_TRUE; - else if (feature == kFloat16Int8_Float16) + } else if (feature == kFloat16Int8_Float16) { float16_int8_feature_.shaderFloat16 = VK_TRUE; - else if (feature == kFloat16Int8_Int8) + } else if (feature == kFloat16Int8_Int8) { float16_int8_feature_.shaderInt8 = VK_TRUE; - else if (feature == k8BitStorage_Storage) + } else if (feature == k8BitStorage_Storage) { storage_8bit_feature_.storageBuffer8BitAccess = VK_TRUE; - else if (feature == k8BitStorage_UniformAndStorage) + } else if (feature == k8BitStorage_UniformAndStorage) { storage_8bit_feature_.uniformAndStorageBuffer8BitAccess = VK_TRUE; - else if (feature == k8BitStorage_PushConstant) + } else if (feature == k8BitStorage_PushConstant) { storage_8bit_feature_.storagePushConstant8 = VK_TRUE; - else if (feature == k16BitStorage_Storage) + } else if (feature == k16BitStorage_Storage) { storage_16bit_feature_.storageBuffer16BitAccess = VK_TRUE; - else if (feature == k16BitStorage_UniformAndStorage) + } else if (feature == k16BitStorage_UniformAndStorage) { storage_16bit_feature_.uniformAndStorageBuffer16BitAccess = VK_TRUE; - else if (feature == k16BitStorage_PushConstant) + } else if (feature == k16BitStorage_PushConstant) { storage_16bit_feature_.storagePushConstant16 = VK_TRUE; - else if (feature == k16BitStorage_InputOutput) + } else if (feature == k16BitStorage_InputOutput) { storage_16bit_feature_.storageInputOutput16 = VK_TRUE; - else if (feature == kSubgroupSizeControl) + } else if (feature == kSubgroupSizeControl) { subgroup_size_control_feature_.subgroupSizeControl = VK_TRUE; - else if (feature == kComputeFullSubgroups) + } else if (feature == kComputeFullSubgroups) { subgroup_size_control_feature_.computeFullSubgroups = VK_TRUE; - else if (feature == kDepthClampZeroOne) + } else if (feature == kDepthClampZeroOne) { depth_clamp_zero_one_feature_.depthClampZeroOne = VK_TRUE; - else if (feature == kShaderSubgroupExtendedTypes) + } else if (feature == kShaderSubgroupExtendedTypes) { shader_subgroup_extended_types_feature_.shaderSubgroupExtendedTypes = VK_TRUE; - else if (feature == kAccelerationStructure) + } else if (feature == kAccelerationStructure) { acceleration_structure_feature_.accelerationStructure = VK_TRUE; - else if (feature == kBufferDeviceAddress) + } else if (feature == kBufferDeviceAddress) { buffer_device_address_feature_.bufferDeviceAddress = VK_TRUE; - else if (feature == kRayTracingPipeline) + } else if (feature == kRayTracingPipeline) { ray_tracing_pipeline_feature_.rayTracingPipeline = VK_TRUE; + } } VkPhysicalDeviceFeatures required_vulkan_features = VkPhysicalDeviceFeatures(); amber::Result r = NamesToVulkanFeatures(feature1_names, &required_vulkan_features); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } available_features2_.features = required_vulkan_features; @@ -1498,26 +1523,31 @@ amber::Result ConfigHelperVulkan::CreateConfig( amber::Result r = CreateVulkanInstance( engine_major, engine_minor, required_instance_extensions, disable_validation_layer, enable_pipeline_runtime_layer); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } if (!disable_validation_layer) { r = CreateDebugReportCallback(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } r = ChooseVulkanPhysicalDevice(required_features, required_device_extensions, selected_device); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } - if (show_version_info) + if (show_version_info) { DumpPhysicalDeviceInfo(); + } r = CreateVulkanDevice(required_features, required_device_extensions); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } vkGetDeviceQueue(vulkan_device_, vulkan_queue_family_index_, 0, &vulkan_queue_); diff --git a/samples/image_diff.cc b/samples/image_diff.cc index ec541fc48..6afac2321 100644 --- a/samples/image_diff.cc +++ b/samples/image_diff.cc @@ -184,15 +184,17 @@ int main(int argc, const char** argv) { } amber::Result res; - if (options.compare_algorithm == CompareAlgorithm::kRMSE) + if (options.compare_algorithm == CompareAlgorithm::kRMSE) { res = buffers[0].CompareRMSE(&buffers[1], options.tolerance); - else if (options.compare_algorithm == CompareAlgorithm::kHISTOGRAM_EMD) + } else if (options.compare_algorithm == CompareAlgorithm::kHISTOGRAM_EMD) { res = buffers[0].CompareHistogramEMD(&buffers[1], options.tolerance); + } - if (res.IsSuccess()) + if (res.IsSuccess()) { std::cout << "Images similar" << std::endl; - else + } else { std::cout << "Images differ: " << res.Error() << std::endl; + } return !res.IsSuccess(); } diff --git a/samples/png.cc b/samples/png.cc index 3dbf4fd63..e7613788b 100644 --- a/samples/png.cc +++ b/samples/png.cc @@ -75,8 +75,9 @@ amber::Result ConvertToPNG(uint32_t width, state.info_png.color.colortype = LodePNGColorType::LCT_RGBA; state.info_png.color.bitdepth = 8; - if (lodepng::encode(*buffer, data, width, height, state) != 0) + if (lodepng::encode(*buffer, data, width, height, state) != 0) { return amber::Result("lodepng::encode() returned non-zero"); + } return {}; } diff --git a/samples/ppm.cc b/samples/ppm.cc index a84251294..a058fe0ba 100644 --- a/samples/ppm.cc +++ b/samples/ppm.cc @@ -51,8 +51,9 @@ amber::Result ConvertToPPM(uint32_t width, image += std::to_string(width) + " " + std::to_string(height) + "\n"; image += std::to_string(kMaximumColorValue) + "\n"; - for (char ch : image) + for (char ch : image) { buffer->push_back(static_cast(ch)); + } // Write PPM data for (amber::Value value : values) { diff --git a/src/acceleration_structure.h b/src/acceleration_structure.h index 180fde0ab..6ed9d8de5 100644 --- a/src/acceleration_structure.h +++ b/src/acceleration_structure.h @@ -262,8 +262,9 @@ class SBT { std::vector>& GetSBTRecords() { return records_; } uint32_t GetSBTSize() { uint32_t size = 0; - for (auto& x : records_) + for (auto& x : records_) { size += x->GetCount(); + } return size; } diff --git a/src/amber.cc b/src/amber.cc index 20ebcf815..6538682a6 100644 --- a/src/amber.cc +++ b/src/amber.cc @@ -37,12 +37,14 @@ Result GetFrameBuffer(Buffer* buffer, std::vector* values) { values->clear(); // TODO(jaebaek): Support other formats - if (buffer->GetFormat()->GetFormatType() != kDefaultFramebufferFormat) + if (buffer->GetFormat()->GetFormatType() != kDefaultFramebufferFormat) { return Result("GetFrameBuffer Unsupported buffer format"); + } const uint8_t* cpu_memory = buffer->ValuePtr()->data(); - if (!cpu_memory) + if (!cpu_memory) { return Result("GetFrameBuffer missing memory pointer"); + } const auto texel_stride = buffer->GetElementStride(); const auto row_stride = buffer->GetRowStride(); @@ -88,18 +90,21 @@ Amber::Amber(Delegate* delegate) : delegate_(delegate) {} Amber::~Amber() = default; amber::Result Amber::Parse(const std::string& input, amber::Recipe* recipe) { - if (!recipe) + if (!recipe) { return Result("Recipe must be provided to Parse."); + } std::unique_ptr parser; - if (input.substr(0, 7) == "#!amber") + if (input.substr(0, 7) == "#!amber") { parser = MakeUnique(GetDelegate()); - else + } else { parser = MakeUnique(GetDelegate()); + } Result r = parser->Parse(input); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } recipe->SetImpl(parser->GetScript().release()); return {}; @@ -116,12 +121,14 @@ Result CreateEngineAndCheckRequirements(const Recipe* recipe, Delegate* delegate, std::unique_ptr* engine_ptr, Script** script_ptr) { - if (!recipe) + if (!recipe) { return Result("Attempting to check an invalid recipe"); + } Script* script = static_cast(recipe->GetImpl()); - if (!script) + if (!script) { return Result("Recipe must contain a parsed script"); + } script->SetSpvTargetEnv(opts->spv_env); @@ -136,8 +143,9 @@ Result CreateEngineAndCheckRequirements(const Recipe* recipe, opts->config, delegate, script->GetRequiredFeatures(), script->GetRequiredProperties(), script->GetRequiredInstanceExtensions(), script->GetRequiredDeviceExtensions()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } *engine_ptr = std::move(engine); *script_ptr = script; @@ -167,8 +175,9 @@ amber::Result Amber::ExecuteWithShaderData(const amber::Recipe* recipe, Script* script = nullptr; Result r = CreateEngineAndCheckRequirements(recipe, opts, GetDelegate(), &engine, &script); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } script->SetSpvTargetEnv(opts->spv_env); Executor executor; @@ -178,8 +187,9 @@ amber::Result Amber::ExecuteWithShaderData(const amber::Recipe* recipe, // us dump any buffers requested even on failure. if (script->GetPipelines().empty()) { - if (!executor_result.IsSuccess()) + if (!executor_result.IsSuccess()) { return executor_result; + } return {}; } @@ -188,8 +198,9 @@ amber::Result Amber::ExecuteWithShaderData(const amber::Recipe* recipe, for (BufferInfo& buffer_info : opts->extractions) { if (buffer_info.is_image_buffer) { auto* buffer = script->GetBuffer(buffer_info.buffer_name); - if (!buffer) + if (!buffer) { continue; + } buffer_info.width = buffer->GetWidth(); buffer_info.height = buffer->GetHeight(); @@ -199,21 +210,24 @@ amber::Result Amber::ExecuteWithShaderData(const amber::Recipe* recipe, DescriptorSetAndBindingParser p; r = p.Parse(buffer_info.buffer_name); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { continue; + } // Extract the named pipeline from the request, otherwise use the // first pipeline which was parsed. Pipeline* pipeline = nullptr; - if (p.HasPipelineName()) + if (p.HasPipelineName()) { pipeline = script->GetPipeline(p.PipelineName()); - else + } else { pipeline = script->GetPipelines()[0].get(); + } const auto* buffer = pipeline->GetBufferForBinding(p.GetDescriptorSet(), p.GetBinding()); - if (!buffer) + if (!buffer) { continue; + } const uint8_t* ptr = buffer->ValuePtr()->data(); auto& values = buffer_info.values; @@ -224,10 +238,12 @@ amber::Result Amber::ExecuteWithShaderData(const amber::Recipe* recipe, } } - if (!executor_result.IsSuccess()) + if (!executor_result.IsSuccess()) { return executor_result; - if (!r.IsSuccess()) + } + if (!r.IsSuccess()) { return r; + } return {}; } diff --git a/src/amberscript/parser.cc b/src/amberscript/parser.cc index 6ea311830..3ad8d3750 100644 --- a/src/amberscript/parser.cc +++ b/src/amberscript/parser.cc @@ -41,16 +41,21 @@ bool IsComparator(const std::string& in) { } ProbeSSBOCommand::Comparator ToComparator(const std::string& in) { - if (in == "EQ") + if (in == "EQ") { return ProbeSSBOCommand::Comparator::kEqual; - if (in == "NE") + } + if (in == "NE") { return ProbeSSBOCommand::Comparator::kNotEqual; - if (in == "GT") + } + if (in == "GT") { return ProbeSSBOCommand::Comparator::kGreater; - if (in == "LT") + } + if (in == "LT") { return ProbeSSBOCommand::Comparator::kLess; - if (in == "GE") + } + if (in == "GE") { return ProbeSSBOCommand::Comparator::kGreaterOrEqual; + } assert(in == "LE"); return ProbeSSBOCommand::Comparator::kLessOrEqual; @@ -91,16 +96,19 @@ std::unique_ptr ToType(const std::string& str_in) { } else if (str == "double") { type = parser.Parse("R64_SFLOAT"); } else if (str.length() > 7 && str.substr(0, 3) == "vec") { - if (str[4] != '<' || str[str.length() - 1] != '>') + if (str[4] != '<' || str[str.length() - 1] != '>') { return nullptr; + } int component_count = str[3] - '0'; - if (component_count < 2 || component_count > 4) + if (component_count < 2 || component_count > 4) { return nullptr; + } type = ToType(str.substr(5, str.length() - 6)); - if (!type) + if (!type) { return nullptr; + } if (!type->IsNumber() || type->IsArray() || type->IsVec() || type->IsMatrix()) { @@ -109,20 +117,24 @@ std::unique_ptr ToType(const std::string& str_in) { type->SetRowCount(static_cast(component_count)); } else if (str.length() > 9 && str.substr(0, 3) == "mat") { - if (str[4] != 'x' || str[6] != '<' || str[str.length() - 1] != '>') + if (str[4] != 'x' || str[6] != '<' || str[str.length() - 1] != '>') { return nullptr; + } int column_count = str[3] - '0'; - if (column_count < 2 || column_count > 4) + if (column_count < 2 || column_count > 4) { return nullptr; + } int row_count = str[5] - '0'; - if (row_count < 2 || row_count > 4) + if (row_count < 2 || row_count > 4) { return nullptr; + } type = ToType(str.substr(7, str.length() - 8)); - if (!type) + if (!type) { return nullptr; + } if (!type->IsNumber() || type->IsArray() || type->IsVec() || type->IsMatrix()) { return nullptr; @@ -132,67 +144,90 @@ std::unique_ptr ToType(const std::string& str_in) { type->SetColumnCount(static_cast(column_count)); } - if (!type) + if (!type) { return nullptr; - if (is_array) + } + if (is_array) { type->SetIsRuntimeArray(); + } return type; } AddressMode StrToAddressMode(std::string str) { - if (str == "repeat") + if (str == "repeat") { return AddressMode::kRepeat; - if (str == "mirrored_repeat") + } + if (str == "mirrored_repeat") { return AddressMode::kMirroredRepeat; - if (str == "clamp_to_edge") + } + if (str == "clamp_to_edge") { return AddressMode::kClampToEdge; - if (str == "clamp_to_border") + } + if (str == "clamp_to_border") { return AddressMode::kClampToBorder; - if (str == "mirror_clamp_to_edge") + } + if (str == "mirror_clamp_to_edge") { return AddressMode::kMirrorClampToEdge; + } return AddressMode::kUnknown; } CompareOp StrToCompareOp(const std::string& str) { - if (str == "never") + if (str == "never") { return CompareOp::kNever; - if (str == "less") + } + if (str == "less") { return CompareOp::kLess; - if (str == "equal") + } + if (str == "equal") { return CompareOp::kEqual; - if (str == "less_or_equal") + } + if (str == "less_or_equal") { return CompareOp::kLessOrEqual; - if (str == "greater") + } + if (str == "greater") { return CompareOp::kGreater; - if (str == "not_equal") + } + if (str == "not_equal") { return CompareOp::kNotEqual; - if (str == "greater_or_equal") + } + if (str == "greater_or_equal") { return CompareOp::kGreaterOrEqual; - if (str == "always") + } + if (str == "always") { return CompareOp::kAlways; + } return CompareOp::kUnknown; } StencilOp StrToStencilOp(const std::string& str) { - if (str == "keep") + if (str == "keep") { return StencilOp::kKeep; - if (str == "zero") + } + if (str == "zero") { return StencilOp::kZero; - if (str == "replace") + } + if (str == "replace") { return StencilOp::kReplace; - if (str == "increment_and_clamp") + } + if (str == "increment_and_clamp") { return StencilOp::kIncrementAndClamp; - if (str == "decrement_and_clamp") + } + if (str == "decrement_and_clamp") { return StencilOp::kDecrementAndClamp; - if (str == "invert") + } + if (str == "invert") { return StencilOp::kInvert; - if (str == "increment_and_wrap") + } + if (str == "increment_and_wrap") { return StencilOp::kIncrementAndWrap; - if (str == "decrement_and_wrap") + } + if (str == "decrement_and_wrap") { return StencilOp::kDecrementAndWrap; + } return StencilOp::kUnknown; } @@ -207,8 +242,9 @@ Result ParseBufferData(Buffer* buffer, std::vector values; for (auto token = tokenizer->NextToken();; token = tokenizer->NextToken()) { - if (token->IsEOL()) + if (token->IsEOL()) { continue; + } if (token->IsEOS()) { if (from_data_file) { break; @@ -216,15 +252,18 @@ Result ParseBufferData(Buffer* buffer, return Result("missing BUFFER END command"); } } - if (token->IsIdentifier() && token->AsString() == "END") + if (token->IsIdentifier() && token->AsString() == "END") { break; - if (!token->IsInteger() && !token->IsDouble() && !token->IsHex()) + } + if (!token->IsInteger() && !token->IsDouble() && !token->IsHex()) { return Result("invalid BUFFER data value: " + token->ToOriginalString()); + } while (segs[seg_idx].IsPadding()) { ++seg_idx; - if (seg_idx >= segs.size()) + if (seg_idx >= segs.size()) { seg_idx = 0; + } } Value v; @@ -246,22 +285,25 @@ Result ParseBufferData(Buffer* buffer, ++value_count; } ++seg_idx; - if (seg_idx >= segs.size()) + if (seg_idx >= segs.size()) { seg_idx = 0; + } values.emplace_back(v); } // Write final padding bytes while (segs[seg_idx].IsPadding()) { ++seg_idx; - if (seg_idx >= segs.size()) + if (seg_idx >= segs.size()) { break; + } } buffer->SetValueCount(value_count); Result r = buffer->SetData(std::move(values)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } @@ -289,10 +331,12 @@ Result Parser::Parse(const std::string& data) { for (auto token = tokenizer_->NextToken(); !token->IsEOS(); token = tokenizer_->NextToken()) { - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result(make_error("expected identifier")); + } Result r; std::string tok = token->AsString(); @@ -331,8 +375,9 @@ Result Parser::Parse(const std::string& data) { } else { r = Result("unknown token: " + tok); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return Result(make_error(r.Error())); + } } script_->SetCommands(std::move(command_list_)); @@ -348,12 +393,14 @@ Result Parser::Parse(const std::string& data) { buf = color_buf.get(); Result r = script_->AddBuffer(std::move(color_buf)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } Result r = pipeline->AddColorAttachment(buf, 0, 0); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } } @@ -361,8 +408,9 @@ Result Parser::Parse(const std::string& data) { // framebuffer sizes are consistent over pipelines. for (const auto& pipeline : script_->GetPipelines()) { Result r = pipeline->Validate(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } return {}; @@ -377,20 +425,27 @@ bool Parser::IsRepeatable(const std::string& name) const { // The given |name| must be one of the repeatable commands or this method // returns an error result. Result Parser::ParseRepeatableCommand(const std::string& name) { - if (name == "CLEAR") + if (name == "CLEAR") { return ParseClear(); - if (name == "CLEAR_COLOR") + } + if (name == "CLEAR_COLOR") { return ParseClearColor(); - if (name == "CLEAR_DEPTH") + } + if (name == "CLEAR_DEPTH") { return ParseClearDepth(); - if (name == "CLEAR_STENCIL") + } + if (name == "CLEAR_STENCIL") { return ParseClearStencil(); - if (name == "COPY") + } + if (name == "COPY") { return ParseCopy(); - if (name == "EXPECT") + } + if (name == "EXPECT") { return ParseExpect(); - if (name == "RUN") + } + if (name == "RUN") { return ParseRun(); + } return Result("invalid repeatable command: " + name); } @@ -398,100 +453,108 @@ Result Parser::ParseRepeatableCommand(const std::string& name) { Result Parser::ToShaderType(const std::string& str, ShaderType* type) { assert(type); - if (str == "vertex") + if (str == "vertex") { *type = kShaderTypeVertex; - else if (str == "fragment") + } else if (str == "fragment") { *type = kShaderTypeFragment; - else if (str == "geometry") + } else if (str == "geometry") { *type = kShaderTypeGeometry; - else if (str == "tessellation_evaluation") + } else if (str == "tessellation_evaluation") { *type = kShaderTypeTessellationEvaluation; - else if (str == "tessellation_control") + } else if (str == "tessellation_control") { *type = kShaderTypeTessellationControl; - else if (str == "compute") + } else if (str == "compute") { *type = kShaderTypeCompute; - else if (str == "ray_generation") + } else if (str == "ray_generation") { *type = kShaderTypeRayGeneration; - else if (str == "any_hit") + } else if (str == "any_hit") { *type = kShaderTypeAnyHit; - else if (str == "closest_hit") + } else if (str == "closest_hit") { *type = kShaderTypeClosestHit; - else if (str == "miss") + } else if (str == "miss") { *type = kShaderTypeMiss; - else if (str == "intersection") + } else if (str == "intersection") { *type = kShaderTypeIntersection; - else if (str == "callable") + } else if (str == "callable") { *type = kShaderTypeCall; - else if (str == "multi") + } else if (str == "multi") { *type = kShaderTypeMulti; - else + } else { return Result("unknown shader type: " + str); + } return {}; } Result Parser::ToShaderFormat(const std::string& str, ShaderFormat* fmt) { assert(fmt); - if (str == "GLSL") + if (str == "GLSL") { *fmt = kShaderFormatGlsl; - else if (str == "HLSL") + } else if (str == "HLSL") { *fmt = kShaderFormatHlsl; - else if (str == "SPIRV-ASM") + } else if (str == "SPIRV-ASM") { *fmt = kShaderFormatSpirvAsm; - else if (str == "SPIRV-HEX") + } else if (str == "SPIRV-HEX") { *fmt = kShaderFormatSpirvHex; - else if (str == "SPIRV-BIN") + } else if (str == "SPIRV-BIN") { *fmt = kShaderFormatSpirvBin; - else if (str == "OPENCL-C") + } else if (str == "OPENCL-C") { *fmt = kShaderFormatOpenCLC; - else + } else { return Result("unknown shader format: " + str); + } return {}; } Result Parser::ToPipelineType(const std::string& str, PipelineType* type) { assert(type); - if (str == "compute") + if (str == "compute") { *type = PipelineType::kCompute; - else if (str == "graphics") + } else if (str == "graphics") { *type = PipelineType::kGraphics; - else if (str == "raytracing") + } else if (str == "raytracing") { *type = PipelineType::kRayTracing; - else + } else { return Result("unknown pipeline type: " + str); + } return {}; } Result Parser::ValidateEndOfStatement(const std::string& name) { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return {}; + } return Result("extra parameters after " + name + ": " + token->ToOriginalString()); } Result Parser::ParseShaderBlock() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for shader type"); + } ShaderType type = kShaderTypeVertex; Result r = ToShaderType(token->AsString(), &type); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } auto shader = MakeUnique(type); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for shader name"); + } shader->SetName(token->AsString()); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for shader format"); + } std::string fmt = token->AsString(); if (fmt == "PASSTHROUGH") { @@ -505,16 +568,18 @@ Result Parser::ParseShaderBlock() { shader->SetTargetEnv("spv1.0"); r = script_->AddShader(std::move(shader)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("SHADER PASSTHROUGH"); } ShaderFormat format = kShaderFormatGlsl; r = ToShaderFormat(fmt, &format); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } shader->SetFormat(format); @@ -522,8 +587,9 @@ Result Parser::ParseShaderBlock() { if (token->IsIdentifier() && token->AsString() == "TARGET_ENV") { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() && !token->IsString()) + if (!token->IsIdentifier() && !token->IsString()) { return Result("expected target environment after TARGET_ENV"); + } shader->SetTargetEnv(token->AsString()); } @@ -534,24 +600,28 @@ Result Parser::ParseShaderBlock() { tokenizer_->NextToken(); // Skip VIRTUAL_FILE or FILE token = tokenizer_->NextToken(); - if (!token->IsIdentifier() && !token->IsString()) + if (!token->IsIdentifier() && !token->IsString()) { return Result("expected file path after VIRTUAL_FILE or FILE"); + } auto path = token->AsString(); std::string data; if (isVirtual) { r = script_->GetVirtualFile(path, &data); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { - if (!delegate_) + if (!delegate_) { return Result("missing delegate for loading shader file"); + } std::vector buffer; r = delegate_->LoadFile(path, &buffer); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } data.insert(data.begin(), buffer.begin(), buffer.end()); } @@ -560,19 +630,22 @@ Result Parser::ParseShaderBlock() { shader->SetFilePath(path); r = script_->AddShader(std::move(shader)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("SHADER command"); } r = ValidateEndOfStatement("SHADER command"); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } std::string data = tokenizer_->ExtractToNext("END"); - if (data.empty()) + if (data.empty()) { return Result("SHADER must not be empty"); + } shader->SetData(data); @@ -581,40 +654,47 @@ Result Parser::ParseShaderBlock() { shader->SetFilePath(path); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "END") + if (!token->IsIdentifier() || token->AsString() != "END") { return Result("SHADER missing END command"); + } - if (shader->GetTargetEnv().empty() && IsRayTracingShader(type)) + if (shader->GetTargetEnv().empty() && IsRayTracingShader(type)) { shader->SetTargetEnv("spv1.4"); + } r = script_->AddShader(std::move(shader)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("END"); } Result Parser::ParsePipelineBlock() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for pipeline type"); + } PipelineType type = PipelineType::kCompute; Result r = ToPipelineType(token->AsString(), &type); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } auto pipeline = MakeUnique(type); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for pipeline name"); + } pipeline->SetName(token->AsString()); r = ValidateEndOfStatement("PIPELINE command"); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ParsePipelineBody("PIPELINE", std::move(pipeline)); } @@ -624,10 +704,12 @@ Result Parser::ParsePipelineBody(const std::string& cmd_name, std::unique_ptr token; for (token = tokenizer_->NextToken(); !token->IsEOS(); token = tokenizer_->NextToken()) { - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("expected identifier"); + } Result r; std::string tok = token->AsString(); @@ -680,80 +762,96 @@ Result Parser::ParsePipelineBody(const std::string& cmd_name, } else { r = Result("unknown token in pipeline block: " + tok); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } - if (!token->IsIdentifier() || token->AsString() != "END") + if (!token->IsIdentifier() || token->AsString() != "END") { return Result(cmd_name + " missing END command"); + } Result r = script_->AddPipeline(std::move(pipeline)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("END"); } Result Parser::ParsePipelineAttach(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token in ATTACH command"); + } auto* shader = script_->GetShader(token->AsString()); - if (!shader) + if (!shader) { return Result("unknown shader in ATTACH command"); + } token = tokenizer_->NextToken(); if (token->IsEOL() || token->IsEOS()) { - if (shader->GetType() == kShaderTypeMulti) + if (shader->GetType() == kShaderTypeMulti) { return Result("multi shader ATTACH requires TYPE"); + } Result r = pipeline->AddShader(shader, shader->GetType()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token after ATTACH"); + } bool set_shader_type = false; ShaderType shader_type = shader->GetType(); auto type = token->AsString(); if (type == "TYPE") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid type in ATTACH"); + } Result r = ToShaderType(token->AsString(), &shader_type); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } set_shader_type = true; token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("ATTACH TYPE requires an ENTRY_POINT"); + } type = token->AsString(); } - if (set_shader_type && type != "ENTRY_POINT") + if (set_shader_type && type != "ENTRY_POINT") { return Result("unknown ATTACH parameter: " + type); + } - if (shader->GetType() == ShaderType::kShaderTypeMulti && !set_shader_type) + if (shader->GetType() == ShaderType::kShaderTypeMulti && !set_shader_type) { return Result("ATTACH missing TYPE for multi shader"); + } Result r = pipeline->AddShader(shader, shader_type); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } if (type == "ENTRY_POINT") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing shader name in ATTACH ENTRY_POINT command"); + } r = pipeline->SetShaderEntryPoint(shader, token->AsString()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } token = tokenizer_->NextToken(); } @@ -761,15 +859,18 @@ Result Parser::ParsePipelineAttach(Pipeline* pipeline) { while (true) { if (token->IsIdentifier() && token->AsString() == "SPECIALIZE") { r = ParseShaderSpecialization(pipeline); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } token = tokenizer_->NextToken(); } else { - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return {}; - if (token->IsIdentifier()) + } + if (token->IsIdentifier()) { return Result("unknown ATTACH parameter: " + token->AsString()); + } return Result("extra parameters after ATTACH command: " + token->ToOriginalString()); } @@ -778,24 +879,29 @@ Result Parser::ParsePipelineAttach(Pipeline* pipeline) { Result Parser::ParseShaderSpecialization(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("specialization ID must be an integer"); + } auto spec_id = token->AsUint32(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "AS") + if (!token->IsIdentifier() || token->AsString() != "AS") { return Result("expected AS as next token"); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("expected data type in SPECIALIZE subcommand"); + } auto type = ToType(token->AsString()); - if (!type) + if (!type) { return Result("invalid data type '" + token->AsString() + "' provided"); - if (!type->IsNumber()) + } + if (!type->IsNumber()) { return Result("only numeric types are accepted for specialization values"); + } auto num = type->AsNumber(); @@ -806,8 +912,9 @@ Result Parser::ParseShaderSpecialization(Pipeline* pipeline) { value = token->AsUint32(); } else if (type::Type::IsFloat32(num->GetFormatMode(), num->NumBits())) { Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return Result("value is not a floating point value"); + } union { uint32_t u; @@ -827,106 +934,129 @@ Result Parser::ParseShaderSpecialization(Pipeline* pipeline) { Result Parser::ParsePipelineShaderOptimizations(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing shader name in SHADER_OPTIMIZATION command"); + } auto* shader = script_->GetShader(token->AsString()); - if (!shader) + if (!shader) { return Result("unknown shader in SHADER_OPTIMIZATION command"); + } token = tokenizer_->NextToken(); - if (!token->IsEOL()) + if (!token->IsEOL()) { return Result("extra parameters after SHADER_OPTIMIZATION command: " + token->ToOriginalString()); + } std::vector optimizations; while (true) { token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (token->IsEOS()) + } + if (token->IsEOS()) { return Result("SHADER_OPTIMIZATION missing END command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("SHADER_OPTIMIZATION options must be identifiers"); - if (token->AsString() == "END") + } + if (token->AsString() == "END") { break; + } optimizations.push_back(token->AsString()); } Result r = pipeline->SetShaderOptimizations(shader, optimizations); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("SHADER_OPTIMIZATION command"); } Result Parser::ParsePipelineShaderCompileOptions(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing shader name in COMPILE_OPTIONS command"); + } auto* shader = script_->GetShader(token->AsString()); - if (!shader) + if (!shader) { return Result("unknown shader in COMPILE_OPTIONS command"); + } if (shader->GetFormat() != kShaderFormatOpenCLC) { return Result("COMPILE_OPTIONS currently only supports OPENCL-C shaders"); } token = tokenizer_->NextToken(); - if (!token->IsEOL()) + if (!token->IsEOL()) { return Result("extra parameters after COMPILE_OPTIONS command: " + token->ToOriginalString()); + } std::vector options; while (true) { token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (token->IsEOS()) + } + if (token->IsEOS()) { return Result("COMPILE_OPTIONS missing END command"); - if (token->AsString() == "END") + } + if (token->AsString() == "END") { break; + } options.push_back(token->AsString()); } Result r = pipeline->SetShaderCompileOptions(shader, options); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("COMPILE_OPTIONS command"); } Result Parser::ParsePipelineSubgroup(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing shader name in SUBGROUP command"); + } auto* shader = script_->GetShader(token->AsString()); - if (!shader) + if (!shader) { return Result("unknown shader in SUBGROUP command"); + } while (true) { token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (token->IsEOS()) + } + if (token->IsEOS()) { return Result("SUBGROUP missing END command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("SUBGROUP options must be identifiers"); - if (token->AsString() == "END") + } + if (token->AsString() == "END") { break; + } if (token->AsString() == "FULLY_POPULATED") { if (!script_->IsRequiredFeature( - "SubgroupSizeControl.computeFullSubgroups")) + "SubgroupSizeControl.computeFullSubgroups")) { return Result( "missing DEVICE_FEATURE SubgroupSizeControl.computeFullSubgroups"); + } token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing value for FULLY_POPULATED command"); + } bool isOn = false; if (token->AsString() == "on") { isOn = true; @@ -936,17 +1066,20 @@ Result Parser::ParsePipelineSubgroup(Pipeline* pipeline) { return Result("invalid value for FULLY_POPULATED command"); } Result r = pipeline->SetShaderRequireFullSubgroups(shader, isOn); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (token->AsString() == "VARYING_SIZE") { if (!script_->IsRequiredFeature( - "SubgroupSizeControl.subgroupSizeControl")) + "SubgroupSizeControl.subgroupSizeControl")) { return Result( "missing DEVICE_FEATURE SubgroupSizeControl.subgroupSizeControl"); + } token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing value for VARYING_SIZE command"); + } bool isOn = false; if (token->AsString() == "on") { isOn = true; @@ -956,16 +1089,19 @@ Result Parser::ParsePipelineSubgroup(Pipeline* pipeline) { return Result("invalid value for VARYING_SIZE command"); } Result r = pipeline->SetShaderVaryingSubgroupSize(shader, isOn); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (token->AsString() == "REQUIRED_SIZE") { if (!script_->IsRequiredFeature( - "SubgroupSizeControl.subgroupSizeControl")) + "SubgroupSizeControl.subgroupSizeControl")) { return Result( "missing DEVICE_FEATURE SubgroupSizeControl.subgroupSizeControl"); + } token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing size for REQUIRED_SIZE command"); + } Result r; if (token->IsInteger()) { r = pipeline->SetShaderRequiredSubgroupSize(shader, token->AsUint32()); @@ -976,8 +1112,9 @@ Result Parser::ParsePipelineSubgroup(Pipeline* pipeline) { } else { return Result("invalid size for REQUIRED_SIZE command"); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { return Result("SUBGROUP invalid value for SUBGROUP " + token->AsString()); } @@ -988,12 +1125,14 @@ Result Parser::ParsePipelineSubgroup(Pipeline* pipeline) { Result Parser::ParsePipelinePatchControlPoints(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result( "missing number of control points in PATCH_CONTROL_POINTS command"); + } - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expecting integer for the number of control points"); + } pipeline->GetPipelineData()->SetPatchControlPoints(token->AsUint32()); @@ -1002,18 +1141,22 @@ Result Parser::ParsePipelinePatchControlPoints(Pipeline* pipeline) { Result Parser::ParsePipelineFramebufferSize(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing size for FRAMEBUFFER_SIZE command"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("invalid width for FRAMEBUFFER_SIZE command"); + } pipeline->SetFramebufferWidth(token->AsUint32()); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing height for FRAMEBUFFER_SIZE command"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("invalid height for FRAMEBUFFER_SIZE command"); + } pipeline->SetFramebufferHeight(token->AsUint32()); @@ -1028,11 +1171,13 @@ Result Parser::ParsePipelineViewport(Pipeline* pipeline) { float val[2]; for (int i = 0; i < 2; i++) { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing offset for VIEWPORT command"); + } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return Result("invalid offset for VIEWPORT command"); + } val[i] = token->AsFloat(); } @@ -1040,16 +1185,19 @@ Result Parser::ParsePipelineViewport(Pipeline* pipeline) { vp.y = val[1]; auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "SIZE") + if (!token->IsIdentifier() || token->AsString() != "SIZE") { return Result("missing SIZE for VIEWPORT command"); + } for (int i = 0; i < 2; i++) { token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing size for VIEWPORT command"); + } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return Result("invalid size for VIEWPORT command"); + } val[i] = token->AsFloat(); } @@ -1061,22 +1209,26 @@ Result Parser::ParsePipelineViewport(Pipeline* pipeline) { if (token->AsString() == "MIN_DEPTH") { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing min_depth for VIEWPORT command"); + } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return Result("invalid min_depth for VIEWPORT command"); + } vp.mind = token->AsFloat(); } if (token->AsString() == "MAX_DEPTH") { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing max_depth for VIEWPORT command"); + } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return Result("invalid max_depth for VIEWPORT command"); + } vp.maxd = token->AsFloat(); } @@ -1091,34 +1243,35 @@ Result Parser::ParsePipelineViewport(Pipeline* pipeline) { Result Parser::ToBufferType(const std::string& name, BufferType* type) { assert(type); - if (name == "color") + if (name == "color") { *type = BufferType::kColor; - else if (name == "depth_stencil") + } else if (name == "depth_stencil") { *type = BufferType::kDepthStencil; - else if (name == "push_constant") + } else if (name == "push_constant") { *type = BufferType::kPushConstant; - else if (name == "uniform") + } else if (name == "uniform") { *type = BufferType::kUniform; - else if (name == "uniform_dynamic") + } else if (name == "uniform_dynamic") { *type = BufferType::kUniformDynamic; - else if (name == "storage") + } else if (name == "storage") { *type = BufferType::kStorage; - else if (name == "storage_dynamic") + } else if (name == "storage_dynamic") { *type = BufferType::kStorageDynamic; - else if (name == "storage_image") + } else if (name == "storage_image") { *type = BufferType::kStorageImage; - else if (name == "sampled_image") + } else if (name == "sampled_image") { *type = BufferType::kSampledImage; - else if (name == "combined_image_sampler") + } else if (name == "combined_image_sampler") { *type = BufferType::kCombinedImageSampler; - else if (name == "uniform_texel_buffer") + } else if (name == "uniform_texel_buffer") { *type = BufferType::kUniformTexelBuffer; - else if (name == "storage_texel_buffer") + } else if (name == "storage_texel_buffer") { *type = BufferType::kStorageTexelBuffer; - else if (name == "resolve") + } else if (name == "resolve") { *type = BufferType::kResolve; - else + } else { return Result("unknown buffer_type: " + name); + } return {}; } @@ -1137,12 +1290,14 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { if (object_type == "BUFFER" || object_type == "BUFFER_ARRAY") { bool is_buffer_array = object_type == "BUFFER_ARRAY"; token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing buffer name in BIND command"); + } auto* buffer = script_->GetBuffer(token->AsString()); - if (!buffer) + if (!buffer) { return Result("unknown buffer: " + token->AsString()); + } std::vector buffers = {buffer}; if (is_buffer_array) { @@ -1153,35 +1308,41 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { token->AsString() != "DESCRIPTOR_SET") { tokenizer_->NextToken(); buffer = script_->GetBuffer(token->AsString()); - if (!buffer) + if (!buffer) { return Result("unknown buffer: " + token->AsString()); + } buffers.push_back(buffer); token = tokenizer_->PeekNextToken(); } - if (buffers.size() < 2) + if (buffers.size() < 2) { return Result("expecting multiple buffer names for BUFFER_ARRAY"); + } } BufferType buffer_type = BufferType::kUnknown; token = tokenizer_->NextToken(); if (token->IsIdentifier() && token->AsString() == "AS") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token for BUFFER type"); + } Result r = ToBufferType(token->AsString(), &buffer_type); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } if (buffer_type == BufferType::kColor) { token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "LOCATION") + if (!token->IsIdentifier() || token->AsString() != "LOCATION") { return Result("BIND missing LOCATION"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for BIND LOCATION"); + } auto location = token->AsUint32(); uint32_t base_mip_level = 0; @@ -1190,47 +1351,56 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for BASE_MIP_LEVEL"); + } base_mip_level = token->AsUint32(); - if (base_mip_level >= buffer->GetMipLevels()) + if (base_mip_level >= buffer->GetMipLevels()) { return Result( "base mip level (now " + token->AsString() + ") needs to be larger than the number of buffer mip maps (" + std::to_string(buffer->GetMipLevels()) + ")"); + } } r = pipeline->AddColorAttachment(buffer, location, base_mip_level); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (buffer_type == BufferType::kDepthStencil) { r = pipeline->SetDepthStencilBuffer(buffer); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (buffer_type == BufferType::kPushConstant) { r = pipeline->SetPushConstantBuffer(buffer); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (buffer_type == BufferType::kCombinedImageSampler) { token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "SAMPLER") + if (!token->IsIdentifier() || token->AsString() != "SAMPLER") { return Result("expecting SAMPLER for combined image sampler"); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing sampler name in BIND command"); + } auto* sampler = script_->GetSampler(token->AsString()); - if (!sampler) + if (!sampler) { return Result("unknown sampler: " + token->AsString()); + } - for (auto& buf : buffers) + for (auto& buf : buffers) { buf->SetSampler(sampler); + } } else if (buffer_type == BufferType::kResolve) { r = pipeline->AddResolveTarget(buffer); } @@ -1251,23 +1421,27 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { // If the buffer type is known, then we proccessed the AS block above // and have to advance to the next token. Otherwise, we're already on // the next token and don't want to advance. - if (buffer_type != BufferType::kUnknown) + if (buffer_type != BufferType::kUnknown) { token = tokenizer_->NextToken(); + } // DESCRIPTOR_SET requires a buffer type to have been specified. if (token->IsIdentifier() && token->AsString() == "DESCRIPTOR_SET") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for DESCRIPTOR_SET in BIND command"); + } uint32_t descriptor_set = token->AsUint32(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "BINDING") + if (!token->IsIdentifier() || token->AsString() != "BINDING") { return Result("missing BINDING for BIND command"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for BINDING in BIND command"); + } auto binding = token->AsUint32(); uint32_t base_mip_level = 0; @@ -1280,16 +1454,18 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for BASE_MIP_LEVEL"); + } base_mip_level = token->AsUint32(); - if (base_mip_level >= buffer->GetMipLevels()) + if (base_mip_level >= buffer->GetMipLevels()) { return Result("base mip level (now " + token->AsString() + ") needs to be larger than the number of buffer " "mip maps (" + std::to_string(buffer->GetMipLevels()) + ")"); + } } } @@ -1297,8 +1473,9 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { if (buffer_type == BufferType::kUniformDynamic || buffer_type == BufferType::kStorageDynamic) { token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "OFFSET") + if (!token->IsIdentifier() || token->AsString() != "OFFSET") { return Result("expecting an OFFSET for dynamic buffer type"); + } for (size_t i = 0; i < buffers.size(); i++) { token = tokenizer_->NextToken(); @@ -1373,19 +1550,22 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { } } else if (token->IsIdentifier() && token->AsString() == "KERNEL") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing kernel arg identifier"); + } if (token->AsString() == "ARG_NAME") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("expected argument identifier"); + } pipeline->AddBuffer(buffer, buffer_type, token->AsString()); } else if (token->AsString() == "ARG_NUMBER") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expected argument number"); + } pipeline->AddBuffer(buffer, buffer_type, token->AsUint32()); } else { @@ -1398,12 +1578,14 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { } else if (object_type == "SAMPLER" || object_type == "SAMPLER_ARRAY") { bool is_sampler_array = object_type == "SAMPLER_ARRAY"; token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing sampler name in BIND command"); + } auto* sampler = script_->GetSampler(token->AsString()); - if (!sampler) + if (!sampler) { return Result("unknown sampler: " + token->AsString()); + } std::vector samplers = {sampler}; if (is_sampler_array) { @@ -1413,33 +1595,39 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { token->AsString() != "DESCRIPTOR_SET") { tokenizer_->NextToken(); sampler = script_->GetSampler(token->AsString()); - if (!sampler) + if (!sampler) { return Result("unknown sampler: " + token->AsString()); + } samplers.push_back(sampler); token = tokenizer_->PeekNextToken(); } - if (samplers.size() < 2) + if (samplers.size() < 2) { return Result("expecting multiple sampler names for SAMPLER_ARRAY"); + } } token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("expected a string token for BIND command"); + } if (token->AsString() == "DESCRIPTOR_SET") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for DESCRIPTOR_SET in BIND command"); + } uint32_t descriptor_set = token->AsUint32(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "BINDING") + if (!token->IsIdentifier() || token->AsString() != "BINDING") { return Result("missing BINDING for BIND command"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for BINDING in BIND command"); + } uint32_t binding = token->AsUint32(); pipeline->ClearSamplers(descriptor_set, binding); @@ -1448,19 +1636,22 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { } } else if (token->AsString() == "KERNEL") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing kernel arg identifier"); + } if (token->AsString() == "ARG_NAME") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("expected argument identifier"); + } pipeline->AddSampler(sampler, token->AsString()); } else if (token->AsString() == "ARG_NUMBER") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expected argument number"); + } pipeline->AddSampler(sampler, token->AsUint32()); } else { @@ -1471,29 +1662,34 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { } } else if (object_type == "ACCELERATION_STRUCTURE") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result( "missing top level acceleration structure name in BIND command"); + } TLAS* tlas = script_->GetTLAS(token->AsString()); - if (!tlas) + if (!tlas) { return Result("unknown top level acceleration structure: " + token->AsString()); + } token = tokenizer_->NextToken(); if (token->AsString() == "DESCRIPTOR_SET") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for DESCRIPTOR_SET in BIND command"); + } uint32_t descriptor_set = token->AsUint32(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "BINDING") + if (!token->IsIdentifier() || token->AsString() != "BINDING") { return Result("missing BINDING for BIND command"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for BINDING in BIND command"); + } uint32_t binding = token->AsUint32(); @@ -1510,20 +1706,24 @@ Result Parser::ParsePipelineBind(Pipeline* pipeline) { Result Parser::ParsePipelineVertexData(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing buffer name in VERTEX_DATA command"); + } auto* buffer = script_->GetBuffer(token->AsString()); - if (!buffer) + if (!buffer) { return Result("unknown buffer: " + token->AsString()); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "LOCATION") + if (!token->IsIdentifier() || token->AsString() != "LOCATION") { return Result("VERTEX_DATA missing LOCATION"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for VERTEX_DATA LOCATION"); + } const uint32_t location = token->AsUint32(); InputRate rate = InputRate::kVertex; @@ -1536,8 +1736,9 @@ Result Parser::ParsePipelineVertexData(Pipeline* pipeline) { if (token->AsString() == "RATE") { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing input rate value for RATE"); + } if (token->AsString() == "instance") { rate = InputRate::kInstance; } else if (token->AsString() != "vertex") { @@ -1546,25 +1747,30 @@ Result Parser::ParsePipelineVertexData(Pipeline* pipeline) { } else if (token->AsString() == "OFFSET") { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expected unsigned integer for OFFSET"); + } offset = token->AsUint32(); } else if (token->AsString() == "STRIDE") { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expected unsigned integer for STRIDE"); + } stride = token->AsUint32(); - if (stride == 0) + if (stride == 0) { return Result("STRIDE needs to be larger than zero"); + } } else if (token->AsString() == "FORMAT") { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("vertex data FORMAT must be an identifier"); + } auto type = script_->ParseType(token->AsString()); - if (!type) + if (!type) { return Result("invalid vertex data FORMAT"); + } auto fmt = MakeUnique(type); format = fmt.get(); script_->RegisterFormat(std::move(fmt)); @@ -1576,29 +1782,34 @@ Result Parser::ParsePipelineVertexData(Pipeline* pipeline) { token = tokenizer_->PeekNextToken(); } - if (stride == 0) + if (stride == 0) { stride = format->SizeInBytes(); + } Result r = pipeline->AddVertexBuffer(buffer, location, rate, format, offset, stride); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("VERTEX_DATA command"); } Result Parser::ParsePipelineIndexData(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing buffer name in INDEX_DATA command"); + } auto* buffer = script_->GetBuffer(token->AsString()); - if (!buffer) + if (!buffer) { return Result("unknown buffer: " + token->AsString()); + } Result r = pipeline->SetIndexBuffer(buffer); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("INDEX_DATA command"); } @@ -1611,25 +1822,29 @@ Result Parser::ParsePipelineSet(Pipeline* pipeline) { } auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "KERNEL") + if (!token->IsIdentifier() || token->AsString() != "KERNEL") { return Result("missing KERNEL in SET command"); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("expected ARG_NAME or ARG_NUMBER"); + } std::string arg_name = ""; uint32_t arg_no = std::numeric_limits::max(); if (token->AsString() == "ARG_NAME") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("expected argument identifier"); + } arg_name = token->AsString(); } else if (token->AsString() == "ARG_NUMBER") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expected argument number"); + } arg_no = token->AsUint32(); } else { @@ -1637,30 +1852,37 @@ Result Parser::ParsePipelineSet(Pipeline* pipeline) { } token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "AS") + if (!token->IsIdentifier() || token->AsString() != "AS") { return Result("missing AS in SET command"); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("expected data type"); + } auto type = ToType(token->AsString()); - if (!type) + if (!type) { return Result("invalid data type '" + token->AsString() + "' provided"); + } - if (type->IsVec() || type->IsMatrix() || type->IsArray() || type->IsStruct()) + if (type->IsVec() || type->IsMatrix() || type->IsArray() || + type->IsStruct()) { return Result("data type must be a scalar type"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger() && !token->IsDouble()) + if (!token->IsInteger() && !token->IsDouble()) { return Result("expected data value"); + } auto fmt = MakeUnique(type.get()); Value value; - if (fmt->IsFloat32() || fmt->IsFloat64()) + if (fmt->IsFloat32() || fmt->IsFloat64()) { value.SetDoubleValue(token->AsDouble()); - else + } else { value.SetIntValue(token->AsUint64()); + } Pipeline::ArgSetInfo info; info.name = arg_name; @@ -1676,19 +1898,21 @@ Result Parser::ParsePipelineSet(Pipeline* pipeline) { Result Parser::ParsePipelinePolygonMode(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing mode in POLYGON_MODE command"); + } auto mode = token->AsString(); - if (mode == "fill") + if (mode == "fill") { pipeline->GetPipelineData()->SetPolygonMode(PolygonMode::kFill); - else if (mode == "line") + } else if (mode == "line") { pipeline->GetPipelineData()->SetPolygonMode(PolygonMode::kLine); - else if (mode == "point") + } else if (mode == "point") { pipeline->GetPipelineData()->SetPolygonMode(PolygonMode::kPoint); - else + } else { return Result("invalid polygon mode: " + mode); + } return ValidateEndOfStatement("POLYGON_MODE command"); } @@ -1696,56 +1920,67 @@ Result Parser::ParsePipelinePolygonMode(Pipeline* pipeline) { Result Parser::ParsePipelineDepth(Pipeline* pipeline) { while (true) { auto token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (token->IsEOS()) + } + if (token->IsEOS()) { return Result("DEPTH missing END command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("DEPTH options must be identifiers"); - if (token->AsString() == "END") + } + if (token->AsString() == "END") { break; + } if (token->AsString() == "TEST") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid value for TEST"); + } - if (token->AsString() == "on") + if (token->AsString() == "on") { pipeline->GetPipelineData()->SetEnableDepthTest(true); - else if (token->AsString() == "off") + } else if (token->AsString() == "off") { pipeline->GetPipelineData()->SetEnableDepthTest(false); - else + } else { return Result("invalid value for TEST: " + token->AsString()); + } } else if (token->AsString() == "CLAMP") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid value for CLAMP"); + } - if (token->AsString() == "on") + if (token->AsString() == "on") { pipeline->GetPipelineData()->SetEnableDepthClamp(true); - else if (token->AsString() == "off") + } else if (token->AsString() == "off") { pipeline->GetPipelineData()->SetEnableDepthClamp(false); - else + } else { return Result("invalid value for CLAMP: " + token->AsString()); + } } else if (token->AsString() == "WRITE") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid value for WRITE"); + } - if (token->AsString() == "on") + if (token->AsString() == "on") { pipeline->GetPipelineData()->SetEnableDepthWrite(true); - else if (token->AsString() == "off") + } else if (token->AsString() == "off") { pipeline->GetPipelineData()->SetEnableDepthWrite(false); - else + } else { return Result("invalid value for WRITE: " + token->AsString()); + } } else if (token->AsString() == "COMPARE_OP") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid value for COMPARE_OP"); + } CompareOp compare_op = StrToCompareOp(token->AsString()); if (compare_op != CompareOp::kUnknown) { @@ -1755,50 +1990,60 @@ Result Parser::ParsePipelineDepth(Pipeline* pipeline) { } } else if (token->AsString() == "BOUNDS") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "min") + if (!token->IsIdentifier() || token->AsString() != "min") { return Result("BOUNDS expecting min"); + } token = tokenizer_->NextToken(); - if (!token->IsDouble()) + if (!token->IsDouble()) { return Result("BOUNDS invalid value for min"); + } pipeline->GetPipelineData()->SetMinDepthBounds(token->AsFloat()); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "max") + if (!token->IsIdentifier() || token->AsString() != "max") { return Result("BOUNDS expecting max"); + } token = tokenizer_->NextToken(); - if (!token->IsDouble()) + if (!token->IsDouble()) { return Result("BOUNDS invalid value for max"); + } pipeline->GetPipelineData()->SetMaxDepthBounds(token->AsFloat()); } else if (token->AsString() == "BIAS") { pipeline->GetPipelineData()->SetEnableDepthBias(true); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "constant") + if (!token->IsIdentifier() || token->AsString() != "constant") { return Result("BIAS expecting constant"); + } token = tokenizer_->NextToken(); - if (!token->IsDouble()) + if (!token->IsDouble()) { return Result("BIAS invalid value for constant"); + } pipeline->GetPipelineData()->SetDepthBiasConstantFactor(token->AsFloat()); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "clamp") + if (!token->IsIdentifier() || token->AsString() != "clamp") { return Result("BIAS expecting clamp"); + } token = tokenizer_->NextToken(); - if (!token->IsDouble()) + if (!token->IsDouble()) { return Result("BIAS invalid value for clamp"); + } pipeline->GetPipelineData()->SetDepthBiasClamp(token->AsFloat()); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "slope") + if (!token->IsIdentifier() || token->AsString() != "slope") { return Result("BIAS expecting slope"); + } token = tokenizer_->NextToken(); - if (!token->IsDouble()) + if (!token->IsDouble()) { return Result("BIAS invalid value for slope"); + } pipeline->GetPipelineData()->SetDepthBiasSlopeFactor(token->AsFloat()); } else { return Result("invalid value for DEPTH: " + token->AsString()); @@ -1810,8 +2055,9 @@ Result Parser::ParsePipelineDepth(Pipeline* pipeline) { Result Parser::ParsePipelineStencil(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("STENCIL missing face"); + } bool setFront = false; bool setBack = false; @@ -1829,117 +2075,144 @@ Result Parser::ParsePipelineStencil(Pipeline* pipeline) { while (true) { token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (token->IsEOS()) + } + if (token->IsEOS()) { return Result("STENCIL missing END command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("STENCIL options must be identifiers"); - if (token->AsString() == "END") + } + if (token->AsString() == "END") { break; + } if (token->AsString() == "TEST") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("STENCIL invalid value for TEST"); + } - if (token->AsString() == "on") + if (token->AsString() == "on") { pipeline->GetPipelineData()->SetEnableStencilTest(true); - else if (token->AsString() == "off") + } else if (token->AsString() == "off") { pipeline->GetPipelineData()->SetEnableStencilTest(false); - else + } else { return Result("STENCIL invalid value for TEST: " + token->AsString()); + } } else if (token->AsString() == "FAIL_OP") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("STENCIL invalid value for FAIL_OP"); + } StencilOp stencil_op = StrToStencilOp(token->AsString()); if (stencil_op == StencilOp::kUnknown) { return Result("STENCIL invalid value for FAIL_OP: " + token->AsString()); } - if (setFront) + if (setFront) { pipeline->GetPipelineData()->SetFrontFailOp(stencil_op); - if (setBack) + } + if (setBack) { pipeline->GetPipelineData()->SetBackFailOp(stencil_op); + } } else if (token->AsString() == "PASS_OP") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("STENCIL invalid value for PASS_OP"); + } StencilOp stencil_op = StrToStencilOp(token->AsString()); if (stencil_op == StencilOp::kUnknown) { return Result("STENCIL invalid value for PASS_OP: " + token->AsString()); } - if (setFront) + if (setFront) { pipeline->GetPipelineData()->SetFrontPassOp(stencil_op); - if (setBack) + } + if (setBack) { pipeline->GetPipelineData()->SetBackPassOp(stencil_op); + } } else if (token->AsString() == "DEPTH_FAIL_OP") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("STENCIL invalid value for DEPTH_FAIL_OP"); + } StencilOp stencil_op = StrToStencilOp(token->AsString()); if (stencil_op == StencilOp::kUnknown) { return Result("STENCIL invalid value for DEPTH_FAIL_OP: " + token->AsString()); } - if (setFront) + if (setFront) { pipeline->GetPipelineData()->SetFrontDepthFailOp(stencil_op); - if (setBack) + } + if (setBack) { pipeline->GetPipelineData()->SetBackDepthFailOp(stencil_op); + } } else if (token->AsString() == "COMPARE_OP") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("STENCIL invalid value for COMPARE_OP"); + } CompareOp compare_op = StrToCompareOp(token->AsString()); if (compare_op == CompareOp::kUnknown) { return Result("STENCIL invalid value for COMPARE_OP: " + token->AsString()); } - if (setFront) + if (setFront) { pipeline->GetPipelineData()->SetFrontCompareOp(compare_op); - if (setBack) + } + if (setBack) { pipeline->GetPipelineData()->SetBackCompareOp(compare_op); + } } else if (token->AsString() == "COMPARE_MASK") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("STENCIL invalid value for COMPARE_MASK"); + } - if (setFront) + if (setFront) { pipeline->GetPipelineData()->SetFrontCompareMask(token->AsUint32()); - if (setBack) + } + if (setBack) { pipeline->GetPipelineData()->SetBackCompareMask(token->AsUint32()); + } } else if (token->AsString() == "WRITE_MASK") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("STENCIL invalid value for WRITE_MASK"); + } - if (setFront) + if (setFront) { pipeline->GetPipelineData()->SetFrontWriteMask(token->AsUint32()); - if (setBack) + } + if (setBack) { pipeline->GetPipelineData()->SetBackWriteMask(token->AsUint32()); + } } else if (token->AsString() == "REFERENCE") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("STENCIL invalid value for REFERENCE"); + } - if (setFront) + if (setFront) { pipeline->GetPipelineData()->SetFrontReference(token->AsUint32()); - if (setBack) + } + if (setBack) { pipeline->GetPipelineData()->SetBackReference(token->AsUint32()); + } } else { return Result("STENCIL invalid value for STENCIL: " + token->AsString()); } @@ -1953,83 +2226,99 @@ Result Parser::ParsePipelineBlend(Pipeline* pipeline) { while (true) { auto token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (token->IsEOS()) + } + if (token->IsEOS()) { return Result("BLEND missing END command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("BLEND options must be identifiers"); - if (token->AsString() == "END") + } + if (token->AsString() == "END") { break; + } if (token->AsString() == "SRC_COLOR_FACTOR") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BLEND invalid value for SRC_COLOR_FACTOR"); + } const auto factor = NameToBlendFactor(token->AsString()); - if (factor == BlendFactor::kUnknown) + if (factor == BlendFactor::kUnknown) { return Result("BLEND invalid value for SRC_COLOR_FACTOR: " + token->AsString()); + } pipeline->GetPipelineData()->SetSrcColorBlendFactor( NameToBlendFactor(token->AsString())); } else if (token->AsString() == "DST_COLOR_FACTOR") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BLEND invalid value for DST_COLOR_FACTOR"); + } const auto factor = NameToBlendFactor(token->AsString()); - if (factor == BlendFactor::kUnknown) + if (factor == BlendFactor::kUnknown) { return Result("BLEND invalid value for DST_COLOR_FACTOR: " + token->AsString()); + } pipeline->GetPipelineData()->SetDstColorBlendFactor( NameToBlendFactor(token->AsString())); } else if (token->AsString() == "SRC_ALPHA_FACTOR") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BLEND invalid value for SRC_ALPHA_FACTOR"); + } const auto factor = NameToBlendFactor(token->AsString()); - if (factor == BlendFactor::kUnknown) + if (factor == BlendFactor::kUnknown) { return Result("BLEND invalid value for SRC_ALPHA_FACTOR: " + token->AsString()); + } pipeline->GetPipelineData()->SetSrcAlphaBlendFactor( NameToBlendFactor(token->AsString())); } else if (token->AsString() == "DST_ALPHA_FACTOR") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BLEND invalid value for DST_ALPHA_FACTOR"); + } const auto factor = NameToBlendFactor(token->AsString()); - if (factor == BlendFactor::kUnknown) + if (factor == BlendFactor::kUnknown) { return Result("BLEND invalid value for DST_ALPHA_FACTOR: " + token->AsString()); + } pipeline->GetPipelineData()->SetDstAlphaBlendFactor( NameToBlendFactor(token->AsString())); } else if (token->AsString() == "COLOR_OP") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BLEND invalid value for COLOR_OP"); + } const auto op = NameToBlendOp(token->AsString()); - if (op == BlendOp::kUnknown) + if (op == BlendOp::kUnknown) { return Result("BLEND invalid value for COLOR_OP: " + token->AsString()); + } pipeline->GetPipelineData()->SetColorBlendOp( NameToBlendOp(token->AsString())); } else if (token->AsString() == "ALPHA_OP") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BLEND invalid value for ALPHA_OP"); + } const auto op = NameToBlendOp(token->AsString()); - if (op == BlendOp::kUnknown) + if (op == BlendOp::kUnknown) { return Result("BLEND invalid value for ALPHA_OP: " + token->AsString()); + } pipeline->GetPipelineData()->SetAlphaBlendOp( NameToBlendOp(token->AsString())); } else { @@ -2042,65 +2331,79 @@ Result Parser::ParsePipelineBlend(Pipeline* pipeline) { Result Parser::ParsePipelineShaderGroup(Pipeline* pipeline) { std::unique_ptr token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Group name expected"); + } auto tok = token->AsString(); - if (pipeline->GetShaderGroup(tok)) + if (pipeline->GetShaderGroup(tok)) { return Result("Group name already exists"); + } std::unique_ptr group = MakeUnique(); group->SetName(tok); while (true) { token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { break; - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Shader name expected"); + } tok = token->AsString(); Shader* shader = script_->GetShader(tok); - if (shader == nullptr) + if (shader == nullptr) { return Result("Shader not found: " + tok); + } if (script_->FindShader(pipeline, shader) == nullptr) { Result r = pipeline->AddShader(shader, shader->GetType()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } switch (shader->GetType()) { case kShaderTypeRayGeneration: case kShaderTypeMiss: case kShaderTypeCall: { - if (group->IsHitGroup()) + if (group->IsHitGroup()) { return Result("Hit group cannot contain general shaders"); - if (group->GetGeneralShader() != nullptr) + } + if (group->GetGeneralShader() != nullptr) { return Result("Two general shaders cannot be in one group"); + } group->SetGeneralShader(shader); break; } case kShaderTypeAnyHit: { - if (group->IsGeneralGroup()) + if (group->IsGeneralGroup()) { return Result("General group cannot contain any hit shaders"); - if (group->GetAnyHitShader() != nullptr) + } + if (group->GetAnyHitShader() != nullptr) { return Result("Two any hit shaders cannot be in one group"); + } group->SetAnyHitShader(shader); break; } case kShaderTypeClosestHit: { - if (group->IsGeneralGroup()) + if (group->IsGeneralGroup()) { return Result("General group cannot contain closest hit shaders"); - if (group->GetClosestHitShader() != nullptr) + } + if (group->GetClosestHitShader() != nullptr) { return Result("Two closest hit shaders cannot be in one group"); + } group->SetClosestHitShader(shader); break; } case kShaderTypeIntersection: { - if (group->IsGeneralGroup()) + if (group->IsGeneralGroup()) { return Result("General group cannot contain intersection shaders"); - if (group->GetIntersectionShader() != nullptr) + } + if (group->GetIntersectionShader() != nullptr) { return Result("Two intersection shaders cannot be in one group"); + } group->SetIntersectionShader(shader); break; } @@ -2116,30 +2419,36 @@ Result Parser::ParsePipelineShaderGroup(Pipeline* pipeline) { Result Parser::ParseStruct() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid STRUCT name provided"); + } auto struct_name = token->AsString(); - if (struct_name == "STRIDE") + if (struct_name == "STRIDE") { return Result("missing STRUCT name"); + } auto s = MakeUnique(); auto type = s.get(); Result r = script_->AddType(struct_name, std::move(s)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } token = tokenizer_->NextToken(); if (token->IsIdentifier()) { - if (token->AsString() != "STRIDE") + if (token->AsString() != "STRIDE") { return Result("invalid token in STRUCT definition"); + } token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing value for STRIDE"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("invalid value for STRIDE"); + } type->SetStrideInBytes(token->AsUint32()); token = tokenizer_->NextToken(); @@ -2152,13 +2461,16 @@ Result Parser::ParseStruct() { std::map seen; for (;;) { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid type for STRUCT member"); - if (token->AsString() == "END") + } + if (token->AsString() == "END") { break; + } - if (token->AsString() == struct_name) + if (token->AsString() == struct_name) { return Result("recursive types are not allowed"); + } type::Type* member_type = script_->GetType(token->AsString()); if (!member_type) { @@ -2173,14 +2485,17 @@ Result Parser::ParseStruct() { } token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { return Result("missing name for STRUCT member"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("invalid name for STRUCT member"); + } auto member_name = token->AsString(); - if (seen.find(member_name) != seen.end()) + if (seen.find(member_name) != seen.end()) { return Result("duplicate name for STRUCT member"); + } seen[member_name] = true; @@ -2191,30 +2506,38 @@ Result Parser::ParseStruct() { while (token->IsIdentifier()) { if (token->AsString() == "OFFSET") { token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { return Result("missing value for STRUCT member OFFSET"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("invalid value for STRUCT member OFFSET"); + } m->offset_in_bytes = token->AsInt32(); } else if (token->AsString() == "ARRAY_STRIDE") { token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { return Result("missing value for STRUCT member ARRAY_STRIDE"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("invalid value for STRUCT member ARRAY_STRIDE"); - if (!member_type->IsArray()) + } + if (!member_type->IsArray()) { return Result("ARRAY_STRIDE only valid on array members"); + } m->array_stride_in_bytes = token->AsInt32(); } else if (token->AsString() == "MATRIX_STRIDE") { token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { return Result("missing value for STRUCT member MATRIX_STRIDE"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("invalid value for STRUCT member MATRIX_STRIDE"); - if (!member_type->IsMatrix()) + } + if (!member_type->IsMatrix()) { return Result("MATRIX_STRIDE only valid on matrix members"); + } m->matrix_stride_in_bytes = token->AsInt32(); } else { @@ -2225,8 +2548,9 @@ Result Parser::ParseStruct() { token = tokenizer_->NextToken(); } - if (!token->IsEOL()) + if (!token->IsEOL()) { return Result("extra param for STRUCT member"); + } } return {}; @@ -2234,16 +2558,19 @@ Result Parser::ParseStruct() { Result Parser::ParseBuffer() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid BUFFER name provided"); + } auto name = token->AsString(); - if (name == "DATA_TYPE" || name == "FORMAT") + if (name == "DATA_TYPE" || name == "FORMAT") { return Result("missing BUFFER name"); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid BUFFER command provided"); + } std::unique_ptr buffer; auto& cmd = token->AsString(); @@ -2251,18 +2578,21 @@ Result Parser::ParseBuffer() { buffer = MakeUnique(); Result r = ParseBufferInitializer(buffer.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (cmd == "FORMAT") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BUFFER FORMAT must be an identifier"); + } buffer = MakeUnique(); auto type = script_->ParseType(token->AsString()); - if (!type) + if (!type) { return Result("invalid BUFFER FORMAT"); + } auto fmt = MakeUnique(type); buffer->SetFormat(fmt.get()); @@ -2274,25 +2604,29 @@ Result Parser::ParseBuffer() { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for MIP_LEVELS"); + } buffer->SetMipLevels(token->AsUint32()); } else if (token->AsString() == "FILE") { tokenizer_->NextToken(); Result r = ParseBufferInitializerFile(buffer.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (token->AsString() == "SAMPLES") { tokenizer_->NextToken(); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expected integer value for SAMPLES"); + } const uint32_t samples = token->AsUint32(); - if (!IsValidSampleCount(samples)) + if (!IsValidSampleCount(samples)) { return Result("invalid sample count: " + token->ToOriginalString()); + } buffer->SetSamples(samples); } else { @@ -2306,20 +2640,23 @@ Result Parser::ParseBuffer() { buffer->SetName(name); Result r = script_->AddBuffer(std::move(buffer)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } Result Parser::ParseImage() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid IMAGE name provided"); + } auto name = token->AsString(); - if (name == "DATA_TYPE" || name == "FORMAT") + if (name == "DATA_TYPE" || name == "FORMAT") { return Result("missing IMAGE name"); + } std::unique_ptr buffer = MakeUnique(); buffer->SetName(name); @@ -2338,8 +2675,9 @@ Result Parser::ParseImage() { if (token->AsString() == "DATA_TYPE") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("IMAGE invalid data type"); + } auto type = script_->ParseType(token->AsString()); std::unique_ptr fmt; @@ -2360,12 +2698,14 @@ Result Parser::ParseImage() { script_->RegisterFormat(std::move(fmt)); } else if (token->AsString() == "FORMAT") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("IMAGE FORMAT must be an identifier"); + } auto type = script_->ParseType(token->AsString()); - if (!type) + if (!type) { return Result("invalid IMAGE FORMAT"); + } auto fmt = MakeUnique(type); buffer->SetFormat(fmt.get()); @@ -2373,8 +2713,9 @@ Result Parser::ParseImage() { } else if (token->AsString() == "MIP_LEVELS") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid value for MIP_LEVELS"); + } buffer->SetMipLevels(token->AsUint32()); } else if (token->AsString() == "DIM_1D") { @@ -2385,33 +2726,38 @@ Result Parser::ParseImage() { buffer->SetImageDimension(ImageDimension::k3D); } else if (token->AsString() == "WIDTH") { token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsUint32() == 0) + if (!token->IsInteger() || token->AsUint32() == 0) { return Result("expected positive IMAGE WIDTH"); + } buffer->SetWidth(token->AsUint32()); width_set = true; } else if (token->AsString() == "HEIGHT") { token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsUint32() == 0) + if (!token->IsInteger() || token->AsUint32() == 0) { return Result("expected positive IMAGE HEIGHT"); + } buffer->SetHeight(token->AsUint32()); height_set = true; } else if (token->AsString() == "DEPTH") { token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsUint32() == 0) + if (!token->IsInteger() || token->AsUint32() == 0) { return Result("expected positive IMAGE DEPTH"); + } buffer->SetDepth(token->AsUint32()); depth_set = true; } else if (token->AsString() == "SAMPLES") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expected integer value for SAMPLES"); + } const uint32_t samples = token->AsUint32(); - if (!IsValidSampleCount(samples)) + if (!IsValidSampleCount(samples)) { return Result("invalid sample count: " + token->ToOriginalString()); + } buffer->SetSamples(samples); } else { @@ -2421,16 +2767,18 @@ Result Parser::ParseImage() { token = tokenizer_->PeekNextToken(); } - if (buffer->GetImageDimension() == ImageDimension::k3D && !depth_set) + if (buffer->GetImageDimension() == ImageDimension::k3D && !depth_set) { return Result("expected IMAGE DEPTH"); + } if ((buffer->GetImageDimension() == ImageDimension::k3D || buffer->GetImageDimension() == ImageDimension::k2D) && !height_set) { return Result("expected IMAGE HEIGHT"); } - if (!width_set) + if (!width_set) { return Result("expected IMAGE WIDTH"); + } const uint32_t size_in_items = buffer->GetWidth() * buffer->GetHeight() * buffer->GetDepth(); @@ -2441,8 +2789,9 @@ Result Parser::ParseImage() { if (token->IsIdentifier()) { if (token->AsString() == "DATA") { Result r = ParseBufferInitializerData(buffer.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } if (size_in_items != buffer->ElementCount()) { return Result( @@ -2452,12 +2801,14 @@ Result Parser::ParseImage() { } } else if (token->AsString() == "FILL") { Result r = ParseBufferInitializerFill(buffer.get(), size_in_items); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (token->AsString() == "SERIES_FROM") { Result r = ParseBufferInitializerSeries(buffer.get(), size_in_items); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { return Result("unexpected IMAGE token: " + token->AsString()); } @@ -2466,16 +2817,18 @@ Result Parser::ParseImage() { } Result r = script_->AddBuffer(std::move(buffer)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } Result Parser::ParseBufferInitializer(Buffer* buffer) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BUFFER invalid data type"); + } auto type = script_->ParseType(token->AsString()); std::unique_ptr fmt; @@ -2484,8 +2837,9 @@ Result Parser::ParseBufferInitializer(Buffer* buffer) { buffer->SetFormat(fmt.get()); } else { auto new_type = ToType(token->AsString()); - if (!new_type) + if (!new_type) { return Result("invalid data type '" + token->AsString() + "' provided"); + } fmt = MakeUnique(new_type.get()); buffer->SetFormat(fmt.get()); @@ -2495,8 +2849,9 @@ Result Parser::ParseBufferInitializer(Buffer* buffer) { script_->RegisterFormat(std::move(fmt)); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BUFFER missing initializer"); + } if (token->AsString() == "STD140") { buffer->GetFormat()->SetLayout(Format::Layout::kStd140); @@ -2506,67 +2861,83 @@ Result Parser::ParseBufferInitializer(Buffer* buffer) { token = tokenizer_->NextToken(); } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BUFFER missing initializer"); + } - if (token->AsString() == "SIZE") + if (token->AsString() == "SIZE") { return ParseBufferInitializerSize(buffer); + } if (token->AsString() == "WIDTH") { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expected an integer for WIDTH"); + } const uint32_t width = token->AsUint32(); - if (width == 0) + if (width == 0) { return Result("expected WIDTH to be positive"); + } buffer->SetWidth(width); buffer->SetImageDimension(ImageDimension::k2D); token = tokenizer_->NextToken(); - if (token->AsString() != "HEIGHT") + if (token->AsString() != "HEIGHT") { return Result("BUFFER HEIGHT missing"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("expected an integer for HEIGHT"); + } const uint32_t height = token->AsUint32(); - if (height == 0) + if (height == 0) { return Result("expected HEIGHT to be positive"); + } buffer->SetHeight(height); token = tokenizer_->NextToken(); uint32_t size_in_items = width * height; buffer->SetElementCount(size_in_items); - if (token->AsString() == "FILL") + if (token->AsString() == "FILL") { return ParseBufferInitializerFill(buffer, size_in_items); - if (token->AsString() == "SERIES_FROM") + } + if (token->AsString() == "SERIES_FROM") { return ParseBufferInitializerSeries(buffer, size_in_items); + } return {}; } - if (token->AsString() == "DATA") + if (token->AsString() == "DATA") { return ParseBufferInitializerData(buffer); + } return Result("unknown initializer for BUFFER"); } Result Parser::ParseBufferInitializerSize(Buffer* buffer) { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("BUFFER size missing"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("BUFFER size invalid"); + } uint32_t size_in_items = token->AsUint32(); buffer->SetElementCount(size_in_items); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("BUFFER invalid initializer"); + } - if (token->AsString() == "FILL") + if (token->AsString() == "FILL") { return ParseBufferInitializerFill(buffer, size_in_items); - if (token->AsString() == "SERIES_FROM") + } + if (token->AsString() == "SERIES_FROM") { return ParseBufferInitializerSeries(buffer, size_in_items); - if (token->AsString() == "FILE") + } + if (token->AsString() == "FILE") { return ParseBufferInitializerFile(buffer); + } return Result("invalid BUFFER initializer provided"); } @@ -2574,10 +2945,12 @@ Result Parser::ParseBufferInitializerSize(Buffer* buffer) { Result Parser::ParseBufferInitializerFill(Buffer* buffer, uint32_t size_in_items) { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("missing BUFFER fill value"); - if (!token->IsInteger() && !token->IsDouble()) + } + if (!token->IsInteger() && !token->IsDouble()) { return Result("invalid BUFFER fill value"); + } auto fmt = buffer->GetFormat(); bool is_double_data = fmt->IsFloat32() || fmt->IsFloat64(); @@ -2588,14 +2961,16 @@ Result Parser::ParseBufferInitializerFill(Buffer* buffer, std::vector values; values.resize(size_in_items); for (size_t i = 0; i < size_in_items; ++i) { - if (is_double_data) + if (is_double_data) { values[i].SetDoubleValue(token->AsDouble()); - else + } else { values[i].SetIntValue(token->AsUint64()); + } } Result r = buffer->SetData(std::move(values)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("BUFFER fill command"); } @@ -2603,14 +2978,17 @@ Result Parser::ParseBufferInitializerFill(Buffer* buffer, Result Parser::ParseBufferInitializerSeries(Buffer* buffer, uint32_t size_in_items) { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("missing BUFFER series_from value"); - if (!token->IsInteger() && !token->IsDouble()) + } + if (!token->IsInteger() && !token->IsDouble()) { return Result("invalid BUFFER series_from value"); + } auto type = buffer->GetFormat()->GetType(); - if (type->IsMatrix() || type->IsVec()) + if (type->IsMatrix() || type->IsVec()) { return Result("BUFFER series_from must not be multi-row/column types"); + } Value counter; @@ -2625,16 +3003,20 @@ Result Parser::ParseBufferInitializerSeries(Buffer* buffer, } token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing BUFFER series_from inc_by"); - if (token->AsString() != "INC_BY") + } + if (token->AsString() != "INC_BY") { return Result("BUFFER series_from invalid command"); + } token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("missing BUFFER series_from inc_by value"); - if (!token->IsInteger() && !token->IsDouble()) + } + if (!token->IsInteger() && !token->IsDouble()) { return Result("invalid BUFFER series_from inc_by value"); + } std::vector values; values.resize(size_in_items); @@ -2651,8 +3033,9 @@ Result Parser::ParseBufferInitializerSeries(Buffer* buffer, } } Result r = buffer->SetData(std::move(values)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("BUFFER series_from command"); } @@ -2660,8 +3043,9 @@ Result Parser::ParseBufferInitializerSeries(Buffer* buffer, Result Parser::ParseBufferInitializerData(Buffer* buffer) { Result r = ParseBufferData(buffer, tokenizer_.get(), false); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return ValidateEndOfStatement("BUFFER data command"); } @@ -2669,8 +3053,9 @@ Result Parser::ParseBufferInitializerData(Buffer* buffer) { Result Parser::ParseBufferInitializerFile(Buffer* buffer) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid value for FILE"); + } BufferDataFileType file_type = BufferDataFileType::kPng; @@ -2684,17 +3069,20 @@ Result Parser::ParseBufferInitializerFile(Buffer* buffer) { token = tokenizer_->NextToken(); } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing file name for FILE"); + } - if (!delegate_) + if (!delegate_) { return Result("missing delegate"); + } BufferInfo info; Result r = delegate_->LoadBufferData(token->AsString(), file_type, &info); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } std::vector* data = buffer->ValuePtr(); @@ -2708,8 +3096,9 @@ Result Parser::ParseBufferInitializerFile(Buffer* buffer) { auto s = std::string(data->begin(), data->end()); Tokenizer tok(s); r = ParseBufferData(buffer, &tok, true); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { buffer->SetElementCount(static_cast(data->size()) / buffer->GetFormat()->SizeInBytes()); @@ -2730,14 +3119,16 @@ Result Parser::ParseRun() { is_timed_execution = true; } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing pipeline name for RUN command"); + } size_t line = tokenizer_->GetCurrentLine(); auto* pipeline = script_->GetPipeline(token->AsString()); - if (!pipeline) + if (!pipeline) { return Result("unknown pipeline for RUN command: " + token->AsString()); + } if (pipeline->IsRayTracing()) { auto cmd = MakeUnique(pipeline); @@ -2747,42 +3138,51 @@ Result Parser::ParseRun() { } while (true) { - if (tokenizer_->PeekNextToken()->IsInteger()) + if (tokenizer_->PeekNextToken()->IsInteger()) { break; + } token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("Incomplete RUN command"); + } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Shader binding table type is expected"); + } std::string tok = token->AsString(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Shader binding table name expected"); + } std::string sbtname = token->AsString(); - if (pipeline->GetSBT(sbtname) == nullptr) + if (pipeline->GetSBT(sbtname) == nullptr) { return Result("Shader binding table with this name was not defined"); + } if (tok == "RAYGEN") { - if (!cmd->GetRayGenSBTName().empty()) + if (!cmd->GetRayGenSBTName().empty()) { return Result("RAYGEN shader binding table can specified only once"); + } cmd->SetRGenSBTName(sbtname); } else if (tok == "MISS") { - if (!cmd->GetMissSBTName().empty()) + if (!cmd->GetMissSBTName().empty()) { return Result("MISS shader binding table can specified only once"); + } cmd->SetMissSBTName(sbtname); } else if (tok == "HIT") { - if (!cmd->GetHitsSBTName().empty()) + if (!cmd->GetHitsSBTName().empty()) { return Result("HIT shader binding table can specified only once"); + } cmd->SetHitsSBTName(sbtname); } else if (tok == "CALL") { - if (!cmd->GetCallSBTName().empty()) + if (!cmd->GetCallSBTName().empty()) { return Result("CALL shader binding table can specified only once"); + } cmd->SetCallSBTName(sbtname); } else { return Result("Unknown shader binding table type"); @@ -2792,15 +3192,17 @@ Result Parser::ParseRun() { for (int i = 0; i < 3; i++) { token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("invalid parameter for RUN command: " + token->ToOriginalString()); - if (i == 0) + } + if (i == 0) { cmd->SetX(token->AsUint32()); - else if (i == 1) + } else if (i == 1) { cmd->SetY(token->AsUint32()); - else + } else { cmd->SetZ(token->AsUint32()); + } } command_list_.push_back(std::move(cmd)); @@ -2808,12 +3210,14 @@ Result Parser::ParseRun() { } token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("RUN command requires parameters"); + } if (token->IsInteger()) { - if (!pipeline->IsCompute()) + if (!pipeline->IsCompute()) { return Result("RUN command requires compute pipeline"); + } auto cmd = MakeUnique(pipeline); cmd->SetLine(line); @@ -2840,12 +3244,14 @@ Result Parser::ParseRun() { return ValidateEndOfStatement("RUN command"); } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token in RUN command: " + token->ToOriginalString()); + } if (token->AsString() == "DRAW_RECT") { - if (!pipeline->IsGraphics()) + if (!pipeline->IsGraphics()) { return Result("RUN command requires graphics pipeline"); + } if (pipeline->GetVertexBuffers().size() > 1) { return Result( @@ -2854,8 +3260,9 @@ Result Parser::ParseRun() { } token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("RUN DRAW_RECT command requires parameters"); + } if (!token->IsIdentifier() || token->AsString() != "POS") { return Result("invalid token in RUN command: " + @@ -2863,8 +3270,9 @@ Result Parser::ParseRun() { } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing X position for RUN command"); + } auto cmd = MakeUnique(pipeline, *pipeline->GetPipelineData()); @@ -2875,17 +3283,20 @@ Result Parser::ParseRun() { } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetX(token->AsFloat()); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing Y position for RUN command"); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetY(token->AsFloat()); token = tokenizer_->NextToken(); @@ -2895,21 +3306,25 @@ Result Parser::ParseRun() { } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing width value for RUN command"); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetWidth(token->AsFloat()); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing height value for RUN command"); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetHeight(token->AsFloat()); command_list_.push_back(std::move(cmd)); @@ -2917,8 +3332,9 @@ Result Parser::ParseRun() { } if (token->AsString() == "DRAW_GRID") { - if (!pipeline->IsGraphics()) + if (!pipeline->IsGraphics()) { return Result("RUN command requires graphics pipeline"); + } if (pipeline->GetVertexBuffers().size() > 0) { return Result( @@ -2927,8 +3343,9 @@ Result Parser::ParseRun() { } token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("RUN DRAW_GRID command requires parameters"); + } if (!token->IsIdentifier() || token->AsString() != "POS") { return Result("invalid token in RUN command: " + @@ -2936,8 +3353,9 @@ Result Parser::ParseRun() { } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing X position for RUN command"); + } auto cmd = MakeUnique(pipeline, *pipeline->GetPipelineData()); @@ -2947,17 +3365,20 @@ Result Parser::ParseRun() { } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetX(token->AsFloat()); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing Y position for RUN command"); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetY(token->AsFloat()); token = tokenizer_->NextToken(); @@ -2967,21 +3388,25 @@ Result Parser::ParseRun() { } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing width value for RUN command"); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetWidth(token->AsFloat()); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing height value for RUN command"); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetHeight(token->AsFloat()); token = tokenizer_->NextToken(); @@ -2991,14 +3416,16 @@ Result Parser::ParseRun() { } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing columns value for RUN command"); + } cmd->SetColumns(token->AsUint32()); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("missing rows value for RUN command"); + } cmd->SetRows(token->AsUint32()); @@ -3007,15 +3434,18 @@ Result Parser::ParseRun() { } if (token->AsString() == "DRAW_ARRAY") { - if (!pipeline->IsGraphics()) + if (!pipeline->IsGraphics()) { return Result("RUN command requires graphics pipeline"); + } - if (pipeline->GetVertexBuffers().empty()) + if (pipeline->GetVertexBuffers().empty()) { return Result("RUN DRAW_ARRAY requires attached vertex buffer"); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "AS") + if (!token->IsIdentifier() || token->AsString() != "AS") { return Result("missing AS for RUN command"); + } token = tokenizer_->NextToken(); if (!token->IsIdentifier()) { @@ -3024,8 +3454,9 @@ Result Parser::ParseRun() { } Topology topo = NameToTopology(token->AsString()); - if (topo == Topology::kUnknown) + if (topo == Topology::kUnknown) { return Result("invalid topology for RUN command: " + token->AsString()); + } bool indexed = false; uint32_t start_idx = 0; @@ -3038,8 +3469,9 @@ Result Parser::ParseRun() { while (!token->IsEOS() && !token->IsEOL()) { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("expecting identifier for RUN command"); + } if (token->AsString() == "INDEXED") { if (!pipeline->GetIndexBuffer()) { @@ -3054,8 +3486,9 @@ Result Parser::ParseRun() { return Result("invalid START_IDX value for RUN command: " + token->ToOriginalString()); } - if (token->AsInt32() < 0) + if (token->AsInt32() < 0) { return Result("START_IDX value must be >= 0 for RUN command"); + } start_idx = token->AsUint32(); } else if (token->AsString() == "COUNT") { token = tokenizer_->NextToken(); @@ -3063,8 +3496,9 @@ Result Parser::ParseRun() { return Result("invalid COUNT value for RUN command: " + token->ToOriginalString()); } - if (token->AsInt32() <= 0) + if (token->AsInt32() <= 0) { return Result("COUNT value must be > 0 for RUN command"); + } count = token->AsUint32(); } else if (token->AsString() == "INSTANCE_COUNT") { @@ -3073,8 +3507,9 @@ Result Parser::ParseRun() { return Result("invalid INSTANCE_COUNT value for RUN command: " + token->ToOriginalString()); } - if (token->AsInt32() <= 0) + if (token->AsInt32() <= 0) { return Result("INSTANCE_COUNT value must be > 0 for RUN command"); + } instance_count = token->AsUint32(); } else if (token->AsString() == "START_INSTANCE") { @@ -3083,8 +3518,9 @@ Result Parser::ParseRun() { return Result("invalid START_INSTANCE value for RUN command: " + token->ToOriginalString()); } - if (token->AsInt32() < 0) + if (token->AsInt32() < 0) { return Result("START_INSTANCE value must be >= 0 for RUN command"); + } start_instance = token->AsUint32(); } else { return Result("Unexpected identifier for RUN command: " + @@ -3100,14 +3536,16 @@ Result Parser::ParseRun() { // If we get here then we never set count, as if count was set it must // be > 0. - if (count == 0) + if (count == 0) { count = vertex_count - start_idx; + } if (start_idx + count > vertex_count) { - if (indexed) + if (indexed) { return Result("START_IDX plus COUNT exceeds index buffer data size"); - else + } else { return Result("START_IDX plus COUNT exceeds vertex buffer data size"); + } } auto cmd = @@ -3122,8 +3560,9 @@ Result Parser::ParseRun() { cmd->SetTimedExecution(); } - if (indexed) + if (indexed) { cmd->EnableIndexed(); + } command_list_.push_back(std::move(cmd)); return ValidateEndOfStatement("RUN command"); @@ -3134,16 +3573,19 @@ Result Parser::ParseRun() { Result Parser::ParseClear() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing pipeline name for CLEAR command"); + } size_t line = tokenizer_->GetCurrentLine(); auto* pipeline = script_->GetPipeline(token->AsString()); - if (!pipeline) + if (!pipeline) { return Result("unknown pipeline for CLEAR command: " + token->AsString()); - if (!pipeline->IsGraphics()) + } + if (!pipeline->IsGraphics()) { return Result("CLEAR command requires graphics pipeline"); + } auto cmd = MakeUnique(pipeline); cmd->SetLine(line); @@ -3165,8 +3607,9 @@ Result Parser::ParseValues(const std::string& name, while (segs[seg_idx].IsPadding()) { ++seg_idx; - if (seg_idx >= segs.size()) + if (seg_idx >= segs.size()) { seg_idx = 0; + } } if (type::Type::IsFloat(segs[seg_idx].GetFormatMode())) { @@ -3176,8 +3619,9 @@ Result Parser::ParseValues(const std::string& name, } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } v.SetDoubleValue(token->AsDouble()); } else { @@ -3190,8 +3634,9 @@ Result Parser::ParseValues(const std::string& name, v.SetIntValue(val); } ++seg_idx; - if (seg_idx >= segs.size()) + if (seg_idx >= segs.size()) { seg_idx = 0; + } values->push_back(v); token = tokenizer_->NextToken(); @@ -3201,15 +3646,19 @@ Result Parser::ParseValues(const std::string& name, Result Parser::ParseExpect() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid buffer name in EXPECT command"); + } - if (token->AsString() == "IDX") + if (token->AsString() == "IDX") { return Result("missing buffer name between EXPECT and IDX"); - if (token->AsString() == "EQ_BUFFER") + } + if (token->AsString() == "EQ_BUFFER") { return Result("missing buffer name between EXPECT and EQ_BUFFER"); - if (token->AsString() == "RMSE_BUFFER") + } + if (token->AsString() == "RMSE_BUFFER") { return Result("missing buffer name between EXPECT and RMSE_BUFFER"); + } if (token->AsString() == "EQ_HISTOGRAM_EMD_BUFFER") { return Result( "missing buffer name between EXPECT and EQ_HISTOGRAM_EMD_BUFFER"); @@ -3217,22 +3666,25 @@ Result Parser::ParseExpect() { size_t line = tokenizer_->GetCurrentLine(); auto* buffer = script_->GetBuffer(token->AsString()); - if (!buffer) + if (!buffer) { return Result("unknown buffer name for EXPECT command: " + token->AsString()); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid comparator in EXPECT command"); + } if (token->AsString() == "EQ_BUFFER" || token->AsString() == "RMSE_BUFFER" || token->AsString() == "EQ_HISTOGRAM_EMD_BUFFER") { auto type = token->AsString(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid buffer name in EXPECT " + type + " command"); + } auto* buffer_2 = script_->GetBuffer(token->AsString()); if (!buffer_2) { @@ -3264,32 +3716,38 @@ Result Parser::ParseExpect() { cmd->SetComparator(CompareBufferCommand::Comparator::kRmse); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() && token->AsString() == "TOLERANCE") + if (!token->IsIdentifier() && token->AsString() == "TOLERANCE") { return Result("missing TOLERANCE for EXPECT RMSE_BUFFER"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger() && !token->IsDouble()) + if (!token->IsInteger() && !token->IsDouble()) { return Result("invalid TOLERANCE for EXPECT RMSE_BUFFER"); + } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetTolerance(token->AsFloat()); } else if (type == "EQ_HISTOGRAM_EMD_BUFFER") { cmd->SetComparator(CompareBufferCommand::Comparator::kHistogramEmd); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() && token->AsString() == "TOLERANCE") + if (!token->IsIdentifier() && token->AsString() == "TOLERANCE") { return Result("missing TOLERANCE for EXPECT EQ_HISTOGRAM_EMD_BUFFER"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger() && !token->IsDouble()) + if (!token->IsInteger() && !token->IsDouble()) { return Result("invalid TOLERANCE for EXPECT EQ_HISTOGRAM_EMD_BUFFER"); + } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetTolerance(token->AsFloat()); } @@ -3300,12 +3758,14 @@ Result Parser::ParseExpect() { return ValidateEndOfStatement("EXPECT " + type + " command"); } - if (token->AsString() != "IDX") + if (token->AsString() != "IDX") { return Result("missing IDX in EXPECT command"); + } token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsInt32() < 0) + if (!token->IsInteger() || token->AsInt32() < 0) { return Result("invalid X value in EXPECT command"); + } token->ConvertToDouble(); float x = token->AsFloat(); @@ -3315,8 +3775,9 @@ Result Parser::ParseExpect() { if (token->IsInteger()) { has_y_val = true; - if (token->AsInt32() < 0) + if (token->AsInt32() < 0) { return Result("invalid Y value in EXPECT command"); + } token->ConvertToDouble(); y = token->AsFloat(); @@ -3324,8 +3785,9 @@ Result Parser::ParseExpect() { } if (token->IsIdentifier() && token->AsString() == "SIZE") { - if (!has_y_val) + if (!has_y_val) { return Result("invalid Y value in EXPECT command"); + } auto probe = MakeUnique(buffer); probe->SetLine(line); @@ -3334,14 +3796,16 @@ Result Parser::ParseExpect() { probe->SetProbeRect(); token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsInt32() <= 0) + if (!token->IsInteger() || token->AsInt32() <= 0) { return Result("invalid width in EXPECT command"); + } token->ConvertToDouble(); probe->SetWidth(token->AsFloat()); token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsInt32() <= 0) + if (!token->IsInteger() || token->AsInt32() <= 0) { return Result("invalid height in EXPECT command"); + } token->ConvertToDouble(); probe->SetHeight(token->AsFloat()); @@ -3359,27 +3823,32 @@ Result Parser::ParseExpect() { } token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) + if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) { return Result("invalid R value in EXPECT command"); + } token->ConvertToDouble(); probe->SetR(token->AsFloat() / 255.f); token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) + if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) { return Result("invalid G value in EXPECT command"); + } token->ConvertToDouble(); probe->SetG(token->AsFloat() / 255.f); token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) + if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) { return Result("invalid B value in EXPECT command"); + } token->ConvertToDouble(); probe->SetB(token->AsFloat() / 255.f); if (probe->IsRGBA()) { token = tokenizer_->NextToken(); - if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) + if (!token->IsInteger() || token->AsInt32() < 0 || + token->AsInt32() > 255) { return Result("invalid A value in EXPECT command"); + } token->ConvertToDouble(); probe->SetA(token->AsFloat() / 255.f); } @@ -3390,11 +3859,13 @@ Result Parser::ParseExpect() { Result r = ParseTolerances(&tolerances); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } - if (tolerances.empty()) + if (tolerances.empty()) { return Result("TOLERANCE specified but no tolerances provided"); + } if (!probe->IsRGBA() && tolerances.size() > 3) { return Result( @@ -3428,13 +3899,16 @@ Result Parser::ParseExpect() { Result r = ParseTolerances(&tolerances); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } - if (tolerances.empty()) + if (tolerances.empty()) { return Result("TOLERANCE specified but no tolerances provided"); - if (tolerances.size() > 4) + } + if (tolerances.size() > 4) { return Result("TOLERANCE has a maximum of 4 values"); + } probe->SetTolerances(std::move(tolerances)); token = tokenizer_->NextToken(); @@ -3445,13 +3919,15 @@ Result Parser::ParseExpect() { token->ToOriginalString()); } - if (has_y_val) + if (has_y_val) { return Result("Y value not needed for non-color comparator"); + } auto cmp = ToComparator(token->AsString()); if (probe->HasTolerances()) { - if (cmp != ProbeSSBOCommand::Comparator::kEqual) + if (cmp != ProbeSSBOCommand::Comparator::kEqual) { return Result("TOLERANCE only available with EQ probes"); + } cmp = ProbeSSBOCommand::Comparator::kFuzzyEqual; } @@ -3462,11 +3938,13 @@ Result Parser::ParseExpect() { std::vector values; Result r = ParseValues("EXPECT", buffer->GetFormat(), &values); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } - if (values.empty()) + if (values.empty()) { return Result("missing comparison values for EXPECT command"); + } probe->SetValues(std::move(values)); command_list_.push_back(std::move(probe)); @@ -3476,49 +3954,60 @@ Result Parser::ParseExpect() { Result Parser::ParseCopy() { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing buffer name after COPY"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("invalid buffer name after COPY"); + } size_t line = tokenizer_->GetCurrentLine(); auto name = token->AsString(); - if (name == "TO") + if (name == "TO") { return Result("missing buffer name between COPY and TO"); + } Buffer* buffer_from = script_->GetBuffer(name); - if (!buffer_from) + if (!buffer_from) { return Result("COPY origin buffer was not declared"); + } token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing 'TO' after COPY and buffer name"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("expected 'TO' after COPY and buffer name"); + } name = token->AsString(); - if (name != "TO") + if (name != "TO") { return Result("expected 'TO' after COPY and buffer name"); + } token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing buffer name after TO"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("invalid buffer name after TO"); + } name = token->AsString(); Buffer* buffer_to = script_->GetBuffer(name); - if (!buffer_to) + if (!buffer_to) { return Result("COPY destination buffer was not declared"); + } // Set destination buffer to mirror origin buffer buffer_to->SetWidth(buffer_from->GetWidth()); buffer_to->SetHeight(buffer_from->GetHeight()); buffer_to->SetElementCount(buffer_from->ElementCount()); - if (buffer_from == buffer_to) + if (buffer_from == buffer_to) { return Result("COPY origin and destination buffers are identical"); + } auto cmd = MakeUnique(buffer_from, buffer_to); cmd->SetLine(line); @@ -3529,8 +4018,9 @@ Result Parser::ParseCopy() { Result Parser::ParseClearColor() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing pipeline name for CLEAR_COLOR command"); + } size_t line = tokenizer_->GetCurrentLine(); @@ -3547,8 +4037,9 @@ Result Parser::ParseClearColor() { cmd->SetLine(line); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing R value for CLEAR_COLOR command"); + } if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) { return Result("invalid R value for CLEAR_COLOR command: " + token->ToOriginalString()); @@ -3557,8 +4048,9 @@ Result Parser::ParseClearColor() { cmd->SetR(token->AsFloat() / 255.f); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing G value for CLEAR_COLOR command"); + } if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) { return Result("invalid G value for CLEAR_COLOR command: " + token->ToOriginalString()); @@ -3567,8 +4059,9 @@ Result Parser::ParseClearColor() { cmd->SetG(token->AsFloat() / 255.f); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing B value for CLEAR_COLOR command"); + } if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) { return Result("invalid B value for CLEAR_COLOR command: " + token->ToOriginalString()); @@ -3577,8 +4070,9 @@ Result Parser::ParseClearColor() { cmd->SetB(token->AsFloat() / 255.f); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing A value for CLEAR_COLOR command"); + } if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) { return Result("invalid A value for CLEAR_COLOR command: " + token->ToOriginalString()); @@ -3592,8 +4086,9 @@ Result Parser::ParseClearColor() { Result Parser::ParseClearDepth() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing pipeline name for CLEAR_DEPTH command"); + } size_t line = tokenizer_->GetCurrentLine(); @@ -3610,8 +4105,9 @@ Result Parser::ParseClearDepth() { cmd->SetLine(line); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing value for CLEAR_DEPTH command"); + } if (!token->IsDouble()) { return Result("invalid value for CLEAR_DEPTH command: " + token->ToOriginalString()); @@ -3624,8 +4120,9 @@ Result Parser::ParseClearDepth() { Result Parser::ParseClearStencil() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing pipeline name for CLEAR_STENCIL command"); + } size_t line = tokenizer_->GetCurrentLine(); @@ -3642,8 +4139,9 @@ Result Parser::ParseClearStencil() { cmd->SetLine(line); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("missing value for CLEAR_STENCIL command"); + } if (!token->IsInteger() || token->AsInt32() < 0 || token->AsInt32() > 255) { return Result("invalid value for CLEAR_STENCIL command: " + token->ToOriginalString()); @@ -3656,12 +4154,15 @@ Result Parser::ParseClearStencil() { Result Parser::ParseDeviceFeature() { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("missing feature name for DEVICE_FEATURE command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("invalid feature name for DEVICE_FEATURE command"); - if (!script_->IsKnownFeature(token->AsString())) + } + if (!script_->IsKnownFeature(token->AsString())) { return Result("unknown feature name for DEVICE_FEATURE command"); + } script_->AddRequiredFeature(token->AsString()); @@ -3670,12 +4171,15 @@ Result Parser::ParseDeviceFeature() { Result Parser::ParseDeviceProperty() { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("missing property name for DEVICE_PROPERTY command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("invalid property name for DEVICE_PROPERTY command"); - if (!script_->IsKnownProperty(token->AsString())) + } + if (!script_->IsKnownProperty(token->AsString())) { return Result("unknown property name for DEVICE_PROPERTY command"); + } script_->AddRequiredProperty(token->AsString()); @@ -3684,14 +4188,16 @@ Result Parser::ParseDeviceProperty() { Result Parser::ParseRepeat() { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOL()) + if (token->IsEOL() || token->IsEOL()) { return Result("missing count parameter for REPEAT command"); + } if (!token->IsInteger()) { return Result("invalid count parameter for REPEAT command: " + token->ToOriginalString()); } - if (token->AsInt32() <= 0) + if (token->AsInt32() <= 0) { return Result("count parameter must be > 0 for REPEAT command"); + } uint32_t count = token->AsUint32(); @@ -3700,23 +4206,29 @@ Result Parser::ParseRepeat() { for (token = tokenizer_->NextToken(); !token->IsEOS(); token = tokenizer_->NextToken()) { - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("expected identifier"); + } std::string tok = token->AsString(); - if (tok == "END") + if (tok == "END") { break; - if (!IsRepeatable(tok)) + } + if (!IsRepeatable(tok)) { return Result("unknown token: " + tok); + } Result r = ParseRepeatableCommand(tok); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } - if (!token->IsIdentifier() || token->AsString() != "END") + if (!token->IsIdentifier() || token->AsString() != "END") { return Result("missing END for REPEAT command"); + } auto cmd = MakeUnique(count); cmd->SetCommands(std::move(command_list_)); @@ -3729,28 +4241,34 @@ Result Parser::ParseRepeat() { Result Parser::ParseDerivePipelineBlock() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() == "FROM") + if (!token->IsIdentifier() || token->AsString() == "FROM") { return Result("missing pipeline name for DERIVE_PIPELINE command"); + } std::string name = token->AsString(); - if (script_->GetPipeline(name) != nullptr) + if (script_->GetPipeline(name) != nullptr) { return Result("duplicate pipeline name for DERIVE_PIPELINE command"); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "FROM") + if (!token->IsIdentifier() || token->AsString() != "FROM") { return Result("missing FROM in DERIVE_PIPELINE command"); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("missing parent pipeline name in DERIVE_PIPELINE command"); + } Pipeline* parent = script_->GetPipeline(token->AsString()); - if (!parent) + if (!parent) { return Result("unknown parent pipeline in DERIVE_PIPELINE command"); + } Result r = ValidateEndOfStatement("DERIVE_PIPELINE command"); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } auto pipeline = parent->Clone(); pipeline->SetName(name); @@ -3760,8 +4278,9 @@ Result Parser::ParseDerivePipelineBlock() { Result Parser::ParseDeviceExtension() { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("DEVICE_EXTENSION missing name"); + } if (!token->IsIdentifier()) { return Result("DEVICE_EXTENSION invalid name: " + token->ToOriginalString()); @@ -3774,8 +4293,9 @@ Result Parser::ParseDeviceExtension() { Result Parser::ParseInstanceExtension() { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("INSTANCE_EXTENSION missing name"); + } if (!token->IsIdentifier()) { return Result("INSTANCE_EXTENSION invalid name: " + token->ToOriginalString()); @@ -3788,24 +4308,30 @@ Result Parser::ParseInstanceExtension() { Result Parser::ParseSet() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "ENGINE_DATA") + if (!token->IsIdentifier() || token->AsString() != "ENGINE_DATA") { return Result("SET missing ENGINE_DATA"); + } token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("SET missing variable to be set"); + } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("SET invalid variable to set: " + token->ToOriginalString()); + } - if (token->AsString() != "fence_timeout_ms") + if (token->AsString() != "fence_timeout_ms") { return Result("SET unknown variable provided: " + token->AsString()); + } token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("SET missing value for fence_timeout_ms"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("SET invalid value for fence_timeout_ms, must be uint32"); + } script_->GetEngineData().fence_timeout_ms = token->AsUint32(); @@ -3814,119 +4340,135 @@ Result Parser::ParseSet() { Result Parser::ParseSampler() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for sampler name"); + } auto sampler = MakeUnique(); sampler->SetName(token->AsString()); token = tokenizer_->NextToken(); while (!token->IsEOS() && !token->IsEOL()) { - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for sampler parameters"); + } auto param = token->AsString(); if (param == "MAG_FILTER") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for MAG_FILTER value"); + } auto filter = token->AsString(); - if (filter == "linear") + if (filter == "linear") { sampler->SetMagFilter(FilterType::kLinear); - else if (filter == "nearest") + } else if (filter == "nearest") { sampler->SetMagFilter(FilterType::kNearest); - else + } else { return Result("invalid MAG_FILTER value " + filter); + } } else if (param == "MIN_FILTER") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for MIN_FILTER value"); + } auto filter = token->AsString(); - if (filter == "linear") + if (filter == "linear") { sampler->SetMinFilter(FilterType::kLinear); - else if (filter == "nearest") + } else if (filter == "nearest") { sampler->SetMinFilter(FilterType::kNearest); - else + } else { return Result("invalid MIN_FILTER value " + filter); + } } else if (param == "ADDRESS_MODE_U") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for ADDRESS_MODE_U value"); + } auto mode_str = token->AsString(); auto mode = StrToAddressMode(mode_str); - if (mode == AddressMode::kUnknown) + if (mode == AddressMode::kUnknown) { return Result("invalid ADDRESS_MODE_U value " + mode_str); + } sampler->SetAddressModeU(mode); } else if (param == "ADDRESS_MODE_V") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for ADDRESS_MODE_V value"); + } auto mode_str = token->AsString(); auto mode = StrToAddressMode(mode_str); - if (mode == AddressMode::kUnknown) + if (mode == AddressMode::kUnknown) { return Result("invalid ADDRESS_MODE_V value " + mode_str); + } sampler->SetAddressModeV(mode); } else if (param == "ADDRESS_MODE_W") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for ADDRESS_MODE_W value"); + } auto mode_str = token->AsString(); auto mode = StrToAddressMode(mode_str); - if (mode == AddressMode::kUnknown) + if (mode == AddressMode::kUnknown) { return Result("invalid ADDRESS_MODE_W value " + mode_str); + } sampler->SetAddressModeW(mode); } else if (param == "BORDER_COLOR") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid token when looking for BORDER_COLOR value"); + } auto color_str = token->AsString(); - if (color_str == "float_transparent_black") + if (color_str == "float_transparent_black") { sampler->SetBorderColor(BorderColor::kFloatTransparentBlack); - else if (color_str == "int_transparent_black") + } else if (color_str == "int_transparent_black") { sampler->SetBorderColor(BorderColor::kIntTransparentBlack); - else if (color_str == "float_opaque_black") + } else if (color_str == "float_opaque_black") { sampler->SetBorderColor(BorderColor::kFloatOpaqueBlack); - else if (color_str == "int_opaque_black") + } else if (color_str == "int_opaque_black") { sampler->SetBorderColor(BorderColor::kIntOpaqueBlack); - else if (color_str == "float_opaque_white") + } else if (color_str == "float_opaque_white") { sampler->SetBorderColor(BorderColor::kFloatOpaqueWhite); - else if (color_str == "int_opaque_white") + } else if (color_str == "int_opaque_white") { sampler->SetBorderColor(BorderColor::kIntOpaqueWhite); - else + } else { return Result("invalid BORDER_COLOR value " + color_str); + } } else if (param == "MIN_LOD") { token = tokenizer_->NextToken(); - if (!token->IsDouble()) + if (!token->IsDouble()) { return Result("invalid token when looking for MIN_LOD value"); + } sampler->SetMinLOD(token->AsFloat()); } else if (param == "MAX_LOD") { token = tokenizer_->NextToken(); - if (!token->IsDouble()) + if (!token->IsDouble()) { return Result("invalid token when looking for MAX_LOD value"); + } sampler->SetMaxLOD(token->AsFloat()); } else if (param == "NORMALIZED_COORDS") { @@ -3938,20 +4480,23 @@ Result Parser::ParseSampler() { } else if (param == "COMPARE") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid value for COMPARE"); + } - if (token->AsString() == "on") + if (token->AsString() == "on") { sampler->SetCompareEnable(true); - else if (token->AsString() == "off") + } else if (token->AsString() == "off") { sampler->SetCompareEnable(false); - else + } else { return Result("invalid value for COMPARE: " + token->AsString()); + } } else if (param == "COMPARE_OP") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid value for COMPARE_OP"); + } CompareOp compare_op = StrToCompareOp(token->AsString()); if (compare_op != CompareOp::kUnknown) { @@ -3981,37 +4526,42 @@ bool Parser::IsRayTracingShader(ShaderType type) { Result Parser::ParseAS() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Acceleration structure requires TOP_LEVEL or BOTTOM_LEVEL"); + } Result r; auto type = token->AsString(); - if (type == "BOTTOM_LEVEL") + if (type == "BOTTOM_LEVEL") { r = ParseBLAS(); - else if (type == "TOP_LEVEL") + } else if (type == "TOP_LEVEL") { r = ParseTLAS(); - else + } else { return Result("Unexpected acceleration structure type"); + } return r; } Result Parser::ParseBLAS() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Bottom level acceleration structure requires a name"); + } auto name = token->AsString(); - if (script_->GetBLAS(name) != nullptr) + if (script_->GetBLAS(name) != nullptr) { return Result( "Bottom level acceleration structure with this name already defined"); + } std::unique_ptr blas = MakeUnique(); blas->SetName(name); token = tokenizer_->NextToken(); - if (!token->IsEOL()) + if (!token->IsEOL()) { return Result("New line expected"); + } Result r; while (true) { @@ -4055,9 +4605,11 @@ Result Parser::ParseBLAS() { if (blas->GetGeometrySize() > 0) { auto type = blas->GetGeometries()[0]->GetType(); auto& geometries = blas->GetGeometries(); - for (auto& g : geometries) - if (g->GetType() != type) + for (auto& g : geometries) { + if (g->GetType() != type) { return Result("Only one type of geometry is allowed within a BLAS"); + } + } } return script_->AddBLAS(std::move(blas)); @@ -4072,10 +4624,12 @@ Result Parser::ParseBLASTriangle(BLAS* blas) { while (true) { auto token = tokenizer_->NextToken(); - if (token->IsEOS()) + if (token->IsEOS()) { return Result("END expected"); - if (token->IsEOL()) + } + if (token->IsEOL()) { continue; + } if (token->IsIdentifier()) { std::string tok = token->AsString(); @@ -4083,8 +4637,9 @@ Result Parser::ParseBLASTriangle(BLAS* blas) { break; } else if (tok == "FLAGS") { Result r = ParseGeometryFlags(&flags); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { return Result("END or float value is expected"); } @@ -4095,14 +4650,17 @@ Result Parser::ParseBLASTriangle(BLAS* blas) { } } - if (g.empty()) + if (g.empty()) { return Result("No triangles have been specified."); + } - if (g.size() % 3 != 0) + if (g.size() % 3 != 0) { return Result("Each vertex consists of three float coordinates."); + } - if ((g.size() / 3) % 3 != 0) + if ((g.size() / 3) % 3 != 0) { return Result("Each triangle should include three vertices."); + } geometry->SetData(g); geometry->SetFlags(flags); @@ -4121,10 +4679,12 @@ Result Parser::ParseBLASAABB(BLAS* blas) { while (true) { auto token = tokenizer_->NextToken(); - if (token->IsEOS()) + if (token->IsEOS()) { return Result("END expected"); - if (token->IsEOL()) + } + if (token->IsEOL()) { continue; + } if (token->IsIdentifier()) { std::string tok = token->AsString(); @@ -4132,8 +4692,9 @@ Result Parser::ParseBLASAABB(BLAS* blas) { break; } else if (tok == "FLAGS") { Result r = ParseGeometryFlags(&flags); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { return Result("END or float value is expected"); } @@ -4146,13 +4707,15 @@ Result Parser::ParseBLASAABB(BLAS* blas) { } } - if (g.empty()) + if (g.empty()) { return Result("No AABBs have been specified."); + } - if ((g.size() % 6) != 0) + if ((g.size() % 6) != 0) { return Result( "Each vertex consists of three float coordinates. Each AABB should " "include two vertices."); + } geometry->SetData(g); geometry->SetFlags(flags); @@ -4175,29 +4738,33 @@ Result Parser::ParseGeometryFlags(uint32_t* flags) { first_eol = false; singleline = (*flags != 0); } - if (singleline) + if (singleline) { break; - else + } else { continue; + } } - if (token->IsEOS()) + if (token->IsEOS()) { return Result("END command missing"); + } if (token->IsIdentifier()) { - if (token->AsString() == "END") + if (token->AsString() == "END") { break; - else if (token->AsString() == "OPAQUE") + } else if (token->AsString() == "OPAQUE") { *flags |= VK_GEOMETRY_OPAQUE_BIT_KHR; - else if (token->AsString() == "NO_DUPLICATE_ANY_HIT") + } else if (token->AsString() == "NO_DUPLICATE_ANY_HIT") { *flags |= VK_GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION_BIT_KHR; - else + } else { return Result("Unknown flag: " + token->AsString()); + } } else { r = Result("Identifier expected"); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } return {}; @@ -4205,14 +4772,16 @@ Result Parser::ParseGeometryFlags(uint32_t* flags) { Result Parser::ParseTLAS() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("invalid TLAS name provided"); + } auto name = token->AsString(); token = tokenizer_->NextToken(); - if (!token->IsEOL()) + if (!token->IsEOL()) { return Result("New line expected"); + } std::unique_ptr tlas = MakeUnique(); @@ -4220,29 +4789,36 @@ Result Parser::ParseTLAS() { while (true) { token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (token->IsEOS()) + } + if (token->IsEOS()) { return Result("END command missing"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("expected identifier"); + } Result r; std::string tok = token->AsString(); - if (tok == "END") + if (tok == "END") { break; - if (tok == "BOTTOM_LEVEL_INSTANCE") + } + if (tok == "BOTTOM_LEVEL_INSTANCE") { r = ParseBLASInstance(tlas.get()); - else + } else { r = Result("unknown token: " + tok); + } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } Result r = script_->AddTLAS(std::move(tlas)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } @@ -4255,27 +4831,32 @@ Result Parser::ParseBLASInstance(TLAS* tlas) { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Bottom level acceleration structure name expected"); + } std::string name = token->AsString(); auto ptr = script_->GetBLAS(name); - if (!ptr) + if (!ptr) { return Result( "Bottom level acceleration structure with given name not found"); + } instance->SetUsedBLAS(name, ptr); while (true) { token = tokenizer_->NextToken(); - if (token->IsEOS()) + if (token->IsEOS()) { return Result("Unexpected end"); - if (token->IsEOL()) + } + if (token->IsEOL()) { continue; + } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("expected identifier"); + } Result r; std::string tok = token->AsString(); @@ -4289,44 +4870,48 @@ Result Parser::ParseBLASInstance(TLAS* tlas) { token = tokenizer_->NextToken(); uint64_t v; - if (token->IsInteger()) + if (token->IsInteger()) { v = token->AsUint64(); - else if (token->IsHex()) + } else if (token->IsHex()) { v = token->AsHex(); - else + } else { return Result("Integer or hex value expected"); + } instance->SetMask(uint32_t(v)); } else if (tok == "OFFSET") { token = tokenizer_->NextToken(); uint64_t v; - if (token->IsInteger()) + if (token->IsInteger()) { v = token->AsUint64(); - else if (token->IsHex()) + } else if (token->IsHex()) { v = token->AsHex(); - else + } else { return Result("Integer or hex value expected"); + } instance->SetOffset(uint32_t(v)); } else if (tok == "INDEX") { token = tokenizer_->NextToken(); uint64_t v; - if (token->IsInteger()) + if (token->IsInteger()) { v = token->AsUint64(); - else if (token->IsHex()) + } else if (token->IsHex()) { v = token->AsHex(); - else + } else { return Result("Integer or hex value expected"); + } instance->SetInstanceIndex(uint32_t(v)); } else { r = Result("Unknown token in BOTTOM_LEVEL_INSTANCE block: " + tok); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } tlas->AddInstance(std::move(instance)); @@ -4342,21 +4927,25 @@ Result Parser::ParseBLASInstanceTransform(BLASInstance* instance) { while (true) { token = tokenizer_->NextToken(); - if (token->IsEOL()) + if (token->IsEOL()) { continue; - if (token->IsEOS()) + } + if (token->IsEOS()) { return Result("END command missing"); + } - if (token->IsIdentifier() && token->AsString() == "END") + if (token->IsIdentifier() && token->AsString() == "END") { break; - else if (token->IsDouble() || token->IsInteger()) + } else if (token->IsDouble() || token->IsInteger()) { transform.push_back(token->AsFloat()); - else + } else { return Result("Unknown token: " + token->AsString()); + } } - if (transform.size() != 12) + if (transform.size() != 12) { return Result("Transform matrix expected to have 12 numbers"); + } instance->SetTransform(transform); @@ -4377,64 +4966,72 @@ Result Parser::ParseBLASInstanceFlags(BLASInstance* instance) { first_eol = false; singleline = (flags != 0); } - if (singleline) + if (singleline) { break; - else + } else { continue; + } } - if (token->IsEOS()) + if (token->IsEOS()) { return Result("END command missing"); + } if (token->IsInteger()) { flags |= token->AsUint32(); } else if (token->IsHex()) { flags |= uint32_t(token->AsHex()); } else if (token->IsIdentifier()) { - if (token->AsString() == "END") + if (token->AsString() == "END") { break; - else if (token->AsString() == "TRIANGLE_FACING_CULL_DISABLE") + } else if (token->AsString() == "TRIANGLE_FACING_CULL_DISABLE") { flags |= VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR; - else if (token->AsString() == "TRIANGLE_FLIP_FACING") + } else if (token->AsString() == "TRIANGLE_FLIP_FACING") { flags |= VK_GEOMETRY_INSTANCE_TRIANGLE_FLIP_FACING_BIT_KHR; - else if (token->AsString() == "FORCE_OPAQUE") + } else if (token->AsString() == "FORCE_OPAQUE") { flags |= VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_KHR; - else if (token->AsString() == "FORCE_NO_OPAQUE") + } else if (token->AsString() == "FORCE_NO_OPAQUE") { flags |= VK_GEOMETRY_INSTANCE_FORCE_NO_OPAQUE_BIT_KHR; - else if (token->AsString() == "FORCE_OPACITY_MICROMAP_2_STATE") + } else if (token->AsString() == "FORCE_OPACITY_MICROMAP_2_STATE") { flags |= VK_GEOMETRY_INSTANCE_FORCE_OPACITY_MICROMAP_2_STATE_EXT; - else if (token->AsString() == "DISABLE_OPACITY_MICROMAPS") + } else if (token->AsString() == "DISABLE_OPACITY_MICROMAPS") { flags |= VK_GEOMETRY_INSTANCE_DISABLE_OPACITY_MICROMAPS_EXT; - else + } else { return Result("Unknown flag: " + token->AsString()); + } } else { r = Result("Identifier expected"); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } - if (r.IsSuccess()) + if (r.IsSuccess()) { instance->SetFlags(flags); + } return {}; } Result Parser::ParseSBT(Pipeline* pipeline) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("SHADER_BINDINGS_TABLE requires a name"); + } auto name = token->AsString(); - if (pipeline->GetSBT(name) != nullptr) + if (pipeline->GetSBT(name) != nullptr) { return Result("SHADER_BINDINGS_TABLE with this name already defined"); + } std::unique_ptr sbt = MakeUnique(); sbt->SetName(name); token = tokenizer_->NextToken(); - if (!token->IsEOL()) + if (!token->IsEOL()) { return Result("New line expected"); + } while (true) { token = tokenizer_->NextToken(); @@ -4456,9 +5053,10 @@ Result Parser::ParseSBT(Pipeline* pipeline) { uint32_t index = 0; ShaderGroup* shader_group = script_->FindShaderGroup(pipeline, tok, &index); - if (shader_group == nullptr) + if (shader_group == nullptr) { return Result( "Shader group not found neither in pipeline, nor in libraries"); + } std::unique_ptr sbtrecord = MakeUnique(); @@ -4473,13 +5071,15 @@ Result Parser::ParseSBT(Pipeline* pipeline) { } Result Parser::ParseMaxRayPayloadSize(Pipeline* pipeline) { - if (!pipeline->IsRayTracing()) + if (!pipeline->IsRayTracing()) { return Result( "Ray payload size parameter is allowed only for ray tracing pipeline"); + } auto token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Ray payload size expects an integer"); + } pipeline->SetMaxPipelineRayPayloadSize(token->AsUint32()); @@ -4487,13 +5087,15 @@ Result Parser::ParseMaxRayPayloadSize(Pipeline* pipeline) { } Result Parser::ParseMaxRayHitAttributeSize(Pipeline* pipeline) { - if (!pipeline->IsRayTracing()) + if (!pipeline->IsRayTracing()) { return Result( "Ray hit attribute size is allowed only for ray tracing pipeline"); + } auto token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Ray hit attribute size expects an integer"); + } pipeline->SetMaxPipelineRayHitAttributeSize(token->AsUint32()); @@ -4501,13 +5103,15 @@ Result Parser::ParseMaxRayHitAttributeSize(Pipeline* pipeline) { } Result Parser::ParseMaxRayRecursionDepth(Pipeline* pipeline) { - if (!pipeline->IsRayTracing()) + if (!pipeline->IsRayTracing()) { return Result( "Ray recursion depth is allowed only for ray tracing pipeline"); + } auto token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Ray recursion depth expects an integer"); + } pipeline->SetMaxPipelineRayRecursionDepth(token->AsUint32()); @@ -4515,8 +5119,9 @@ Result Parser::ParseMaxRayRecursionDepth(Pipeline* pipeline) { } Result Parser::ParseFlags(Pipeline* pipeline) { - if (!pipeline->IsRayTracing()) + if (!pipeline->IsRayTracing()) { return Result("Flags are allowed only for ray tracing pipeline"); + } std::unique_ptr token; uint32_t flags = pipeline->GetCreateFlags(); @@ -4531,57 +5136,66 @@ Result Parser::ParseFlags(Pipeline* pipeline) { first_eol = false; singleline = (flags != 0); } - if (singleline) + if (singleline) { break; - else + } else { continue; + } } - if (token->IsEOS()) + if (token->IsEOS()) { return Result("END command missing"); + } if (token->IsInteger()) { flags |= token->AsUint32(); } else if (token->IsHex()) { flags |= uint32_t(token->AsHex()); } else if (token->IsIdentifier()) { - if (token->AsString() == "END") + if (token->AsString() == "END") { break; - else if (token->AsString() == "LIBRARY") + } else if (token->AsString() == "LIBRARY") { flags |= VK_PIPELINE_CREATE_LIBRARY_BIT_KHR; - else + } else { return Result("Unknown flag: " + token->AsString()); + } } else { r = Result("Identifier expected"); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } - if (r.IsSuccess()) + if (r.IsSuccess()) { pipeline->SetCreateFlags(flags); + } return {}; } Result Parser::ParseUseLibrary(Pipeline* pipeline) { - if (!pipeline->IsRayTracing()) + if (!pipeline->IsRayTracing()) { return Result("Use library is allowed only for ray tracing pipeline"); + } while (true) { auto token = tokenizer_->NextToken(); - if (token->IsEOS()) + if (token->IsEOS()) { return Result("EOL expected"); - if (token->IsEOL()) + } + if (token->IsEOL()) { break; + } if (token->IsIdentifier()) { std::string tok = token->AsString(); Pipeline* use_pipeline = script_->GetPipeline(tok); - if (!use_pipeline) + if (!use_pipeline) { return Result("Pipeline not found: " + tok); + } pipeline->AddPipelineLibrary(use_pipeline); } else { @@ -4595,13 +5209,15 @@ Result Parser::ParseUseLibrary(Pipeline* pipeline) { Result Parser::ParseTolerances(std::vector* tolerances) { auto token = tokenizer_->PeekNextToken(); while (!token->IsEOL() && !token->IsEOS()) { - if (!token->IsInteger() && !token->IsDouble()) + if (!token->IsInteger() && !token->IsDouble()) { break; + } token = tokenizer_->NextToken(); Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } double value = token->AsDouble(); token = tokenizer_->PeekNextToken(); @@ -4619,20 +5235,23 @@ Result Parser::ParseTolerances(std::vector* tolerances) { Result Parser::ParseVirtualFile() { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier() && !token->IsString()) + if (!token->IsIdentifier() && !token->IsString()) { return Result("invalid virtual file path"); + } auto path = token->AsString(); auto r = ValidateEndOfStatement("VIRTUAL_FILE command"); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } auto data = tokenizer_->ExtractToNext("END"); token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "END") + if (!token->IsIdentifier() || token->AsString() != "END") { return Result("VIRTUAL_FILE missing END command"); + } return script_->AddVirtualFile(path, data); } diff --git a/src/amberscript/parser_blend_test.cc b/src/amberscript/parser_blend_test.cc index 013ccbd00..85d17c94b 100644 --- a/src/amberscript/parser_blend_test.cc +++ b/src/amberscript/parser_blend_test.cc @@ -58,15 +58,13 @@ END)"; pipeline->GetPipelineData()->GetSrcColorBlendFactor()); ASSERT_EQ(BlendFactor::kOneMinusSrcAlpha, pipeline->GetPipelineData()->GetDstColorBlendFactor()); - ASSERT_EQ(BlendOp::kAdd, - pipeline->GetPipelineData()->GetColorBlendOp()); + ASSERT_EQ(BlendOp::kAdd, pipeline->GetPipelineData()->GetColorBlendOp()); ASSERT_EQ(BlendFactor::kOne, pipeline->GetPipelineData()->GetSrcAlphaBlendFactor()); ASSERT_EQ(BlendFactor::kZero, pipeline->GetPipelineData()->GetDstAlphaBlendFactor()); - ASSERT_EQ(BlendOp::kMax, - pipeline->GetPipelineData()->GetAlphaBlendOp()); + ASSERT_EQ(BlendOp::kMax, pipeline->GetPipelineData()->GetAlphaBlendOp()); } TEST_F(AmberScriptParserTest, BlendDefaultValues) { @@ -101,15 +99,13 @@ END)"; pipeline->GetPipelineData()->GetSrcColorBlendFactor()); ASSERT_EQ(BlendFactor::kZero, pipeline->GetPipelineData()->GetDstColorBlendFactor()); - ASSERT_EQ(BlendOp::kAdd, - pipeline->GetPipelineData()->GetColorBlendOp()); + ASSERT_EQ(BlendOp::kAdd, pipeline->GetPipelineData()->GetColorBlendOp()); ASSERT_EQ(BlendFactor::kOne, pipeline->GetPipelineData()->GetSrcAlphaBlendFactor()); ASSERT_EQ(BlendFactor::kZero, pipeline->GetPipelineData()->GetDstAlphaBlendFactor()); - ASSERT_EQ(BlendOp::kAdd, - pipeline->GetPipelineData()->GetAlphaBlendOp()); + ASSERT_EQ(BlendOp::kAdd, pipeline->GetPipelineData()->GetAlphaBlendOp()); } TEST_F(AmberScriptParserTest, BlendInvalidColorFactor) { diff --git a/src/amberscript/parser_raytracing_test.cc b/src/amberscript/parser_raytracing_test.cc index c92dfe67b..3e21418b7 100644 --- a/src/amberscript/parser_raytracing_test.cc +++ b/src/amberscript/parser_raytracing_test.cc @@ -1191,7 +1191,6 @@ RUN my_rtpipeline 0.0 EXPECT_EQ("14: Shader binding table type is expected", r.Error()); } - TEST_F(AmberScriptParserTest, RayTracingRunExpectsSBTName) { std::string in = R"( SHADER ray_generation raygen1 GLSL @@ -1296,8 +1295,7 @@ RUN my_rtpipeline MISS sbt1 MISS sbt1 Parser parser; Result r = parser.Parse(in); ASSERT_FALSE(r.IsSuccess()); - EXPECT_EQ("14: MISS shader binding table can specified only once", - r.Error()); + EXPECT_EQ("14: MISS shader binding table can specified only once", r.Error()); } TEST_F(AmberScriptParserTest, RayTracingRunSBTHitDup) { diff --git a/src/buffer.cc b/src/buffer.cc index 71f295d3b..5387b5475 100644 --- a/src/buffer.cc +++ b/src/buffer.cc @@ -40,31 +40,41 @@ double CalculateDiff(const Format::Segment* seg, const uint8_t* buf2) { FormatMode mode = seg->GetFormatMode(); uint32_t num_bits = seg->GetNumBits(); - if (type::Type::IsInt8(mode, num_bits)) + if (type::Type::IsInt8(mode, num_bits)) { return Sub(buf1, buf2); - if (type::Type::IsInt16(mode, num_bits)) + } + if (type::Type::IsInt16(mode, num_bits)) { return Sub(buf1, buf2); - if (type::Type::IsInt32(mode, num_bits)) + } + if (type::Type::IsInt32(mode, num_bits)) { return Sub(buf1, buf2); - if (type::Type::IsInt64(mode, num_bits)) + } + if (type::Type::IsInt64(mode, num_bits)) { return Sub(buf1, buf2); - if (type::Type::IsUint8(mode, num_bits)) + } + if (type::Type::IsUint8(mode, num_bits)) { return Sub(buf1, buf2); - if (type::Type::IsUint16(mode, num_bits)) + } + if (type::Type::IsUint16(mode, num_bits)) { return Sub(buf1, buf2); - if (type::Type::IsUint32(mode, num_bits)) + } + if (type::Type::IsUint32(mode, num_bits)) { return Sub(buf1, buf2); - if (type::Type::IsUint64(mode, num_bits)) + } + if (type::Type::IsUint64(mode, num_bits)) { return Sub(buf1, buf2); + } if (type::Type::IsFloat16(mode, num_bits)) { float val1 = float16::HexFloatToFloat(buf1, 16); float val2 = float16::HexFloatToFloat(buf2, 16); return static_cast(val1 - val2); } - if (type::Type::IsFloat32(mode, num_bits)) + if (type::Type::IsFloat32(mode, num_bits)) { return Sub(buf1, buf2); - if (type::Type::IsFloat64(mode, num_bits)) + } + if (type::Type::IsFloat64(mode, num_bits)) { return Sub(buf1, buf2); + } assert(false && "NOTREACHED"); return 0.0; @@ -77,20 +87,24 @@ Buffer::Buffer() = default; Buffer::~Buffer() = default; Result Buffer::CopyTo(Buffer* buffer) const { - if (buffer->width_ != width_) + if (buffer->width_ != width_) { return Result("Buffer::CopyBaseFields() buffers have a different width"); - if (buffer->height_ != height_) + } + if (buffer->height_ != height_) { return Result("Buffer::CopyBaseFields() buffers have a different height"); - if (buffer->element_count_ != element_count_) + } + if (buffer->element_count_ != element_count_) { return Result("Buffer::CopyBaseFields() buffers have a different size"); + } buffer->bytes_ = bytes_; return {}; } Result Buffer::IsEqual(Buffer* buffer) const { auto result = CheckCompability(buffer); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } uint32_t num_different = 0; uint32_t first_different_index = 0; @@ -144,29 +158,36 @@ std::vector Buffer::CalculateDiffs(const Buffer* buffer) const { } Result Buffer::CheckCompability(Buffer* buffer) const { - if (!buffer->format_->Equal(format_)) + if (!buffer->format_->Equal(format_)) { return Result{"Buffers have a different format"}; - if (buffer->element_count_ != element_count_) + } + if (buffer->element_count_ != element_count_) { return Result{"Buffers have a different size"}; - if (buffer->width_ != width_) + } + if (buffer->width_ != width_) { return Result{"Buffers have a different width"}; - if (buffer->height_ != height_) + } + if (buffer->height_ != height_) { return Result{"Buffers have a different height"}; - if (buffer->ValueCount() != ValueCount()) + } + if (buffer->ValueCount() != ValueCount()) { return Result{"Buffers have a different number of values"}; + } return {}; } Result Buffer::CompareRMSE(Buffer* buffer, float tolerance) const { auto result = CheckCompability(buffer); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } auto diffs = CalculateDiffs(buffer); double sum = 0.0; - for (const auto val : diffs) + for (const auto val : diffs) { sum += (val * val); + } sum /= static_cast(diffs.size()); double rmse = std::sqrt(sum); @@ -207,8 +228,9 @@ std::vector Buffer::GetHistogramForChannel(uint32_t channel, Result Buffer::CompareHistogramEMD(Buffer* buffer, float tolerance) const { auto result = CheckCompability(buffer); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } const int num_bins = 256; auto num_channels = format_->InputNeededPerElement(); @@ -282,8 +304,9 @@ Result Buffer::RecalculateMaxSizeInBytes(const std::vector& data, // values per element. element_count = value_count / format_->InputNeededPerElement(); } - if (GetMaxSizeInBytes() < element_count * format_->SizeInBytes()) + if (GetMaxSizeInBytes() < element_count * format_->SizeInBytes()) { SetMaxSizeInBytes(element_count * format_->SizeInBytes()); + } return {}; } @@ -298,8 +321,9 @@ Result Buffer::SetDataWithOffset(const std::vector& data, // The buffer should only be resized to become bigger. This means that if a // command was run to set the buffer size we'll honour that size until a // request happens to make the buffer bigger. - if (value_count > ValueCount()) + if (value_count > ValueCount()) { SetValueCount(value_count); + } // Even if the value count doesn't change, the buffer is still resized because // this maybe the first time data is set into the buffer. @@ -311,11 +335,13 @@ Result Buffer::SetDataWithOffset(const std::vector& data, format_->SizeInBytes(); assert(new_space + offset <= GetSizeInBytes()); - if (new_space > 0) + if (new_space > 0) { memset(bytes_.data() + offset, 0, new_space); + } - if (data.size() > (ElementCount() * format_->InputNeededPerElement())) + if (data.size() > (ElementCount() * format_->InputNeededPerElement())) { return Result("Mismatched number of items in buffer"); + } uint8_t* ptr = bytes_.data() + offset; const auto& segments = format_->GetSegments(); @@ -329,8 +355,9 @@ Result Buffer::SetDataWithOffset(const std::vector& data, Value v = data[i++]; ptr += WriteValueFromComponent(v, seg.GetFormatMode(), seg.GetNumBits(), ptr); - if (i >= data.size()) + if (i >= data.size()) { break; + } } } return {}; @@ -406,15 +433,17 @@ void Buffer::SetMaxSizeInBytes(uint32_t max_size_in_bytes) { } uint32_t Buffer::GetMaxSizeInBytes() const { - if (max_size_in_bytes_ != 0) + if (max_size_in_bytes_ != 0) { return max_size_in_bytes_; - else + } else { return GetSizeInBytes(); + } } Result Buffer::SetDataFromBuffer(const Buffer* src, uint32_t offset) { - if (bytes_.size() < offset + src->bytes_.size()) + if (bytes_.size() < offset + src->bytes_.size()) { bytes_.resize(offset + src->bytes_.size()); + } std::memcpy(bytes_.data() + offset, src->bytes_.data(), src->bytes_.size()); element_count_ = diff --git a/src/buffer.h b/src/buffer.h index 90f3b0131..b7d14b8f2 100644 --- a/src/buffer.h +++ b/src/buffer.h @@ -150,18 +150,21 @@ class Buffer { } /// Returns the number of values in the buffer. uint32_t ValueCount() const { - if (!format_) + if (!format_) { return 0; + } // Packed formats are single values. - if (format_->IsPacked()) + if (format_->IsPacked()) { return element_count_; + } return element_count_ * format_->InputNeededPerElement(); } /// Returns the number of bytes needed for the data in the buffer. uint32_t GetSizeInBytes() const { - if (!format_) + if (!format_) { return 0; + } return ElementCount() * format_->SizeInBytes(); } diff --git a/src/buffer_test.cc b/src/buffer_test.cc index 1868b9595..b12f028d1 100644 --- a/src/buffer_test.cc +++ b/src/buffer_test.cc @@ -136,16 +136,18 @@ TEST_F(BufferTest, GetHistogramForChannelGradient) { // Creates 10 RBGA pixel values with the blue channels ranging from 0 to 255. // Every value gets multiplied by 25 to create a gradient std::vector values(40); - for (uint32_t i = 0; i < values.size(); i += 4) + for (uint32_t i = 0; i < values.size(); i += 4) { values[i + 2].SetIntValue(i / 4 * 25); + } Buffer b; b.SetFormat(&fmt); b.SetData(values); std::vector bins = b.GetHistogramForChannel(2, 256); - for (uint32_t i = 0; i < values.size(); i += 4) + for (uint32_t i = 0; i < values.size(); i += 4) { EXPECT_EQ(1u, bins[i / 4 * 25]); + } } // Creates 10 RGBA pixel values, with all channels being 0, and checks that all @@ -156,8 +158,9 @@ TEST_F(BufferTest, GetHistogramForChannelAllBlack) { Format fmt(type.get()); std::vector values(40); - for (uint32_t i = 0; i < values.size(); i++) + for (uint32_t i = 0; i < values.size(); i++) { values[i].SetIntValue(0); + } Buffer b; b.SetFormat(&fmt); @@ -165,8 +168,9 @@ TEST_F(BufferTest, GetHistogramForChannelAllBlack) { for (uint8_t i = 0; i < 4; i++) { std::vector bins = b.GetHistogramForChannel(i, 256); - for (uint32_t y = 0; y < values.size(); y++) + for (uint32_t y = 0; y < values.size(); y++) { EXPECT_EQ(10u, bins[0]); + } } } @@ -179,8 +183,9 @@ TEST_F(BufferTest, GetHistogramForChannelAllWhite) { Format fmt(type.get()); std::vector values(40); - for (uint32_t i = 0; i < values.size(); i++) + for (uint32_t i = 0; i < values.size(); i++) { values[i].SetIntValue(std::numeric_limits::max()); + } Buffer b; b.SetFormat(&fmt); @@ -188,8 +193,9 @@ TEST_F(BufferTest, GetHistogramForChannelAllWhite) { for (uint8_t i = 0; i < 4; i++) { std::vector bins = b.GetHistogramForChannel(i, 256); - for (uint32_t y = 0; y < values.size(); y++) + for (uint32_t y = 0; y < values.size(); y++) { EXPECT_EQ(10u, bins[255]); + } } } @@ -203,8 +209,9 @@ TEST_F(BufferTest, CompareHistogramEMDToleranceFalse) { // Every value gets multiplied by 25 to create a gradient std::vector values1(40); - for (uint32_t i = 0; i < values1.size(); i += 4) + for (uint32_t i = 0; i < values1.size(); i += 4) { values1[i].SetIntValue(i / 4 * 25); + } std::vector values2 = values1; values2[4].SetIntValue(values2[4].AsUint8() + 50); @@ -230,8 +237,9 @@ TEST_F(BufferTest, CompareHistogramEMDToleranceTrue) { // Every value gets multiplied by 25 to create a gradient std::vector values1(40); - for (uint32_t i = 0; i < values1.size(); i += 4) + for (uint32_t i = 0; i < values1.size(); i += 4) { values1[i].SetIntValue(i / 4 * 25); + } std::vector values2 = values1; values2[4].SetIntValue(values2[4].AsUint8() + 50); @@ -255,8 +263,9 @@ TEST_F(BufferTest, CompareHistogramEMDToleranceAllBlack) { Format fmt(type.get()); std::vector values1(40); - for (uint32_t i = 0; i < values1.size(); i++) + for (uint32_t i = 0; i < values1.size(); i++) { values1[i].SetIntValue(0); + } std::vector values2 = values1; @@ -279,8 +288,9 @@ TEST_F(BufferTest, CompareHistogramEMDToleranceAllWhite) { Format fmt(type.get()); std::vector values1(40); - for (uint32_t i = 0; i < values1.size(); i++) + for (uint32_t i = 0; i < values1.size(); i++) { values1[i].SetIntValue(std::numeric_limits().max()); + } std::vector values2 = values1; diff --git a/src/command_data.cc b/src/command_data.cc index c0b76123c..9208f229d 100644 --- a/src/command_data.cc +++ b/src/command_data.cc @@ -47,161 +47,164 @@ Topology NameToTopology(const std::string& name) { // TODO(dsinclair): Make smarter if needed for (auto& topo : topologies) { - if (topo.name == name) + if (topo.name == name) { return topo.val; + } } return Topology::kUnknown; } BlendFactor NameToBlendFactor(const std::string& name) { - if (name == "zero") + if (name == "zero") { return BlendFactor::kZero; - else if (name == "one") + } else if (name == "one") { return BlendFactor::kOne; - else if (name == "src_color") + } else if (name == "src_color") { return BlendFactor::kSrcColor; - else if (name == "one_minus_src_color") + } else if (name == "one_minus_src_color") { return BlendFactor::kOneMinusSrcColor; - else if (name == "dst_color") + } else if (name == "dst_color") { return BlendFactor::kDstColor; - else if (name == "one_minus_dst_color") + } else if (name == "one_minus_dst_color") { return BlendFactor::kOneMinusDstColor; - else if (name == "src_alpha") + } else if (name == "src_alpha") { return BlendFactor::kSrcAlpha; - else if (name == "one_minus_src_alpha") + } else if (name == "one_minus_src_alpha") { return BlendFactor::kOneMinusSrcAlpha; - else if (name == "dst_alpha") + } else if (name == "dst_alpha") { return BlendFactor::kDstAlpha; - else if (name == "one_minus_dst_alpha") + } else if (name == "one_minus_dst_alpha") { return BlendFactor::kOneMinusDstAlpha; - else if (name == "constant_color") + } else if (name == "constant_color") { return BlendFactor::kConstantColor; - else if (name == "one_minus_constant_color") + } else if (name == "one_minus_constant_color") { return BlendFactor::kOneMinusConstantColor; - else if (name == "costant_alpha") + } else if (name == "costant_alpha") { return BlendFactor::kConstantAlpha; - else if (name == "one_minus_constant_alpha") + } else if (name == "one_minus_constant_alpha") { return BlendFactor::kOneMinusConstantAlpha; - else if (name == "src_alpha_saturate") + } else if (name == "src_alpha_saturate") { return BlendFactor::kSrcAlphaSaturate; - else if (name == "src1_color") + } else if (name == "src1_color") { return BlendFactor::kSrc1Color; - else if (name == "one_minus_src1_color") + } else if (name == "one_minus_src1_color") { return BlendFactor::kOneMinusSrc1Color; - else if (name == "src1_alpha") + } else if (name == "src1_alpha") { return BlendFactor::kSrc1Alpha; - else if (name == "one_minus_src1_alpha") + } else if (name == "one_minus_src1_alpha") { return BlendFactor::kOneMinusSrc1Alpha; - else + } else { return BlendFactor::kUnknown; + } } BlendOp NameToBlendOp(const std::string& name) { - if (name == "add") + if (name == "add") { return BlendOp::kAdd; - else if (name == "substract") + } else if (name == "substract") { return BlendOp::kSubtract; - else if (name == "reverse_substract") + } else if (name == "reverse_substract") { return BlendOp::kReverseSubtract; - else if (name == "min") + } else if (name == "min") { return BlendOp::kMin; - else if (name == "max") + } else if (name == "max") { return BlendOp::kMax; - else if (name == "zero") + } else if (name == "zero") { return BlendOp::kZero; - else if (name == "src") + } else if (name == "src") { return BlendOp::kSrc; - else if (name == "dst") + } else if (name == "dst") { return BlendOp::kDst; - else if (name == "src_over") + } else if (name == "src_over") { return BlendOp::kSrcOver; - else if (name == "dst_over") + } else if (name == "dst_over") { return BlendOp::kDstOver; - else if (name == "src_in") + } else if (name == "src_in") { return BlendOp::kSrcIn; - else if (name == "dst_in") + } else if (name == "dst_in") { return BlendOp::kDstIn; - else if (name == "src_out") + } else if (name == "src_out") { return BlendOp::kSrcOut; - else if (name == "dst_out") + } else if (name == "dst_out") { return BlendOp::kDstOut; - else if (name == "src_atop") + } else if (name == "src_atop") { return BlendOp::kSrcAtop; - else if (name == "dst_atop") + } else if (name == "dst_atop") { return BlendOp::kDstAtop; - else if (name == "xor") + } else if (name == "xor") { return BlendOp::kXor; - else if (name == "multiply") + } else if (name == "multiply") { return BlendOp::kMultiply; - else if (name == "screen") + } else if (name == "screen") { return BlendOp::kScreen; - else if (name == "overlay") + } else if (name == "overlay") { return BlendOp::kOverlay; - else if (name == "darken") + } else if (name == "darken") { return BlendOp::kDarken; - else if (name == "lighten") + } else if (name == "lighten") { return BlendOp::kLighten; - else if (name == "color_dodge") + } else if (name == "color_dodge") { return BlendOp::kColorDodge; - else if (name == "color_burn") + } else if (name == "color_burn") { return BlendOp::kColorBurn; - else if (name == "hard_light") + } else if (name == "hard_light") { return BlendOp::kHardLight; - else if (name == "soft_light") + } else if (name == "soft_light") { return BlendOp::kSoftLight; - else if (name == "difference") + } else if (name == "difference") { return BlendOp::kDifference; - else if (name == "exclusion") + } else if (name == "exclusion") { return BlendOp::kExclusion; - else if (name == "invert") + } else if (name == "invert") { return BlendOp::kInvert; - else if (name == "invert_rgb") + } else if (name == "invert_rgb") { return BlendOp::kInvertRGB; - else if (name == "linear_dodge") + } else if (name == "linear_dodge") { return BlendOp::kLinearDodge; - else if (name == "linear_burn") + } else if (name == "linear_burn") { return BlendOp::kLinearBurn; - else if (name == "vivid_light") + } else if (name == "vivid_light") { return BlendOp::kVividLight; - else if (name == "linear_light") + } else if (name == "linear_light") { return BlendOp::kLinearLight; - else if (name == "pin_light") + } else if (name == "pin_light") { return BlendOp::kPinLight; - else if (name == "hard_mix") + } else if (name == "hard_mix") { return BlendOp::kHardMix; - else if (name == "hsl_hue") + } else if (name == "hsl_hue") { return BlendOp::kHslHue; - else if (name == "hsl_saturation") + } else if (name == "hsl_saturation") { return BlendOp::kHslSaturation; - else if (name == "hsl_color") + } else if (name == "hsl_color") { return BlendOp::kHslColor; - else if (name == "hsl_luminosity") + } else if (name == "hsl_luminosity") { return BlendOp::kHslLuminosity; - else if (name == "plus") + } else if (name == "plus") { return BlendOp::kPlus; - else if (name == "plus_clamped") + } else if (name == "plus_clamped") { return BlendOp::kPlusClamped; - else if (name == "plus_clamped_alpha") + } else if (name == "plus_clamped_alpha") { return BlendOp::kPlusClampedAlpha; - else if (name == "plus_darker") + } else if (name == "plus_darker") { return BlendOp::kPlusDarker; - else if (name == "minus") + } else if (name == "minus") { return BlendOp::kMinus; - else if (name == "minus_clamped") + } else if (name == "minus_clamped") { return BlendOp::kMinusClamped; - else if (name == "contrast") + } else if (name == "contrast") { return BlendOp::kContrast; - else if (name == "invert_ovg") + } else if (name == "invert_ovg") { return BlendOp::kInvertOvg; - else if (name == "red") + } else if (name == "red") { return BlendOp::kRed; - else if (name == "green") + } else if (name == "green") { return BlendOp::kGreen; - else if (name == "blue") + } else if (name == "blue") { return BlendOp::kBlue; - else + } else { return BlendOp::kUnknown; + } } } // namespace amber diff --git a/src/dawn/engine_dawn.cc b/src/dawn/engine_dawn.cc index 1666e4a42..a159ece4e 100644 --- a/src/dawn/engine_dawn.cc +++ b/src/dawn/engine_dawn.cc @@ -164,8 +164,9 @@ Result MakeTexture(const ::dawn::Device& device, ::dawn::TextureUsage::CopySrc | ::dawn::TextureUsage::OutputAttachment; // TODO(dneto): Get a better message by using the Dawn error callback. *result_ptr = device.CreateTexture(&descriptor); - if (*result_ptr) + if (*result_ptr) { return {}; + } return Result("Dawn: Failed to allocate a framebuffer texture"); } @@ -335,8 +336,9 @@ Result EngineDawn::MapDeviceTextureToHostBuffer( queue.Submit(1, &commands); MapResult mapped_device_texture = MapBuffer(device, copy_buffer); - if (!mapped_device_texture.result.IsSuccess()) + if (!mapped_device_texture.result.IsSuccess()) { return mapped_device_texture.result; + } auto& host_texture = render_pipeline.pipeline->GetColorAttachments()[i]; auto* values = host_texture.buffer->ValuePtr(); @@ -396,8 +398,9 @@ Result EngineDawn::MapDeviceBufferToHostBuffer( copy_size); copy_device_buffer.Unmap(); - if (!mapped_device_buffer.result.IsSuccess()) + if (!mapped_device_buffer.result.IsSuccess()) { return mapped_device_buffer.result; + } } return {}; } @@ -413,8 +416,9 @@ ::dawn::Buffer CreateBufferFromData(const ::dawn::Device& device, descriptor.usage = usage | ::dawn::BufferUsage::CopyDst; ::dawn::Buffer buffer = device.CreateBuffer(&descriptor); - if (data != nullptr) + if (data != nullptr) { buffer.SetSubData(0, size, reinterpret_cast(data)); + } return buffer; } @@ -509,8 +513,9 @@ ::dawn::PipelineLayout MakeBasicPipelineLayout( // result. Result GetDawnTextureFormat(const ::amber::Format& amber_format, ::dawn::TextureFormat* dawn_format_ptr) { - if (!dawn_format_ptr) + if (!dawn_format_ptr) { return Result("Internal error: format pointer argument is null"); + } ::dawn::TextureFormat& dawn_format = *dawn_format_ptr; switch (amber_format.GetFormatType()) { @@ -732,20 +737,21 @@ ::dawn::BlendOperation GetDawnBlendOperation(BlendOp op) { } ::dawn::ColorWriteMask GetDawnColorWriteMask(uint8_t amber_color_write_mask) { - if (amber_color_write_mask == 0x00000000) + if (amber_color_write_mask == 0x00000000) { return ::dawn::ColorWriteMask::None; - else if (amber_color_write_mask == 0x00000001) + } else if (amber_color_write_mask == 0x00000001) { return ::dawn::ColorWriteMask::Red; - else if (amber_color_write_mask == 0x00000002) + } else if (amber_color_write_mask == 0x00000002) { return ::dawn::ColorWriteMask::Green; - else if (amber_color_write_mask == 0x00000004) + } else if (amber_color_write_mask == 0x00000004) { return ::dawn::ColorWriteMask::Blue; - else if (amber_color_write_mask == 0x00000008) + } else if (amber_color_write_mask == 0x00000008) { return ::dawn::ColorWriteMask::Alpha; - else if (amber_color_write_mask == 0x0000000F) + } else if (amber_color_write_mask == 0x0000000F) { return ::dawn::ColorWriteMask::All; - else + } else { assert(false && "Dawn::Unknown ColorWriteMask"); + } return ::dawn::ColorWriteMask::All; } @@ -777,14 +783,17 @@ Result EngineDawn::Initialize(EngineConfig* config, const std::vector&, const std::vector&, const std::vector&) { - if (device_) + if (device_) { return Result("Dawn:Initialize device_ already exists"); + } - if (!config) + if (!config) { return Result("Dawn::Initialize config is null"); + } DawnEngineConfig* dawn_config = static_cast(config); - if (dawn_config->device == nullptr) + if (dawn_config->device == nullptr) { return Result("Dawn:Initialize device is a null pointer"); + } device_ = dawn_config->device; @@ -819,15 +828,17 @@ Result EngineDawn::CreatePipeline(::amber::Pipeline* pipeline) { switch (pipeline->GetType()) { case PipelineType::kCompute: { auto& module = module_for_type[kShaderTypeCompute]; - if (!module) + if (!module) { return Result("Dawn::CreatePipeline: no compute shader provided"); + } pipeline_map_[pipeline].compute_pipeline.reset( new ComputePipelineInfo(pipeline, module)); Result result = AttachBuffers(pipeline_map_[pipeline].compute_pipeline.get()); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } break; } @@ -850,8 +861,9 @@ Result EngineDawn::CreatePipeline(::amber::Pipeline* pipeline) { new RenderPipelineInfo(pipeline, vs, fs)); Result result = AttachBuffersAndTextures( pipeline_map_[pipeline].render_pipeline.get()); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } break; } @@ -862,8 +874,9 @@ Result EngineDawn::CreatePipeline(::amber::Pipeline* pipeline) { Result EngineDawn::DoClearColor(const ClearColorCommand* command) { RenderPipelineInfo* render_pipeline = GetRenderPipeline(command); - if (!render_pipeline) + if (!render_pipeline) { return Result("ClearColor invoked on invalid or missing render pipeline"); + } render_pipeline->clear_color_value = ::dawn::Color{ command->GetR(), command->GetG(), command->GetB(), command->GetA()}; @@ -873,8 +886,9 @@ Result EngineDawn::DoClearColor(const ClearColorCommand* command) { Result EngineDawn::DoClearStencil(const ClearStencilCommand* command) { RenderPipelineInfo* render_pipeline = GetRenderPipeline(command); - if (!render_pipeline) + if (!render_pipeline) { return Result("ClearStencil invoked on invalid or missing render pipeline"); + } render_pipeline->clear_stencil_value = command->GetValue(); return {}; @@ -882,8 +896,9 @@ Result EngineDawn::DoClearStencil(const ClearStencilCommand* command) { Result EngineDawn::DoClearDepth(const ClearDepthCommand* command) { RenderPipelineInfo* render_pipeline = GetRenderPipeline(command); - if (!render_pipeline) + if (!render_pipeline) { return Result("ClearDepth invoked on invalid or missing render pipeline"); + } render_pipeline->clear_depth_value = command->GetValue(); return {}; @@ -892,18 +907,21 @@ Result EngineDawn::DoClearDepth(const ClearDepthCommand* command) { Result EngineDawn::DoClear(const ClearCommand* command) { Result result; RenderPipelineInfo* render_pipeline = GetRenderPipeline(command); - if (!render_pipeline) + if (!render_pipeline) { return Result("Clear invoked on invalid or missing render pipeline"); + } DawnPipelineHelper helper; result = helper.CreateRenderPipelineDescriptor(*render_pipeline, *device_, false, nullptr); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } result = helper.CreateRenderPassDescriptor( *render_pipeline, *device_, texture_views_, ::dawn::LoadOp::Clear); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } ::dawn::RenderPassDescriptor* renderPassDescriptor = &helper.renderPassDescriptor; @@ -935,23 +953,27 @@ Result DawnPipelineHelper::CreateRenderPipelineDescriptor( auto* amber_format = render_pipeline.pipeline->GetColorAttachments()[0].buffer->GetFormat(); - if (!amber_format) + if (!amber_format) { return Result("Color attachment 0 has no format!"); + } ::dawn::TextureFormat fb_format{}; result = GetDawnTextureFormat(*amber_format, &fb_format); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } ::dawn::TextureFormat depth_stencil_format{}; auto* depthBuffer = render_pipeline.pipeline->GetDepthBuffer().buffer; if (depthBuffer) { auto* amber_depth_stencil_format = depthBuffer->GetFormat(); - if (!amber_depth_stencil_format) + if (!amber_depth_stencil_format) { return Result("The depth/stencil attachment has no format!"); + } result = GetDawnTextureFormat(*amber_depth_stencil_format, &depth_stencil_format); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } } else { depth_stencil_format = ::dawn::TextureFormat::Depth24PlusStencil8; } @@ -1009,8 +1031,9 @@ Result DawnPipelineHelper::CreateRenderPipelineDescriptor( render_pipeline.pipeline->GetVertexBuffers()[i].buffer->GetFormat(); result = GetDawnVertexFormat( *amber_vertex_format, &vertexInputDescriptor.cAttributes[i].format); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } } } } @@ -1020,8 +1043,9 @@ Result DawnPipelineHelper::CreateRenderPipelineDescriptor( auto* amber_index_format = render_pipeline.pipeline->GetIndexBuffer()->GetFormat(); GetDawnIndexFormat(*amber_index_format, &vertexInputDescriptor.indexFormat); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } } renderPipelineDescriptor.vertexInput = @@ -1099,13 +1123,15 @@ Result DawnPipelineHelper::CreateRenderPipelineDescriptor( if (i < render_pipeline.pipeline->GetColorAttachments().size()) { auto* amber_format = render_pipeline.pipeline->GetColorAttachments()[i] .buffer->GetFormat(); - if (!amber_format) + if (!amber_format) { return Result( "AttachBuffersAndTextures: One Color attachment has no " "format!"); + } result = GetDawnTextureFormat(*amber_format, &fb_format); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } } else { fb_format = ::dawn::TextureFormat::RGBA8Unorm; } @@ -1202,12 +1228,14 @@ Result DawnPipelineHelper::CreateRenderPassDescriptor( auto* depthBuffer = render_pipeline.pipeline->GetDepthBuffer().buffer; if (depthBuffer) { auto* amber_depth_stencil_format = depthBuffer->GetFormat(); - if (!amber_depth_stencil_format) + if (!amber_depth_stencil_format) { return Result("The depth/stencil attachment has no format!"); + } Result result = GetDawnTextureFormat(*amber_depth_stencil_format, &depth_stencil_format); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } } else { depth_stencil_format = ::dawn::TextureFormat::Depth24PlusStencil8; } @@ -1239,12 +1267,14 @@ Result DawnPipelineHelper::CreateRenderPassDescriptor( Result EngineDawn::DoDrawRect(const DrawRectCommand* command) { RenderPipelineInfo* render_pipeline = GetRenderPipeline(command); - if (!render_pipeline) + if (!render_pipeline) { return Result("DrawRect invoked on invalid or missing render pipeline"); - if (render_pipeline->vertex_buffers.size() > 1) + } + if (render_pipeline->vertex_buffers.size() > 1) { return Result( "DrawRect invoked on a render pipeline with more than one " "VERTEX_DATA attached"); + } float x = command->GetX(); float y = command->GetY(); @@ -1336,12 +1366,14 @@ Result EngineDawn::DoDrawArrays(const DrawArraysCommand* command) { Result result; RenderPipelineInfo* render_pipeline = GetRenderPipeline(command); - if (!render_pipeline) + if (!render_pipeline) { return Result("DrawArrays invoked on invalid or missing render pipeline"); + } if (command->IsIndexed()) { - if (!render_pipeline->index_buffer) + if (!render_pipeline->index_buffer) { return Result("DrawArrays: Draw indexed is used without given indices"); + } } else { std::vector indexData; for (uint32_t i = 0; @@ -1354,18 +1386,21 @@ Result EngineDawn::DoDrawArrays(const DrawArraysCommand* command) { } uint32_t instance_count = command->GetInstanceCount(); - if (instance_count == 0 && command->GetVertexCount() != 0) + if (instance_count == 0 && command->GetVertexCount() != 0) { instance_count = 1; + } DawnPipelineHelper helper; result = helper.CreateRenderPipelineDescriptor( *render_pipeline, *device_, false, command->GetPipelineData()); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } result = helper.CreateRenderPassDescriptor( *render_pipeline, *device_, texture_views_, ::dawn::LoadOp::Load); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } ::dawn::RenderPipelineDescriptor* renderPipelineDescriptor = &helper.renderPipelineDescriptor; @@ -1374,8 +1409,9 @@ Result EngineDawn::DoDrawArrays(const DrawArraysCommand* command) { result = GetDawnTopology(command->GetTopology(), &renderPipelineDescriptor->primitiveTopology); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } const ::dawn::RenderPipeline pipeline = device_->CreateRenderPipeline(renderPipelineDescriptor); @@ -1417,8 +1453,9 @@ Result EngineDawn::DoCompute(const ComputeCommand* command) { Result result; ComputePipelineInfo* compute_pipeline = GetComputePipeline(command); - if (!compute_pipeline) + if (!compute_pipeline) { return Result("DoComput: invoked on invalid or missing compute pipeline"); + } ::dawn::ComputePipelineDescriptor computePipelineDescriptor; computePipelineDescriptor.layout = MakeBasicPipelineLayout( @@ -1486,10 +1523,12 @@ Result EngineDawn::DoBuffer(const BufferCommand* command) { } } - if (!render_pipeline && !compute_pipeline) + if (!render_pipeline && !compute_pipeline) { return Result("DoBuffer: invoked on invalid or missing pipeline"); - if (!command->IsSSBO() && !command->IsUniform()) + } + if (!command->IsSSBO() && !command->IsUniform()) { return Result("DoBuffer: only supports SSBO and uniform buffer type"); + } if (!dawn_buffer) { return Result("DoBuffer: no Dawn buffer at descriptor set " + std::to_string(descriptor_set) + " and binding " + @@ -1518,8 +1557,9 @@ Result EngineDawn::AttachBuffersAndTextures( render_pipeline->pipeline->GetColorAttachments().size(), -1); for (auto info : render_pipeline->pipeline->GetColorAttachments()) { if (info.location >= - render_pipeline->pipeline->GetColorAttachments().size()) + render_pipeline->pipeline->GetColorAttachments().size()) { return Result("color attachment locations must be sequential from 0"); + } if (seen_idx[info.location] != -1) { return Result("duplicate attachment location: " + std::to_string(info.location)); @@ -1534,13 +1574,15 @@ Result EngineDawn::AttachBuffersAndTextures( if (i < render_pipeline->pipeline->GetColorAttachments().size()) { auto* amber_format = render_pipeline->pipeline->GetColorAttachments()[i] .buffer->GetFormat(); - if (!amber_format) + if (!amber_format) { return Result( "AttachBuffersAndTextures: One Color attachment has no " "format!"); + } result = GetDawnTextureFormat(*amber_format, &fb_format); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } } else { fb_format = ::dawn::TextureFormat::RGBA8Unorm; } @@ -1556,20 +1598,23 @@ Result EngineDawn::AttachBuffersAndTextures( if (depthBuffer) { if (!depth_stencil_texture_) { auto* amber_depth_stencil_format = depthBuffer->GetFormat(); - if (!amber_depth_stencil_format) + if (!amber_depth_stencil_format) { return Result( "AttachBuffersAndTextures: The depth/stencil attachment has no " "format!"); + } ::dawn::TextureFormat depth_stencil_format{}; result = GetDawnTextureFormat(*amber_depth_stencil_format, &depth_stencil_format); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } result = MakeTexture(*device_, depth_stencil_format, width, height, &depth_stencil_texture_); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } render_pipeline->depth_stencil_texture = depth_stencil_texture_; } else { render_pipeline->depth_stencil_texture = depth_stencil_texture_; @@ -1612,8 +1657,9 @@ Result EngineDawn::AttachBuffersAndTextures( if (!render_pipeline->pipeline->GetBuffers().empty()) { std::vector max_binding_seen(kMaxDawnBindGroup, -1); for (auto& buf_info : render_pipeline->pipeline->GetBuffers()) { - while (layouts_info[buf_info.descriptor_set].size() <= buf_info.binding) + while (layouts_info[buf_info.descriptor_set].size() <= buf_info.binding) { layouts_info[buf_info.descriptor_set].push_back(empty_layout_info); + } } } @@ -1711,8 +1757,9 @@ Result EngineDawn::AttachBuffers(ComputePipelineInfo* compute_pipeline) { if (!compute_pipeline->pipeline->GetBuffers().empty()) { std::vector max_binding_seen(kMaxDawnBindGroup, -1); for (auto& buf_info : compute_pipeline->pipeline->GetBuffers()) { - while (layouts_info[buf_info.descriptor_set].size() <= buf_info.binding) + while (layouts_info[buf_info.descriptor_set].size() <= buf_info.binding) { layouts_info[buf_info.descriptor_set].push_back(empty_layout_info); + } } } diff --git a/src/descriptor_set_and_binding_parser.cc b/src/descriptor_set_and_binding_parser.cc index d35193542..7e72c50d7 100644 --- a/src/descriptor_set_and_binding_parser.cc +++ b/src/descriptor_set_and_binding_parser.cc @@ -33,16 +33,18 @@ Result DescriptorSetAndBindingParser::Parse(const std::string& buffer_id) { if (!std::isdigit(buffer_id[idx]) && std::isalpha(buffer_id[idx]) && buffer_id[idx] != ':' && buffer_id[idx] != '-') { idx++; - while (idx < buffer_id.size() && buffer_id[idx] != ':') + while (idx < buffer_id.size() && buffer_id[idx] != ':') { idx++; + } pipeline_name_ = buffer_id.substr(0, idx); // Move past the : idx += 1; } - if (idx >= buffer_id.size()) + if (idx >= buffer_id.size()) { return Result("Invalid buffer id: " + buffer_id); + } Tokenizer t(buffer_id.substr(idx)); auto token = t.NextToken(); @@ -65,12 +67,14 @@ Result DescriptorSetAndBindingParser::Parse(const std::string& buffer_id) { descriptor_set_ = val; } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Invalid buffer id: " + buffer_id); + } auto& str = token->AsString(); - if (str.size() < 2 || str[0] != ':') + if (str.size() < 2 || str[0] != ':') { return Result("Invalid buffer id: " + buffer_id); + } auto substr = str.substr(1, str.size()); // Validate all characters are integers. @@ -84,9 +88,10 @@ Result DescriptorSetAndBindingParser::Parse(const std::string& buffer_id) { } uint64_t binding_val = strtoul(substr.c_str(), nullptr, 10); - if (binding_val > std::numeric_limits::max()) + if (binding_val > std::numeric_limits::max()) { return Result("binding value too large in probe ssbo command: " + token->ToOriginalString()); + } if (static_cast(binding_val) < 0) { return Result( "Binding for a buffer must be non-negative integer, but you gave: " + diff --git a/src/dxc_helper.cc b/src/dxc_helper.cc index 2ef678965..81344d6b4 100644 --- a/src/dxc_helper.cc +++ b/src/dxc_helper.cc @@ -198,8 +198,9 @@ Result Compile(const std::string& src, "Invalid target environment. Choose spv1.3 or vulkan1.1 for vulkan1.1 " "and spv1.0 or vulkan1.0 for vulkan1.0."); } - if (target_env) + if (target_env) { dxc_flags.push_back(target_env); + } IDxcOperationResult* result; if (compiler->Compile( diff --git a/src/dxc_helper.h b/src/dxc_helper.h index 43cb13009..3739071ca 100644 --- a/src/dxc_helper.h +++ b/src/dxc_helper.h @@ -15,9 +15,9 @@ #ifndef SRC_DXC_HELPER_H_ #define SRC_DXC_HELPER_H_ +#include #include #include -#include #include "amber/result.h" diff --git a/src/executor.cc b/src/executor.cc index 40cb35315..8162b536b 100644 --- a/src/executor.cc +++ b/src/executor.cc @@ -37,8 +37,9 @@ Result Executor::CompileShaders(const amber::Script* script, for (auto& pipeline : script->GetPipelines()) { for (auto& shader_info : pipeline->GetShaders()) { std::string target_env = shader_info.GetShader()->GetTargetEnv(); - if (target_env.empty()) + if (target_env.empty()) { target_env = script->GetSpvTargetEnv(); + } ShaderCompiler sc(target_env, options->disable_spirv_validation, script->GetVirtualFiles()); @@ -46,8 +47,9 @@ Result Executor::CompileShaders(const amber::Script* script, Result r; std::vector data; std::tie(r, data) = sc.Compile(pipeline.get(), &shader_info, shader_map); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } shader_info.SetData(std::move(data)); } @@ -64,34 +66,41 @@ Result Executor::Execute(Engine* engine, if (!script->GetPipelines().empty()) { Result r = CompileShaders(script, shader_map, options); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } // OpenCL specific pipeline updates. for (auto& pipeline : script->GetPipelines()) { r = pipeline->UpdateOpenCLBufferBindings(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = pipeline->GenerateOpenCLPodBuffers(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = pipeline->GenerateOpenCLLiteralSamplers(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = pipeline->GenerateOpenCLPushConstants(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } for (auto& pipeline : script->GetPipelines()) { r = engine->CreatePipeline(pipeline.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } } - if (options->execution_type == ExecutionType::kPipelineCreateOnly) + if (options->execution_type == ExecutionType::kPipelineCreateOnly) { return {}; + } // Process Commands for (const auto& cmd : script->GetCommands()) { @@ -100,8 +109,9 @@ Result Executor::Execute(Engine* engine, } Result r = ExecuteCommand(engine, cmd.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } return {}; } @@ -125,14 +135,18 @@ Result Executor::ExecuteCommand(Engine* engine, Command* cmd) { return verifier_.ProbeSSBO(probe_ssbo, buffer->ElementCount(), buffer->ValuePtr()->data()); } - if (cmd->IsClear()) + if (cmd->IsClear()) { return engine->DoClear(cmd->AsClear()); - if (cmd->IsClearColor()) + } + if (cmd->IsClearColor()) { return engine->DoClearColor(cmd->AsClearColor()); - if (cmd->IsClearDepth()) + } + if (cmd->IsClearDepth()) { return engine->DoClearDepth(cmd->AsClearDepth()); - if (cmd->IsClearStencil()) + } + if (cmd->IsClearStencil()) { return engine->DoClearStencil(cmd->AsClearStencil()); + } if (cmd->IsCompareBuffer()) { auto compare = cmd->AsCompareBuffer(); auto buffer_1 = compare->GetBuffer1(); @@ -152,28 +166,37 @@ Result Executor::ExecuteCommand(Engine* engine, Command* cmd) { auto buffer_to = copy->GetBufferTo(); return buffer_from->CopyTo(buffer_to); } - if (cmd->IsDrawRect()) + if (cmd->IsDrawRect()) { return engine->DoDrawRect(cmd->AsDrawRect()); - if (cmd->IsDrawGrid()) + } + if (cmd->IsDrawGrid()) { return engine->DoDrawGrid(cmd->AsDrawGrid()); - if (cmd->IsDrawArrays()) + } + if (cmd->IsDrawArrays()) { return engine->DoDrawArrays(cmd->AsDrawArrays()); - if (cmd->IsCompute()) + } + if (cmd->IsCompute()) { return engine->DoCompute(cmd->AsCompute()); - if (cmd->IsRayTracing()) + } + if (cmd->IsRayTracing()) { return engine->DoTraceRays(cmd->AsRayTracing()); - if (cmd->IsEntryPoint()) + } + if (cmd->IsEntryPoint()) { return engine->DoEntryPoint(cmd->AsEntryPoint()); - if (cmd->IsPatchParameterVertices()) + } + if (cmd->IsPatchParameterVertices()) { return engine->DoPatchParameterVertices(cmd->AsPatchParameterVertices()); - if (cmd->IsBuffer()) + } + if (cmd->IsBuffer()) { return engine->DoBuffer(cmd->AsBuffer()); + } if (cmd->IsRepeat()) { for (uint32_t i = 0; i < cmd->AsRepeat()->GetCount(); ++i) { for (const auto& sub_cmd : cmd->AsRepeat()->GetCommands()) { Result r = ExecuteCommand(engine, sub_cmd.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } } return {}; diff --git a/src/executor_test.cc b/src/executor_test.cc index 2f9429e3b..36de27f80 100644 --- a/src/executor_test.cc +++ b/src/executor_test.cc @@ -61,8 +61,9 @@ class EngineStub : public Engine { Result DoClearColor(const ClearColorCommand* cmd) override { did_clear_color_command_ = true; - if (fail_clear_color_command_) + if (fail_clear_color_command_) { return Result("clear color command failed"); + } last_clear_color_ = const_cast(cmd); return {}; @@ -73,8 +74,9 @@ class EngineStub : public Engine { Result DoClearStencil(const ClearStencilCommand*) override { did_clear_stencil_command_ = true; - if (fail_clear_stencil_command_) + if (fail_clear_stencil_command_) { return Result("clear stencil command failed"); + } return {}; } @@ -84,8 +86,9 @@ class EngineStub : public Engine { Result DoClearDepth(const ClearDepthCommand*) override { did_clear_depth_command_ = true; - if (fail_clear_depth_command_) + if (fail_clear_depth_command_) { return Result("clear depth command failed"); + } return {}; } @@ -95,8 +98,9 @@ class EngineStub : public Engine { Result DoClear(const ClearCommand*) override { did_clear_command_ = true; - if (fail_clear_command_) + if (fail_clear_command_) { return Result("clear command failed"); + } return {}; } @@ -105,16 +109,18 @@ class EngineStub : public Engine { Result DoDrawRect(const DrawRectCommand*) override { did_draw_rect_command_ = true; - if (fail_draw_rect_command_) + if (fail_draw_rect_command_) { return Result("draw rect command failed"); + } return {}; } Result DoDrawGrid(const DrawGridCommand*) override { did_draw_grid_command_ = true; - if (fail_draw_grid_command_) + if (fail_draw_grid_command_) { return Result("draw grid command failed"); + } return {}; } @@ -123,8 +129,9 @@ class EngineStub : public Engine { Result DoDrawArrays(const DrawArraysCommand*) override { did_draw_arrays_command_ = true; - if (fail_draw_arrays_command_) + if (fail_draw_arrays_command_) { return Result("draw arrays command failed"); + } return {}; } @@ -133,8 +140,9 @@ class EngineStub : public Engine { Result DoCompute(const ComputeCommand*) override { did_compute_command_ = true; - if (fail_compute_command_) + if (fail_compute_command_) { return Result("compute command failed"); + } return {}; } @@ -143,8 +151,9 @@ class EngineStub : public Engine { Result DoEntryPoint(const EntryPointCommand*) override { did_entry_point_command_ = true; - if (fail_entry_point_command_) + if (fail_entry_point_command_) { return Result("entrypoint command failed"); + } return {}; } @@ -154,8 +163,9 @@ class EngineStub : public Engine { const PatchParameterVerticesCommand*) override { did_patch_command_ = true; - if (fail_patch_command_) + if (fail_patch_command_) { return Result("patch command failed"); + } return {}; } @@ -164,8 +174,9 @@ class EngineStub : public Engine { Result DoBuffer(const BufferCommand*) override { did_buffer_command_ = true; - if (fail_buffer_command_) + if (fail_buffer_command_) { return Result("buffer command failed"); + } return {}; } diff --git a/src/float16_helper.cc b/src/float16_helper.cc index 5cb35e755..ebac76905 100644 --- a/src/float16_helper.cc +++ b/src/float16_helper.cc @@ -46,8 +46,9 @@ uint16_t FloatSign(const uint32_t hex_float) { uint16_t FloatExponent(const uint32_t hex_float) { uint32_t exponent_bits = ((hex_float >> 23U) & ((1U << 8U) - 1U)); // Handle zero and denormals. - if (exponent_bits == 0U) + if (exponent_bits == 0U) { return 0; + } uint32_t exponent = exponent_bits - 112U; const uint32_t half_exponent_mask = (1U << 5U) - 1U; assert(((exponent & ~half_exponent_mask) == 0U) && "Float exponent overflow"); diff --git a/src/format.cc b/src/format.cc index 9aeb190b0..aeb2512ad 100644 --- a/src/format.cc +++ b/src/format.cc @@ -49,8 +49,9 @@ std::string FormatModeToName(FormatMode mode) { } uint32_t CalculatePad(uint32_t val) { - if ((val % 16) == 0) + if ((val % 16) == 0) { return 0; + } return 16 - (val % 16); } @@ -58,10 +59,11 @@ uint32_t CalculatePad(uint32_t val) { Format::Format(type::Type* type) : type_(type) { auto name = GenerateName(); - if (name == "") + if (name == "") { format_type_ = FormatType::kUnknown; - else + } else { format_type_ = TypeParser::NameToFormatType(name); + } RebuildSegments(); } @@ -88,8 +90,9 @@ bool Format::Equal(const Format* b) const { uint32_t Format::InputNeededPerElement() const { uint32_t count = 0; for (const auto& seg : segments_) { - if (seg.IsPadding()) + if (seg.IsPadding()) { continue; + } count += 1; } @@ -97,8 +100,9 @@ uint32_t Format::InputNeededPerElement() const { } void Format::SetLayout(Layout layout) { - if (layout == layout_) + if (layout == layout_) { return; + } layout_ = layout; RebuildSegments(); @@ -132,8 +136,9 @@ bool Format::AddSegment(const Segment& seg) { last.SizeInBytes() >= seg.SizeInBytes()) { segments_.back() = seg; auto pad = last.SizeInBytes() - seg.SizeInBytes(); - if (pad > 0) + if (pad > 0) { AddPaddedSegmentPackable(pad); + } return false; } @@ -143,17 +148,20 @@ bool Format::AddSegment(const Segment& seg) { } bool Format::NeedsPadding(type::Type* t) const { - if (layout_ == Layout::kStd140 && (t->IsMatrix() || t->IsArray())) + if (layout_ == Layout::kStd140 && (t->IsMatrix() || t->IsArray())) { return true; - if (t->IsVec3() || (t->IsMatrix() && t->RowCount() == 3)) + } + if (t->IsVec3() || (t->IsMatrix() && t->RowCount() == 3)) { return true; + } return false; } uint32_t Format::CalcVecBaseAlignmentInBytes(type::Number* n) const { // vec3 rounds up to a Vec4, so 4 * N - if (n->IsVec3()) + if (n->IsVec3()) { return 4 * n->SizeInBytes(); + } // vec2 and vec4 are 2 * N and 4 * N respectively return n->RowCount() * n->SizeInBytes(); @@ -174,8 +182,9 @@ uint32_t Format::CalcArrayBaseAlignmentInBytes(type::Type* t) const { } // In std140 array elements round up to multiple of vec4. - if (layout_ == Layout::kStd140) + if (layout_ == Layout::kStd140) { align += CalculatePad(align); + } return align; } @@ -195,14 +204,16 @@ uint32_t Format::CalcMatrixBaseAlignmentInBytes(type::Number* m) const { // the matrix is column major. uint32_t align = 0; - if (m->RowCount() == 3) + if (m->RowCount() == 3) { align = 4 * m->SizeInBytes(); - else + } else { align = m->RowCount() * m->SizeInBytes(); + } // STD140 rounds up to 16 byte alignment - if (layout_ == Layout::kStd140) + if (layout_ == Layout::kStd140) { align += CalculatePad(align); + } return align; } @@ -212,21 +223,27 @@ uint32_t Format::CalcListBaseAlignmentInBytes(type::List* l) const { } uint32_t Format::CalcTypeBaseAlignmentInBytes(type::Type* t) const { - if (t->IsArray()) + if (t->IsArray()) { return CalcArrayBaseAlignmentInBytes(t); - if (t->IsVec()) + } + if (t->IsVec()) { return CalcVecBaseAlignmentInBytes(t->AsNumber()); - if (t->IsMatrix()) + } + if (t->IsMatrix()) { return CalcMatrixBaseAlignmentInBytes(t->AsNumber()); - if (t->IsNumber()) + } + if (t->IsNumber()) { return t->SizeInBytes(); - if (t->IsList()) + } + if (t->IsList()) { return CalcListBaseAlignmentInBytes(t->AsList()); + } if (t->IsStruct()) { // Pad struct to 16 bytes in STD140 uint32_t base = CalcStructBaseAlignmentInBytes(t->AsStruct()); - if (layout_ == Layout::kStd140) + if (layout_ == Layout::kStd140) { base += CalculatePad(base); + } return base; } @@ -247,8 +264,9 @@ uint32_t Format::AddSegmentsForType(type::Type* type) { // Remove packable from previous packing for types which can't pack back. if (type->IsStruct() || type->IsVec() || type->IsMatrix() || type->IsArray()) { - if (!segments_.empty() && segments_.back().IsPadding()) + if (!segments_.empty() && segments_.back().IsPadding()) { segments_.back().SetPackable(false); + } } // TODO(dsinclair): How to handle matrix stride .... Stride comes from parent @@ -273,8 +291,9 @@ uint32_t Format::AddSegmentsForType(type::Type* type) { for (size_t i = 0; i < member.type->ArraySize(); ++i) { auto ary_seg_size = AddSegmentsForType(member.type); // Don't allow array members to pack together - if (!segments_.empty() && segments_.back().IsPadding()) + if (!segments_.empty() && segments_.back().IsPadding()) { segments_.back().SetPackable(false); + } if (member.HasArrayStride()) { uint32_t array_stride = @@ -320,8 +339,9 @@ uint32_t Format::AddSegmentsForType(type::Type* type) { auto l = type->AsList(); for (uint32_t i = 0; i < type->ColumnCount(); ++i) { for (const auto& m : l->Members()) { - if (AddSegment(Segment{m.name, m.mode, m.num_bits})) + if (AddSegment(Segment{m.name, m.mode, m.num_bits})) { size += m.SizeInBytes(); + } } if (NeedsPadding(type)) { @@ -357,15 +377,17 @@ uint32_t Format::AddSegmentsForType(type::Type* type) { } // Make sure matrix rows don't accidentally pack together. - if (type->IsMatrix() && segments_.back().IsPadding()) + if (type->IsMatrix() && segments_.back().IsPadding()) { segments_.back().SetPackable(false); + } } return size; } std::string Format::GenerateName() const { - if (type_->IsMatrix()) + if (type_->IsMatrix()) { return ""; + } static const char NAME_PARTS[] = "RGBAXDS"; if (type_->IsList()) { @@ -384,24 +406,28 @@ std::string Format::GenerateName() const { for (size_t i = 0; i < parts.size(); ++i) { name += parts[i].first; - if (i + 1 < parts.size() && parts[i].second != parts[i + 1].second) + if (i + 1 < parts.size() && parts[i].second != parts[i + 1].second) { name += "_" + parts[i].second + "_"; + } // Handle the X8_D24 underscore. - if (parts[i].first[0] == 'X') + if (parts[i].first[0] == 'X') { name += "_"; + } } name += "_" + parts.back().second; - if (type_->AsList()->IsPacked()) + if (type_->AsList()->IsPacked()) { name += "_PACK" + std::to_string(type_->AsList()->PackSizeInBits()); + } return name; } if (type_->IsNumber()) { std::string name = ""; - for (uint32_t i = 0; i < type_->RowCount(); ++i) + for (uint32_t i = 0; i < type_->RowCount(); ++i) { name += NAME_PARTS[i] + std::to_string(type_->SizeInBytes() * 8); + } name += "_" + FormatModeToName(type_->AsNumber()->GetFormatMode()); return name; diff --git a/src/format.h b/src/format.h index bfef06d53..aa509cb72 100644 --- a/src/format.h +++ b/src/format.h @@ -98,8 +98,9 @@ class Format { /// Returns a pointer to the only type in this format. Only valid if /// there is only an int or float type, nullptr otherwise. type::Type* GetOnlyType() const { - if (type_->IsNumber()) + if (type_->IsNumber()) { return type_; + } return nullptr; } @@ -131,8 +132,9 @@ class Format { /// Returns true if the format components are normalized. bool IsNormalized() const { - if (type_->IsNumber() && IsNormalized(type_->AsNumber()->GetFormatMode())) + if (type_->IsNumber() && IsNormalized(type_->AsNumber()->GetFormatMode())) { return true; + } if (type_->IsList()) { for (auto& member : type_->AsList()->Members()) { diff --git a/src/format_test.cc b/src/format_test.cc index f4542977d..56a3da004 100644 --- a/src/format_test.cc +++ b/src/format_test.cc @@ -78,8 +78,9 @@ TEST_P(FormatStdTest, Test) { type->SetColumnCount(test_data.column_count); Format fmt(type.get()); - if (test_data.is_std140) + if (test_data.is_std140) { fmt.SetLayout(Format::Format::Layout::kStd140); + } EXPECT_EQ(test_data.size_in_bytes, fmt.SizeInBytes()) << test_data.name; } diff --git a/src/pipeline.cc b/src/pipeline.cc index 4be1de248..8d3dd381d 100644 --- a/src/pipeline.cc +++ b/src/pipeline.cc @@ -62,8 +62,7 @@ Pipeline::ShaderInfo::ShaderInfo(const ShaderInfo&) = default; Pipeline::ShaderInfo::~ShaderInfo() = default; -Pipeline::Pipeline(PipelineType type) : pipeline_type_(type) { -} +Pipeline::Pipeline(PipelineType type) : pipeline_type_(type) {} Pipeline::~Pipeline() = default; @@ -89,8 +88,9 @@ std::unique_ptr Pipeline::Clone() const { } Result Pipeline::AddShader(Shader* shader, ShaderType shader_type) { - if (!shader) + if (!shader) { return Result("shader can not be null when attached to pipeline"); + } if (pipeline_type_ == PipelineType::kCompute && shader_type != kShaderTypeCompute) { @@ -104,8 +104,9 @@ Result Pipeline::AddShader(Shader* shader, ShaderType shader_type) { if (pipeline_type_ != PipelineType::kRayTracing) { for (auto& info : shaders_) { const auto* is = info.GetShader(); - if (is == shader) + if (is == shader) { return Result("can not add duplicate shader to pipeline"); + } if (is->GetType() == shader_type) { info.SetShader(shader); return {}; @@ -119,13 +120,15 @@ Result Pipeline::AddShader(Shader* shader, ShaderType shader_type) { Result Pipeline::SetShaderOptimizations(const Shader* shader, const std::vector& opts) { - if (!shader) + if (!shader) { return Result("invalid shader specified for optimizations"); + } std::set seen; for (const auto& opt : opts) { - if (seen.count(opt) != 0) + if (seen.count(opt) != 0) { return Result("duplicate optimization flag (" + opt + ") set on shader"); + } seen.insert(opt); } @@ -144,8 +147,9 @@ Result Pipeline::SetShaderOptimizations(const Shader* shader, Result Pipeline::SetShaderCompileOptions(const Shader* shader, const std::vector& opts) { - if (!shader) + if (!shader) { return Result("invalid shader specified for compile options"); + } for (auto& info : shaders_) { const auto* is = info.GetShader(); @@ -163,8 +167,9 @@ Result Pipeline::SetShaderRequiredSubgroupSize( const Shader* shader, const ShaderInfo::RequiredSubgroupSizeSetting setting, const uint32_t size) { - if (!shader) + if (!shader) { return Result("invalid shader specified for required subgroup size"); + } for (auto& info : shaders_) { const auto* is = info.GetShader(); @@ -206,8 +211,9 @@ Result Pipeline::SetShaderRequiredSubgroupSizeToMaximum(const Shader* shader) { Result Pipeline::SetShaderVaryingSubgroupSize(const Shader* shader, const bool isSet) { - if (!shader) + if (!shader) { return Result("invalid shader specified for varying subgroup size"); + } for (auto& info : shaders_) { const auto* is = info.GetShader(); @@ -223,8 +229,9 @@ Result Pipeline::SetShaderVaryingSubgroupSize(const Shader* shader, Result Pipeline::SetShaderRequireFullSubgroups(const Shader* shader, const bool isSet) { - if (!shader) + if (!shader) { return Result("invalid shader specified for optimizations"); + } for (auto& info : shaders_) { const auto* is = info.GetShader(); @@ -240,15 +247,18 @@ Result Pipeline::SetShaderRequireFullSubgroups(const Shader* shader, Result Pipeline::SetShaderEntryPoint(const Shader* shader, const std::string& name) { - if (!shader) + if (!shader) { return Result("invalid shader specified for entry point"); - if (name.empty()) + } + if (name.empty()) { return Result("entry point should not be blank"); + } for (auto& info : shaders_) { if (info.GetShader() == shader) { - if (info.GetEntryPoint() != "main") + if (info.GetEntryPoint() != "main") { return Result("multiple entry points given for the same shader"); + } info.SetEntryPoint(name); return {}; @@ -260,8 +270,9 @@ Result Pipeline::SetShaderEntryPoint(const Shader* shader, } Result Pipeline::SetShaderType(const Shader* shader, ShaderType type) { - if (!shader) + if (!shader) { return Result("invalid shader specified for shader type"); + } for (auto& info : shaders_) { if (info.GetShader() == shader) { @@ -296,24 +307,27 @@ Result Pipeline::Validate() const { } } - if (pipeline_type_ == PipelineType::kRayTracing) + if (pipeline_type_ == PipelineType::kRayTracing) { return ValidateRayTracing(); - else if (pipeline_type_ == PipelineType::kGraphics) + } else if (pipeline_type_ == PipelineType::kGraphics) { return ValidateGraphics(); + } return ValidateCompute(); } Result Pipeline::ValidateRayTracing() const { - if (shader_groups_.empty() && shaders_.empty() && tlases_.empty()) + if (shader_groups_.empty() && shaders_.empty() && tlases_.empty()) { return Result("Shader groups are missing"); + } return {}; } Result Pipeline::ValidateGraphics() const { - if (color_attachments_.empty()) + if (color_attachments_.empty()) { return Result("PIPELINE missing color attachment"); + } bool found_vertex = false; for (const auto& info : shaders_) { @@ -324,25 +338,28 @@ Result Pipeline::ValidateGraphics() const { } } - if (!found_vertex) + if (!found_vertex) { return Result("graphics pipeline requires a vertex shader"); + } for (const auto& att : color_attachments_) { auto width = att.buffer->GetWidth(); auto height = att.buffer->GetHeight(); for (uint32_t level = 1; level < att.buffer->GetMipLevels(); level++) { width >>= 1; - if (width == 0) + if (width == 0) { return Result("color attachment with " + std::to_string(att.buffer->GetMipLevels()) + " mip levels would have zero width for level " + std::to_string(level)); + } height >>= 1; - if (height == 0) + if (height == 0) { return Result("color attachment with " + std::to_string(att.buffer->GetMipLevels()) + " mip levels would have zero height for level " + std::to_string(level)); + } } } @@ -350,16 +367,18 @@ Result Pipeline::ValidateGraphics() const { } Result Pipeline::ValidateCompute() const { - if (shaders_.empty()) + if (shaders_.empty()) { return Result("compute pipeline requires a compute shader"); + } return {}; } void Pipeline::UpdateFramebufferSizes() { uint32_t size = fb_width_ * fb_height_; - if (size == 0) + if (size == 0) { return; + } for (auto& attachment : color_attachments_) { auto mip0_width = fb_width_ << attachment.base_mip_level; @@ -380,10 +399,12 @@ Result Pipeline::AddColorAttachment(Buffer* buf, uint32_t location, uint32_t base_mip_level) { for (const auto& attachment : color_attachments_) { - if (attachment.location == location) + if (attachment.location == location) { return Result("can not bind two color buffers to the same LOCATION"); - if (attachment.buffer == buf) + } + if (attachment.buffer == buf) { return Result("color buffer may only be bound to a PIPELINE once"); + } } color_attachments_.push_back(BufferInfo{buf}); @@ -425,8 +446,9 @@ Result Pipeline::GetLocationForColorAttachment(Buffer* buf, } Result Pipeline::SetDepthStencilBuffer(Buffer* buf) { - if (depth_stencil_buffer_.buffer != nullptr) + if (depth_stencil_buffer_.buffer != nullptr) { return Result("can only bind one depth/stencil buffer in a PIPELINE"); + } depth_stencil_buffer_.buffer = buf; depth_stencil_buffer_.type = BufferType::kDepthStencil; @@ -438,8 +460,9 @@ Result Pipeline::SetDepthStencilBuffer(Buffer* buf) { } Result Pipeline::SetIndexBuffer(Buffer* buf) { - if (index_buffer_ != nullptr) + if (index_buffer_ != nullptr) { return Result("can only bind one INDEX_DATA buffer in a pipeline"); + } index_buffer_ = buf; return {}; @@ -452,8 +475,9 @@ Result Pipeline::AddVertexBuffer(Buffer* buf, uint32_t offset, uint32_t stride) { for (const auto& vtex : vertex_buffers_) { - if (vtex.location == location) + if (vtex.location == location) { return Result("can not bind two vertex buffers to the same LOCATION"); + } } vertex_buffers_.push_back(BufferInfo{buf}); @@ -467,8 +491,9 @@ Result Pipeline::AddVertexBuffer(Buffer* buf, } Result Pipeline::SetPushConstantBuffer(Buffer* buf) { - if (push_constant_buffer_.buffer != nullptr) + if (push_constant_buffer_.buffer != nullptr) { return Result("can only bind one push constant buffer in a PIPELINE"); + } push_constant_buffer_.buffer = buf; push_constant_buffer_.type = BufferType::kPushConstant; @@ -476,8 +501,9 @@ Result Pipeline::SetPushConstantBuffer(Buffer* buf) { } Result Pipeline::CreatePushConstantBuffer() { - if (push_constant_buffer_.buffer != nullptr) + if (push_constant_buffer_.buffer != nullptr) { return Result("can only bind one push constant buffer in a PIPELINE"); + } TypeParser parser; auto type = parser.Parse("R8_UINT"); @@ -529,8 +555,9 @@ Pipeline::GenerateDefaultDepthStencilAttachmentBuffer() { Buffer* Pipeline::GetBufferForBinding(uint32_t descriptor_set, uint32_t binding) const { for (const auto& info : buffers_) { - if (info.descriptor_set == descriptor_set && info.binding == binding) + if (info.descriptor_set == descriptor_set && info.binding == binding) { return info.buffer; + } } return nullptr; } @@ -695,12 +722,14 @@ Result Pipeline::UpdateOpenCLBufferBindings() { const auto& shader_info = GetShaders()[0]; const auto& descriptor_map = shader_info.GetDescriptorMap(); - if (descriptor_map.empty()) + if (descriptor_map.empty()) { return {}; + } const auto iter = descriptor_map.find(shader_info.GetEntryPoint()); - if (iter == descriptor_map.end()) + if (iter == descriptor_map.end()) { return {}; + } for (auto& info : samplers_) { if (info.descriptor_set == std::numeric_limits::max() && @@ -795,12 +824,14 @@ Result Pipeline::GenerateOpenCLPodBuffers() { const auto& shader_info = GetShaders()[0]; const auto& descriptor_map = shader_info.GetDescriptorMap(); - if (descriptor_map.empty()) + if (descriptor_map.empty()) { return {}; + } const auto iter = descriptor_map.find(shader_info.GetEntryPoint()); - if (iter == descriptor_map.end()) + if (iter == descriptor_map.end()) { return {}; + } // For each SET command, do the following: // 1. Find the descriptor map entry for that argument. @@ -840,8 +871,9 @@ Result Pipeline::GenerateOpenCLPodBuffers() { Pipeline::ShaderInfo::DescriptorMapEntry::Kind::POD_PUSHCONSTANT) { if (GetPushConstantBuffer().buffer == nullptr) { auto r = CreatePushConstantBuffer(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } buffer = GetPushConstantBuffer().buffer; } else { @@ -950,8 +982,9 @@ Result Pipeline::GenerateOpenCLPodBuffers() { data_bytes.push_back(v); } Result r = buffer->SetDataWithOffset(data_bytes, offset); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } return {}; @@ -959,8 +992,9 @@ Result Pipeline::GenerateOpenCLPodBuffers() { Result Pipeline::GenerateOpenCLLiteralSamplers() { for (auto& info : samplers_) { - if (info.sampler || info.mask == std::numeric_limits::max()) + if (info.sampler || info.mask == std::numeric_limits::max()) { continue; + } auto literal_sampler = MakeUnique(); literal_sampler->SetName("literal." + std::to_string(info.descriptor_set) + @@ -1026,12 +1060,14 @@ Result Pipeline::GenerateOpenCLPushConstants() { } const auto& shader_info = GetShaders()[0]; - if (shader_info.GetPushConstants().empty()) + if (shader_info.GetPushConstants().empty()) { return {}; + } Result r = CreatePushConstantBuffer(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } auto* buf = GetPushConstantBuffer().buffer; assert(buf); @@ -1041,8 +1077,9 @@ Result Pipeline::GenerateOpenCLPushConstants() { assert(pc.size % sizeof(uint32_t) == 0); assert(pc.offset % sizeof(uint32_t) == 0); - if (buf->GetSizeInBytes() < pc.offset + pc.size) + if (buf->GetSizeInBytes() < pc.offset + pc.size) { buf->SetSizeInBytes(pc.offset + pc.size); + } std::vector bytes(pc.size / sizeof(uint32_t)); uint32_t base = 0; diff --git a/src/pipeline.h b/src/pipeline.h index 3c93d6cc8..ca7ea7717 100644 --- a/src/pipeline.h +++ b/src/pipeline.h @@ -269,8 +269,9 @@ class Pipeline { /// Returns the ShaderInfo for |shader| or nullptr. const ShaderInfo* GetShader(Shader* shader) const { for (const auto& info : shaders_) { - if (info.GetShader() == shader) + if (info.GetShader() == shader) { return &info; + } } return nullptr; } @@ -423,8 +424,9 @@ class Pipeline { /// Adds |sbt| to the list of known shader binding tables. /// The |sbt| must have a unique name within pipeline. Result AddSBT(std::unique_ptr sbt) { - if (name_to_sbt_.count(sbt->GetName()) > 0) + if (name_to_sbt_.count(sbt->GetName()) > 0) { return Result("duplicate SBT name provided"); + } sbts_.push_back(std::move(sbt)); name_to_sbt_[sbts_.back()->GetName()] = sbts_.back().get(); @@ -444,8 +446,9 @@ class Pipeline { /// Adds |group| to the list of known shader groups. /// The |group| must have a unique name within pipeline. Result AddShaderGroup(std::shared_ptr group) { - if (name_to_shader_group_.count(group->GetName()) > 0) + if (name_to_shader_group_.count(group->GetName()) > 0) { return Result("shader group name already exists"); + } shader_groups_.push_back(std::move(group)); name_to_shader_group_[shader_groups_.back()->GetName()] = @@ -544,12 +547,8 @@ class Pipeline { uint32_t GetMaxPipelineRayRecursionDepth() { return max_pipeline_ray_recursion_depth_; } - void SetCreateFlags(uint32_t flags) { - create_flags_ = flags; - } - uint32_t GetCreateFlags() const { - return create_flags_; - } + void SetCreateFlags(uint32_t flags) { create_flags_ = flags; } + uint32_t GetCreateFlags() const { return create_flags_; } void AddPipelineLibrary(Pipeline* pipeline) { libs_.push_back(pipeline); } const std::vector& GetPipelineLibraries() const { return libs_; } diff --git a/src/pipeline_test.cc b/src/pipeline_test.cc index c0d2f673e..a22aab2da 100644 --- a/src/pipeline_test.cc +++ b/src/pipeline_test.cc @@ -35,15 +35,17 @@ class PipelineTest : public testing::Test { } void SetupColorAttachment(Pipeline* p, uint32_t location) { - if (!color_buffer_) + if (!color_buffer_) { color_buffer_ = p->GenerateDefaultColorAttachmentBuffer(); + } p->AddColorAttachment(color_buffer_.get(), location, 0); } void SetupDepthStencilAttachment(Pipeline* p) { - if (!depth_stencil_buffer_) + if (!depth_stencil_buffer_) { depth_stencil_buffer_ = p->GenerateDefaultDepthStencilAttachmentBuffer(); + } p->SetDepthStencilBuffer(depth_stencil_buffer_.get()); } diff --git a/src/recipe.cc b/src/recipe.cc index 7d46f05eb..2a4f41820 100644 --- a/src/recipe.cc +++ b/src/recipe.cc @@ -26,8 +26,9 @@ Recipe::~Recipe() { } std::vector Recipe::GetShaderInfo() const { - if (!impl_) + if (!impl_) { return {}; + } return impl_->GetShaderInfo(); } @@ -50,13 +51,15 @@ std::vector Recipe::GetRequiredInstanceExtensions() const { } void Recipe::SetFenceTimeout(uint32_t timeout_ms) { - if (impl_) + if (impl_) { impl_->SetFenceTimeout(timeout_ms); + } } void Recipe::SetPipelineRuntimeLayerEnabled(bool enabled) { - if (impl_) + if (impl_) { impl_->SetPipelineRuntimeLayerEnabled(enabled); + } } } // namespace amber diff --git a/src/script.cc b/src/script.cc index 79708884e..591d86bc1 100644 --- a/src/script.cc +++ b/src/script.cc @@ -58,10 +58,11 @@ std::vector Script::GetShaderInfo() const { void Script::AddRequiredExtension(const std::string& ext) { // Make this smarter when we have more instance extensions to match. - if (ext == "VK_KHR_get_physical_device_properties2") + if (ext == "VK_KHR_get_physical_device_properties2") { AddRequiredInstanceExtension(ext); - else + } else { AddRequiredDeviceExtension(ext); + } } bool Script::IsKnownFeature(const std::string& name) const { @@ -163,8 +164,9 @@ bool Script::IsKnownProperty(const std::string& name) const { type::Type* Script::ParseType(const std::string& str) { auto type = GetType(str); - if (type) + if (type) { return type; + } TypeParser parser; auto new_type = parser.Parse(str); diff --git a/src/script.h b/src/script.h index 1b36e8b04..327986fe8 100644 --- a/src/script.h +++ b/src/script.h @@ -82,8 +82,9 @@ class Script : public RecipeImpl { /// Adds |pipeline| to the list of known pipelines. The |pipeline| must have /// a unique name over all pipelines in the script. Result AddPipeline(std::unique_ptr pipeline) { - if (name_to_pipeline_.count(pipeline->GetName()) > 0) + if (name_to_pipeline_.count(pipeline->GetName()) > 0) { return Result("duplicate pipeline name provided"); + } pipelines_.push_back(std::move(pipeline)); name_to_pipeline_[pipelines_.back()->GetName()] = pipelines_.back().get(); @@ -104,8 +105,9 @@ class Script : public RecipeImpl { /// Adds |shader| to the list of known shaders. The |shader| must have a /// unique name over all shaders in the script. Result AddShader(std::unique_ptr shader) { - if (name_to_shader_.count(shader->GetName()) > 0) + if (name_to_shader_.count(shader->GetName()) > 0) { return Result("duplicate shader name provided"); + } shaders_.push_back(std::move(shader)); name_to_shader_[shaders_.back()->GetName()] = shaders_.back().get(); @@ -130,14 +132,16 @@ class Script : public RecipeImpl { if (shader) { for (auto group : pipeline->GetShaderGroups()) { Shader* test_shader = group->GetShaderByType(shader->GetType()); - if (test_shader == shader) + if (test_shader == shader) { return shader; + } } for (auto lib : pipeline->GetPipelineLibraries()) { shader = FindShader(lib, shader); - if (shader) + if (shader) { return shader; + } } } @@ -162,8 +166,9 @@ class Script : public RecipeImpl { for (auto lib : pipeline->GetPipelineLibraries()) { result = FindShaderGroup(lib, name, index); - if (result) + if (result) { return result; + } } *index = static_cast(-1); @@ -174,8 +179,9 @@ class Script : public RecipeImpl { /// Adds |buffer| to the list of known buffers. The |buffer| must have a /// unique name over all buffers in the script. Result AddBuffer(std::unique_ptr buffer) { - if (name_to_buffer_.count(buffer->GetName()) > 0) + if (name_to_buffer_.count(buffer->GetName()) > 0) { return Result("duplicate buffer name provided"); + } buffers_.push_back(std::move(buffer)); name_to_buffer_[buffers_.back()->GetName()] = buffers_.back().get(); @@ -196,8 +202,9 @@ class Script : public RecipeImpl { /// Adds |sampler| to the list of known sampler. The |sampler| must have a /// unique name over all samplers in the script. Result AddSampler(std::unique_ptr sampler) { - if (name_to_sampler_.count(sampler->GetName()) > 0) + if (name_to_sampler_.count(sampler->GetName()) > 0) { return Result("duplicate sampler name provided"); + } samplers_.push_back(std::move(sampler)); name_to_sampler_[samplers_.back()->GetName()] = samplers_.back().get(); @@ -218,8 +225,9 @@ class Script : public RecipeImpl { /// Adds |blas| to the list of known bottom level acceleration structures. /// The |blas| must have a unique name over all BLASes in the script. Result AddBLAS(std::unique_ptr blas) { - if (name_to_blas_.count(blas->GetName()) > 0) + if (name_to_blas_.count(blas->GetName()) > 0) { return Result("duplicate BLAS name provided"); + } blases_.push_back(std::move(blas)); name_to_blas_[blases_.back()->GetName()] = blases_.back().get(); @@ -241,8 +249,9 @@ class Script : public RecipeImpl { /// Adds |tlas| to the list of known top level acceleration structures. /// The |tlas| must have a unique name over all TLASes in the script. Result AddTLAS(std::unique_ptr tlas) { - if (name_to_tlas_.count(tlas->GetName()) > 0) + if (name_to_tlas_.count(tlas->GetName()) > 0) { return Result("duplicate TLAS name provided"); + } tlases_.push_back(std::move(tlas)); name_to_tlas_[tlases_.back()->GetName()] = tlases_.back().get(); @@ -337,8 +346,9 @@ class Script : public RecipeImpl { /// Adds |type| to the list of known types. The |type| must have /// a unique name over all types in the script. Result AddType(const std::string& name, std::unique_ptr type) { - if (name_to_type_.count(name) > 0) + if (name_to_type_.count(name) > 0) { return Result("duplicate type name provided"); + } name_to_type_[name] = std::move(type); return {}; diff --git a/src/shader_compiler.cc b/src/shader_compiler.cc index 1615fb969..4dd3bd6f8 100644 --- a/src/shader_compiler.cc +++ b/src/shader_compiler.cc @@ -87,8 +87,9 @@ std::pair> ShaderCompiler::Compile( spv_target_env target_env = SPV_ENV_UNIVERSAL_1_0; if (!spv_env_.empty()) { - if (!spvParseTargetEnv(spv_env_.c_str(), &target_env)) + if (!spvParseTargetEnv(spv_env_.c_str(), &target_env)) { return {Result("Unable to parse SPIR-V target environment"), {}}; + } } auto msg_consumer = [&spv_errors](spv_message_level_t level, const char*, @@ -122,8 +123,9 @@ std::pair> ShaderCompiler::Compile( if (shader->GetFormat() == kShaderFormatSpirvHex) { Result r = ParseHex(shader->GetData(), &results); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return {Result("Unable to parse shader hex."), {}}; + } } else if (shader->GetFormat() == kShaderFormatSpirvBin) { results.resize(shader->GetData().size() / 4); memcpy(results.data(), shader->GetData().data(), shader->GetData().size()); @@ -131,15 +133,17 @@ std::pair> ShaderCompiler::Compile( #if AMBER_ENABLE_SHADERC } else if (shader->GetFormat() == kShaderFormatGlsl) { Result r = CompileGlsl(shader, &results); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return {r, {}}; + } #endif // AMBER_ENABLE_SHADERC #if AMBER_ENABLE_DXC } else if (shader->GetFormat() == kShaderFormatHlsl) { Result r = CompileHlsl(shader, &results); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return {r, {}}; + } #endif // AMBER_ENABLE_DXC #if AMBER_ENABLE_SPIRV_TOOLS @@ -153,8 +157,9 @@ std::pair> ShaderCompiler::Compile( #if AMBER_ENABLE_CLSPV } else if (shader->GetFormat() == kShaderFormatOpenCLC) { Result r = CompileOpenCLC(shader_info, pipeline, target_env, &results); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return {r, {}}; + } #endif // AMBER_ENABLE_CLSPV } else { @@ -167,8 +172,9 @@ std::pair> ShaderCompiler::Compile( if (!disable_spirv_validation_) { #if AMBER_ENABLE_SPIRV_TOOLS spvtools::ValidatorOptions options; - if (!tools.Validate(results.data(), results.size(), options)) + if (!tools.Validate(results.data(), results.size(), options)) { return {Result("Invalid shader: " + spv_errors), {}}; + } #endif // AMBER_ENABLE_SPIRV_TOOLS } @@ -181,8 +187,9 @@ std::pair> ShaderCompiler::Compile( shader_info->GetShaderOptimizations())) { return {Result("Invalid optimizations: " + spv_errors), {}}; } - if (!optimizer.Run(results.data(), results.size(), &results)) + if (!optimizer.Run(results.data(), results.size(), &results)) { return {Result("Optimizations failed: " + spv_errors), {}}; + } } #endif // AMBER_ENABLE_SPIRV_TOOLS @@ -225,46 +232,49 @@ Result ShaderCompiler::CompileGlsl(const Shader* shader, uint32_t env_version = 0u; uint32_t spirv_version = 0u; auto r = ParseSpvEnv(spv_env_, &env, &env_version, &spirv_version); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } options.SetTargetEnvironment(static_cast(env), env_version); options.SetTargetSpirv(static_cast(spirv_version)); shaderc_shader_kind kind; - if (shader->GetType() == kShaderTypeCompute) + if (shader->GetType() == kShaderTypeCompute) { kind = shaderc_compute_shader; - else if (shader->GetType() == kShaderTypeFragment) + } else if (shader->GetType() == kShaderTypeFragment) { kind = shaderc_fragment_shader; - else if (shader->GetType() == kShaderTypeGeometry) + } else if (shader->GetType() == kShaderTypeGeometry) { kind = shaderc_geometry_shader; - else if (shader->GetType() == kShaderTypeVertex) + } else if (shader->GetType() == kShaderTypeVertex) { kind = shaderc_vertex_shader; - else if (shader->GetType() == kShaderTypeTessellationControl) + } else if (shader->GetType() == kShaderTypeTessellationControl) { kind = shaderc_tess_control_shader; - else if (shader->GetType() == kShaderTypeTessellationEvaluation) + } else if (shader->GetType() == kShaderTypeTessellationEvaluation) { kind = shaderc_tess_evaluation_shader; - else if (shader->GetType() == kShaderTypeRayGeneration) + } else if (shader->GetType() == kShaderTypeRayGeneration) { kind = shaderc_raygen_shader; - else if (shader->GetType() == kShaderTypeAnyHit) + } else if (shader->GetType() == kShaderTypeAnyHit) { kind = shaderc_anyhit_shader; - else if (shader->GetType() == kShaderTypeClosestHit) + } else if (shader->GetType() == kShaderTypeClosestHit) { kind = shaderc_closesthit_shader; - else if (shader->GetType() == kShaderTypeMiss) + } else if (shader->GetType() == kShaderTypeMiss) { kind = shaderc_miss_shader; - else if (shader->GetType() == kShaderTypeIntersection) + } else if (shader->GetType() == kShaderTypeIntersection) { kind = shaderc_intersection_shader; - else if (shader->GetType() == kShaderTypeCall) + } else if (shader->GetType() == kShaderTypeCall) { kind = shaderc_callable_shader; - else + } else { return Result("Unknown shader type"); + } shaderc::SpvCompilationResult module = compiler.CompileGlslToSpv(shader->GetData(), kind, "-", options); - if (module.GetCompilationStatus() != shaderc_compilation_status_success) + if (module.GetCompilationStatus() != shaderc_compilation_status_success) { return Result(module.GetErrorMessage()); + } std::copy(module.cbegin(), module.cend(), std::back_inserter(*result)); return {}; @@ -280,16 +290,17 @@ Result ShaderCompiler::CompileGlsl(const Shader*, Result ShaderCompiler::CompileHlsl(const Shader* shader, std::vector* result) const { std::string target; - if (shader->GetType() == kShaderTypeCompute) + if (shader->GetType() == kShaderTypeCompute) { target = "cs_6_2"; - else if (shader->GetType() == kShaderTypeFragment) + } else if (shader->GetType() == kShaderTypeFragment) { target = "ps_6_2"; - else if (shader->GetType() == kShaderTypeGeometry) + } else if (shader->GetType() == kShaderTypeGeometry) { target = "gs_6_2"; - else if (shader->GetType() == kShaderTypeVertex) + } else if (shader->GetType() == kShaderTypeVertex) { target = "vs_6_2"; - else + } else { return Result("Unknown shader type"); + } return dxchelper::Compile(shader->GetData(), "main", target, spv_env_, shader->GetFilePath(), virtual_files_, result); @@ -357,8 +368,9 @@ Result ParseSpvEnv(const std::string& spv_env, uint32_t* target_env, uint32_t* target_env_version, uint32_t* spirv_version) { - if (!target_env || !target_env_version || !spirv_version) + if (!target_env || !target_env_version || !spirv_version) { return Result("ParseSpvEnv: null pointer parameter"); + } // Use the same values as in Shaderc's shaderc/env.h struct Values { diff --git a/src/tokenizer.cc b/src/tokenizer.cc index 4475aab3a..22416b665 100644 --- a/src/tokenizer.cc +++ b/src/tokenizer.cc @@ -28,11 +28,13 @@ Token::Token(TokenType type) : type_(type) {} Token::~Token() = default; Result Token::ConvertToDouble() { - if (IsDouble()) + if (IsDouble()) { return {}; + } - if (IsIdentifier() || IsEOL() || IsEOS()) + if (IsIdentifier() || IsEOL() || IsEOS()) { return Result("Invalid conversion to double"); + } if (IsInteger()) { if (is_negative_ || @@ -58,15 +60,17 @@ Tokenizer::~Tokenizer() = default; std::unique_ptr Tokenizer::NextToken() { SkipWhitespace(); - if (current_position_ >= data_.length()) + if (current_position_ >= data_.length()) { return MakeUnique(TokenType::kEOS); + } if (data_[current_position_] == '#') { SkipComment(); SkipWhitespace(); } - if (current_position_ >= data_.length()) + if (current_position_ >= data_.length()) { return MakeUnique(TokenType::kEOS); + } if (data_[current_position_] == '\n') { ++current_line_; @@ -243,8 +247,9 @@ std::unique_ptr Tokenizer::NextToken() { uint64_t val = uint64_t(std::strtoull(tok_str.c_str(), &final_pos, 10)); tok->SetUint64Value(static_cast(val)); } - if (tok_str.size() > 1 && tok_str[0] == '-') + if (tok_str.size() > 1 && tok_str[0] == '-') { tok->SetNegative(); + } tok->SetOriginalString( tok_str.substr(0, static_cast(final_pos - tok_str.c_str()))); @@ -252,8 +257,9 @@ std::unique_ptr Tokenizer::NextToken() { // If the number isn't the whole token then move back so we can then parse // the string portion. auto diff = size_t(final_pos - tok_str.c_str()); - if (diff > 0) + if (diff > 0) { current_position_ -= tok_str.length() - diff; + } return tok; } @@ -283,8 +289,9 @@ std::string Tokenizer::ExtractToNext(const std::string& str) { // Account for any new lines in the extracted text so our current line // number stays correct. for (const char c : ret) { - if (c == '\n') + if (c == '\n') { ++current_line_; + } } return ret; diff --git a/src/type.cc b/src/type.cc index f25e79f4b..2ff088af9 100644 --- a/src/type.cc +++ b/src/type.cc @@ -77,12 +77,14 @@ List::List() = default; List::~List() = default; uint32_t List::SizeInBytes() const { - if (pack_size_in_bits_ > 0) + if (pack_size_in_bits_ > 0) { return pack_size_in_bits_; + } uint32_t size = 0; - for (const auto& member : members_) + for (const auto& member : members_) { size += member.SizeInBytes(); + } return size; } diff --git a/src/type.h b/src/type.h index c63779ba6..c2feb0641 100644 --- a/src/type.h +++ b/src/type.h @@ -154,8 +154,9 @@ class Number : public Type { uint32_t SizeInBytes() const override { return bits_ / 8; } bool Equal(const Type* b) const override { - if (!b->IsNumber()) + if (!b->IsNumber()) { return false; + } auto n = b->AsNumber(); return format_mode_ == n->format_mode_ && bits_ == n->bits_; @@ -188,23 +189,29 @@ class List : public Type { bool IsList() const override { return true; } bool Equal(const Type* b) const override { - if (!b->IsList()) + if (!b->IsList()) { return false; + } auto l = b->AsList(); - if (pack_size_in_bits_ != l->pack_size_in_bits_) + if (pack_size_in_bits_ != l->pack_size_in_bits_) { return false; - if (members_.size() != l->members_.size()) + } + if (members_.size() != l->members_.size()) { return false; + } auto& lm = l->Members(); for (size_t i = 0; i < members_.size(); ++i) { - if (members_[i].name != lm[i].name) + if (members_[i].name != lm[i].name) { return false; - if (members_[i].mode != lm[i].mode) + } + if (members_[i].mode != lm[i].mode) { return false; - if (members_[i].num_bits != lm[i].num_bits) + } + if (members_[i].num_bits != lm[i].num_bits) { return false; + } } return true; } @@ -248,27 +255,35 @@ class Struct : public Type { bool IsStruct() const override { return true; } bool Equal(const Type* b) const override { - if (!b->IsStruct()) + if (!b->IsStruct()) { return false; + } auto s = b->AsStruct(); - if (is_stride_specified_ != s->is_stride_specified_) + if (is_stride_specified_ != s->is_stride_specified_) { return false; - if (stride_in_bytes_ != s->stride_in_bytes_) + } + if (stride_in_bytes_ != s->stride_in_bytes_) { return false; - if (members_.size() != s->members_.size()) + } + if (members_.size() != s->members_.size()) { return false; + } auto& sm = s->Members(); for (size_t i = 0; i < members_.size(); ++i) { - if (members_[i].offset_in_bytes != sm[i].offset_in_bytes) + if (members_[i].offset_in_bytes != sm[i].offset_in_bytes) { return false; - if (members_[i].array_stride_in_bytes != sm[i].array_stride_in_bytes) + } + if (members_[i].array_stride_in_bytes != sm[i].array_stride_in_bytes) { return false; - if (members_[i].matrix_stride_in_bytes != sm[i].matrix_stride_in_bytes) + } + if (members_[i].matrix_stride_in_bytes != sm[i].matrix_stride_in_bytes) { return false; - if (!members_[i].type->Equal(sm[i].type)) + } + if (!members_[i].type->Equal(sm[i].type)) { return false; + } } return true; } diff --git a/src/type_parser.cc b/src/type_parser.cc index 7df8be5e2..b426e772f 100644 --- a/src/type_parser.cc +++ b/src/type_parser.cc @@ -27,12 +27,14 @@ TypeParser::TypeParser() = default; TypeParser::~TypeParser() = default; std::unique_ptr TypeParser::Parse(const std::string& data) { - if (data.empty()) + if (data.empty()) { return nullptr; + } // See if this is a custom glsl string format. - if (data.find('/', 0) != std::string::npos) + if (data.find('/', 0) != std::string::npos) { return ParseGlslFormat(data); + } // Walk the string backwards. This means we'll know if it's pack and we'll // know the mode before we get to a given named component. @@ -41,20 +43,23 @@ std::unique_ptr TypeParser::Parse(const std::string& data) { size_t next_pos = data.rfind('_', cur_pos); if (next_pos == std::string::npos) { if (cur_pos != std::string::npos) { - if (!ProcessChunk(data.substr(0, cur_pos + 1))) + if (!ProcessChunk(data.substr(0, cur_pos + 1))) { return nullptr; + } } break; } - if (!ProcessChunk(data.substr(next_pos + 1, cur_pos - next_pos))) + if (!ProcessChunk(data.substr(next_pos + 1, cur_pos - next_pos))) { return nullptr; + } cur_pos = next_pos - 1; } - if (pieces_.empty()) + if (pieces_.empty()) { return nullptr; + } std::unique_ptr type = nullptr; if (pack_size_ == 0 && pieces_.size() == 1 && @@ -65,8 +70,9 @@ std::unique_ptr TypeParser::Parse(const std::string& data) { type->SetRowCount(static_cast(pieces_.size())); type->AsList()->SetPackSizeInBits(pack_size_); - for (const auto& piece : pieces_) + for (const auto& piece : pieces_) { type->AsList()->AddMember(piece.type, piece.mode, piece.num_bits); + } } pack_size_ = 0; @@ -83,52 +89,56 @@ void TypeParser::AddPiece(FormatComponentType type, } bool TypeParser::ProcessChunk(const std::string& data) { - if (data.size() == 0) + if (data.size() == 0) { return false; + } if (data[0] == 'P') { - if (data == "PACK8") + if (data == "PACK8") { pack_size_ = 8; - else if (data == "PACK16") + } else if (data == "PACK16") { pack_size_ = 16; - else if (data == "PACK32") + } else if (data == "PACK32") { pack_size_ = 32; - else + } else { return false; + } return true; } if (data[0] == 'U') { - if (data == "UINT") + if (data == "UINT") { mode_ = FormatMode::kUInt; - else if (data == "UNORM") + } else if (data == "UNORM") { mode_ = FormatMode::kUNorm; - else if (data == "UFLOAT") + } else if (data == "UFLOAT") { mode_ = FormatMode::kUFloat; - else if (data == "USCALED") + } else if (data == "USCALED") { mode_ = FormatMode::kUScaled; - else + } else { return false; + } return true; } if (data[0] == 'S') { - if (data == "SINT") + if (data == "SINT") { mode_ = FormatMode::kSInt; - else if (data == "SNORM") + } else if (data == "SNORM") { mode_ = FormatMode::kSNorm; - else if (data == "SSCALED") + } else if (data == "SSCALED") { mode_ = FormatMode::kSScaled; - else if (data == "SFLOAT") + } else if (data == "SFLOAT") { mode_ = FormatMode::kSFloat; - else if (data == "SRGB") + } else if (data == "SRGB") { mode_ = FormatMode::kSRGB; - else if (data == "S8") + } else if (data == "S8") { AddPiece(FormatComponentType::kS, mode_, 8); - else + } else { return false; + } return true; } @@ -164,11 +174,13 @@ bool TypeParser::ProcessChunk(const std::string& data) { const char* str = data.c_str() + cur_pos + 1; uint64_t val = static_cast(std::strtol(str, &next_str, 10)); - if (val > 0) + if (val > 0) { AddPiece(type, mode_, static_cast(val)); + } - if (cur_pos == 0) + if (cur_pos == 0) { break; + } --cur_pos; } @@ -177,264 +189,393 @@ bool TypeParser::ProcessChunk(const std::string& data) { // static FormatType TypeParser::NameToFormatType(const std::string& data) { - if (data == "A1R5G5B5_UNORM_PACK16") + if (data == "A1R5G5B5_UNORM_PACK16") { return FormatType::kA1R5G5B5_UNORM_PACK16; - if (data == "A2B10G10R10_SINT_PACK32") + } + if (data == "A2B10G10R10_SINT_PACK32") { return FormatType::kA2B10G10R10_SINT_PACK32; - if (data == "A2B10G10R10_SNORM_PACK32") + } + if (data == "A2B10G10R10_SNORM_PACK32") { return FormatType::kA2B10G10R10_SNORM_PACK32; - if (data == "A2B10G10R10_SSCALED_PACK32") + } + if (data == "A2B10G10R10_SSCALED_PACK32") { return FormatType::kA2B10G10R10_SSCALED_PACK32; - if (data == "A2B10G10R10_UINT_PACK32") + } + if (data == "A2B10G10R10_UINT_PACK32") { return FormatType::kA2B10G10R10_UINT_PACK32; - if (data == "A2B10G10R10_UNORM_PACK32") + } + if (data == "A2B10G10R10_UNORM_PACK32") { return FormatType::kA2B10G10R10_UNORM_PACK32; - if (data == "A2B10G10R10_USCALED_PACK32") + } + if (data == "A2B10G10R10_USCALED_PACK32") { return FormatType::kA2B10G10R10_USCALED_PACK32; - if (data == "A2R10G10B10_SINT_PACK32") + } + if (data == "A2R10G10B10_SINT_PACK32") { return FormatType::kA2R10G10B10_SINT_PACK32; - if (data == "A2R10G10B10_SNORM_PACK32") + } + if (data == "A2R10G10B10_SNORM_PACK32") { return FormatType::kA2R10G10B10_SNORM_PACK32; - if (data == "A2R10G10B10_SSCALED_PACK32") + } + if (data == "A2R10G10B10_SSCALED_PACK32") { return FormatType::kA2R10G10B10_SSCALED_PACK32; - if (data == "A2R10G10B10_UINT_PACK32") + } + if (data == "A2R10G10B10_UINT_PACK32") { return FormatType::kA2R10G10B10_UINT_PACK32; - if (data == "A2R10G10B10_UNORM_PACK32") + } + if (data == "A2R10G10B10_UNORM_PACK32") { return FormatType::kA2R10G10B10_UNORM_PACK32; - if (data == "A2R10G10B10_USCALED_PACK32") + } + if (data == "A2R10G10B10_USCALED_PACK32") { return FormatType::kA2R10G10B10_USCALED_PACK32; - if (data == "A8B8G8R8_SINT_PACK32") + } + if (data == "A8B8G8R8_SINT_PACK32") { return FormatType::kA8B8G8R8_SINT_PACK32; - if (data == "A8B8G8R8_SNORM_PACK32") + } + if (data == "A8B8G8R8_SNORM_PACK32") { return FormatType::kA8B8G8R8_SNORM_PACK32; - if (data == "A8B8G8R8_SRGB_PACK32") + } + if (data == "A8B8G8R8_SRGB_PACK32") { return FormatType::kA8B8G8R8_SRGB_PACK32; - if (data == "A8B8G8R8_SSCALED_PACK32") + } + if (data == "A8B8G8R8_SSCALED_PACK32") { return FormatType::kA8B8G8R8_SSCALED_PACK32; - if (data == "A8B8G8R8_UINT_PACK32") + } + if (data == "A8B8G8R8_UINT_PACK32") { return FormatType::kA8B8G8R8_UINT_PACK32; - if (data == "A8B8G8R8_UNORM_PACK32") + } + if (data == "A8B8G8R8_UNORM_PACK32") { return FormatType::kA8B8G8R8_UNORM_PACK32; - if (data == "A8B8G8R8_USCALED_PACK32") + } + if (data == "A8B8G8R8_USCALED_PACK32") { return FormatType::kA8B8G8R8_USCALED_PACK32; - if (data == "B10G11R11_UFLOAT_PACK32") + } + if (data == "B10G11R11_UFLOAT_PACK32") { return FormatType::kB10G11R11_UFLOAT_PACK32; - if (data == "B4G4R4A4_UNORM_PACK16") + } + if (data == "B4G4R4A4_UNORM_PACK16") { return FormatType::kB4G4R4A4_UNORM_PACK16; - if (data == "B5G5R5A1_UNORM_PACK16") + } + if (data == "B5G5R5A1_UNORM_PACK16") { return FormatType::kB5G5R5A1_UNORM_PACK16; - if (data == "B5G6R5_UNORM_PACK16") + } + if (data == "B5G6R5_UNORM_PACK16") { return FormatType::kB5G6R5_UNORM_PACK16; - if (data == "B8G8R8A8_SINT") + } + if (data == "B8G8R8A8_SINT") { return FormatType::kB8G8R8A8_SINT; - if (data == "B8G8R8A8_SNORM") + } + if (data == "B8G8R8A8_SNORM") { return FormatType::kB8G8R8A8_SNORM; - if (data == "B8G8R8A8_SRGB") + } + if (data == "B8G8R8A8_SRGB") { return FormatType::kB8G8R8A8_SRGB; - if (data == "B8G8R8A8_SSCALED") + } + if (data == "B8G8R8A8_SSCALED") { return FormatType::kB8G8R8A8_SSCALED; - if (data == "B8G8R8A8_UINT") + } + if (data == "B8G8R8A8_UINT") { return FormatType::kB8G8R8A8_UINT; - if (data == "B8G8R8A8_UNORM") + } + if (data == "B8G8R8A8_UNORM") { return FormatType::kB8G8R8A8_UNORM; - if (data == "B8G8R8A8_USCALED") + } + if (data == "B8G8R8A8_USCALED") { return FormatType::kB8G8R8A8_USCALED; - if (data == "B8G8R8_SINT") + } + if (data == "B8G8R8_SINT") { return FormatType::kB8G8R8_SINT; - if (data == "B8G8R8_SNORM") + } + if (data == "B8G8R8_SNORM") { return FormatType::kB8G8R8_SNORM; - if (data == "B8G8R8_SRGB") + } + if (data == "B8G8R8_SRGB") { return FormatType::kB8G8R8_SRGB; - if (data == "B8G8R8_SSCALED") + } + if (data == "B8G8R8_SSCALED") { return FormatType::kB8G8R8_SSCALED; - if (data == "B8G8R8_UINT") + } + if (data == "B8G8R8_UINT") { return FormatType::kB8G8R8_UINT; - if (data == "B8G8R8_UNORM") + } + if (data == "B8G8R8_UNORM") { return FormatType::kB8G8R8_UNORM; - if (data == "B8G8R8_USCALED") + } + if (data == "B8G8R8_USCALED") { return FormatType::kB8G8R8_USCALED; - if (data == "D16_UNORM") + } + if (data == "D16_UNORM") { return FormatType::kD16_UNORM; - if (data == "D16_UNORM_S8_UINT") + } + if (data == "D16_UNORM_S8_UINT") { return FormatType::kD16_UNORM_S8_UINT; - if (data == "D24_UNORM_S8_UINT") + } + if (data == "D24_UNORM_S8_UINT") { return FormatType::kD24_UNORM_S8_UINT; - if (data == "D32_SFLOAT") + } + if (data == "D32_SFLOAT") { return FormatType::kD32_SFLOAT; - if (data == "D32_SFLOAT_S8_UINT") + } + if (data == "D32_SFLOAT_S8_UINT") { return FormatType::kD32_SFLOAT_S8_UINT; - if (data == "R16G16B16A16_SFLOAT") + } + if (data == "R16G16B16A16_SFLOAT") { return FormatType::kR16G16B16A16_SFLOAT; - if (data == "R16G16B16A16_SINT") + } + if (data == "R16G16B16A16_SINT") { return FormatType::kR16G16B16A16_SINT; - if (data == "R16G16B16A16_SNORM") + } + if (data == "R16G16B16A16_SNORM") { return FormatType::kR16G16B16A16_SNORM; - if (data == "R16G16B16A16_SSCALED") + } + if (data == "R16G16B16A16_SSCALED") { return FormatType::kR16G16B16A16_SSCALED; - if (data == "R16G16B16A16_UINT") + } + if (data == "R16G16B16A16_UINT") { return FormatType::kR16G16B16A16_UINT; - if (data == "R16G16B16A16_UNORM") + } + if (data == "R16G16B16A16_UNORM") { return FormatType::kR16G16B16A16_UNORM; - if (data == "R16G16B16A16_USCALED") + } + if (data == "R16G16B16A16_USCALED") { return FormatType::kR16G16B16A16_USCALED; - if (data == "R16G16B16_SFLOAT") + } + if (data == "R16G16B16_SFLOAT") { return FormatType::kR16G16B16_SFLOAT; - if (data == "R16G16B16_SINT") + } + if (data == "R16G16B16_SINT") { return FormatType::kR16G16B16_SINT; - if (data == "R16G16B16_SNORM") + } + if (data == "R16G16B16_SNORM") { return FormatType::kR16G16B16_SNORM; - if (data == "R16G16B16_SSCALED") + } + if (data == "R16G16B16_SSCALED") { return FormatType::kR16G16B16_SSCALED; - if (data == "R16G16B16_UINT") + } + if (data == "R16G16B16_UINT") { return FormatType::kR16G16B16_UINT; - if (data == "R16G16B16_UNORM") + } + if (data == "R16G16B16_UNORM") { return FormatType::kR16G16B16_UNORM; - if (data == "R16G16B16_USCALED") + } + if (data == "R16G16B16_USCALED") { return FormatType::kR16G16B16_USCALED; - if (data == "R16G16_SFLOAT") + } + if (data == "R16G16_SFLOAT") { return FormatType::kR16G16_SFLOAT; - if (data == "R16G16_SINT") + } + if (data == "R16G16_SINT") { return FormatType::kR16G16_SINT; - if (data == "R16G16_SNORM") + } + if (data == "R16G16_SNORM") { return FormatType::kR16G16_SNORM; - if (data == "R16G16_SSCALED") + } + if (data == "R16G16_SSCALED") { return FormatType::kR16G16_SSCALED; - if (data == "R16G16_UINT") + } + if (data == "R16G16_UINT") { return FormatType::kR16G16_UINT; - if (data == "R16G16_UNORM") + } + if (data == "R16G16_UNORM") { return FormatType::kR16G16_UNORM; - if (data == "R16G16_USCALED") + } + if (data == "R16G16_USCALED") { return FormatType::kR16G16_USCALED; - if (data == "R16_SFLOAT") + } + if (data == "R16_SFLOAT") { return FormatType::kR16_SFLOAT; - if (data == "R16_SINT") + } + if (data == "R16_SINT") { return FormatType::kR16_SINT; - if (data == "R16_SNORM") + } + if (data == "R16_SNORM") { return FormatType::kR16_SNORM; - if (data == "R16_SSCALED") + } + if (data == "R16_SSCALED") { return FormatType::kR16_SSCALED; - if (data == "R16_UINT") + } + if (data == "R16_UINT") { return FormatType::kR16_UINT; - if (data == "R16_UNORM") + } + if (data == "R16_UNORM") { return FormatType::kR16_UNORM; - if (data == "R16_USCALED") + } + if (data == "R16_USCALED") { return FormatType::kR16_USCALED; - if (data == "R32G32B32A32_SFLOAT") + } + if (data == "R32G32B32A32_SFLOAT") { return FormatType::kR32G32B32A32_SFLOAT; - if (data == "R32G32B32A32_SINT") + } + if (data == "R32G32B32A32_SINT") { return FormatType::kR32G32B32A32_SINT; - if (data == "R32G32B32A32_UINT") + } + if (data == "R32G32B32A32_UINT") { return FormatType::kR32G32B32A32_UINT; - if (data == "R32G32B32_SFLOAT") + } + if (data == "R32G32B32_SFLOAT") { return FormatType::kR32G32B32_SFLOAT; - if (data == "R32G32B32_SINT") + } + if (data == "R32G32B32_SINT") { return FormatType::kR32G32B32_SINT; - if (data == "R32G32B32_UINT") + } + if (data == "R32G32B32_UINT") { return FormatType::kR32G32B32_UINT; - if (data == "R32G32_SFLOAT") + } + if (data == "R32G32_SFLOAT") { return FormatType::kR32G32_SFLOAT; - if (data == "R32G32_SINT") + } + if (data == "R32G32_SINT") { return FormatType::kR32G32_SINT; - if (data == "R32G32_UINT") + } + if (data == "R32G32_UINT") { return FormatType::kR32G32_UINT; - if (data == "R32_SFLOAT") + } + if (data == "R32_SFLOAT") { return FormatType::kR32_SFLOAT; - if (data == "R32_SINT") + } + if (data == "R32_SINT") { return FormatType::kR32_SINT; - if (data == "R32_UINT") + } + if (data == "R32_UINT") { return FormatType::kR32_UINT; - if (data == "R4G4B4A4_UNORM_PACK16") + } + if (data == "R4G4B4A4_UNORM_PACK16") { return FormatType::kR4G4B4A4_UNORM_PACK16; - if (data == "R4G4_UNORM_PACK8") + } + if (data == "R4G4_UNORM_PACK8") { return FormatType::kR4G4_UNORM_PACK8; - if (data == "R5G5B5A1_UNORM_PACK16") + } + if (data == "R5G5B5A1_UNORM_PACK16") { return FormatType::kR5G5B5A1_UNORM_PACK16; - if (data == "R5G6B5_UNORM_PACK16") + } + if (data == "R5G6B5_UNORM_PACK16") { return FormatType::kR5G6B5_UNORM_PACK16; - if (data == "R64G64B64A64_SFLOAT") + } + if (data == "R64G64B64A64_SFLOAT") { return FormatType::kR64G64B64A64_SFLOAT; - if (data == "R64G64B64A64_SINT") + } + if (data == "R64G64B64A64_SINT") { return FormatType::kR64G64B64A64_SINT; - if (data == "R64G64B64A64_UINT") + } + if (data == "R64G64B64A64_UINT") { return FormatType::kR64G64B64A64_UINT; - if (data == "R64G64B64_SFLOAT") + } + if (data == "R64G64B64_SFLOAT") { return FormatType::kR64G64B64_SFLOAT; - if (data == "R64G64B64_SINT") + } + if (data == "R64G64B64_SINT") { return FormatType::kR64G64B64_SINT; - if (data == "R64G64B64_UINT") + } + if (data == "R64G64B64_UINT") { return FormatType::kR64G64B64_UINT; - if (data == "R64G64_SFLOAT") + } + if (data == "R64G64_SFLOAT") { return FormatType::kR64G64_SFLOAT; - if (data == "R64G64_SINT") + } + if (data == "R64G64_SINT") { return FormatType::kR64G64_SINT; - if (data == "R64G64_UINT") + } + if (data == "R64G64_UINT") { return FormatType::kR64G64_UINT; - if (data == "R64_SFLOAT") + } + if (data == "R64_SFLOAT") { return FormatType::kR64_SFLOAT; - if (data == "R64_SINT") + } + if (data == "R64_SINT") { return FormatType::kR64_SINT; - if (data == "R64_UINT") + } + if (data == "R64_UINT") { return FormatType::kR64_UINT; - if (data == "R8G8B8A8_SINT") + } + if (data == "R8G8B8A8_SINT") { return FormatType::kR8G8B8A8_SINT; - if (data == "R8G8B8A8_SNORM") + } + if (data == "R8G8B8A8_SNORM") { return FormatType::kR8G8B8A8_SNORM; - if (data == "R8G8B8A8_SRGB") + } + if (data == "R8G8B8A8_SRGB") { return FormatType::kR8G8B8A8_SRGB; - if (data == "R8G8B8A8_SSCALED") + } + if (data == "R8G8B8A8_SSCALED") { return FormatType::kR8G8B8A8_SSCALED; - if (data == "R8G8B8A8_UINT") + } + if (data == "R8G8B8A8_UINT") { return FormatType::kR8G8B8A8_UINT; - if (data == "R8G8B8A8_UNORM") + } + if (data == "R8G8B8A8_UNORM") { return FormatType::kR8G8B8A8_UNORM; - if (data == "R8G8B8A8_USCALED") + } + if (data == "R8G8B8A8_USCALED") { return FormatType::kR8G8B8A8_USCALED; - if (data == "R8G8B8_SINT") + } + if (data == "R8G8B8_SINT") { return FormatType::kR8G8B8_SINT; - if (data == "R8G8B8_SNORM") + } + if (data == "R8G8B8_SNORM") { return FormatType::kR8G8B8_SNORM; - if (data == "R8G8B8_SRGB") + } + if (data == "R8G8B8_SRGB") { return FormatType::kR8G8B8_SRGB; - if (data == "R8G8B8_SSCALED") + } + if (data == "R8G8B8_SSCALED") { return FormatType::kR8G8B8_SSCALED; - if (data == "R8G8B8_UINT") + } + if (data == "R8G8B8_UINT") { return FormatType::kR8G8B8_UINT; - if (data == "R8G8B8_UNORM") + } + if (data == "R8G8B8_UNORM") { return FormatType::kR8G8B8_UNORM; - if (data == "R8G8B8_USCALED") + } + if (data == "R8G8B8_USCALED") { return FormatType::kR8G8B8_USCALED; - if (data == "R8G8_SINT") + } + if (data == "R8G8_SINT") { return FormatType::kR8G8_SINT; - if (data == "R8G8_SNORM") + } + if (data == "R8G8_SNORM") { return FormatType::kR8G8_SNORM; - if (data == "R8G8_SRGB") + } + if (data == "R8G8_SRGB") { return FormatType::kR8G8_SRGB; - if (data == "R8G8_SSCALED") + } + if (data == "R8G8_SSCALED") { return FormatType::kR8G8_SSCALED; - if (data == "R8G8_UINT") + } + if (data == "R8G8_UINT") { return FormatType::kR8G8_UINT; - if (data == "R8G8_UNORM") + } + if (data == "R8G8_UNORM") { return FormatType::kR8G8_UNORM; - if (data == "R8G8_USCALED") + } + if (data == "R8G8_USCALED") { return FormatType::kR8G8_USCALED; - if (data == "R8_SINT") + } + if (data == "R8_SINT") { return FormatType::kR8_SINT; - if (data == "R8_SNORM") + } + if (data == "R8_SNORM") { return FormatType::kR8_SNORM; - if (data == "R8_SRGB") + } + if (data == "R8_SRGB") { return FormatType::kR8_SRGB; - if (data == "R8_SSCALED") + } + if (data == "R8_SSCALED") { return FormatType::kR8_SSCALED; - if (data == "R8_UINT") + } + if (data == "R8_UINT") { return FormatType::kR8_UINT; - if (data == "R8_UNORM") + } + if (data == "R8_UNORM") { return FormatType::kR8_UNORM; - if (data == "R8_USCALED") + } + if (data == "R8_USCALED") { return FormatType::kR8_USCALED; - if (data == "S8_UINT") + } + if (data == "S8_UINT") { return FormatType::kS8_UINT; - if (data == "X8_D24_UNORM_PACK32") + } + if (data == "X8_D24_UNORM_PACK32") { return FormatType::kX8_D24_UNORM_PACK32; + } return FormatType::kUnknown; } @@ -462,21 +603,24 @@ std::unique_ptr TypeParser::ParseGlslFormat( }; for (auto& type : types) { if (gl_type == std::string(type.name)) { - if (type.is_int) + if (type.is_int) { mode = type.is_signed ? FormatMode::kSInt : FormatMode::kUInt; - else + } else { mode = FormatMode::kSFloat; + } bits = type.bits; } } // Failed to find gl type. - if (mode == FormatMode::kUNorm) + if (mode == FormatMode::kUNorm) { return nullptr; + } - if (fmt.length() < 4) + if (fmt.length() < 4) { return nullptr; + } int8_t num_components = 0; if (glsl_type == "float" || glsl_type == "double" || glsl_type == "int" || @@ -485,31 +629,36 @@ std::unique_ptr TypeParser::ParseGlslFormat( } else if (glsl_type.substr(0, 3) == "vec") { num_components = static_cast(strtol(glsl_type.c_str() + 3, nullptr, 10)); - if (num_components < 2) + if (num_components < 2) { return nullptr; + } } else if ((glsl_type[0] == 'd' || glsl_type[0] == 'i' || glsl_type[0] == 'u') && glsl_type.substr(1, 3) == "vec") { num_components = static_cast(strtol(glsl_type.c_str() + 4, nullptr, 10)); - if (num_components < 2) + if (num_components < 2) { return nullptr; + } } - if (num_components > 4) + if (num_components > 4) { return nullptr; + } std::string new_name = ""; static const char* prefix = "RGBA"; - for (int8_t i = 0; i < num_components; ++i) + for (int8_t i = 0; i < num_components; ++i) { new_name += prefix[i] + std::to_string(bits); + } new_name += "_"; - if (mode == FormatMode::kSInt) + if (mode == FormatMode::kSInt) { new_name += "SINT"; - else if (mode == FormatMode::kUInt) + } else if (mode == FormatMode::kUInt) { new_name += "UINT"; - else if (mode == FormatMode::kSFloat) + } else if (mode == FormatMode::kSFloat) { new_name += "SFLOAT"; + } return Parse(new_name); } diff --git a/src/verifier.cc b/src/verifier.cc index 18d60c837..14120c1a7 100644 --- a/src/verifier.cc +++ b/src/verifier.cc @@ -52,8 +52,9 @@ void CopyBitsOfMemoryToBuffer(uint8_t* dst, } data >>= src_bit_offset; - if (bits != 64) + if (bits != 64) { data &= (1ULL << bits) - 1ULL; + } std::memcpy(dst, &data, static_cast((bits + 7) / kBitsPerByte)); } @@ -61,8 +62,9 @@ void CopyBitsOfMemoryToBuffer(uint8_t* dst, // This is based on "18.3. sRGB transfer functions" of // https://www.khronos.org/registry/DataFormat/specs/1.2/dataformat.1.2.html double SRGBToLinearValue(double sRGB) { - if (sRGB <= 0.04045) + if (sRGB <= 0.04045) { return sRGB / 12.92; + } return pow((sRGB + 0.055) / 1.055, 2.4); } @@ -139,24 +141,28 @@ Result CheckActualValue(const ProbeSSBOCommand* command, } break; case ProbeSSBOCommand::Comparator::kLess: - if (actual_value >= val) + if (actual_value >= val) { return Result(std::to_string(actual_value) + " < " + std::to_string(val)); + } break; case ProbeSSBOCommand::Comparator::kLessOrEqual: - if (actual_value > val) + if (actual_value > val) { return Result(std::to_string(actual_value) + " <= " + std::to_string(val)); + } break; case ProbeSSBOCommand::Comparator::kGreater: - if (actual_value <= val) + if (actual_value <= val) { return Result(std::to_string(actual_value) + " > " + std::to_string(val)); + } break; case ProbeSSBOCommand::Comparator::kGreaterOrEqual: - if (actual_value < val) + if (actual_value < val) { return Result(std::to_string(actual_value) + " >= " + std::to_string(val)); + } break; } return {}; @@ -285,8 +291,9 @@ void ScaleTexelValuesIfNeeded(std::vector* texel, const Format* fmt) { for (size_t i = 0; i < fmt->GetSegments().size(); ++i) { const auto& seg = fmt->GetSegments()[i]; - if (seg.IsPadding()) + if (seg.IsPadding()) { continue; + } double scaled_value = (*texel)[i]; if (seg.GetFormatMode() == FormatMode::kUNorm) { @@ -295,8 +302,9 @@ void ScaleTexelValuesIfNeeded(std::vector* texel, const Format* fmt) { scaled_value /= static_cast((1 << (seg.GetNumBits() - 1)) - 1); } else if (seg.GetFormatMode() == FormatMode::kSRGB) { scaled_value /= static_cast((1 << seg.GetNumBits()) - 1); - if (seg.GetName() != FormatComponentType::kA) + if (seg.GetName() != FormatComponentType::kA) { scaled_value = SRGBToLinearValue(scaled_value); + } } else if (seg.GetFormatMode() == FormatMode::kSScaled || seg.GetFormatMode() == FormatMode::kUScaled) { assert(false && "UScaled and SScaled are not implemented"); @@ -318,8 +326,9 @@ bool IsTexelEqualToExpected(const std::vector& texel, const bool* is_tolerance_percent) { for (size_t i = 0; i < fmt->GetSegments().size(); ++i) { const auto& seg = fmt->GetSegments()[i]; - if (seg.IsPadding()) + if (seg.IsPadding()) { continue; + } double texel_for_component = texel[i]; double expected = 0; @@ -327,8 +336,9 @@ bool IsTexelEqualToExpected(const std::vector& texel, bool is_current_tolerance_percent = false; switch (seg.GetName()) { case FormatComponentType::kA: - if (!command->IsRGBA()) + if (!command->IsRGBA()) { continue; + } expected = static_cast(command->GetA()); current_tolerance = tolerance[3]; @@ -367,8 +377,9 @@ std::vector GetTexelInRGBA(const std::vector& texel, std::vector texel_in_rgba(texel.size()); for (size_t i = 0; i < fmt->GetSegments().size(); ++i) { const auto& seg = fmt->GetSegments()[i]; - if (seg.IsPadding()) + if (seg.IsPadding()) { continue; + } switch (seg.GetName()) { case FormatComponentType::kR: @@ -403,12 +414,15 @@ Result Verifier::Probe(const ProbeCommand* command, uint32_t frame_width, uint32_t frame_height, const void* buf) { - if (!command) + if (!command) { return Result("Verifier::Probe given ProbeCommand is nullptr"); - if (!fmt) + } + if (!fmt) { return Result("Verifier::Probe given texel's Format is nullptr"); - if (!buf) + } + if (!buf) { return Result("Verifier::Probe given buffer to probe is nullptr"); + } uint32_t x = 0; uint32_t y = 0; @@ -518,8 +532,9 @@ Result Verifier::ProbeSSBO(const ProbeSSBOCommand* command, const void* buffer) { const auto& values = command->GetValues(); if (!buffer) { - if (values.empty()) + if (values.empty()) { return {}; + } return Result( "Verifier::ProbeSSBO actual data is empty while expected " "data is not"); @@ -549,8 +564,9 @@ Result Verifier::ProbeSSBO(const ProbeSSBOCommand* command, const uint8_t* ptr = static_cast(buffer) + offset; for (size_t i = 0, k = 0; i < values.size(); ++i, ++k) { - if (k >= segments.size()) + if (k >= segments.size()) { k = 0; + } const auto& value = values[i]; auto segment = segments[k]; @@ -558,8 +574,9 @@ Result Verifier::ProbeSSBO(const ProbeSSBOCommand* command, while (segment.IsPadding()) { ptr += segment.PaddingBytes(); ++k; - if (k >= segments.size()) + if (k >= segments.size()) { k = 0; + } segment = segments[k]; } diff --git a/src/verifier_test.cc b/src/verifier_test.cc index d550e2900..e049bf3b8 100644 --- a/src/verifier_test.cc +++ b/src/verifier_test.cc @@ -37,8 +37,9 @@ class VerifierTest : public testing::Test { ~VerifierTest() override = default; const Format* GetColorFormat() { - if (color_frame_format_) + if (color_frame_format_) { return color_frame_format_.get(); + } TypeParser parser; color_frame_type_ = parser.Parse("B8G8R8A8_UNORM"); diff --git a/src/vkscript/command_parser.cc b/src/vkscript/command_parser.cc index 3429d4d5c..bf5f429ef 100644 --- a/src/vkscript/command_parser.cc +++ b/src/vkscript/command_parser.cc @@ -32,16 +32,21 @@ namespace vkscript { namespace { ShaderType ShaderNameToType(const std::string& name) { - if (name == "fragment") + if (name == "fragment") { return kShaderTypeFragment; - if (name == "compute") + } + if (name == "compute") { return kShaderTypeCompute; - if (name == "geometry") + } + if (name == "geometry") { return kShaderTypeGeometry; - if (name == "tessellation evaluation") + } + if (name == "tessellation evaluation") { return kShaderTypeTessellationEvaluation; - if (name == "tessellation control") + } + if (name == "tessellation control") { return kShaderTypeTessellationControl; + } return kShaderTypeVertex; } @@ -86,8 +91,9 @@ Result CommandParser::ParseBoolean(const std::string& str, bool* result) { Result CommandParser::Parse() { for (auto token = tokenizer_->NextToken(); !token->IsEOS(); token = tokenizer_->NextToken()) { - if (token->IsEOL()) + if (token->IsEOL()) { continue; + } if (!token->IsIdentifier()) { return Result(make_error( @@ -99,17 +105,19 @@ Result CommandParser::Parse() { Result r; if (cmd_name == "draw") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result(make_error("Invalid draw command in test: " + token->ToOriginalString())); + } cmd_name = token->AsString(); - if (cmd_name == "rect") + if (cmd_name == "rect") { r = ProcessDrawRect(); - else if (cmd_name == "arrays") + } else if (cmd_name == "arrays") { r = ProcessDrawArrays(); - else + } else { r = Result("Unknown draw command: " + cmd_name); + } } else if (cmd_name == "clear") { r = ProcessClear(); @@ -125,9 +133,10 @@ Result CommandParser::Parse() { r = ProcessTolerance(); } else if (cmd_name == "relative") { token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "probe") + if (!token->IsIdentifier() || token->AsString() != "probe") { return Result(make_error("relative must be used with probe: " + token->ToOriginalString())); + } r = ProcessProbe(true); } else if (cmd_name == "compute") { @@ -148,8 +157,9 @@ Result CommandParser::Parse() { } token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "entrypoint") + if (!token->IsIdentifier() || token->AsString() != "entrypoint") { return Result(make_error("Unknown command: " + shader_name)); + } r = ProcessEntryPoint(shader_name); @@ -244,8 +254,9 @@ Result CommandParser::Parse() { r = Result("Unknown command: " + cmd_name); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return Result(make_error(r.Error())); + } } return {}; @@ -264,8 +275,9 @@ Result CommandParser::ProcessDrawRect() { auto token = tokenizer_->NextToken(); while (token->IsIdentifier()) { std::string str = token->AsString(); - if (str != "ortho" && str != "patch") + if (str != "ortho" && str != "patch") { return Result("Unknown parameter to draw rect: " + str); + } if (str == "ortho") { cmd->EnableOrtho(); @@ -276,32 +288,37 @@ Result CommandParser::ProcessDrawRect() { } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetX(token->AsFloat()); token = tokenizer_->NextToken(); r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetY(token->AsFloat()); token = tokenizer_->NextToken(); r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetWidth(token->AsFloat()); token = tokenizer_->NextToken(); r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetHeight(token->AsFloat()); token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter to draw rect command: " + token->ToOriginalString()); + } commands_.push_back(std::move(cmd)); return {}; @@ -335,35 +352,40 @@ Result CommandParser::ProcessDrawArrays() { token = tokenizer_->NextToken(); } - if (cmd->GetTopology() == Topology::kUnknown) + if (cmd->GetTopology() == Topology::kUnknown) { return Result("Missing draw arrays topology"); + } - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Missing integer first vertex value for draw arrays: " + token->ToOriginalString()); + } cmd->SetFirstVertexIndex(token->AsUint32()); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Missing integer vertex count value for draw arrays: " + token->ToOriginalString()); + } cmd->SetVertexCount(token->AsUint32()); token = tokenizer_->NextToken(); if (instanced) { if (!token->IsEOL() && !token->IsEOS()) { - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Invalid instance count for draw arrays: " + token->ToOriginalString()); + } cmd->SetInstanceCount(token->AsUint32()); } token = tokenizer_->NextToken(); } - if (!token->IsEOL() && !token->IsEOS()) + if (!token->IsEOL() && !token->IsEOS()) { return Result("Extra parameter to draw arrays command: " + token->ToOriginalString()); + } commands_.push_back(std::move(cmd)); return {}; @@ -376,30 +398,35 @@ Result CommandParser::ProcessCompute() { auto token = tokenizer_->NextToken(); // Compute can start a compute line or an entryp oint line ... - if (token->IsIdentifier() && token->AsString() == "entrypoint") + if (token->IsIdentifier() && token->AsString() == "entrypoint") { return ProcessEntryPoint("compute"); + } - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Missing integer value for compute X entry: " + token->ToOriginalString()); + } cmd->SetX(token->AsUint32()); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Missing integer value for compute Y entry: " + token->ToOriginalString()); + } cmd->SetY(token->AsUint32()); token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Missing integer value for compute Z entry: " + token->ToOriginalString()); + } cmd->SetZ(token->AsUint32()); token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter to compute command: " + token->ToOriginalString()); + } commands_.push_back(std::move(cmd)); return {}; @@ -419,8 +446,9 @@ Result CommandParser::ProcessClear() { token = tokenizer_->NextToken(); Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->AsClearDepth()->SetValue(token->AsFloat()); } else if (str == "stencil") { @@ -428,12 +456,14 @@ Result CommandParser::ProcessClear() { cmd->SetLine(tokenizer_->GetCurrentLine()); token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("Missing stencil value for clear stencil command: " + token->ToOriginalString()); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("Invalid stencil value for clear stencil command: " + token->ToOriginalString()); + } cmd->AsClearStencil()->SetValue(token->AsUint32()); } else if (str == "color") { @@ -442,26 +472,30 @@ Result CommandParser::ProcessClear() { token = tokenizer_->NextToken(); Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->AsClearColor()->SetR(token->AsFloat()); token = tokenizer_->NextToken(); r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->AsClearColor()->SetG(token->AsFloat()); token = tokenizer_->NextToken(); r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->AsClearColor()->SetB(token->AsFloat()); token = tokenizer_->NextToken(); r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->AsClearColor()->SetA(token->AsFloat()); } else { return Result("Extra parameter to clear command: " + @@ -473,9 +507,10 @@ Result CommandParser::ProcessClear() { cmd = MakeUnique(pipeline_); cmd->SetLine(tokenizer_->GetCurrentLine()); } - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter to clear " + cmd_suffix + "command: " + token->ToOriginalString()); + } commands_.push_back(std::move(cmd)); return {}; @@ -498,8 +533,9 @@ Result CommandParser::ParseValues(const std::string& name, } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } v.SetDoubleValue(token->AsDouble()); } else { @@ -534,10 +570,12 @@ Result CommandParser::ProcessSSBO() { cmd->SetLine(tokenizer_->GetCurrentLine()); auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("Missing binding and size values for ssbo command"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("Invalid binding value for ssbo command"); + } uint32_t val = token->AsUint32(); @@ -549,8 +587,9 @@ Result CommandParser::ProcessSSBO() { auto substr = str.substr(1, str.size()); uint64_t binding_val = strtoul(substr.c_str(), nullptr, 10); - if (binding_val > std::numeric_limits::max()) + if (binding_val > std::numeric_limits::max()) { return Result("binding value too large in ssbo command"); + } cmd->SetBinding(static_cast(binding_val)); } else { @@ -585,14 +624,16 @@ Result CommandParser::ProcessSSBO() { cmd->SetIsSubdata(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Invalid type for ssbo command: " + token->ToOriginalString()); + } DatumTypeParser tp; auto type = tp.Parse(token->AsString()); - if (!type) + if (!type) { return Result("Invalid type provided: " + token->AsString()); + } auto fmt = MakeUnique(type.get()); auto* buf = cmd->GetBuffer(); @@ -623,20 +664,23 @@ Result CommandParser::ProcessSSBO() { std::vector values; Result r = ParseValues("ssbo", buf->GetFormat(), &values); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } buf->RecalculateMaxSizeInBytes(values, cmd->GetOffset()); cmd->SetValues(std::move(values)); } else { - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("Missing size value for ssbo command: " + token->ToOriginalString()); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("Invalid size value for ssbo command: " + token->ToOriginalString()); + } // Resize the buffer so we'll correctly create the descriptor sets. auto* buf = cmd->GetBuffer(); @@ -657,9 +701,10 @@ Result CommandParser::ProcessSSBO() { } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for ssbo command: " + token->ToOriginalString()); + } } commands_.push_back(std::move(cmd)); @@ -668,12 +713,14 @@ Result CommandParser::ProcessSSBO() { Result CommandParser::ProcessUniform() { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("Missing binding and size values for uniform command: " + token->ToOriginalString()); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Invalid type value for uniform command: " + token->ToOriginalString()); + } std::unique_ptr cmd; bool is_ubo = false; @@ -702,9 +749,10 @@ Result CommandParser::ProcessUniform() { auto substr = str.substr(1, str.size()); uint64_t binding_val = strtoul(substr.c_str(), nullptr, 10); - if (binding_val > std::numeric_limits::max()) + if (binding_val > std::numeric_limits::max()) { return Result("binding value too large in uniform ubo command: " + token->ToOriginalString()); + } cmd->SetBinding(static_cast(binding_val)); @@ -749,14 +797,16 @@ Result CommandParser::ProcessUniform() { DatumTypeParser tp; auto type = tp.Parse(token->AsString()); - if (!type) + if (!type) { return Result("Invalid type provided: " + token->AsString()); + } auto fmt = MakeUnique(type.get()); // uniform is always std140. - if (is_ubo) + if (is_ubo) { fmt->SetLayout(Format::Layout::kStd140); + } auto* buf = cmd->GetBuffer(); if (buf->FormatIsDefault() || !buf->GetFormat()) { @@ -778,22 +828,25 @@ Result CommandParser::ProcessUniform() { } auto buf_size = static_cast(buf->GetFormat()->SizeInBytes()); - if (token->AsInt32() % buf_size != 0) + if (token->AsInt32() % buf_size != 0) { return Result("offset for uniform must be multiple of data size"); + } cmd->SetOffset(token->AsUint32()); std::vector values; Result r = ParseValues("uniform", buf->GetFormat(), &values); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } buf->RecalculateMaxSizeInBytes(values, cmd->GetOffset()); - if (cmd->IsPushConstant()) + if (cmd->IsPushConstant()) { buf->SetData(values); - else + } else { cmd->SetValues(std::move(values)); + } commands_.push_back(std::move(cmd)); return {}; @@ -812,15 +865,17 @@ Result CommandParser::ProcessTolerance() { if (token->IsInteger() || token->IsDouble()) { Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } double value = token->AsDouble(); token = tokenizer_->NextToken(); if (token->IsIdentifier() && token->AsString() != ",") { - if (token->AsString() != "%") + if (token->AsString() != "%") { return Result("Invalid value for tolerance command: " + token->ToOriginalString()); + } current_tolerances_.push_back(Probe::Tolerance{true, value}); token = tokenizer_->NextToken(); @@ -834,14 +889,17 @@ Result CommandParser::ProcessTolerance() { ++found_tokens; } - if (found_tokens == 0) + if (found_tokens == 0) { return Result("Missing value for tolerance command"); - if (found_tokens != 1 && found_tokens != 4) + } + if (found_tokens != 1 && found_tokens != 4) { return Result("Invalid number of tolerance parameters provided"); + } - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for tolerance command: " + token->ToOriginalString()); + } return {}; } @@ -851,25 +909,29 @@ Result CommandParser::ProcessPatch() { cmd->SetLine(tokenizer_->GetCurrentLine()); auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "parameter") + if (!token->IsIdentifier() || token->AsString() != "parameter") { return Result("Missing parameter flag to patch command: " + token->ToOriginalString()); + } token = tokenizer_->NextToken(); - if (!token->IsIdentifier() || token->AsString() != "vertices") + if (!token->IsIdentifier() || token->AsString() != "vertices") { return Result("Missing vertices flag to patch command: " + token->ToOriginalString()); + } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Invalid count parameter for patch parameter vertices: " + token->ToOriginalString()); + } cmd->SetControlPointCount(token->AsUint32()); token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for patch parameter vertices command: " + token->ToOriginalString()); + } commands_.push_back(std::move(cmd)); return {}; @@ -880,20 +942,23 @@ Result CommandParser::ProcessEntryPoint(const std::string& name) { cmd->SetLine(tokenizer_->GetCurrentLine()); auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("Missing entrypoint name"); + } - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Entrypoint name must be a string: " + token->ToOriginalString()); + } cmd->SetShaderType(ShaderNameToType(name)); cmd->SetEntryPointName(token->AsString()); token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for entrypoint command: " + token->ToOriginalString()); + } commands_.push_back(std::move(cmd)); @@ -902,29 +967,34 @@ Result CommandParser::ProcessEntryPoint(const std::string& name) { Result CommandParser::ProcessProbe(bool relative) { auto token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Invalid token in probe command: " + token->ToOriginalString()); + } // The SSBO syntax is different from probe or probe all so handle specially. - if (token->AsString() == "ssbo") + if (token->AsString() == "ssbo") { return ProcessProbeSSBO(); + } - if (pipeline_->GetColorAttachments().empty()) + if (pipeline_->GetColorAttachments().empty()) { return Result("Pipeline missing color buffers. Something went wrong."); + } // VkScript has a single generated colour buffer which should always be // available. auto* buffer = pipeline_->GetColorAttachments()[0].buffer; - if (!buffer) + if (!buffer) { return Result("Pipeline missing color buffers, something went wrong."); + } auto cmd = MakeUnique(buffer); cmd->SetLine(tokenizer_->GetCurrentLine()); cmd->SetTolerances(current_tolerances_); - if (relative) + if (relative) { cmd->SetRelative(); + } bool is_rect = false; if (token->AsString() == "rect") { @@ -932,26 +1002,30 @@ Result CommandParser::ProcessProbe(bool relative) { cmd->SetProbeRect(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Invalid token in probe command: " + token->ToOriginalString()); + } } else if (token->AsString() == "all") { cmd->SetWholeWindow(); cmd->SetProbeRect(); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Invalid token in probe command: " + token->ToOriginalString()); + } } std::string format = token->AsString(); - if (format != "rgba" && format != "rgb") + if (format != "rgba" && format != "rgb") { return Result("Invalid format specified to probe command: " + token->ToOriginalString()); + } - if (format == "rgba") + if (format == "rgba") { cmd->SetIsRGBA(); + } token = tokenizer_->NextToken(); if (!cmd->IsWholeWindow()) { @@ -962,44 +1036,52 @@ Result CommandParser::ProcessProbe(bool relative) { } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetX(token->AsFloat()); token = tokenizer_->NextToken(); - if (token->IsComma()) + if (token->IsComma()) { token = tokenizer_->NextToken(); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetY(token->AsFloat()); if (is_rect) { token = tokenizer_->NextToken(); - if (token->IsComma()) + if (token->IsComma()) { token = tokenizer_->NextToken(); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetWidth(token->AsFloat()); token = tokenizer_->NextToken(); - if (token->IsComma()) + if (token->IsComma()) { token = tokenizer_->NextToken(); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetHeight(token->AsFloat()); } token = tokenizer_->NextToken(); if (token->IsCloseBracket()) { // Close bracket without an open - if (!got_rect_open_bracket) + if (!got_rect_open_bracket) { return Result("Missing open bracket for probe command"); + } token = tokenizer_->NextToken(); } else if (got_rect_open_bracket) { @@ -1015,36 +1097,43 @@ Result CommandParser::ProcessProbe(bool relative) { } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetR(token->AsFloat()); token = tokenizer_->NextToken(); - if (token->IsComma()) + if (token->IsComma()) { token = tokenizer_->NextToken(); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetG(token->AsFloat()); token = tokenizer_->NextToken(); - if (token->IsComma()) + if (token->IsComma()) { token = tokenizer_->NextToken(); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetB(token->AsFloat()); if (format == "rgba") { token = tokenizer_->NextToken(); - if (token->IsComma()) + if (token->IsComma()) { token = tokenizer_->NextToken(); + } r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetA(token->AsFloat()); } @@ -1060,9 +1149,10 @@ Result CommandParser::ProcessProbe(bool relative) { return Result("Missing close bracket for probe command"); } - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter to probe command: " + token->ToOriginalString()); + } commands_.push_back(std::move(cmd)); return {}; @@ -1070,45 +1160,49 @@ Result CommandParser::ProcessProbe(bool relative) { Result CommandParser::ProcessTopology() { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("Missing value for topology command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Invalid value for topology command: " + token->ToOriginalString()); + } Topology topology = Topology::kPatchList; std::string topo = token->AsString(); - if (topo == "VK_PRIMITIVE_TOPOLOGY_PATCH_LIST") + if (topo == "VK_PRIMITIVE_TOPOLOGY_PATCH_LIST") { topology = Topology::kPatchList; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_POINT_LIST") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_POINT_LIST") { topology = Topology::kPointList; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_LINE_LIST") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_LINE_LIST") { topology = Topology::kLineList; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY") { topology = Topology::kLineListWithAdjacency; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_LINE_STRIP") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_LINE_STRIP") { topology = Topology::kLineStrip; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY") { topology = Topology::kLineStripWithAdjacency; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN") { topology = Topology::kTriangleFan; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST") { topology = Topology::kTriangleList; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY") { topology = Topology::kTriangleListWithAdjacency; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP") { topology = Topology::kTriangleStrip; - else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY") + } else if (topo == "VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY") { topology = Topology::kTriangleStripWithAdjacency; - else + } else { return Result("Unknown value for topology command: " + token->ToOriginalString()); + } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for topology command: " + token->ToOriginalString()); + } pipeline_data_.SetTopology(topology); return {}; @@ -1116,28 +1210,32 @@ Result CommandParser::ProcessTopology() { Result CommandParser::ProcessPolygonMode() { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("Missing value for polygonMode command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Invalid value for polygonMode command: " + token->ToOriginalString()); + } PolygonMode mode = PolygonMode::kFill; std::string m = token->AsString(); - if (m == "VK_POLYGON_MODE_FILL") + if (m == "VK_POLYGON_MODE_FILL") { mode = PolygonMode::kFill; - else if (m == "VK_POLYGON_MODE_LINE") + } else if (m == "VK_POLYGON_MODE_LINE") { mode = PolygonMode::kLine; - else if (m == "VK_POLYGON_MODE_POINT") + } else if (m == "VK_POLYGON_MODE_POINT") { mode = PolygonMode::kPoint; - else + } else { return Result("Unknown value for polygonMode command: " + token->ToOriginalString()); + } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for polygonMode command: " + token->ToOriginalString()); + } pipeline_data_.SetPolygonMode(mode); return {}; @@ -1145,54 +1243,58 @@ Result CommandParser::ProcessPolygonMode() { Result CommandParser::ProcessLogicOp() { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("Missing value for logicOp command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Invalid value for logicOp command: " + token->ToOriginalString()); + } LogicOp op = LogicOp::kClear; std::string name = token->AsString(); - if (name == "VK_LOGIC_OP_CLEAR") + if (name == "VK_LOGIC_OP_CLEAR") { op = LogicOp::kClear; - else if (name == "VK_LOGIC_OP_AND") + } else if (name == "VK_LOGIC_OP_AND") { op = LogicOp::kAnd; - else if (name == "VK_LOGIC_OP_AND_REVERSE") + } else if (name == "VK_LOGIC_OP_AND_REVERSE") { op = LogicOp::kAndReverse; - else if (name == "VK_LOGIC_OP_COPY") + } else if (name == "VK_LOGIC_OP_COPY") { op = LogicOp::kCopy; - else if (name == "VK_LOGIC_OP_AND_INVERTED") + } else if (name == "VK_LOGIC_OP_AND_INVERTED") { op = LogicOp::kAndInverted; - else if (name == "VK_LOGIC_OP_NO_OP") + } else if (name == "VK_LOGIC_OP_NO_OP") { op = LogicOp::kNoOp; - else if (name == "VK_LOGIC_OP_XOR") + } else if (name == "VK_LOGIC_OP_XOR") { op = LogicOp::kXor; - else if (name == "VK_LOGIC_OP_OR") + } else if (name == "VK_LOGIC_OP_OR") { op = LogicOp::kOr; - else if (name == "VK_LOGIC_OP_NOR") + } else if (name == "VK_LOGIC_OP_NOR") { op = LogicOp::kNor; - else if (name == "VK_LOGIC_OP_EQUIVALENT") + } else if (name == "VK_LOGIC_OP_EQUIVALENT") { op = LogicOp::kEquivalent; - else if (name == "VK_LOGIC_OP_INVERT") + } else if (name == "VK_LOGIC_OP_INVERT") { op = LogicOp::kInvert; - else if (name == "VK_LOGIC_OP_OR_REVERSE") + } else if (name == "VK_LOGIC_OP_OR_REVERSE") { op = LogicOp::kOrReverse; - else if (name == "VK_LOGIC_OP_COPY_INVERTED") + } else if (name == "VK_LOGIC_OP_COPY_INVERTED") { op = LogicOp::kCopyInverted; - else if (name == "VK_LOGIC_OP_OR_INVERTED") + } else if (name == "VK_LOGIC_OP_OR_INVERTED") { op = LogicOp::kOrInverted; - else if (name == "VK_LOGIC_OP_NAND") + } else if (name == "VK_LOGIC_OP_NAND") { op = LogicOp::kNand; - else if (name == "VK_LOGIC_OP_SET") + } else if (name == "VK_LOGIC_OP_SET") { op = LogicOp::kSet; - else + } else { return Result("Unknown value for logicOp command: " + token->ToOriginalString()); + } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for logicOp command: " + token->ToOriginalString()); + } pipeline_data_.SetLogicOp(op); return {}; @@ -1200,11 +1302,13 @@ Result CommandParser::ProcessLogicOp() { Result CommandParser::ProcessCullMode() { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("Missing value for cullMode command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Invalid value for cullMode command: " + token->ToOriginalString()); + } CullMode mode = CullMode::kNone; while (!token->IsEOS() && !token->IsEOL()) { @@ -1213,15 +1317,17 @@ Result CommandParser::ProcessCullMode() { if (name == "|") { // We treat everything as an |. } else if (name == "VK_CULL_MODE_FRONT_BIT") { - if (mode == CullMode::kNone) + if (mode == CullMode::kNone) { mode = CullMode::kFront; - else if (mode == CullMode::kBack) + } else if (mode == CullMode::kBack) { mode = CullMode::kFrontAndBack; + } } else if (name == "VK_CULL_MODE_BACK_BIT") { - if (mode == CullMode::kNone) + if (mode == CullMode::kNone) { mode = CullMode::kBack; - else if (mode == CullMode::kFront) + } else if (mode == CullMode::kFront) { mode = CullMode::kFrontAndBack; + } } else if (name == "VK_CULL_MODE_FRONT_AND_BACK") { mode = CullMode::kFrontAndBack; } else if (name == "VK_CULL_MODE_NONE") { @@ -1240,26 +1346,30 @@ Result CommandParser::ProcessCullMode() { Result CommandParser::ProcessFrontFace() { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("Missing value for frontFace command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Invalid value for frontFace command: " + token->ToOriginalString()); + } FrontFace face = FrontFace::kCounterClockwise; std::string f = token->AsString(); - if (f == "VK_FRONT_FACE_COUNTER_CLOCKWISE") + if (f == "VK_FRONT_FACE_COUNTER_CLOCKWISE") { face = FrontFace::kCounterClockwise; - else if (f == "VK_FRONT_FACE_CLOCKWISE") + } else if (f == "VK_FRONT_FACE_CLOCKWISE") { face = FrontFace::kClockwise; - else + } else { return Result("Unknown value for frontFace command: " + token->ToOriginalString()); + } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for frontFace command: " + token->ToOriginalString()); + } pipeline_data_.SetFrontFace(face); return {}; @@ -1268,20 +1378,24 @@ Result CommandParser::ProcessFrontFace() { Result CommandParser::ProcessBooleanPipelineData(const std::string& name, bool* value) { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("Missing value for " + name + " command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Invalid value for " + name + " command: " + token->ToOriginalString()); + } Result r = ParseBoolean(token->AsString(), value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for " + name + " command: " + token->ToOriginalString()); + } return {}; } @@ -1289,8 +1403,9 @@ Result CommandParser::ProcessBooleanPipelineData(const std::string& name, Result CommandParser::ProcessPrimitiveRestartEnable() { bool value = false; Result r = ProcessBooleanPipelineData("primitiveRestartEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnablePrimitiveRestart(value); return {}; @@ -1299,8 +1414,9 @@ Result CommandParser::ProcessPrimitiveRestartEnable() { Result CommandParser::ProcessDepthClampEnable() { bool value = false; Result r = ProcessBooleanPipelineData("depthClampEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnableDepthClamp(value); return {}; @@ -1309,8 +1425,9 @@ Result CommandParser::ProcessDepthClampEnable() { Result CommandParser::ProcessRasterizerDiscardEnable() { bool value = false; Result r = ProcessBooleanPipelineData("rasterizerDiscardEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnableRasterizerDiscard(value); return {}; @@ -1319,8 +1436,9 @@ Result CommandParser::ProcessRasterizerDiscardEnable() { Result CommandParser::ProcessDepthBiasEnable() { bool value = false; Result r = ProcessBooleanPipelineData("depthBiasEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnableDepthBias(value); return {}; @@ -1329,8 +1447,9 @@ Result CommandParser::ProcessDepthBiasEnable() { Result CommandParser::ProcessLogicOpEnable() { bool value = false; Result r = ProcessBooleanPipelineData("logicOpEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnableLogicOp(value); return {}; @@ -1339,8 +1458,9 @@ Result CommandParser::ProcessLogicOpEnable() { Result CommandParser::ProcessBlendEnable() { bool value = false; Result r = ProcessBooleanPipelineData("blendEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnableBlend(value); return {}; @@ -1349,8 +1469,9 @@ Result CommandParser::ProcessBlendEnable() { Result CommandParser::ProcessDepthTestEnable() { bool value = false; Result r = ProcessBooleanPipelineData("depthTestEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnableDepthTest(value); return {}; @@ -1359,8 +1480,9 @@ Result CommandParser::ProcessDepthTestEnable() { Result CommandParser::ProcessDepthWriteEnable() { bool value = false; Result r = ProcessBooleanPipelineData("depthWriteEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnableDepthWrite(value); return {}; @@ -1369,8 +1491,9 @@ Result CommandParser::ProcessDepthWriteEnable() { Result CommandParser::ProcessDepthBoundsTestEnable() { bool value = false; Result r = ProcessBooleanPipelineData("depthBoundsTestEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnableDepthBoundsTest(value); return {}; @@ -1379,8 +1502,9 @@ Result CommandParser::ProcessDepthBoundsTestEnable() { Result CommandParser::ProcessStencilTestEnable() { bool value = false; Result r = ProcessBooleanPipelineData("stencilTestEnable", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetEnableStencilTest(value); return {}; @@ -1391,19 +1515,22 @@ Result CommandParser::ProcessFloatPipelineData(const std::string& name, assert(value); auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("Missing value for " + name + " command"); + } Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } *value = token->AsFloat(); token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for " + name + " command: " + token->ToOriginalString()); + } return {}; } @@ -1411,8 +1538,9 @@ Result CommandParser::ProcessFloatPipelineData(const std::string& name, Result CommandParser::ProcessDepthBiasConstantFactor() { float value = 0.0; Result r = ProcessFloatPipelineData("depthBiasConstantFactor", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetDepthBiasConstantFactor(value); return {}; @@ -1421,8 +1549,9 @@ Result CommandParser::ProcessDepthBiasConstantFactor() { Result CommandParser::ProcessDepthBiasClamp() { float value = 0.0; Result r = ProcessFloatPipelineData("depthBiasClamp", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetDepthBiasClamp(value); return {}; @@ -1431,8 +1560,9 @@ Result CommandParser::ProcessDepthBiasClamp() { Result CommandParser::ProcessDepthBiasSlopeFactor() { float value = 0.0; Result r = ProcessFloatPipelineData("depthBiasSlopeFactor", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetDepthBiasSlopeFactor(value); return {}; @@ -1441,8 +1571,9 @@ Result CommandParser::ProcessDepthBiasSlopeFactor() { Result CommandParser::ProcessLineWidth() { float value = 0.0; Result r = ProcessFloatPipelineData("lineWidth", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetLineWidth(value); return {}; @@ -1451,8 +1582,9 @@ Result CommandParser::ProcessLineWidth() { Result CommandParser::ProcessMinDepthBounds() { float value = 0.0; Result r = ProcessFloatPipelineData("minDepthBounds", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetMinDepthBounds(value); return {}; @@ -1461,8 +1593,9 @@ Result CommandParser::ProcessMinDepthBounds() { Result CommandParser::ProcessMaxDepthBounds() { float value = 0.0; Result r = ProcessFloatPipelineData("maxDepthBounds", &value); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetMaxDepthBounds(value); return {}; @@ -1472,46 +1605,47 @@ Result CommandParser::ParseBlendFactorName(const std::string& name, BlendFactor* factor) { assert(factor); - if (name == "VK_BLEND_FACTOR_ZERO") + if (name == "VK_BLEND_FACTOR_ZERO") { *factor = BlendFactor::kZero; - else if (name == "VK_BLEND_FACTOR_ONE") + } else if (name == "VK_BLEND_FACTOR_ONE") { *factor = BlendFactor::kOne; - else if (name == "VK_BLEND_FACTOR_SRC_COLOR") + } else if (name == "VK_BLEND_FACTOR_SRC_COLOR") { *factor = BlendFactor::kSrcColor; - else if (name == "VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR") + } else if (name == "VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR") { *factor = BlendFactor::kOneMinusSrcColor; - else if (name == "VK_BLEND_FACTOR_DST_COLOR") + } else if (name == "VK_BLEND_FACTOR_DST_COLOR") { *factor = BlendFactor::kDstColor; - else if (name == "VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR") + } else if (name == "VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR") { *factor = BlendFactor::kOneMinusDstColor; - else if (name == "VK_BLEND_FACTOR_SRC_ALPHA") + } else if (name == "VK_BLEND_FACTOR_SRC_ALPHA") { *factor = BlendFactor::kSrcAlpha; - else if (name == "VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA") + } else if (name == "VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA") { *factor = BlendFactor::kOneMinusSrcAlpha; - else if (name == "VK_BLEND_FACTOR_DST_ALPHA") + } else if (name == "VK_BLEND_FACTOR_DST_ALPHA") { *factor = BlendFactor::kDstAlpha; - else if (name == "VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA") + } else if (name == "VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA") { *factor = BlendFactor::kOneMinusDstAlpha; - else if (name == "VK_BLEND_FACTOR_CONSTANT_COLOR") + } else if (name == "VK_BLEND_FACTOR_CONSTANT_COLOR") { *factor = BlendFactor::kConstantColor; - else if (name == "VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR") + } else if (name == "VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR") { *factor = BlendFactor::kOneMinusConstantColor; - else if (name == "VK_BLEND_FACTOR_CONSTANT_ALPHA") + } else if (name == "VK_BLEND_FACTOR_CONSTANT_ALPHA") { *factor = BlendFactor::kConstantAlpha; - else if (name == "VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA") + } else if (name == "VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA") { *factor = BlendFactor::kOneMinusConstantAlpha; - else if (name == "VK_BLEND_FACTOR_SRC_ALPHA_SATURATE") + } else if (name == "VK_BLEND_FACTOR_SRC_ALPHA_SATURATE") { *factor = BlendFactor::kSrcAlphaSaturate; - else if (name == "VK_BLEND_FACTOR_SRC1_COLOR") + } else if (name == "VK_BLEND_FACTOR_SRC1_COLOR") { *factor = BlendFactor::kSrc1Color; - else if (name == "VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR") + } else if (name == "VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR") { *factor = BlendFactor::kOneMinusSrc1Color; - else if (name == "VK_BLEND_FACTOR_SRC1_ALPHA") + } else if (name == "VK_BLEND_FACTOR_SRC1_ALPHA") { *factor = BlendFactor::kSrc1Alpha; - else if (name == "VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA") + } else if (name == "VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA") { *factor = BlendFactor::kOneMinusSrc1Alpha; - else + } else { return Result("Unknown BlendFactor provided: " + name); + } return {}; } @@ -1519,20 +1653,24 @@ Result CommandParser::ParseBlendFactorName(const std::string& name, Result CommandParser::ParseBlendFactor(const std::string& name, BlendFactor* factor) { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result(std::string("Missing parameter for ") + name + " command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result(std::string("Invalid parameter for ") + name + " command: " + token->ToOriginalString()); + } Result r = ParseBlendFactorName(token->AsString(), factor); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result(std::string("Extra parameter for ") + name + " command: " + token->ToOriginalString()); + } return {}; } @@ -1540,8 +1678,9 @@ Result CommandParser::ParseBlendFactor(const std::string& name, Result CommandParser::ProcessSrcAlphaBlendFactor() { BlendFactor factor = BlendFactor::kZero; Result r = ParseBlendFactor("srcAlphaBlendFactor", &factor); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetSrcAlphaBlendFactor(factor); return {}; @@ -1550,8 +1689,9 @@ Result CommandParser::ProcessSrcAlphaBlendFactor() { Result CommandParser::ProcessDstAlphaBlendFactor() { BlendFactor factor = BlendFactor::kZero; Result r = ParseBlendFactor("dstAlphaBlendFactor", &factor); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetDstAlphaBlendFactor(factor); return {}; @@ -1560,8 +1700,9 @@ Result CommandParser::ProcessDstAlphaBlendFactor() { Result CommandParser::ProcessSrcColorBlendFactor() { BlendFactor factor = BlendFactor::kZero; Result r = ParseBlendFactor("srcColorBlendFactor", &factor); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetSrcColorBlendFactor(factor); return {}; @@ -1570,8 +1711,9 @@ Result CommandParser::ProcessSrcColorBlendFactor() { Result CommandParser::ProcessDstColorBlendFactor() { BlendFactor factor = BlendFactor::kZero; Result r = ParseBlendFactor("dstColorBlendFactor", &factor); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetDstColorBlendFactor(factor); return {}; @@ -1580,132 +1722,137 @@ Result CommandParser::ProcessDstColorBlendFactor() { Result CommandParser::ParseBlendOpName(const std::string& name, BlendOp* op) { assert(op); - if (name == "VK_BLEND_OP_ADD") + if (name == "VK_BLEND_OP_ADD") { *op = BlendOp::kAdd; - else if (name == "VK_BLEND_OP_ADD") + } else if (name == "VK_BLEND_OP_ADD") { *op = BlendOp::kAdd; - else if (name == "VK_BLEND_OP_SUBTRACT") + } else if (name == "VK_BLEND_OP_SUBTRACT") { *op = BlendOp::kSubtract; - else if (name == "VK_BLEND_OP_REVERSE_SUBTRACT") + } else if (name == "VK_BLEND_OP_REVERSE_SUBTRACT") { *op = BlendOp::kReverseSubtract; - else if (name == "VK_BLEND_OP_MIN") + } else if (name == "VK_BLEND_OP_MIN") { *op = BlendOp::kMin; - else if (name == "VK_BLEND_OP_MAX") + } else if (name == "VK_BLEND_OP_MAX") { *op = BlendOp::kMax; - else if (name == "VK_BLEND_OP_ZERO_EXT") + } else if (name == "VK_BLEND_OP_ZERO_EXT") { *op = BlendOp::kZero; - else if (name == "VK_BLEND_OP_SRC_EXT") + } else if (name == "VK_BLEND_OP_SRC_EXT") { *op = BlendOp::kSrc; - else if (name == "VK_BLEND_OP_DST_EXT") + } else if (name == "VK_BLEND_OP_DST_EXT") { *op = BlendOp::kDst; - else if (name == "VK_BLEND_OP_SRC_OVER_EXT") + } else if (name == "VK_BLEND_OP_SRC_OVER_EXT") { *op = BlendOp::kSrcOver; - else if (name == "VK_BLEND_OP_DST_OVER_EXT") + } else if (name == "VK_BLEND_OP_DST_OVER_EXT") { *op = BlendOp::kDstOver; - else if (name == "VK_BLEND_OP_SRC_IN_EXT") + } else if (name == "VK_BLEND_OP_SRC_IN_EXT") { *op = BlendOp::kSrcIn; - else if (name == "VK_BLEND_OP_DST_IN_EXT") + } else if (name == "VK_BLEND_OP_DST_IN_EXT") { *op = BlendOp::kDstIn; - else if (name == "VK_BLEND_OP_SRC_OUT_EXT") + } else if (name == "VK_BLEND_OP_SRC_OUT_EXT") { *op = BlendOp::kSrcOut; - else if (name == "VK_BLEND_OP_DST_OUT_EXT") + } else if (name == "VK_BLEND_OP_DST_OUT_EXT") { *op = BlendOp::kDstOut; - else if (name == "VK_BLEND_OP_SRC_ATOP_EXT") + } else if (name == "VK_BLEND_OP_SRC_ATOP_EXT") { *op = BlendOp::kSrcAtop; - else if (name == "VK_BLEND_OP_DST_ATOP_EXT") + } else if (name == "VK_BLEND_OP_DST_ATOP_EXT") { *op = BlendOp::kDstAtop; - else if (name == "VK_BLEND_OP_XOR_EXT") + } else if (name == "VK_BLEND_OP_XOR_EXT") { *op = BlendOp::kXor; - else if (name == "VK_BLEND_OP_MULTIPLY_EXT") + } else if (name == "VK_BLEND_OP_MULTIPLY_EXT") { *op = BlendOp::kMultiply; - else if (name == "VK_BLEND_OP_SCREEN_EXT") + } else if (name == "VK_BLEND_OP_SCREEN_EXT") { *op = BlendOp::kScreen; - else if (name == "VK_BLEND_OP_OVERLAY_EXT") + } else if (name == "VK_BLEND_OP_OVERLAY_EXT") { *op = BlendOp::kOverlay; - else if (name == "VK_BLEND_OP_DARKEN_EXT") + } else if (name == "VK_BLEND_OP_DARKEN_EXT") { *op = BlendOp::kDarken; - else if (name == "VK_BLEND_OP_LIGHTEN_EXT") + } else if (name == "VK_BLEND_OP_LIGHTEN_EXT") { *op = BlendOp::kLighten; - else if (name == "VK_BLEND_OP_COLORDODGE_EXT") + } else if (name == "VK_BLEND_OP_COLORDODGE_EXT") { *op = BlendOp::kColorDodge; - else if (name == "VK_BLEND_OP_COLORBURN_EXT") + } else if (name == "VK_BLEND_OP_COLORBURN_EXT") { *op = BlendOp::kColorBurn; - else if (name == "VK_BLEND_OP_HARDLIGHT_EXT") + } else if (name == "VK_BLEND_OP_HARDLIGHT_EXT") { *op = BlendOp::kHardLight; - else if (name == "VK_BLEND_OP_SOFTLIGHT_EXT") + } else if (name == "VK_BLEND_OP_SOFTLIGHT_EXT") { *op = BlendOp::kSoftLight; - else if (name == "VK_BLEND_OP_DIFFERENCE_EXT") + } else if (name == "VK_BLEND_OP_DIFFERENCE_EXT") { *op = BlendOp::kDifference; - else if (name == "VK_BLEND_OP_EXCLUSION_EXT") + } else if (name == "VK_BLEND_OP_EXCLUSION_EXT") { *op = BlendOp::kExclusion; - else if (name == "VK_BLEND_OP_INVERT_EXT") + } else if (name == "VK_BLEND_OP_INVERT_EXT") { *op = BlendOp::kInvert; - else if (name == "VK_BLEND_OP_INVERT_RGB_EXT") + } else if (name == "VK_BLEND_OP_INVERT_RGB_EXT") { *op = BlendOp::kInvertRGB; - else if (name == "VK_BLEND_OP_LINEARDODGE_EXT") + } else if (name == "VK_BLEND_OP_LINEARDODGE_EXT") { *op = BlendOp::kLinearDodge; - else if (name == "VK_BLEND_OP_LINEARBURN_EXT") + } else if (name == "VK_BLEND_OP_LINEARBURN_EXT") { *op = BlendOp::kLinearBurn; - else if (name == "VK_BLEND_OP_VIVIDLIGHT_EXT") + } else if (name == "VK_BLEND_OP_VIVIDLIGHT_EXT") { *op = BlendOp::kVividLight; - else if (name == "VK_BLEND_OP_LINEARLIGHT_EXT") + } else if (name == "VK_BLEND_OP_LINEARLIGHT_EXT") { *op = BlendOp::kLinearLight; - else if (name == "VK_BLEND_OP_PINLIGHT_EXT") + } else if (name == "VK_BLEND_OP_PINLIGHT_EXT") { *op = BlendOp::kPinLight; - else if (name == "VK_BLEND_OP_HARDMIX_EXT") + } else if (name == "VK_BLEND_OP_HARDMIX_EXT") { *op = BlendOp::kHardMix; - else if (name == "VK_BLEND_OP_HSL_HUE_EXT") + } else if (name == "VK_BLEND_OP_HSL_HUE_EXT") { *op = BlendOp::kHslHue; - else if (name == "VK_BLEND_OP_HSL_SATURATION_EXT") + } else if (name == "VK_BLEND_OP_HSL_SATURATION_EXT") { *op = BlendOp::kHslSaturation; - else if (name == "VK_BLEND_OP_HSL_COLOR_EXT") + } else if (name == "VK_BLEND_OP_HSL_COLOR_EXT") { *op = BlendOp::kHslColor; - else if (name == "VK_BLEND_OP_HSL_LUMINOSITY_EXT") + } else if (name == "VK_BLEND_OP_HSL_LUMINOSITY_EXT") { *op = BlendOp::kHslLuminosity; - else if (name == "VK_BLEND_OP_PLUS_EXT") + } else if (name == "VK_BLEND_OP_PLUS_EXT") { *op = BlendOp::kPlus; - else if (name == "VK_BLEND_OP_PLUS_CLAMPED_EXT") + } else if (name == "VK_BLEND_OP_PLUS_CLAMPED_EXT") { *op = BlendOp::kPlusClamped; - else if (name == "VK_BLEND_OP_PLUS_CLAMPED_ALPHA_EXT") + } else if (name == "VK_BLEND_OP_PLUS_CLAMPED_ALPHA_EXT") { *op = BlendOp::kPlusClampedAlpha; - else if (name == "VK_BLEND_OP_PLUS_DARKER_EXT") + } else if (name == "VK_BLEND_OP_PLUS_DARKER_EXT") { *op = BlendOp::kPlusDarker; - else if (name == "VK_BLEND_OP_MINUS_EXT") + } else if (name == "VK_BLEND_OP_MINUS_EXT") { *op = BlendOp::kMinus; - else if (name == "VK_BLEND_OP_MINUS_CLAMPED_EXT") + } else if (name == "VK_BLEND_OP_MINUS_CLAMPED_EXT") { *op = BlendOp::kMinusClamped; - else if (name == "VK_BLEND_OP_CONTRAST_EXT") + } else if (name == "VK_BLEND_OP_CONTRAST_EXT") { *op = BlendOp::kContrast; - else if (name == "VK_BLEND_OP_INVERT_OVG_EXT") + } else if (name == "VK_BLEND_OP_INVERT_OVG_EXT") { *op = BlendOp::kInvertOvg; - else if (name == "VK_BLEND_OP_RED_EXT") + } else if (name == "VK_BLEND_OP_RED_EXT") { *op = BlendOp::kRed; - else if (name == "VK_BLEND_OP_GREEN_EXT") + } else if (name == "VK_BLEND_OP_GREEN_EXT") { *op = BlendOp::kGreen; - else if (name == "VK_BLEND_OP_BLUE_EXT") + } else if (name == "VK_BLEND_OP_BLUE_EXT") { *op = BlendOp::kBlue; - else + } else { return Result("Unknown BlendOp provided: " + name); + } return {}; } Result CommandParser::ParseBlendOp(const std::string& name, BlendOp* op) { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result(std::string("Missing parameter for ") + name + " command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result(std::string("Invalid parameter for ") + name + " command: " + token->ToOriginalString()); + } Result r = ParseBlendOpName(token->AsString(), op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result(std::string("Extra parameter for ") + name + " command: " + token->ToOriginalString()); + } return {}; } @@ -1713,8 +1860,9 @@ Result CommandParser::ParseBlendOp(const std::string& name, BlendOp* op) { Result CommandParser::ProcessColorBlendOp() { BlendOp op = BlendOp::kAdd; Result r = ParseBlendOp("colorBlendOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetColorBlendOp(op); return {}; @@ -1723,8 +1871,9 @@ Result CommandParser::ProcessColorBlendOp() { Result CommandParser::ProcessAlphaBlendOp() { BlendOp op = BlendOp::kAdd; Result r = ParseBlendOp("alphaBlendOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetAlphaBlendOp(op); return {}; @@ -1732,20 +1881,24 @@ Result CommandParser::ProcessAlphaBlendOp() { Result CommandParser::ParseCompareOp(const std::string& name, CompareOp* op) { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result(std::string("Missing parameter for ") + name + " command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result(std::string("Invalid parameter for ") + name + " command: " + token->ToOriginalString()); + } Result r = ParseCompareOpName(token->AsString(), op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result(std::string("Extra parameter for ") + name + " command: " + token->ToOriginalString()); + } return {}; } @@ -1754,24 +1907,25 @@ Result CommandParser::ParseCompareOpName(const std::string& name, CompareOp* op) { assert(op); - if (name == "VK_COMPARE_OP_NEVER") + if (name == "VK_COMPARE_OP_NEVER") { *op = CompareOp::kNever; - else if (name == "VK_COMPARE_OP_LESS") + } else if (name == "VK_COMPARE_OP_LESS") { *op = CompareOp::kLess; - else if (name == "VK_COMPARE_OP_EQUAL") + } else if (name == "VK_COMPARE_OP_EQUAL") { *op = CompareOp::kEqual; - else if (name == "VK_COMPARE_OP_LESS_OR_EQUAL") + } else if (name == "VK_COMPARE_OP_LESS_OR_EQUAL") { *op = CompareOp::kLessOrEqual; - else if (name == "VK_COMPARE_OP_GREATER") + } else if (name == "VK_COMPARE_OP_GREATER") { *op = CompareOp::kGreater; - else if (name == "VK_COMPARE_OP_NOT_EQUAL") + } else if (name == "VK_COMPARE_OP_NOT_EQUAL") { *op = CompareOp::kNotEqual; - else if (name == "VK_COMPARE_OP_GREATER_OR_EQUAL") + } else if (name == "VK_COMPARE_OP_GREATER_OR_EQUAL") { *op = CompareOp::kGreaterOrEqual; - else if (name == "VK_COMPARE_OP_ALWAYS") + } else if (name == "VK_COMPARE_OP_ALWAYS") { *op = CompareOp::kAlways; - else + } else { return Result("Unknown CompareOp provided: " + name); + } return {}; } @@ -1779,8 +1933,9 @@ Result CommandParser::ParseCompareOpName(const std::string& name, Result CommandParser::ProcessDepthCompareOp() { CompareOp op = CompareOp::kNever; Result r = ParseCompareOp("depthCompareOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetDepthCompareOp(op); return {}; @@ -1789,8 +1944,9 @@ Result CommandParser::ProcessDepthCompareOp() { Result CommandParser::ProcessFrontCompareOp() { CompareOp op = CompareOp::kNever; Result r = ParseCompareOp("front.compareOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetFrontCompareOp(op); return {}; @@ -1799,8 +1955,9 @@ Result CommandParser::ProcessFrontCompareOp() { Result CommandParser::ProcessBackCompareOp() { CompareOp op = CompareOp::kNever; Result r = ParseCompareOp("back.compareOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetBackCompareOp(op); return {}; @@ -1808,20 +1965,24 @@ Result CommandParser::ProcessBackCompareOp() { Result CommandParser::ParseStencilOp(const std::string& name, StencilOp* op) { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result(std::string("Missing parameter for ") + name + " command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result(std::string("Invalid parameter for ") + name + " command: " + token->ToOriginalString()); + } Result r = ParseStencilOpName(token->AsString(), op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result(std::string("Extra parameter for ") + name + " command: " + token->ToOriginalString()); + } return {}; } @@ -1830,24 +1991,25 @@ Result CommandParser::ParseStencilOpName(const std::string& name, StencilOp* op) { assert(op); - if (name == "VK_STENCIL_OP_KEEP") + if (name == "VK_STENCIL_OP_KEEP") { *op = StencilOp::kKeep; - else if (name == "VK_STENCIL_OP_ZERO") + } else if (name == "VK_STENCIL_OP_ZERO") { *op = StencilOp::kZero; - else if (name == "VK_STENCIL_OP_REPLACE") + } else if (name == "VK_STENCIL_OP_REPLACE") { *op = StencilOp::kReplace; - else if (name == "VK_STENCIL_OP_INCREMENT_AND_CLAMP") + } else if (name == "VK_STENCIL_OP_INCREMENT_AND_CLAMP") { *op = StencilOp::kIncrementAndClamp; - else if (name == "VK_STENCIL_OP_DECREMENT_AND_CLAMP") + } else if (name == "VK_STENCIL_OP_DECREMENT_AND_CLAMP") { *op = StencilOp::kDecrementAndClamp; - else if (name == "VK_STENCIL_OP_INVERT") + } else if (name == "VK_STENCIL_OP_INVERT") { *op = StencilOp::kInvert; - else if (name == "VK_STENCIL_OP_INCREMENT_AND_WRAP") + } else if (name == "VK_STENCIL_OP_INCREMENT_AND_WRAP") { *op = StencilOp::kIncrementAndWrap; - else if (name == "VK_STENCIL_OP_DECREMENT_AND_WRAP") + } else if (name == "VK_STENCIL_OP_DECREMENT_AND_WRAP") { *op = StencilOp::kDecrementAndWrap; - else + } else { return Result("Unknown StencilOp provided: " + name); + } return {}; } @@ -1855,8 +2017,9 @@ Result CommandParser::ParseStencilOpName(const std::string& name, Result CommandParser::ProcessFrontFailOp() { StencilOp op = StencilOp::kKeep; Result r = ParseStencilOp("front.failOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetFrontFailOp(op); return {}; @@ -1865,8 +2028,9 @@ Result CommandParser::ProcessFrontFailOp() { Result CommandParser::ProcessFrontPassOp() { StencilOp op = StencilOp::kKeep; Result r = ParseStencilOp("front.passOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetFrontPassOp(op); return {}; @@ -1875,8 +2039,9 @@ Result CommandParser::ProcessFrontPassOp() { Result CommandParser::ProcessFrontDepthFailOp() { StencilOp op = StencilOp::kKeep; Result r = ParseStencilOp("front.depthFailOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetFrontDepthFailOp(op); return {}; @@ -1885,8 +2050,9 @@ Result CommandParser::ProcessFrontDepthFailOp() { Result CommandParser::ProcessBackFailOp() { StencilOp op = StencilOp::kKeep; Result r = ParseStencilOp("back.failOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetBackFailOp(op); return {}; @@ -1895,8 +2061,9 @@ Result CommandParser::ProcessBackFailOp() { Result CommandParser::ProcessBackPassOp() { StencilOp op = StencilOp::kKeep; Result r = ParseStencilOp("back.passOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetBackPassOp(op); return {}; @@ -1905,8 +2072,9 @@ Result CommandParser::ProcessBackPassOp() { Result CommandParser::ProcessBackDepthFailOp() { StencilOp op = StencilOp::kKeep; Result r = ParseStencilOp("back.depthFailOp", &op); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } pipeline_data_.SetBackDepthFailOp(op); return {}; @@ -1930,47 +2098,55 @@ Result CommandParser::ProcessBackWriteMask() { Result CommandParser::ProcessFrontReference() { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("Missing parameter for front.reference command"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("Invalid parameter for front.reference command: " + token->ToOriginalString()); + } pipeline_data_.SetFrontReference(token->AsUint32()); token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for front.reference command: " + token->ToOriginalString()); + } return {}; } Result CommandParser::ProcessBackReference() { auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("Missing parameter for back.reference command"); - if (!token->IsInteger()) + } + if (!token->IsInteger()) { return Result("Invalid parameter for back.reference command: " + token->ToOriginalString()); + } pipeline_data_.SetBackReference(token->AsUint32()); token = tokenizer_->NextToken(); - if (!token->IsEOS() && !token->IsEOL()) + if (!token->IsEOS() && !token->IsEOL()) { return Result("Extra parameter for back.reference command: " + token->ToOriginalString()); + } return {}; } Result CommandParser::ProcessColorWriteMask() { auto token = tokenizer_->NextToken(); - if (token->IsEOS() || token->IsEOL()) + if (token->IsEOS() || token->IsEOL()) { return Result("Missing parameter for colorWriteMask command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Invalid parameter for colorWriteMask command: " + token->ToOriginalString()); + } uint8_t mask = 0; while (!token->IsEOS() && !token->IsEOL()) { @@ -1999,22 +2175,23 @@ Result CommandParser::ProcessColorWriteMask() { Result CommandParser::ParseComparator(const std::string& name, ProbeSSBOCommand::Comparator* op) { - if (name == "==") + if (name == "==") { *op = ProbeSSBOCommand::Comparator::kEqual; - else if (name == "!=") + } else if (name == "!=") { *op = ProbeSSBOCommand::Comparator::kNotEqual; - else if (name == "~=") + } else if (name == "~=") { *op = ProbeSSBOCommand::Comparator::kFuzzyEqual; - else if (name == "<") + } else if (name == "<") { *op = ProbeSSBOCommand::Comparator::kLess; - else if (name == "<=") + } else if (name == "<=") { *op = ProbeSSBOCommand::Comparator::kLessOrEqual; - else if (name == ">") + } else if (name == ">") { *op = ProbeSSBOCommand::Comparator::kGreater; - else if (name == ">=") + } else if (name == ">=") { *op = ProbeSSBOCommand::Comparator::kGreaterOrEqual; - else + } else { return Result("Invalid comparator: " + name); + } return {}; } @@ -2022,21 +2199,25 @@ Result CommandParser::ProcessProbeSSBO() { size_t cur_line = tokenizer_->GetCurrentLine(); auto token = tokenizer_->NextToken(); - if (token->IsEOL() || token->IsEOS()) + if (token->IsEOL() || token->IsEOS()) { return Result("Missing values for probe ssbo command"); - if (!token->IsIdentifier()) + } + if (!token->IsIdentifier()) { return Result("Invalid type for probe ssbo command: " + token->ToOriginalString()); + } DatumTypeParser tp; auto type = tp.Parse(token->AsString()); - if (!type) + if (!type) { return Result("Invalid type provided: " + token->AsString()); + } token = tokenizer_->NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Invalid binding value for probe ssbo command: " + token->ToOriginalString()); + } uint32_t val = token->AsUint32(); @@ -2050,9 +2231,10 @@ Result CommandParser::ProcessProbeSSBO() { auto substr = str.substr(1, str.size()); uint64_t binding_val = strtoul(substr.c_str(), nullptr, 10); - if (binding_val > std::numeric_limits::max()) + if (binding_val > std::numeric_limits::max()) { return Result("binding value too large in probe ssbo command: " + token->ToOriginalString()); + } binding = static_cast(binding_val); } else { @@ -2089,28 +2271,32 @@ Result CommandParser::ProcessProbeSSBO() { script_->RegisterFormat(std::move(fmt)); script_->RegisterType(std::move(type)); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result("Invalid offset for probe ssbo command: " + token->ToOriginalString()); + } cmd->SetOffset(token->AsUint32()); token = tokenizer_->NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result("Invalid comparator for probe ssbo command: " + token->ToOriginalString()); + } ProbeSSBOCommand::Comparator comp = ProbeSSBOCommand::Comparator::kEqual; Result r = ParseComparator(token->AsString(), &comp); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetComparator(comp); std::vector values; r = ParseValues("probe ssbo", cmd->GetFormat(), &values); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } cmd->SetValues(std::move(values)); diff --git a/src/vkscript/command_parser_test.cc b/src/vkscript/command_parser_test.cc index 6cf053014..af8aa5bd9 100644 --- a/src/vkscript/command_parser_test.cc +++ b/src/vkscript/command_parser_test.cc @@ -751,8 +751,9 @@ TEST_F(CommandParserTest, EntryPointNameMissing) { TEST_F(CommandParserTest, EntryPointEntryPointMissing) { for (const auto& ep : kEntryPoints) { // Skip compute because compute is also a command .... - if (std::string(ep.name) == "compute") + if (std::string(ep.name) == "compute") { continue; + } std::string data = std::string(ep.name) + " main"; @@ -1465,8 +1466,9 @@ TEST_P(CommandDataPipelineDataInvalidParser, ExtraPipelineParamValue) { const auto& test_data = GetParam(); // CullMode consumes all parameters, so skip this test. - if (std::string(test_data.name) == "cullMode") + if (std::string(test_data.name) == "cullMode") { return; + } std::string data = std::string(test_data.name) + " " + test_data.arg + " EXTRA"; @@ -3696,10 +3698,11 @@ TEST_F(CommandParserTest, ToleranceMultiFloatValueWithPercent) { std::vector results = {0.5, 2.4, 3.9, 99.7}; ASSERT_EQ(results.size(), tolerances.size()); for (size_t i = 0; i < results.size(); ++i) { - if (i % 2 == 0) + if (i % 2 == 0) { EXPECT_TRUE(tolerances[i].is_percent); - else + } else { EXPECT_FALSE(tolerances[i].is_percent); + } EXPECT_DOUBLE_EQ(results[i], tolerances[i].value); } @@ -3736,10 +3739,11 @@ TEST_F(CommandParserTest, ToleranceMultiIntValueWithPercent) { std::vector results = {5.0, 4.0, 3.0, 99.0}; ASSERT_EQ(results.size(), tolerances.size()); for (size_t i = 0; i < results.size(); ++i) { - if (i % 2 == 0) + if (i % 2 == 0) { EXPECT_TRUE(tolerances[i].is_percent); - else + } else { EXPECT_FALSE(tolerances[i].is_percent); + } EXPECT_DOUBLE_EQ(results[i], tolerances[i].value); } diff --git a/src/vkscript/datum_type_parser.cc b/src/vkscript/datum_type_parser.cc index 90629608a..dd253d974 100644 --- a/src/vkscript/datum_type_parser.cc +++ b/src/vkscript/datum_type_parser.cc @@ -26,26 +26,36 @@ DatumTypeParser::~DatumTypeParser() = default; std::unique_ptr DatumTypeParser::Parse(const std::string& data) { TypeParser tp; - if (data == "int") + if (data == "int") { return tp.Parse("R32_SINT"); - if (data == "uint") + } + if (data == "uint") { return tp.Parse("R32_UINT"); - if (data == "int8_t") + } + if (data == "int8_t") { return tp.Parse("R8_SINT"); - if (data == "uint8_t") + } + if (data == "uint8_t") { return tp.Parse("R8_UINT"); - if (data == "int16_t") + } + if (data == "int16_t") { return tp.Parse("R16_SINT"); - if (data == "uint16_t") + } + if (data == "uint16_t") { return tp.Parse("R16_UINT"); - if (data == "int64_t") + } + if (data == "int64_t") { return tp.Parse("R64_SINT"); - if (data == "uint64_t") + } + if (data == "uint64_t") { return tp.Parse("R64_UINT"); - if (data == "float") + } + if (data == "float") { return tp.Parse("R32_SFLOAT"); - if (data == "double") + } + if (data == "double") { return tp.Parse("R64_SFLOAT"); + } int row_count = 4; int column_count = 1; @@ -61,39 +71,46 @@ std::unique_ptr DatumTypeParser::Parse(const std::string& data) { num_bits = 64; } - if (data[1] == '8') + if (data[1] == '8') { num_bits = 8; - else if (data[1] == '1' && data[2] == '6') + } else if (data[1] == '1' && data[2] == '6') { num_bits = 16; - else if (data[1] == '6' && data[2] == '4') + } else if (data[1] == '6' && data[2] == '4') { num_bits = 64; + } - if ((vec_pos + 3) < data.length()) + if ((vec_pos + 3) < data.length()) { row_count = data[vec_pos + 3] - '0'; + } } else { size_t mat_pos = data.find("mat"); - if (mat_pos == std::string::npos) + if (mat_pos == std::string::npos) { return nullptr; + } - if (data[0] == 'd') + if (data[0] == 'd') { num_bits = 64; + } - if (mat_pos + 3 < data.length()) + if (mat_pos + 3 < data.length()) { column_count = data[mat_pos + 3] - '0'; + } - if (mat_pos + 5 < data.length()) + if (mat_pos + 5 < data.length()) { row_count = data[mat_pos + 5] - '0'; - else + } else { row_count = column_count; + } } std::unique_ptr type; - if (mode == FormatMode::kSFloat) + if (mode == FormatMode::kSFloat) { type = type::Number::Float(num_bits); - else if (mode == FormatMode::kSInt) + } else if (mode == FormatMode::kSInt) { type = type::Number::Int(num_bits); - else + } else { type = type::Number::Uint(num_bits); + } type->SetRowCount(static_cast(row_count)); type->SetColumnCount(static_cast(column_count)); diff --git a/src/vkscript/datum_type_parser_test.cc b/src/vkscript/datum_type_parser_test.cc index a9d6089b9..393ff5e62 100644 --- a/src/vkscript/datum_type_parser_test.cc +++ b/src/vkscript/datum_type_parser_test.cc @@ -23,12 +23,15 @@ namespace { bool AllCompsAreType(Format* fmt, FormatMode mode, uint8_t num_bits) { for (auto& seg : fmt->GetSegments()) { - if (seg.IsPadding()) + if (seg.IsPadding()) { continue; - if (seg.GetNumBits() != num_bits) + } + if (seg.GetNumBits() != num_bits) { return false; - if (seg.GetFormatMode() != mode) + } + if (seg.GetFormatMode() != mode) { return false; + } } return true; diff --git a/src/vkscript/parser.cc b/src/vkscript/parser.cc index c84e2d9c7..2df6cd56e 100644 --- a/src/vkscript/parser.cc +++ b/src/vkscript/parser.cc @@ -48,24 +48,28 @@ std::string Parser::make_error(const Tokenizer& tokenizer, Result Parser::Parse(const std::string& input) { SectionParser section_parser; Result r = section_parser.Parse(input); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = GenerateDefaultPipeline(section_parser); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } for (const auto& section : section_parser.Sections()) { r = ProcessSection(section); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } if (!skip_validation_for_test_) { for (const auto& pipeline : script_->GetPipelines()) { r = pipeline->Validate(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } } @@ -76,8 +80,9 @@ Result Parser::GenerateDefaultPipeline(const SectionParser& section_parser) { // Generate a pipeline for VkScript. PipelineType pipeline_type = PipelineType::kCompute; for (const auto& section : section_parser.Sections()) { - if (!SectionParser::HasShader(section.section_type)) + if (!SectionParser::HasShader(section.section_type)) { continue; + } if (section.shader_type != kShaderTypeCompute) { pipeline_type = PipelineType::kGraphics; @@ -92,37 +97,46 @@ Result Parser::GenerateDefaultPipeline(const SectionParser& section_parser) { pipeline->SetFramebufferHeight(kDefaultFrameBufferSize); Result r = script_->AddPipeline(std::move(new_pipeline)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } // Generate and add a framebuffer auto color_buf = pipeline->GenerateDefaultColorAttachmentBuffer(); r = pipeline->AddColorAttachment(color_buf.get(), 0, 0); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = script_->AddBuffer(std::move(color_buf)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } Result Parser::ProcessSection(const SectionParser::Section& section) { // Should never get here, but skip it anyway. - if (section.section_type == NodeType::kComment) + if (section.section_type == NodeType::kComment) { return {}; + } - if (SectionParser::HasShader(section.section_type)) + if (SectionParser::HasShader(section.section_type)) { return ProcessShaderBlock(section); - if (section.section_type == NodeType::kRequire) + } + if (section.section_type == NodeType::kRequire) { return ProcessRequireBlock(section); - if (section.section_type == NodeType::kIndices) + } + if (section.section_type == NodeType::kIndices) { return ProcessIndicesBlock(section); - if (section.section_type == NodeType::kVertexData) + } + if (section.section_type == NodeType::kVertexData) { return ProcessVertexDataBlock(section); - if (section.section_type == NodeType::kTest) + } + if (section.section_type == NodeType::kTest) { return ProcessTestBlock(section); + } return Result("Unknown node type ...."); } @@ -138,12 +152,14 @@ Result Parser::ProcessShaderBlock(const SectionParser::Section& section) { Result r = script_->GetPipeline(kDefaultPipelineName) ->AddShader(shader.get(), shader->GetType()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = script_->AddShader(std::move(shader)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } @@ -154,8 +170,9 @@ Result Parser::ProcessRequireBlock(const SectionParser::Section& section) { for (auto token = tokenizer.NextToken(); !token->IsEOS(); token = tokenizer.NextToken()) { - if (token->IsEOL()) + if (token->IsEOL()) { continue; + } if (!token->IsIdentifier()) { return Result(make_error( tokenizer, @@ -167,8 +184,9 @@ Result Parser::ProcessRequireBlock(const SectionParser::Section& section) { script_->AddRequiredFeature(str); } else if (str == Pipeline::kGeneratedColorBuffer) { token = tokenizer.NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result(make_error(tokenizer, "Missing framebuffer format")); + } TypeParser type_parser; auto type = type_parser.Parse(token->AsString()); @@ -187,8 +205,9 @@ Result Parser::ProcessRequireBlock(const SectionParser::Section& section) { } else if (str == "depthstencil") { token = tokenizer.NextToken(); - if (!token->IsIdentifier()) + if (!token->IsIdentifier()) { return Result(make_error(tokenizer, "Missing depthStencil format")); + } TypeParser type_parser; auto type = type_parser.Parse(token->AsString()); @@ -199,8 +218,9 @@ Result Parser::ProcessRequireBlock(const SectionParser::Section& section) { } auto* pipeline = script_->GetPipeline(kDefaultPipelineName); - if (pipeline->GetDepthStencilBuffer().buffer != nullptr) + if (pipeline->GetDepthStencilBuffer().buffer != nullptr) { return Result("Only one depthstencil command allowed"); + } auto fmt = MakeUnique(type.get()); // Generate and add a depth buffer @@ -210,17 +230,20 @@ Result Parser::ProcessRequireBlock(const SectionParser::Section& section) { script_->RegisterType(std::move(type)); Result r = pipeline->SetDepthStencilBuffer(depth_buf.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = script_->AddBuffer(std::move(depth_buf)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (str == "fence_timeout") { token = tokenizer.NextToken(); - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result(make_error(tokenizer, "Missing fence_timeout value")); + } script_->GetEngineData().fence_timeout_ms = token->AsUint32(); @@ -279,12 +302,14 @@ Result Parser::ProcessIndicesBlock(const SectionParser::Section& section) { tokenizer.SetCurrentLine(section.starting_line_number); for (auto token = tokenizer.NextToken(); !token->IsEOS(); token = tokenizer.NextToken()) { - if (token->IsEOL()) + if (token->IsEOL()) { continue; + } - if (!token->IsInteger()) + if (!token->IsInteger()) { return Result(make_error(tokenizer, "Invalid value in indices block: " + token->ToOriginalString())); + } if (token->AsUint64() > static_cast(std::numeric_limits::max())) { return Result(make_error(tokenizer, "Value too large in indices block: " + @@ -308,8 +333,9 @@ Result Parser::ProcessIndicesBlock(const SectionParser::Section& section) { script_->RegisterType(std::move(type)); Result r = script_->AddBuffer(std::move(b)); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } script_->GetPipeline(kDefaultPipelineName)->SetIndexBuffer(buf); } @@ -323,12 +349,14 @@ Result Parser::ProcessVertexDataBlock(const SectionParser::Section& section) { // Skip blank and comment lines auto token = tokenizer.NextToken(); - while (token->IsEOL()) + while (token->IsEOL()) { token = tokenizer.NextToken(); + } // Skip empty vertex data blocks - if (token->IsEOS()) + if (token->IsEOS()) { return {}; + } // Process the header line. struct Header { @@ -355,9 +383,10 @@ Result Parser::ProcessVertexDataBlock(const SectionParser::Section& section) { } std::string fmt_name = token->AsString(); - if (fmt_name.size() < 2) + if (fmt_name.size() < 2) { return Result(make_error(tokenizer, "Vertex data format too short: " + token->ToOriginalString())); + } TypeParser parser; auto type = parser.Parse(fmt_name.substr(1, fmt_name.length())); @@ -381,8 +410,9 @@ Result Parser::ProcessVertexDataBlock(const SectionParser::Section& section) { // Process data lines for (; !token->IsEOS(); token = tokenizer.NextToken()) { - if (token->IsEOL()) + if (token->IsEOL()) { continue; + } for (size_t j = 0; j < headers.size(); ++j) { const auto& header = headers[j]; @@ -402,8 +432,9 @@ Result Parser::ProcessVertexDataBlock(const SectionParser::Section& section) { } else { auto& segs = header.format->GetSegments(); for (const auto& seg : segs) { - if (seg.IsPadding()) + if (seg.IsPadding()) { continue; + } if (token->IsEOS() || token->IsEOL()) { return Result(make_error(tokenizer, @@ -414,8 +445,9 @@ Result Parser::ProcessVertexDataBlock(const SectionParser::Section& section) { if (seg.GetFormatMode() == FormatMode::kUFloat || seg.GetFormatMode() == FormatMode::kSFloat) { Result r = token->ConvertToDouble(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } v.SetDoubleValue(token->AsDouble()); } else if (token->IsInteger()) { @@ -439,8 +471,9 @@ Result Parser::ProcessVertexDataBlock(const SectionParser::Section& section) { buffer->SetName("Vertices" + std::to_string(i)); buffer->SetFormat(headers[i].format); Result r = buffer->SetData(std::move(values[i])); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } script_->AddBuffer(std::move(buffer)); @@ -457,8 +490,9 @@ Result Parser::ProcessTestBlock(const SectionParser::Section& section) { CommandParser cp(script_.get(), pipeline, section.starting_line_number + 1, section.contents); Result r = cp.Parse(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } script_->SetCommands(cp.TakeCommands()); diff --git a/src/vkscript/section_parser.cc b/src/vkscript/section_parser.cc index 7c0094d5d..3445d9f58 100644 --- a/src/vkscript/section_parser.cc +++ b/src/vkscript/section_parser.cc @@ -36,8 +36,9 @@ SectionParser::~SectionParser() = default; Result SectionParser::Parse(const std::string& data) { Result result = SplitSections(data); - if (!result.IsSuccess()) + if (!result.IsSuccess()) { return result; + } return {}; } @@ -85,33 +86,39 @@ Result SectionParser::NameToNodeType(const std::string& data, } else if (name == "compute shader") { *section_type = NodeType::kShader; *shader_type = kShaderTypeCompute; - if (*fmt == kShaderFormatText) + if (*fmt == kShaderFormatText) { *fmt = kShaderFormatGlsl; + } } else if (name == "fragment shader") { *section_type = NodeType::kShader; *shader_type = kShaderTypeFragment; - if (*fmt == kShaderFormatText) + if (*fmt == kShaderFormatText) { *fmt = kShaderFormatGlsl; + } } else if (name == "geometry shader") { *section_type = NodeType::kShader; *shader_type = kShaderTypeGeometry; - if (*fmt == kShaderFormatText) + if (*fmt == kShaderFormatText) { *fmt = kShaderFormatGlsl; + } } else if (name == "tessellation control shader") { *section_type = NodeType::kShader; *shader_type = kShaderTypeTessellationControl; - if (*fmt == kShaderFormatText) + if (*fmt == kShaderFormatText) { *fmt = kShaderFormatGlsl; + } } else if (name == "tessellation evaluation shader") { *section_type = NodeType::kShader; *shader_type = kShaderTypeTessellationEvaluation; - if (*fmt == kShaderFormatText) + if (*fmt == kShaderFormatText) { *fmt = kShaderFormatGlsl; + } } else if (name == "vertex shader") { *section_type = NodeType::kShader; *shader_type = kShaderTypeVertex; - if (*fmt == kShaderFormatText) + if (*fmt == kShaderFormatText) { *fmt = kShaderFormatGlsl; + } } else { return Result("Invalid name: " + data); } @@ -130,8 +137,9 @@ void SectionParser::AddSection(NodeType section_type, ShaderFormat fmt, size_t line_count, const std::string& contents) { - if (section_type == NodeType::kComment) + if (section_type == NodeType::kComment) { return; + } if (fmt == kShaderFormatDefault) { sections_.push_back({section_type, shader_type, kShaderFormatSpirvAsm, @@ -167,11 +175,13 @@ Result SectionParser::SplitSections(const std::string& data) { ++line_count; if (!in_section) { - if (line.empty() || line[0] == '#' || line == "\r") + if (line.empty() || line[0] == '#' || line == "\r") { continue; + } - if (line[0] != '[') + if (line[0] != '[') { return Result(std::to_string(line_count) + ": Invalid character"); + } section_start = line_count; in_section = true; @@ -189,15 +199,17 @@ Result SectionParser::SplitSections(const std::string& data) { section_contents = ""; size_t name_end = line.rfind("]"); - if (name_end == std::string::npos) + if (name_end == std::string::npos) { return Result(std::to_string(line_count) + ": Missing section close"); + } std::string name = line.substr(1, name_end - 1); Result r = NameToNodeType(name, ¤t_type, ¤t_shader, ¤t_fmt); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return Result(std::to_string(line_count) + ": " + r.Error()); + } } else { section_contents += line + "\n"; } diff --git a/src/vulkan/blas.cc b/src/vulkan/blas.cc index bdd41012d..1797df0b0 100644 --- a/src/vulkan/blas.cc +++ b/src/vulkan/blas.cc @@ -36,8 +36,9 @@ BLAS::~BLAS() { } Result BLAS::CreateBLAS(amber::BLAS* blas) { - if (blas_ != VK_NULL_HANDLE) + if (blas_ != VK_NULL_HANDLE) { return Result("Cannot recreate acceleration structure"); + } std::vector>& geometries = blas->GetGeometries(); std::vector vertexBufferOffsets; @@ -87,12 +88,8 @@ Result BLAS::CreateBLAS(amber::BLAS* blas) { } const VkAccelerationStructureGeometryKHR accelerationStructureGeometry = { - VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR, - nullptr, - geometryType, - geometry, - VkGeometryFlagsKHR(geometryData->GetFlags()) - }; + VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR, nullptr, + geometryType, geometry, VkGeometryFlagsKHR(geometryData->GetFlags())}; const VkAccelerationStructureBuildRangeInfoKHR accelerationStructureBuildRangeInfosKHR = { static_cast(geometryData->getPrimitiveCount()), 0, 0, 0}; @@ -156,8 +153,9 @@ Result BLAS::CreateBLAS(amber::BLAS* blas) { if (device_->GetPtrs()->vkCreateAccelerationStructureKHR( device_->GetVkDevice(), &accelerationStructureCreateInfoKHR, nullptr, - &blas_) != VK_SUCCESS) + &blas_) != VK_SUCCESS) { return Result("Vulkan::Calling vkCreateAccelerationStructureKHR failed"); + } accelerationStructureBuildGeometryInfoKHR_.dstAccelerationStructure = blas_; @@ -218,10 +216,12 @@ Result BLAS::CreateBLAS(amber::BLAS* blas) { } Result BLAS::BuildBLAS(CommandBuffer* command_buffer) { - if (blas_ == VK_NULL_HANDLE) + if (blas_ == VK_NULL_HANDLE) { return Result("Acceleration structure should be created first"); - if (built_) + } + if (built_) { return {}; + } VkCommandBuffer cmdBuffer = command_buffer->GetVkCommandBuffer(); diff --git a/src/vulkan/blas.h b/src/vulkan/blas.h index 7a2209747..55c632100 100644 --- a/src/vulkan/blas.h +++ b/src/vulkan/blas.h @@ -16,8 +16,8 @@ #ifndef SRC_VULKAN_BLAS_H_ #define SRC_VULKAN_BLAS_H_ -#include #include +#include #include "src/acceleration_structure.h" #include "src/vulkan/device.h" diff --git a/src/vulkan/buffer_backed_descriptor.cc b/src/vulkan/buffer_backed_descriptor.cc index a2e874dd6..f50c88599 100644 --- a/src/vulkan/buffer_backed_descriptor.cc +++ b/src/vulkan/buffer_backed_descriptor.cc @@ -42,8 +42,9 @@ Result BufferBackedDescriptor::RecordCopyBufferDataToTransferResourceIfNeeded( // If the resource is read-only, keep the buffer data; Amber won't copy // read-only resources back into the host buffers, so it makes sense to // leave the buffer intact. - if (!transfer_resource->IsReadOnly()) + if (!transfer_resource->IsReadOnly()) { buffer->ValuePtr()->clear(); + } transfer_resource->CopyToDevice(command_buffer); return {}; diff --git a/src/vulkan/buffer_descriptor.cc b/src/vulkan/buffer_descriptor.cc index d60ce08ee..cf5917994 100644 --- a/src/vulkan/buffer_descriptor.cc +++ b/src/vulkan/buffer_descriptor.cc @@ -77,8 +77,9 @@ Result BufferDescriptor::CreateResourceIfNeeded() { Result r = transfer_resources[amber_buffer]->AsTransferBuffer()->AddUsageFlags( flags); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } is_descriptor_set_update_needed_ = true; @@ -90,8 +91,9 @@ Result BufferDescriptor::CreateResourceIfNeeded() { void BufferDescriptor::UpdateDescriptorSetIfNeeded( VkDescriptorSet descriptor_set) { - if (!is_descriptor_set_update_needed_) + if (!is_descriptor_set_update_needed_) { return; + } std::vector buffer_infos; std::vector buffer_views; diff --git a/src/vulkan/command_buffer.cc b/src/vulkan/command_buffer.cc index d5546a82f..867e122a0 100644 --- a/src/vulkan/command_buffer.cc +++ b/src/vulkan/command_buffer.cc @@ -29,8 +29,9 @@ CommandBuffer::CommandBuffer(Device* device, CommandPool* pool) CommandBuffer::~CommandBuffer() { Reset(); - if (fence_ != VK_NULL_HANDLE) + if (fence_ != VK_NULL_HANDLE) { device_->GetPtrs()->vkDestroyFence(device_->GetVkDevice(), fence_, nullptr); + } if (command_ != VK_NULL_HANDLE) { device_->GetPtrs()->vkFreeCommandBuffers( @@ -75,8 +76,9 @@ Result CommandBuffer::BeginRecording() { Result CommandBuffer::SubmitAndReset(uint32_t timeout_ms, bool pipeline_runtime_layer_enabled) { - if (device_->GetPtrs()->vkEndCommandBuffer(command_) != VK_SUCCESS) + if (device_->GetPtrs()->vkEndCommandBuffer(command_) != VK_SUCCESS) { return Result("Vulkan::Calling vkEndCommandBuffer Fail"); + } if (device_->GetPtrs()->vkResetFences(device_->GetVkDevice(), 1, &fence_) != VK_SUCCESS) { @@ -101,8 +103,9 @@ Result CommandBuffer::SubmitAndReset(uint32_t timeout_ms, : static_cast(timeout_ms) * 1000ULL * 1000ULL; VkResult r = device_->GetPtrs()->vkWaitForFences( device_->GetVkDevice(), 1, &fence_, VK_TRUE, timeout_ns); - if (r == VK_TIMEOUT) + if (r == VK_TIMEOUT) { return Result("Vulkan::Calling vkWaitForFences Timeout"); + } if (r != VK_SUCCESS) { std::string result_str; switch (r) { @@ -128,11 +131,13 @@ vkQueueWaitIdle in order to report the information. Since we want to be able to use that layer in conjunction with Amber we need to somehow communicate that the Amber script has completed. */ - if (pipeline_runtime_layer_enabled) + if (pipeline_runtime_layer_enabled) { device_->GetPtrs()->vkQueueWaitIdle(device_->GetVkQueue()); + } - if (device_->GetPtrs()->vkResetCommandBuffer(command_, 0) != VK_SUCCESS) + if (device_->GetPtrs()->vkResetCommandBuffer(command_, 0) != VK_SUCCESS) { return Result("Vulkan::Calling vkResetCommandBuffer Fail"); + } return {}; } @@ -151,8 +156,9 @@ CommandBufferGuard::CommandBufferGuard(CommandBuffer* buffer) } CommandBufferGuard::~CommandBufferGuard() { - if (buffer_->guarded_) + if (buffer_->guarded_) { buffer_->Reset(); + } } Result CommandBufferGuard::Submit(uint32_t timeout_ms, diff --git a/src/vulkan/command_pool.cc b/src/vulkan/command_pool.cc index 417a549d0..a18b10ff8 100644 --- a/src/vulkan/command_pool.cc +++ b/src/vulkan/command_pool.cc @@ -22,8 +22,9 @@ namespace vulkan { CommandPool::CommandPool(Device* device) : device_(device) {} CommandPool::~CommandPool() { - if (pool_ == VK_NULL_HANDLE) + if (pool_ == VK_NULL_HANDLE) { return; + } device_->GetPtrs()->vkDestroyCommandPool(device_->GetVkDevice(), pool_, nullptr); diff --git a/src/vulkan/compute_pipeline.cc b/src/vulkan/compute_pipeline.cc index 23fd127e1..33c75899c 100644 --- a/src/vulkan/compute_pipeline.cc +++ b/src/vulkan/compute_pipeline.cc @@ -48,8 +48,9 @@ Result ComputePipeline::CreateVkComputePipeline( "pipeline is not 1"); } - if (shader_stage_info[0].stage != VK_SHADER_STAGE_COMPUTE_BIT) + if (shader_stage_info[0].stage != VK_SHADER_STAGE_COMPUTE_BIT) { return Result("Vulkan: Non compute shader for compute pipeline"); + } shader_stage_info[0].pName = GetEntryPointName(VK_SHADER_STAGE_COMPUTE_BIT); @@ -72,18 +73,21 @@ Result ComputePipeline::Compute(uint32_t x, uint32_t z, bool is_timed_execution) { Result r = SendDescriptorDataToDeviceIfNeeded(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } VkPipelineLayout pipeline_layout = VK_NULL_HANDLE; r = CreateVkPipelineLayout(&pipeline_layout); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } VkPipeline pipeline = VK_NULL_HANDLE; r = CreateVkComputePipeline(pipeline_layout, &pipeline); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } // Note that a command updating a descriptor set and a command using // it must be submitted separately, because using a descriptor set @@ -92,14 +96,16 @@ Result ComputePipeline::Compute(uint32_t x, CreateTimingQueryObjectIfNeeded(is_timed_execution); { CommandBufferGuard guard(GetCommandBuffer()); - if (!guard.IsRecording()) + if (!guard.IsRecording()) { return guard.GetResult(); + } BindVkDescriptorSets(pipeline_layout); r = RecordPushConstant(pipeline_layout); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } device_->GetPtrs()->vkCmdBindPipeline(command_->GetVkCommandBuffer(), VK_PIPELINE_BIND_POINT_COMPUTE, @@ -109,13 +115,15 @@ Result ComputePipeline::Compute(uint32_t x, EndTimerQuery(); r = guard.Submit(GetFenceTimeout(), GetPipelineRuntimeLayerEnabled()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } DestroyTimingQueryObjectIfNeeded(); r = ReadbackDescriptorsToHostDataQueue(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } device_->GetPtrs()->vkDestroyPipeline(device_->GetVkDevice(), pipeline, nullptr); diff --git a/src/vulkan/device.cc b/src/vulkan/device.cc index 801d2e6d8..538c0b31d 100644 --- a/src/vulkan/device.cc +++ b/src/vulkan/device.cc @@ -106,285 +106,344 @@ struct BaseOutStructure { bool AreAllRequiredFeaturesSupported( const VkPhysicalDeviceFeatures& available_features, const std::vector& required_features) { - if (required_features.empty()) + if (required_features.empty()) { return true; + } for (const auto& feature : required_features) { if (feature == "robustBufferAccess") { - if (available_features.robustBufferAccess == VK_FALSE) + if (available_features.robustBufferAccess == VK_FALSE) { return false; + } continue; } if (feature == "fullDrawIndexUint32") { - if (available_features.fullDrawIndexUint32 == VK_FALSE) + if (available_features.fullDrawIndexUint32 == VK_FALSE) { return false; + } continue; } if (feature == "imageCubeArray") { - if (available_features.imageCubeArray == VK_FALSE) + if (available_features.imageCubeArray == VK_FALSE) { return false; + } continue; } if (feature == "independentBlend") { - if (available_features.independentBlend == VK_FALSE) + if (available_features.independentBlend == VK_FALSE) { return false; + } continue; } if (feature == "geometryShader") { - if (available_features.geometryShader == VK_FALSE) + if (available_features.geometryShader == VK_FALSE) { return false; + } continue; } if (feature == "tessellationShader") { - if (available_features.tessellationShader == VK_FALSE) + if (available_features.tessellationShader == VK_FALSE) { return false; + } continue; } if (feature == "sampleRateShading") { - if (available_features.sampleRateShading == VK_FALSE) + if (available_features.sampleRateShading == VK_FALSE) { return false; + } continue; } if (feature == "dualSrcBlend") { - if (available_features.dualSrcBlend == VK_FALSE) + if (available_features.dualSrcBlend == VK_FALSE) { return false; + } continue; } if (feature == "logicOp") { - if (available_features.logicOp == VK_FALSE) + if (available_features.logicOp == VK_FALSE) { return false; + } continue; } if (feature == "multiDrawIndirect") { - if (available_features.multiDrawIndirect == VK_FALSE) + if (available_features.multiDrawIndirect == VK_FALSE) { return false; + } continue; } if (feature == "drawIndirectFirstInstance") { - if (available_features.drawIndirectFirstInstance == VK_FALSE) + if (available_features.drawIndirectFirstInstance == VK_FALSE) { return false; + } continue; } if (feature == "depthClamp") { - if (available_features.depthClamp == VK_FALSE) + if (available_features.depthClamp == VK_FALSE) { return false; + } continue; } if (feature == "depthBiasClamp") { - if (available_features.depthBiasClamp == VK_FALSE) + if (available_features.depthBiasClamp == VK_FALSE) { return false; + } continue; } if (feature == "fillModeNonSolid") { - if (available_features.fillModeNonSolid == VK_FALSE) + if (available_features.fillModeNonSolid == VK_FALSE) { return false; + } continue; } if (feature == "depthBounds") { - if (available_features.depthBounds == VK_FALSE) + if (available_features.depthBounds == VK_FALSE) { return false; + } continue; } if (feature == "wideLines") { - if (available_features.wideLines == VK_FALSE) + if (available_features.wideLines == VK_FALSE) { return false; + } continue; } if (feature == "largePoints") { - if (available_features.largePoints == VK_FALSE) + if (available_features.largePoints == VK_FALSE) { return false; + } continue; } if (feature == "alphaToOne") { - if (available_features.alphaToOne == VK_FALSE) + if (available_features.alphaToOne == VK_FALSE) { return false; + } continue; } if (feature == "multiViewport") { - if (available_features.multiViewport == VK_FALSE) + if (available_features.multiViewport == VK_FALSE) { return false; + } continue; } if (feature == "samplerAnisotropy") { - if (available_features.samplerAnisotropy == VK_FALSE) + if (available_features.samplerAnisotropy == VK_FALSE) { return false; + } continue; } if (feature == "textureCompressionETC2") { - if (available_features.textureCompressionETC2 == VK_FALSE) + if (available_features.textureCompressionETC2 == VK_FALSE) { return false; + } continue; } if (feature == "textureCompressionASTC_LDR") { - if (available_features.textureCompressionASTC_LDR == VK_FALSE) + if (available_features.textureCompressionASTC_LDR == VK_FALSE) { return false; + } continue; } if (feature == "textureCompressionBC") { - if (available_features.textureCompressionBC == VK_FALSE) + if (available_features.textureCompressionBC == VK_FALSE) { return false; + } continue; } if (feature == "occlusionQueryPrecise") { - if (available_features.occlusionQueryPrecise == VK_FALSE) + if (available_features.occlusionQueryPrecise == VK_FALSE) { return false; + } continue; } if (feature == "pipelineStatisticsQuery") { - if (available_features.pipelineStatisticsQuery == VK_FALSE) + if (available_features.pipelineStatisticsQuery == VK_FALSE) { return false; + } continue; } if (feature == "vertexPipelineStoresAndAtomics") { - if (available_features.vertexPipelineStoresAndAtomics == VK_FALSE) + if (available_features.vertexPipelineStoresAndAtomics == VK_FALSE) { return false; + } continue; } if (feature == "fragmentStoresAndAtomics") { - if (available_features.fragmentStoresAndAtomics == VK_FALSE) + if (available_features.fragmentStoresAndAtomics == VK_FALSE) { return false; + } continue; } if (feature == "shaderTessellationAndGeometryPointSize") { - if (available_features.shaderTessellationAndGeometryPointSize == VK_FALSE) + if (available_features.shaderTessellationAndGeometryPointSize == + VK_FALSE) { return false; + } continue; } if (feature == "shaderImageGatherExtended") { - if (available_features.shaderImageGatherExtended == VK_FALSE) + if (available_features.shaderImageGatherExtended == VK_FALSE) { return false; + } continue; } if (feature == "shaderStorageImageExtendedFormats") { - if (available_features.shaderStorageImageExtendedFormats == VK_FALSE) + if (available_features.shaderStorageImageExtendedFormats == VK_FALSE) { return false; + } continue; } if (feature == "shaderStorageImageMultisample") { - if (available_features.shaderStorageImageMultisample == VK_FALSE) + if (available_features.shaderStorageImageMultisample == VK_FALSE) { return false; + } continue; } if (feature == "shaderStorageImageReadWithoutFormat") { - if (available_features.shaderStorageImageReadWithoutFormat == VK_FALSE) + if (available_features.shaderStorageImageReadWithoutFormat == VK_FALSE) { return false; + } continue; } if (feature == "shaderStorageImageWriteWithoutFormat") { - if (available_features.shaderStorageImageWriteWithoutFormat == VK_FALSE) + if (available_features.shaderStorageImageWriteWithoutFormat == VK_FALSE) { return false; + } continue; } if (feature == "shaderUniformBufferArrayDynamicIndexing") { if (available_features.shaderUniformBufferArrayDynamicIndexing == - VK_FALSE) + VK_FALSE) { return false; + } continue; } if (feature == "shaderSampledImageArrayDynamicIndexing") { - if (available_features.shaderSampledImageArrayDynamicIndexing == VK_FALSE) + if (available_features.shaderSampledImageArrayDynamicIndexing == + VK_FALSE) { return false; + } continue; } if (feature == "shaderStorageBufferArrayDynamicIndexing") { if (available_features.shaderStorageBufferArrayDynamicIndexing == - VK_FALSE) + VK_FALSE) { return false; + } continue; } if (feature == "shaderStorageImageArrayDynamicIndexing") { - if (available_features.shaderStorageImageArrayDynamicIndexing == VK_FALSE) + if (available_features.shaderStorageImageArrayDynamicIndexing == + VK_FALSE) { return false; + } continue; } if (feature == "shaderClipDistance") { - if (available_features.shaderClipDistance == VK_FALSE) + if (available_features.shaderClipDistance == VK_FALSE) { return false; + } continue; } if (feature == "shaderCullDistance") { - if (available_features.shaderCullDistance == VK_FALSE) + if (available_features.shaderCullDistance == VK_FALSE) { return false; + } continue; } if (feature == "shaderFloat64") { - if (available_features.shaderFloat64 == VK_FALSE) + if (available_features.shaderFloat64 == VK_FALSE) { return false; + } continue; } if (feature == "shaderInt64") { - if (available_features.shaderInt64 == VK_FALSE) + if (available_features.shaderInt64 == VK_FALSE) { return false; + } continue; } if (feature == "shaderInt16") { - if (available_features.shaderInt16 == VK_FALSE) + if (available_features.shaderInt16 == VK_FALSE) { return false; + } continue; } if (feature == "shaderResourceResidency") { - if (available_features.shaderResourceResidency == VK_FALSE) + if (available_features.shaderResourceResidency == VK_FALSE) { return false; + } continue; } if (feature == "shaderResourceMinLod") { - if (available_features.shaderResourceMinLod == VK_FALSE) + if (available_features.shaderResourceMinLod == VK_FALSE) { return false; + } continue; } if (feature == "sparseBinding") { - if (available_features.sparseBinding == VK_FALSE) + if (available_features.sparseBinding == VK_FALSE) { return false; + } continue; } if (feature == "sparseResidencyBuffer") { - if (available_features.sparseResidencyBuffer == VK_FALSE) + if (available_features.sparseResidencyBuffer == VK_FALSE) { return false; + } continue; } if (feature == "sparseResidencyImage2D") { - if (available_features.sparseResidencyImage2D == VK_FALSE) + if (available_features.sparseResidencyImage2D == VK_FALSE) { return false; + } continue; } if (feature == "sparseResidencyImage3D") { - if (available_features.sparseResidencyImage3D == VK_FALSE) + if (available_features.sparseResidencyImage3D == VK_FALSE) { return false; + } continue; } if (feature == "sparseResidency2Samples") { - if (available_features.sparseResidency2Samples == VK_FALSE) + if (available_features.sparseResidency2Samples == VK_FALSE) { return false; + } continue; } if (feature == "sparseResidency4Samples") { - if (available_features.sparseResidency4Samples == VK_FALSE) + if (available_features.sparseResidency4Samples == VK_FALSE) { return false; + } continue; } if (feature == "sparseResidency8Samples") { - if (available_features.sparseResidency8Samples == VK_FALSE) + if (available_features.sparseResidency8Samples == VK_FALSE) { return false; + } continue; } if (feature == "sparseResidency16Samples") { - if (available_features.sparseResidency16Samples == VK_FALSE) + if (available_features.sparseResidency16Samples == VK_FALSE) { return false; + } continue; } if (feature == "sparseResidencyAliased") { - if (available_features.sparseResidencyAliased == VK_FALSE) + if (available_features.sparseResidencyAliased == VK_FALSE) { return false; + } continue; } if (feature == "variableMultisampleRate") { - if (available_features.variableMultisampleRate == VK_FALSE) + if (available_features.variableMultisampleRate == VK_FALSE) { return false; + } continue; } if (feature == "inheritedQueries") { - if (available_features.inheritedQueries == VK_FALSE) + if (available_features.inheritedQueries == VK_FALSE) { return false; + } continue; } } @@ -395,8 +454,9 @@ bool AreAllRequiredFeaturesSupported( bool AreAllExtensionsSupported( const std::vector& available_extensions, const std::vector& required_extensions) { - if (required_extensions.empty()) + if (required_extensions.empty()) { return true; + } std::set required_extension_set(required_extensions.begin(), required_extensions.end()); @@ -429,8 +489,9 @@ Result Device::LoadVulkanPointers(PFN_vkGetInstanceProcAddr getInstanceProcAddr, // Note: logging Vulkan calls is done via the delegate rather than a Vulkan // layer because we want such logging even when Amber is built as a native // executable on Android, where Vulkan layers are usable only with APKs. - if (delegate && delegate->LogGraphicsCalls()) + if (delegate && delegate->LogGraphicsCalls()) { delegate->Log("Loading Vulkan Pointers"); + } #include "vk-wrappers-1-0.inc" @@ -470,8 +531,9 @@ Result Device::Initialize( const VkPhysicalDeviceProperties2KHR& available_properties2, const std::vector& available_extensions) { Result r = LoadVulkanPointers(getInstanceProcAddr, delegate_); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } // Check for the core features. We don't know if available_features or // available_features2 is provided, so check both. @@ -532,7 +594,7 @@ Result Device::Initialize( break; case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLAMP_ZERO_ONE_FEATURES_EXT: depth_clamp_zero_one_features = - static_cast(ptr); + static_cast(ptr); break; // NOLINTNEXTLINE(whitespace/line_length) case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_EXTENDED_TYPES_FEATURES: @@ -628,31 +690,38 @@ Result Device::Initialize( return amber::Result("Depth clamp zero one requested but not returned"); } if (feature == kAccelerationStructure) { - if (acceleration_structure_ptrs == nullptr) + if (acceleration_structure_ptrs == nullptr) { return amber::Result( "Acceleration structure requested but feature not returned"); - if (ptrs_.vkCreateAccelerationStructureKHR == nullptr) + } + if (ptrs_.vkCreateAccelerationStructureKHR == nullptr) { return amber::Result( "vkCreateAccelerationStructureKHR is required, but not provided"); - if (ptrs_.vkDestroyAccelerationStructureKHR == nullptr) + } + if (ptrs_.vkDestroyAccelerationStructureKHR == nullptr) { return amber::Result( "vkDestroyAccelerationStructureKHR is required, but not provided"); - if (ptrs_.vkGetAccelerationStructureBuildSizesKHR == nullptr) + } + if (ptrs_.vkGetAccelerationStructureBuildSizesKHR == nullptr) { return amber::Result( "vkGetAccelerationStructureBuildSizesKHR is required, but not " "provided"); - if (ptrs_.vkBuildAccelerationStructuresKHR == nullptr) + } + if (ptrs_.vkBuildAccelerationStructuresKHR == nullptr) { return amber::Result( "vkBuildAccelerationStructuresKHR is required, but not " "provided"); - if (ptrs_.vkCmdBuildAccelerationStructuresKHR == nullptr) + } + if (ptrs_.vkCmdBuildAccelerationStructuresKHR == nullptr) { return amber::Result( "vkCmdBuildAccelerationStructuresKHR is required, but not " "provided"); - if (ptrs_.vkGetAccelerationStructureDeviceAddressKHR == nullptr) + } + if (ptrs_.vkGetAccelerationStructureDeviceAddressKHR == nullptr) { return amber::Result( "vkGetAccelerationStructureDeviceAddressKHR is required, but not " "provided"); + } } if (feature == kBufferDeviceAddress && bda_ptrs == nullptr && vulkan12_ptrs == nullptr) { @@ -660,19 +729,22 @@ Result Device::Initialize( "Buffer device address requested but feature not returned"); } if (feature == kRayTracingPipeline) { - if (ray_tracing_pipeline_ptrs == nullptr) + if (ray_tracing_pipeline_ptrs == nullptr) { return amber::Result( "Ray tracing pipeline requested but feature not returned"); - if (ptrs_.vkCreateRayTracingPipelinesKHR == nullptr) + } + if (ptrs_.vkCreateRayTracingPipelinesKHR == nullptr) { return amber::Result( "vkCreateRayTracingPipelinesKHR is required, but not provided"); - if (ptrs_.vkCmdTraceRaysKHR == nullptr) - return amber::Result( - "vkCmdTraceRaysKHR is required, but not provided"); - if (ptrs_.vkGetRayTracingShaderGroupHandlesKHR == nullptr) + } + if (ptrs_.vkCmdTraceRaysKHR == nullptr) { + return amber::Result("vkCmdTraceRaysKHR is required, but not provided"); + } + if (ptrs_.vkGetRayTracingShaderGroupHandlesKHR == nullptr) { return amber::Result( "vkGetRayTracingShaderGroupHandlesKHR is required, but not " "provided"); + } } // Next check the fields of the feature structures. @@ -893,10 +965,11 @@ Result Device::Initialize( int supported = -1; if (supported == -1 && prefix == "FloatControlsProperties") { - if (pfc == nullptr && pv12 == nullptr) + if (pfc == nullptr && pv12 == nullptr) { return Result( "Vulkan: Device::Initialize given physical device does not support " "required float control properties"); + } CHK_P(supported, name, shaderSignedZeroInfNanPreserveFloat16, pfc, pv12); CHK_P(supported, name, shaderSignedZeroInfNanPreserveFloat32, pfc, pv12); @@ -915,11 +988,13 @@ Result Device::Initialize( CHK_P(supported, name, shaderRoundingModeRTZFloat64, pfc, pv12); } - if (supported == 0) + if (supported == 0) { return Result("Vulkan: Device::Initialize missing " + prop + " property"); + } - if (supported == -1) + if (supported == -1) { return Result("Vulkan: Device::Initialize property not handled " + prop); + } } ptrs_.vkGetPhysicalDeviceMemoryProperties(physical_device_, @@ -934,14 +1009,18 @@ Result Device::Initialize( bool needs_subgroup_supported_stages = false; // Search for subgroup supported operations requirements. - for (const auto& feature : required_features) - if (feature.find(kSubgroupSupportedOperations) != std::string::npos) + for (const auto& feature : required_features) { + if (feature.find(kSubgroupSupportedOperations) != std::string::npos) { needs_subgroup_supported_operations = true; + } + } // Search for subgroup supported stages requirements. - for (const auto& feature : required_features) - if (feature.find(kSubgroupSupportedStages) != std::string::npos) + for (const auto& feature : required_features) { + if (feature.find(kSubgroupSupportedStages) != std::string::npos) { needs_subgroup_supported_stages = true; + } + } const bool needs_subgroup_properties = needs_subgroup_supported_operations || needs_subgroup_supported_stages; diff --git a/src/vulkan/engine_vulkan.cc b/src/vulkan/engine_vulkan.cc index 18e506adb..e63eca89b 100644 --- a/src/vulkan/engine_vulkan.cc +++ b/src/vulkan/engine_vulkan.cc @@ -82,8 +82,9 @@ Result ToVkShaderStage(ShaderType type, VkShaderStageFlagBits* ret) { bool AreAllExtensionsSupported( const std::vector& available_extensions, const std::vector& required_extensions) { - if (required_extensions.empty()) + if (required_extensions.empty()) { return true; + } std::set required_extension_set(required_extensions.begin(), required_extensions.end()); @@ -118,18 +119,23 @@ Result EngineVulkan::Initialize( const std::vector& properties, const std::vector& instance_extensions, const std::vector& device_extensions) { - if (device_) + if (device_) { return Result("Vulkan::Initialize device_ already exists"); + } VulkanEngineConfig* vk_config = static_cast(config); - if (!vk_config || vk_config->vkGetInstanceProcAddr == VK_NULL_HANDLE) + if (!vk_config || vk_config->vkGetInstanceProcAddr == VK_NULL_HANDLE) { return Result("Vulkan::Initialize vkGetInstanceProcAddr must be provided."); - if (vk_config->device == VK_NULL_HANDLE) + } + if (vk_config->device == VK_NULL_HANDLE) { return Result("Vulkan::Initialize device must be provided"); - if (vk_config->physical_device == VK_NULL_HANDLE) + } + if (vk_config->physical_device == VK_NULL_HANDLE) { return Result("Vulkan::Initialize physical device handle is null."); - if (vk_config->queue == VK_NULL_HANDLE) + } + if (vk_config->queue == VK_NULL_HANDLE) { return Result("Vulkan::Initialize queue handle is null."); + } // Validate instance extensions if (!AreAllExtensionsSupported(vk_config->available_instance_extensions, @@ -145,14 +151,16 @@ Result EngineVulkan::Initialize( vk_config->vkGetInstanceProcAddr, features, properties, device_extensions, vk_config->available_features, vk_config->available_features2, vk_config->available_properties2, vk_config->available_device_extensions); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } if (!pool_) { pool_ = MakeUnique(device_.get()); r = pool_->Initialize(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } return {}; @@ -165,14 +173,16 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { for (size_t i = 0; i < pipeline->GetShaders().size(); i++) { Result r = SetShader(pipeline, pipeline->GetShaders()[i], i); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } for (const auto& colour_info : pipeline->GetColorAttachments()) { auto fmt = colour_info.buffer->GetFormat(); - if (!device_->IsFormatSupportedByPhysicalDevice(*fmt, colour_info.type)) + if (!device_->IsFormatSupportedByPhysicalDevice(*fmt, colour_info.type)) { return Result("Vulkan color attachment format is not supported"); + } } if (pipeline->GetDepthStencilBuffer().buffer) { @@ -187,8 +197,9 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { std::vector stage_create_info; Result r = GetVkShaderStageInfo(pipeline, &stage_create_info); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } const auto& engine_data = GetEngineData(); std::unique_ptr vk_pipeline; @@ -196,8 +207,9 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { std::vector shader_group_create_info; r = GetVkShaderGroupInfo(pipeline, &shader_group_create_info); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } vk_pipeline = MakeUnique( device_.get(), &blases_, &tlases_, engine_data.fence_timeout_ms, @@ -225,8 +237,9 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { pool_.get()); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } info.vk_pipeline = std::move(vk_pipeline); @@ -234,8 +247,9 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { for (const auto& shader_info : pipeline->GetShaders()) { VkShaderStageFlagBits stage = VK_SHADER_STAGE_FLAG_BITS_MAX_ENUM; r = ToVkShaderStage(shader_info.GetShaderType(), &stage); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } const auto& name = shader_info.GetEntryPoint(); if (!name.empty()) { info.vk_pipeline->SetEntryPointName(stage, name); @@ -244,10 +258,12 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { for (const auto& vtex_info : pipeline->GetVertexBuffers()) { auto fmt = vtex_info.buffer->GetFormat(); - if (!device_->IsFormatSupportedByPhysicalDevice(*fmt, vtex_info.type)) + if (!device_->IsFormatSupportedByPhysicalDevice(*fmt, vtex_info.type)) { return Result("Vulkan vertex buffer format is not supported"); - if (!info.vertex_buffer) + } + if (!info.vertex_buffer) { info.vertex_buffer = MakeUnique(device_.get()); + } info.vertex_buffer->SetData(static_cast(vtex_info.location), vtex_info.buffer, vtex_info.input_rate, @@ -263,8 +279,9 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { if (pipeline->GetPushConstantBuffer().buffer != nullptr) { r = info.vk_pipeline->AddPushConstantBuffer( pipeline->GetPushConstantBuffer().buffer, 0); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } for (const auto& buf_info : pipeline->GetBuffers()) { @@ -307,8 +324,9 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { } r = info.vk_pipeline->AddBufferDescriptor(cmd.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } for (const auto& sampler_info : pipeline->GetSamplers()) { @@ -318,8 +336,9 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { cmd->SetSampler(sampler_info.sampler); r = info.vk_pipeline->AddSamplerDescriptor(cmd.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } if (info.vk_pipeline->IsRayTracing()) { @@ -330,8 +349,9 @@ Result EngineVulkan::CreatePipeline(amber::Pipeline* pipeline) { cmd->SetTLAS(tlas_info.tlas); r = info.vk_pipeline->AddTLASDescriptor(cmd.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } } @@ -349,8 +369,9 @@ Result EngineVulkan::SetShader(amber::Pipeline* pipeline, if (!rt) { auto it = info.shader_info.find(type); - if (it != info.shader_info.end()) + if (it != info.shader_info.end()) { return Result("Vulkan::Setting Duplicated Shader Types Fail"); + } } VkShaderModule shader_module = VK_NULL_HANDLE; @@ -385,8 +406,9 @@ Result EngineVulkan::SetShader(amber::Pipeline* pipeline, } for (auto& shader_info : pipeline->GetShaders()) { - if (shader_info.GetShaderType() != type) + if (shader_info.GetShaderType() != type) { continue; + } const auto required_subgroup_size_setting = shader_info.GetRequiredSubgroupSizeSetting(); @@ -426,8 +448,9 @@ Result EngineVulkan::SetShader(amber::Pipeline* pipeline, } const auto& shader_spec_info = shader_info.GetSpecialization(); - if (shader_spec_info.empty()) + if (shader_spec_info.empty()) { continue; + } auto& entries = info.shader_info[type].specialization_entries; entries.reset(new std::vector()); @@ -458,8 +481,9 @@ Result EngineVulkan::GetVkShaderStageInfo( VkPipelineShaderStageCreateInfo* stage_info) { VkShaderStageFlagBits stage = VK_SHADER_STAGE_FLAG_BITS_MAX_ENUM; Result r = ToVkShaderStage(shader_type, &stage); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } *stage_info = VkPipelineShaderStageCreateInfo(); stage_info->sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; @@ -488,16 +512,18 @@ Result EngineVulkan::GetVkShaderStageInfo( for (size_t i = 0; i < info.shader_info_rt.size(); i++) { Result r = GetVkShaderStageInfo(info.shader_info_rt[i].type, info.shader_info_rt[i], &stage_info[i]); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } } else { uint32_t stage_count = 0; for (auto& it : info.shader_info) { Result r = GetVkShaderStageInfo(it.first, it.second, &stage_info[stage_count]); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } if (it.first == kShaderTypeCompute && it.second.required_subgroup_size > 0) { @@ -530,8 +556,9 @@ Result EngineVulkan::GetVkShaderGroupInfo( auto& g = groups[i]; ShaderGroup* sg = g.get(); - if (sg == nullptr) + if (sg == nullptr) { return Result("Invalid shader group"); + } VkRayTracingShaderGroupCreateInfoKHR group_info = { VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR, @@ -547,8 +574,9 @@ Result EngineVulkan::GetVkShaderGroupInfo( group_info.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR; r = pipeline->GetShaderIndex(sg->GetGeneralShader(), &group_info.generalShader); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (sg->IsHitGroup()) { group_info.type = sg->GetIntersectionShader() == nullptr @@ -558,22 +586,25 @@ Result EngineVulkan::GetVkShaderGroupInfo( if (sg->GetClosestHitShader()) { r = pipeline->GetShaderIndex(sg->GetClosestHitShader(), &group_info.closestHitShader); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } if (sg->GetAnyHitShader()) { r = pipeline->GetShaderIndex(sg->GetAnyHitShader(), &group_info.anyHitShader); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } if (sg->GetIntersectionShader()) { r = pipeline->GetShaderIndex(sg->GetIntersectionShader(), &group_info.intersectionShader); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } } else { return Result("Uninitialized shader group"); @@ -587,8 +618,9 @@ Result EngineVulkan::GetVkShaderGroupInfo( Result EngineVulkan::DoClearColor(const ClearColorCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline->IsGraphics()) + if (!info.vk_pipeline->IsGraphics()) { return Result("Vulkan::Clear Color Command for Non-Graphics Pipeline"); + } return info.vk_pipeline->AsGraphics()->SetClearColor( command->GetR(), command->GetG(), command->GetB(), command->GetA()); @@ -596,32 +628,36 @@ Result EngineVulkan::DoClearColor(const ClearColorCommand* command) { Result EngineVulkan::DoClearStencil(const ClearStencilCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline->IsGraphics()) + if (!info.vk_pipeline->IsGraphics()) { return Result("Vulkan::Clear Stencil Command for Non-Graphics Pipeline"); + } return info.vk_pipeline->AsGraphics()->SetClearStencil(command->GetValue()); } Result EngineVulkan::DoClearDepth(const ClearDepthCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline->IsGraphics()) + if (!info.vk_pipeline->IsGraphics()) { return Result("Vulkan::Clear Depth Command for Non-Graphics Pipeline"); + } return info.vk_pipeline->AsGraphics()->SetClearDepth(command->GetValue()); } Result EngineVulkan::DoClear(const ClearCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline->IsGraphics()) + if (!info.vk_pipeline->IsGraphics()) { return Result("Vulkan::Clear Command for Non-Graphics Pipeline"); + } return info.vk_pipeline->AsGraphics()->Clear(); } Result EngineVulkan::DoDrawRect(const DrawRectCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline->IsGraphics()) + if (!info.vk_pipeline->IsGraphics()) { return Result("Vulkan::DrawRect for Non-Graphics Pipeline"); + } auto* graphics = info.vk_pipeline->AsGraphics(); @@ -681,16 +717,18 @@ Result EngineVulkan::DoDrawRect(const DrawRectCommand* command) { Result r = graphics->Draw(&draw, vertex_buffer.get(), command->IsTimedExecution()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } Result EngineVulkan::DoDrawGrid(const DrawGridCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline->IsGraphics()) + if (!info.vk_pipeline->IsGraphics()) { return Result("Vulkan::DrawGrid for Non-Graphics Pipeline"); + } auto* graphics = info.vk_pipeline->AsGraphics(); @@ -772,16 +810,18 @@ Result EngineVulkan::DoDrawGrid(const DrawGridCommand* command) { Result r = graphics->Draw(&draw, vertex_buffer.get(), command->IsTimedExecution()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } Result EngineVulkan::DoDrawArrays(const DrawArraysCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline) + if (!info.vk_pipeline) { return Result("Vulkan::DrawArrays for Non-Graphics Pipeline"); + } return info.vk_pipeline->AsGraphics()->Draw(command, info.vertex_buffer.get(), command->IsTimedExecution()); @@ -789,8 +829,9 @@ Result EngineVulkan::DoDrawArrays(const DrawArraysCommand* command) { Result EngineVulkan::DoCompute(const ComputeCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline->IsCompute()) + if (!info.vk_pipeline->IsCompute()) { return Result("Vulkan: Compute called for non-compute pipeline."); + } return info.vk_pipeline->AsCompute()->Compute( command->GetX(), command->GetY(), command->GetZ(), @@ -810,8 +851,9 @@ Result EngineVulkan::InitDependendLibraries(amber::Pipeline* pipeline, if (!sub_pipeline->GetPipelineLibraries().empty()) { Result r = InitDependendLibraries(sub_pipeline, &sub_libs); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } if (vk_sub_pipeline->GetVkPipeline() == VK_NULL_HANDLE) { @@ -833,16 +875,18 @@ Result EngineVulkan::InitDependendLibraries(amber::Pipeline* pipeline, Result EngineVulkan::DoTraceRays(const RayTracingCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline->IsRayTracing()) + if (!info.vk_pipeline->IsRayTracing()) { return Result("Vulkan: RayTracing called for non-RayTracing pipeline."); + } amber::Pipeline* pipeline = command->GetPipeline(); std::vector libs; if (!pipeline->GetPipelineLibraries().empty()) { Result r = InitDependendLibraries(pipeline, &libs); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } amber::SBT* rSBT = pipeline->GetSBT(command->GetRayGenSBTName()); @@ -860,13 +904,15 @@ Result EngineVulkan::DoTraceRays(const RayTracingCommand* command) { Result EngineVulkan::DoEntryPoint(const EntryPointCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline) + if (!info.vk_pipeline) { return Result("Vulkan::DoEntryPoint no Pipeline exists"); + } VkShaderStageFlagBits stage = VK_SHADER_STAGE_FLAG_BITS_MAX_ENUM; Result r = ToVkShaderStage(command->GetShaderType(), &stage); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } info.vk_pipeline->SetEntryPointName(stage, command->GetEntryPointName()); return {}; @@ -875,8 +921,9 @@ Result EngineVulkan::DoEntryPoint(const EntryPointCommand* command) { Result EngineVulkan::DoPatchParameterVertices( const PatchParameterVerticesCommand* command) { auto& info = pipeline_map_[command->GetPipeline()]; - if (!info.vk_pipeline->IsGraphics()) + if (!info.vk_pipeline->IsGraphics()) { return Result("Vulkan::DoPatchParameterVertices for Non-Graphics Pipeline"); + } info.vk_pipeline->AsGraphics()->SetPatchControlPoints( command->GetControlPointCount()); diff --git a/src/vulkan/frame_buffer.cc b/src/vulkan/frame_buffer.cc index b6ad13aeb..889c2a41f 100644 --- a/src/vulkan/frame_buffer.cc +++ b/src/vulkan/frame_buffer.cc @@ -53,8 +53,9 @@ Result FrameBuffer::Initialize(VkRenderPass render_pass) { if (!color_attachments_.empty()) { std::vector seen_idx(color_attachments_.size(), -1); for (auto* info : color_attachments_) { - if (info->location >= color_attachments_.size()) + if (info->location >= color_attachments_.size()) { return Result("color attachment locations must be sequential from 0"); + } if (seen_idx[info->location] != -1) { return Result("duplicate attachment location: " + std::to_string(info->location)); @@ -74,8 +75,9 @@ Result FrameBuffer::Initialize(VkRenderPass render_pass) { info->base_mip_level, 1u, info->buffer->GetSamples())); Result r = color_images_.back()->Initialize(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } attachments[info->location] = color_images_.back()->GetVkImageView(); } @@ -84,10 +86,12 @@ Result FrameBuffer::Initialize(VkRenderPass render_pass) { if (depth_stencil_attachment_.buffer && depth_stencil_attachment_.buffer->GetFormat()->IsFormatKnown()) { VkImageAspectFlags aspect = 0; - if (depth_stencil_attachment_.buffer->GetFormat()->HasDepthComponent()) + if (depth_stencil_attachment_.buffer->GetFormat()->HasDepthComponent()) { aspect |= VK_IMAGE_ASPECT_DEPTH_BIT; - if (depth_stencil_attachment_.buffer->GetFormat()->HasStencilComponent()) + } + if (depth_stencil_attachment_.buffer->GetFormat()->HasStencilComponent()) { aspect |= VK_IMAGE_ASPECT_STENCIL_BIT; + } assert(aspect != 0); const VkImageUsageFlags usage_flags = @@ -99,8 +103,9 @@ Result FrameBuffer::Initialize(VkRenderPass render_pass) { VK_IMAGE_TYPE_2D, usage_flags, width_, height_, depth_, 1u, 0u, 1u, 1u); Result r = depth_stencil_image_->Initialize(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } attachments.push_back(depth_stencil_image_->GetVkImageView()); } @@ -115,8 +120,9 @@ Result FrameBuffer::Initialize(VkRenderPass render_pass) { 1u)); Result r = resolve_images_.back()->Initialize(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } attachments.push_back(resolve_images_.back()->GetVkImageView()); } @@ -144,14 +150,17 @@ void FrameBuffer::ChangeFrameLayout(CommandBuffer* command, VkPipelineStageFlags color_stage, VkImageLayout depth_layout, VkPipelineStageFlags depth_stage) { - for (auto& img : color_images_) + for (auto& img : color_images_) { img->ImageBarrier(command, color_layout, color_stage); + } - for (auto& img : resolve_images_) + for (auto& img : resolve_images_) { img->ImageBarrier(command, color_layout, color_stage); + } - if (depth_stencil_image_) + if (depth_stencil_image_) { depth_stencil_image_->ImageBarrier(command, depth_layout, depth_stage); + } } void FrameBuffer::ChangeFrameToDrawLayout(CommandBuffer* command) { @@ -183,14 +192,17 @@ void FrameBuffer::ChangeFrameToWriteLayout(CommandBuffer* command) { } void FrameBuffer::TransferImagesToHost(CommandBuffer* command) { - for (auto& img : color_images_) + for (auto& img : color_images_) { img->CopyToHost(command); + } - for (auto& img : resolve_images_) + for (auto& img : resolve_images_) { img->CopyToHost(command); + } - if (depth_stencil_image_) + if (depth_stencil_image_) { depth_stencil_image_->CopyToHost(command); + } } void FrameBuffer::CopyImagesToBuffers() { @@ -221,11 +233,13 @@ void FrameBuffer::CopyImagesToBuffers() { } void FrameBuffer::TransferImagesToDevice(CommandBuffer* command) { - for (auto& img : color_images_) + for (auto& img : color_images_) { img->CopyToDevice(command); + } - if (depth_stencil_image_) + if (depth_stencil_image_) { depth_stencil_image_->CopyToDevice(command); + } } void FrameBuffer::CopyBuffersToImages() { @@ -234,8 +248,9 @@ void FrameBuffer::CopyBuffersToImages() { auto* info = color_attachments_[i]; auto* values = info->buffer->ValuePtr(); // Nothing to do if our local buffer is empty - if (values->empty()) + if (values->empty()) { continue; + } std::memcpy(img->HostAccessibleMemoryPtr(), values->data(), info->buffer->GetSizeInBytes()); @@ -246,8 +261,9 @@ void FrameBuffer::CopyBuffersToImages() { auto* info = resolve_targets_[i]; auto* values = info->buffer->ValuePtr(); // Nothing to do if our local buffer is empty - if (values->empty()) + if (values->empty()) { continue; + } std::memcpy(img->HostAccessibleMemoryPtr(), values->data(), info->buffer->GetSizeInBytes()); diff --git a/src/vulkan/graphics_pipeline.cc b/src/vulkan/graphics_pipeline.cc index 556c91f3e..592c9ac5a 100644 --- a/src/vulkan/graphics_pipeline.cc +++ b/src/vulkan/graphics_pipeline.cc @@ -400,10 +400,12 @@ GraphicsPipeline::GraphicsPipeline( pipeline_runtime_layer_enabled, shader_stage_info), depth_stencil_buffer_(depth_stencil_buffer) { - for (const auto& info : color_buffers) + for (const auto& info : color_buffers) { color_buffers_.push_back(&info); - for (const auto& info : resolve_targets) + } + for (const auto& info : resolve_targets) { resolve_targets_.push_back(&info); + } } GraphicsPipeline::~GraphicsPipeline() { @@ -736,19 +738,22 @@ Result GraphicsPipeline::Initialize(uint32_t width, uint32_t height, CommandPool* pool) { Result r = Pipeline::Initialize(pool); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = CreateRenderPass(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } frame_ = MakeUnique(device_, color_buffers_, depth_stencil_buffer_, resolve_targets_, width, height); r = frame_->Initialize(render_pass_); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } frame_width_ = width; frame_height_ = height; @@ -758,8 +763,9 @@ Result GraphicsPipeline::Initialize(uint32_t width, Result GraphicsPipeline::SendVertexBufferDataIfNeeded( VertexBuffer* vertex_buffer) { - if (!vertex_buffer || vertex_buffer->VertexDataSent()) + if (!vertex_buffer || vertex_buffer->VertexDataSent()) { return {}; + } return vertex_buffer->SendVertexData(command_.get()); } @@ -773,12 +779,14 @@ Result GraphicsPipeline::SetIndexBuffer(Buffer* buffer) { index_buffer_ = MakeUnique(device_); CommandBufferGuard guard(GetCommandBuffer()); - if (!guard.IsRecording()) + if (!guard.IsRecording()) { return guard.GetResult(); + } Result r = index_buffer_->SendIndexData(command_.get(), buffer); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return guard.Submit(GetFenceTimeout(), GetPipelineRuntimeLayerEnabled()); } @@ -821,8 +829,9 @@ Result GraphicsPipeline::Clear() { {clear_color_r_, clear_color_g_, clear_color_b_, clear_color_a_}}; CommandBufferGuard cmd_buf_guard(GetCommandBuffer()); - if (!cmd_buf_guard.IsRecording()) + if (!cmd_buf_guard.IsRecording()) { return cmd_buf_guard.GetResult(); + } frame_->ChangeFrameToWriteLayout(GetCommandBuffer()); frame_->CopyBuffersToImages(); @@ -847,8 +856,9 @@ Result GraphicsPipeline::Clear() { depth_stencil_clear.depthStencil = {clear_depth_, clear_stencil_}; VkImageAspectFlags aspect = VK_IMAGE_ASPECT_DEPTH_BIT; - if (depth_stencil_buffer_.buffer->GetFormat()->HasStencilComponent()) + if (depth_stencil_buffer_.buffer->GetFormat()->HasStencilComponent()) { aspect |= VK_IMAGE_ASPECT_STENCIL_BIT; + } VkClearAttachment clear_attachment = VkClearAttachment(); clear_attachment.aspectMask = aspect; @@ -873,8 +883,9 @@ Result GraphicsPipeline::Clear() { Result r = cmd_buf_guard.Submit(GetFenceTimeout(), GetPipelineRuntimeLayerEnabled()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } frame_->CopyImagesToBuffers(); return {}; @@ -884,20 +895,23 @@ Result GraphicsPipeline::Draw(const DrawArraysCommand* command, VertexBuffer* vertex_buffer, bool is_timed_execution) { Result r = SendDescriptorDataToDeviceIfNeeded(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } VkPipelineLayout pipeline_layout = VK_NULL_HANDLE; r = CreateVkPipelineLayout(&pipeline_layout); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } VkPipeline pipeline = VK_NULL_HANDLE; r = CreateVkGraphicsPipeline(command->GetPipelineData(), ToVkTopology(command->GetTopology()), vertex_buffer, pipeline_layout, &pipeline); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } // Note that a command updating a descriptor set and a command using // it must be submitted separately, because using a descriptor set @@ -906,12 +920,14 @@ Result GraphicsPipeline::Draw(const DrawArraysCommand* command, CreateTimingQueryObjectIfNeeded(is_timed_execution); { CommandBufferGuard cmd_buf_guard(GetCommandBuffer()); - if (!cmd_buf_guard.IsRecording()) + if (!cmd_buf_guard.IsRecording()) { return cmd_buf_guard.GetResult(); + } r = SendVertexBufferDataIfNeeded(vertex_buffer); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } frame_->ChangeFrameToWriteLayout(GetCommandBuffer()); frame_->CopyBuffersToImages(); @@ -927,23 +943,27 @@ Result GraphicsPipeline::Draw(const DrawArraysCommand* command, BindVkDescriptorSets(pipeline_layout); r = RecordPushConstant(pipeline_layout); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } device_->GetPtrs()->vkCmdBindPipeline(command_->GetVkCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - if (vertex_buffer != nullptr) + if (vertex_buffer != nullptr) { vertex_buffer->BindToCommandBuffer(command_.get()); + } if (command->IsIndexed()) { - if (!index_buffer_) + if (!index_buffer_) { return Result("Vulkan: Draw indexed is used without given indices"); + } r = index_buffer_->BindToCommandBuffer(command_.get()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } // VkRunner spec says // "vertexCount will be used as the index count, firstVertex @@ -969,13 +989,15 @@ Result GraphicsPipeline::Draw(const DrawArraysCommand* command, r = cmd_buf_guard.Submit(GetFenceTimeout(), GetPipelineRuntimeLayerEnabled()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } DestroyTimingQueryObjectIfNeeded(); r = ReadbackDescriptorsToHostDataQueue(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } frame_->CopyImagesToBuffers(); diff --git a/src/vulkan/image_descriptor.cc b/src/vulkan/image_descriptor.cc index 1d20244ad..4edd3b22a 100644 --- a/src/vulkan/image_descriptor.cc +++ b/src/vulkan/image_descriptor.cc @@ -41,8 +41,9 @@ Result ImageDescriptor::CreateResourceIfNeeded() { auto& transfer_resources = pipeline_->GetDescriptorTransferResources(); for (const auto& amber_buffer : GetAmberBuffers()) { - if (amber_buffer->ValuePtr()->empty()) + if (amber_buffer->ValuePtr()->empty()) { continue; + } // Check if the transfer image is already created. if (transfer_resources.count(amber_buffer) > 0) { @@ -99,8 +100,9 @@ Result ImageDescriptor::CreateResourceIfNeeded() { if (amber_sampler_) { Result r = vulkan_sampler_.CreateSampler(amber_sampler_); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } is_descriptor_set_update_needed_ = true; @@ -109,8 +111,9 @@ Result ImageDescriptor::CreateResourceIfNeeded() { void ImageDescriptor::UpdateDescriptorSetIfNeeded( VkDescriptorSet descriptor_set) { - if (!is_descriptor_set_update_needed_) + if (!is_descriptor_set_update_needed_) { return; + } // Always use general layout. VkImageLayout layout = VK_IMAGE_LAYOUT_GENERAL; diff --git a/src/vulkan/index_buffer.cc b/src/vulkan/index_buffer.cc index 30b223d9b..a64e026a9 100644 --- a/src/vulkan/index_buffer.cc +++ b/src/vulkan/index_buffer.cc @@ -33,28 +33,32 @@ Result IndexBuffer::SendIndexData(CommandBuffer* command, Buffer* buffer) { "IndexBuffer::SendIndexData must be called once when it is created"); } - if (buffer->ElementCount() == 0) + if (buffer->ElementCount() == 0) { return Result("IndexBuffer::SendIndexData |buffer| is empty"); + } - if (buffer->GetFormat()->IsUint32()) + if (buffer->GetFormat()->IsUint32()) { index_type_ = VK_INDEX_TYPE_UINT32; - else if (buffer->GetFormat()->IsUint16()) + } else if (buffer->GetFormat()->IsUint16()) { index_type_ = VK_INDEX_TYPE_UINT16; - else if (buffer->GetFormat()->IsUint8()) + } else if (buffer->GetFormat()->IsUint8()) { index_type_ = VK_INDEX_TYPE_UINT8_EXT; - else + } else { return Result("IndexBuffer::SendIndexData unexpected index buffer format"); + } transfer_buffer_ = MakeUnique(device_, buffer->GetSizeInBytes(), nullptr); Result r = transfer_buffer_->AddUsageFlags(VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = transfer_buffer_->Initialize(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } std::memcpy(transfer_buffer_->HostAccessibleMemoryPtr(), buffer->ValuePtr()->data(), buffer->GetSizeInBytes()); diff --git a/src/vulkan/pipeline.cc b/src/vulkan/pipeline.cc index fd8dd4eef..6274778ae 100644 --- a/src/vulkan/pipeline.cc +++ b/src/vulkan/pipeline.cc @@ -72,8 +72,9 @@ Pipeline::~Pipeline() { info.layout, nullptr); } - if (info.empty) + if (info.empty) { continue; + } if (info.pool != VK_NULL_HANDLE) { device_->GetPtrs()->vkDestroyDescriptorPool(device_->GetVkDevice(), @@ -144,8 +145,9 @@ Result Pipeline::CreateDescriptorSetLayouts() { Result Pipeline::CreateDescriptorPools() { for (auto& info : descriptor_set_info_) { - if (info.empty) + if (info.empty) { continue; + } std::vector pool_sizes; for (auto& desc : info.descriptors) { @@ -182,8 +184,9 @@ Result Pipeline::CreateDescriptorPools() { Result Pipeline::CreateDescriptorSets() { for (size_t i = 0; i < descriptor_set_info_.size(); ++i) { - if (descriptor_set_info_[i].empty) + if (descriptor_set_info_[i].empty) { continue; + } VkDescriptorSetAllocateInfo desc_set_info = VkDescriptorSetAllocateInfo(); desc_set_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; @@ -204,12 +207,14 @@ Result Pipeline::CreateDescriptorSets() { Result Pipeline::CreateVkPipelineLayout(VkPipelineLayout* pipeline_layout) { Result r = CreateVkDescriptorRelatedObjectsIfNeeded(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } std::vector descriptor_set_layouts; - for (const auto& desc_set : descriptor_set_info_) + for (const auto& desc_set : descriptor_set_info_) { descriptor_set_layouts.push_back(desc_set.layout); + } VkPipelineLayoutCreateInfo pipeline_layout_info = VkPipelineLayoutCreateInfo(); @@ -235,20 +240,24 @@ Result Pipeline::CreateVkPipelineLayout(VkPipelineLayout* pipeline_layout) { } Result Pipeline::CreateVkDescriptorRelatedObjectsIfNeeded() { - if (descriptor_related_objects_already_created_) + if (descriptor_related_objects_already_created_) { return {}; + } Result r = CreateDescriptorSetLayouts(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = CreateDescriptorPools(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = CreateDescriptorSets(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } descriptor_related_objects_already_created_ = true; return {}; @@ -256,8 +265,9 @@ Result Pipeline::CreateVkDescriptorRelatedObjectsIfNeeded() { void Pipeline::UpdateDescriptorSetsIfNeeded() { for (auto& info : descriptor_set_info_) { - for (auto& desc : info.descriptors) + for (auto& desc : info.descriptors) { desc->UpdateDescriptorSetIfNeeded(info.vk_desc_set); + } } } @@ -345,8 +355,9 @@ Result Pipeline::RecordPushConstant(const VkPipelineLayout& pipeline_layout) { } Result Pipeline::AddPushConstantBuffer(const Buffer* buf, uint32_t offset) { - if (!buf) + if (!buf) { return Result("Missing push constant buffer data"); + } return push_constant_->AddBuffer(buf, offset); } @@ -375,8 +386,9 @@ Result Pipeline::GetDescriptorSlot(uint32_t desc_set, auto& descriptors = descriptor_set_info_[desc_set].descriptors; for (auto& descriptor : descriptors) { - if (descriptor->GetBinding() == binding) + if (descriptor->GetBinding() == binding) { *desc = descriptor.get(); + } } return {}; @@ -395,8 +407,9 @@ Result Pipeline::AddDescriptorBuffer(Buffer* amber_buffer) { } Result Pipeline::AddBufferDescriptor(const BufferCommand* cmd) { - if (cmd == nullptr) + if (cmd == nullptr) { return Result("Pipeline::AddBufferDescriptor BufferCommand is nullptr"); + } if (!cmd->IsSSBO() && !cmd->IsUniform() && !cmd->IsStorageImage() && !cmd->IsSampledImage() && !cmd->IsCombinedImageSampler() && !cmd->IsUniformTexelBuffer() && !cmd->IsStorageTexelBuffer() && @@ -407,8 +420,9 @@ Result Pipeline::AddBufferDescriptor(const BufferCommand* cmd) { Descriptor* desc; Result r = GetDescriptorSlot(cmd->GetDescriptorSet(), cmd->GetBinding(), &desc); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } auto& descriptors = descriptor_set_info_[cmd->GetDescriptorSet()].descriptors; @@ -441,8 +455,9 @@ Result Pipeline::AddBufferDescriptor(const BufferCommand* cmd) { auto image_desc = MakeUnique( cmd->GetBuffer(), desc_type, device_, cmd->GetBaseMipLevel(), cmd->GetDescriptorSet(), cmd->GetBinding(), this); - if (cmd->IsCombinedImageSampler()) + if (cmd->IsCombinedImageSampler()) { image_desc->SetAmberSampler(cmd->GetSampler()); + } descriptors.push_back(std::move(image_desc)); } else { @@ -463,8 +478,9 @@ Result Pipeline::AddBufferDescriptor(const BufferCommand* cmd) { AddDescriptorBuffer(cmd->GetBuffer()); } - if (cmd->IsUniformDynamic() || cmd->IsSSBODynamic()) + if (cmd->IsUniformDynamic() || cmd->IsSSBODynamic()) { desc->AsBufferDescriptor()->AddDynamicOffset(cmd->GetDynamicOffset()); + } if (cmd->IsUniform() || cmd->IsUniformDynamic() || cmd->IsSSBO() || cmd->IsSSBODynamic()) { @@ -490,14 +506,16 @@ Result Pipeline::AddBufferDescriptor(const BufferCommand* cmd) { } Result Pipeline::AddSamplerDescriptor(const SamplerCommand* cmd) { - if (cmd == nullptr) + if (cmd == nullptr) { return Result("Pipeline::AddSamplerDescriptor SamplerCommand is nullptr"); + } Descriptor* desc; Result r = GetDescriptorSlot(cmd->GetDescriptorSet(), cmd->GetBinding(), &desc); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } auto& descriptors = descriptor_set_info_[cmd->GetDescriptorSet()].descriptors; @@ -519,14 +537,16 @@ Result Pipeline::AddSamplerDescriptor(const SamplerCommand* cmd) { } Result Pipeline::AddTLASDescriptor(const TLASCommand* cmd) { - if (cmd == nullptr) + if (cmd == nullptr) { return Result("Pipeline::AddTLASDescriptor TLASCommand is nullptr"); + } Descriptor* desc; Result r = GetDescriptorSlot(cmd->GetDescriptorSet(), cmd->GetBinding(), &desc); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } auto& descriptors = descriptor_set_info_[cmd->GetDescriptorSet()].descriptors; @@ -550,14 +570,16 @@ Result Pipeline::AddTLASDescriptor(const TLASCommand* cmd) { Result Pipeline::SendDescriptorDataToDeviceIfNeeded() { { CommandBufferGuard guard(GetCommandBuffer()); - if (!guard.IsRecording()) + if (!guard.IsRecording()) { return guard.GetResult(); + } for (auto& info : descriptor_set_info_) { for (auto& desc : info.descriptors) { Result r = desc->CreateResourceIfNeeded(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } } @@ -569,8 +591,9 @@ Result Pipeline::SendDescriptorDataToDeviceIfNeeded() { "descriptor's transfer resource is not found"); } Result r = descriptor_transfer_resources_[buffer]->Initialize(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } // Note that if a buffer for a descriptor is host accessible and @@ -581,13 +604,15 @@ Result Pipeline::SendDescriptorDataToDeviceIfNeeded() { // guarantee this. Result r = guard.Submit(GetFenceTimeout(), GetPipelineRuntimeLayerEnabled()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } CommandBufferGuard guard(GetCommandBuffer()); - if (!guard.IsRecording()) + if (!guard.IsRecording()) { return guard.GetResult(); + } // Copy descriptor data to transfer resources. for (auto& buffer : descriptor_buffers_) { @@ -617,8 +642,9 @@ Result Pipeline::SendDescriptorDataToDeviceIfNeeded() { void Pipeline::BindVkDescriptorSets(const VkPipelineLayout& pipeline_layout) { for (size_t i = 0; i < descriptor_set_info_.size(); ++i) { - if (descriptor_set_info_[i].empty) + if (descriptor_set_info_[i].empty) { continue; + } // Sort descriptors by binding number to get correct order of dynamic // offsets. @@ -655,14 +681,16 @@ void Pipeline::BindVkDescriptorSets(const VkPipelineLayout& pipeline_layout) { } Result Pipeline::ReadbackDescriptorsToHostDataQueue() { - if (descriptor_buffers_.empty()) + if (descriptor_buffers_.empty()) { return Result{}; + } // Record required commands to copy the data to a host visible buffer. { CommandBufferGuard guard(GetCommandBuffer()); - if (!guard.IsRecording()) + if (!guard.IsRecording()) { return guard.GetResult(); + } for (auto& buffer : descriptor_buffers_) { if (descriptor_transfer_resources_.count(buffer) == 0) { @@ -674,8 +702,9 @@ Result Pipeline::ReadbackDescriptorsToHostDataQueue() { descriptor_transfer_resources_[buffer]->AsTransferBuffer()) { Result r = BufferBackedDescriptor::RecordCopyTransferResourceToHost( GetCommandBuffer(), transfer_buffer); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else if (auto transfer_image = descriptor_transfer_resources_[buffer] ->AsTransferImage()) { transfer_image->ImageBarrier(GetCommandBuffer(), @@ -683,8 +712,9 @@ Result Pipeline::ReadbackDescriptorsToHostDataQueue() { VK_PIPELINE_STAGE_TRANSFER_BIT); Result r = BufferBackedDescriptor::RecordCopyTransferResourceToHost( GetCommandBuffer(), transfer_image); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { return Result( "Vulkan: Pipeline::ReadbackDescriptorsToHostDataQueue() " @@ -694,8 +724,9 @@ Result Pipeline::ReadbackDescriptorsToHostDataQueue() { Result r = guard.Submit(GetFenceTimeout(), GetPipelineRuntimeLayerEnabled()); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } // Move data from transfer buffers to output buffers. @@ -703,8 +734,9 @@ Result Pipeline::ReadbackDescriptorsToHostDataQueue() { auto& transfer_resource = descriptor_transfer_resources_[buffer]; Result r = BufferBackedDescriptor::MoveTransferResourceToBufferOutput( transfer_resource.get(), buffer); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } descriptor_transfer_resources_.clear(); return {}; @@ -712,8 +744,9 @@ Result Pipeline::ReadbackDescriptorsToHostDataQueue() { const char* Pipeline::GetEntryPointName(VkShaderStageFlagBits stage) const { auto it = entry_points_.find(stage); - if (it != entry_points_.end()) + if (it != entry_points_.end()) { return it->second.c_str(); + } return kDefaultEntryPointName; } diff --git a/src/vulkan/push_constant.cc b/src/vulkan/push_constant.cc index dd9a24f9d..23dfad87f 100644 --- a/src/vulkan/push_constant.cc +++ b/src/vulkan/push_constant.cc @@ -31,8 +31,9 @@ PushConstant::PushConstant(Device* device) PushConstant::~PushConstant() = default; VkPushConstantRange PushConstant::GetVkPushConstantRange() { - if (push_constant_data_.empty()) + if (push_constant_data_.empty()) { return VkPushConstantRange(); + } auto it = std::min_element(push_constant_data_.begin(), push_constant_data_.end(), @@ -71,8 +72,9 @@ VkPushConstantRange PushConstant::GetVkPushConstantRange() { Result PushConstant::RecordPushConstantVkCommand( CommandBuffer* command, VkPipelineLayout pipeline_layout) { - if (push_constant_data_.empty()) + if (push_constant_data_.empty()) { return {}; + } auto push_const_range = GetVkPushConstantRange(); if (push_const_range.offset + push_const_range.size > @@ -84,16 +86,19 @@ Result PushConstant::RecordPushConstantVkCommand( for (const auto& data : push_constant_data_) { Result r = UpdateMemoryWithInput(data); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } // Based on spec, offset and size in bytes of push constant must // be multiple of 4. - if (push_const_range.offset % 4U != 0) + if (push_const_range.offset % 4U != 0) { return Result("PushConstant:: Offset must be a multiple of 4"); - if (push_const_range.size % 4U != 0) + } + if (push_const_range.size % 4U != 0) { return Result("PushConstant:: Size must be a multiple of 4"); + } device_->GetPtrs()->vkCmdPushConstants( command->GetVkCommandBuffer(), pipeline_layout, VK_SHADER_STAGE_ALL, diff --git a/src/vulkan/raytracing_pipeline.cc b/src/vulkan/raytracing_pipeline.cc index 7a4f85697..a63250b4a 100644 --- a/src/vulkan/raytracing_pipeline.cc +++ b/src/vulkan/raytracing_pipeline.cc @@ -87,8 +87,9 @@ Result RayTracingPipeline::CreateVkRayTracingPipeline( std::vector shader_stage_info = GetVkShaderStageInfo(); - for (auto& info : shader_stage_info) + for (auto& info : shader_stage_info) { info.pName = GetEntryPointName(info.stage); + } const bool lib = (create_flags_ & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) != 0; const VkPipelineLibraryCreateInfoKHR libraryInfo = { @@ -118,8 +119,9 @@ Result RayTracingPipeline::CreateVkRayTracingPipeline( VkResult r = device_->GetPtrs()->vkCreateRayTracingPipelinesKHR( device_->GetVkDevice(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1u, &pipelineCreateInfo, nullptr, pipeline); - if (r != VK_SUCCESS) + if (r != VK_SUCCESS) { return Result("Vulkan::Calling vkCreateRayTracingPipelinesKHR Fail"); + } return {}; } @@ -141,8 +143,9 @@ Result RayTracingPipeline::getVulkanSBTRegion( vSBT = sbt_vulkan.first->second; Result r = vSBT->Create(aSBT, pipeline); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { vSBT = x->second; } @@ -163,15 +166,17 @@ Result RayTracingPipeline::InitLibrary(const std::vector& libs, uint32_t maxPipelineRayRecursionDepth) { assert(pipeline_layout_ == VK_NULL_HANDLE); Result r = CreateVkPipelineLayout(&pipeline_layout_); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } assert(pipeline_ == VK_NULL_HANDLE); r = CreateVkRayTracingPipeline( pipeline_layout_, &pipeline_, libs, maxPipelineRayPayloadSize, maxPipelineRayHitAttributeSize, maxPipelineRayRecursionDepth); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } @@ -189,13 +194,15 @@ Result RayTracingPipeline::TraceRays(amber::SBT* rSBT, const std::vector& libs, bool is_timed_execution) { Result r = SendDescriptorDataToDeviceIfNeeded(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = InitLibrary(libs, maxPipelineRayPayloadSize, maxPipelineRayHitAttributeSize, maxPipelineRayRecursionDepth); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } // Note that a command updating a descriptor set and a command using // it must be submitted separately, because using a descriptor set @@ -204,8 +211,9 @@ Result RayTracingPipeline::TraceRays(amber::SBT* rSBT, CreateTimingQueryObjectIfNeeded(is_timed_execution); { CommandBufferGuard guard(GetCommandBuffer()); - if (!guard.IsRecording()) + if (!guard.IsRecording()) { return guard.GetResult(); + } for (auto& i : *blases_) { i.second->BuildBLAS(GetCommandBuffer()); @@ -217,8 +225,9 @@ Result RayTracingPipeline::TraceRays(amber::SBT* rSBT, BindVkDescriptorSets(pipeline_layout_); r = RecordPushConstant(pipeline_layout_); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } device_->GetPtrs()->vkCmdBindPipeline( command_->GetVkCommandBuffer(), VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, @@ -230,20 +239,24 @@ Result RayTracingPipeline::TraceRays(amber::SBT* rSBT, VkStridedDeviceAddressRegionKHR cSBTRegion = {}; r = getVulkanSBTRegion(pipeline_, rSBT, &rSBTRegion); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = getVulkanSBTRegion(pipeline_, mSBT, &mSBTRegion); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = getVulkanSBTRegion(pipeline_, hSBT, &hSBTRegion); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = getVulkanSBTRegion(pipeline_, cSBT, &cSBTRegion); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } device_->GetPtrs()->vkCmdTraceRaysKHR(command_->GetVkCommandBuffer(), &rSBTRegion, &mSBTRegion, &hSBTRegion, @@ -251,13 +264,15 @@ Result RayTracingPipeline::TraceRays(amber::SBT* rSBT, BeginTimerQuery(); r = guard.Submit(GetFenceTimeout(), GetPipelineRuntimeLayerEnabled()); EndTimerQuery(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } DestroyTimingQueryObjectIfNeeded(); r = ReadbackDescriptorsToHostDataQueue(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return {}; } diff --git a/src/vulkan/resource.cc b/src/vulkan/resource.cc index 15537a1e3..30f5d99c0 100644 --- a/src/vulkan/resource.cc +++ b/src/vulkan/resource.cc @@ -54,8 +54,9 @@ Resource::Resource(Device* device, uint32_t size_in_bytes) Resource::~Resource() = default; Result Resource::CreateVkBuffer(VkBuffer* buffer, VkBufferUsageFlags usage) { - if (!buffer) + if (!buffer) { return Result("Vulkan::Given VkBuffer pointer is nullptr"); + } VkBufferCreateInfo buffer_info = VkBufferCreateInfo(); buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; @@ -83,19 +84,22 @@ uint32_t Resource::ChooseMemory(uint32_t memory_type_bits, uint32_t memory_type_index = 0; while (memory_type_bits) { if (memory_type_bits % 2) { - if (first_non_zero == std::numeric_limits::max()) + if (first_non_zero == std::numeric_limits::max()) { first_non_zero = memory_type_index; + } - if (device_->HasMemoryFlags(memory_type_index, flags)) + if (device_->HasMemoryFlags(memory_type_index, flags)) { return memory_type_index; + } } ++memory_type_index; memory_type_bits >>= 1; } - if (require_flags_found) + if (require_flags_found) { return std::numeric_limits::max(); + } return first_non_zero; } @@ -112,10 +116,12 @@ Result Resource::AllocateAndBindMemoryToVkBuffer(VkBuffer buffer, *memory_type_index = 0; - if (buffer == VK_NULL_HANDLE) + if (buffer == VK_NULL_HANDLE) { return Result("Vulkan::Given VkBuffer is VK_NULL_HANDLE"); - if (memory == nullptr) + } + if (memory == nullptr) { return Result("Vulkan::Given VkDeviceMemory pointer is nullptr"); + } VkMemoryRequirements requirement; device_->GetPtrs()->vkGetBufferMemoryRequirements(device_->GetVkDevice(), @@ -123,12 +129,14 @@ Result Resource::AllocateAndBindMemoryToVkBuffer(VkBuffer buffer, *memory_type_index = ChooseMemory(requirement.memoryTypeBits, flags, require_flags_found); - if (*memory_type_index == std::numeric_limits::max()) + if (*memory_type_index == std::numeric_limits::max()) { return Result("Vulkan::Find Proper Memory Fail"); + } Result r = AllocateMemory(memory, requirement.size, *memory_type_index); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } if (device_->GetPtrs()->vkBindBufferMemory(device_->GetVkDevice(), buffer, *memory, 0) != VK_SUCCESS) { diff --git a/src/vulkan/sampler_descriptor.cc b/src/vulkan/sampler_descriptor.cc index 59f6c7734..9b7a00e0e 100644 --- a/src/vulkan/sampler_descriptor.cc +++ b/src/vulkan/sampler_descriptor.cc @@ -36,8 +36,9 @@ Result SamplerDescriptor::CreateResourceIfNeeded() { for (const auto& sampler : amber_samplers_) { vulkan_samplers_.emplace_back(MakeUnique(device_)); Result r = vulkan_samplers_.back()->CreateSampler(sampler); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } return {}; diff --git a/src/vulkan/sbt.cc b/src/vulkan/sbt.cc index e7fa49ba3..b16bc1c26 100644 --- a/src/vulkan/sbt.cc +++ b/src/vulkan/sbt.cc @@ -15,8 +15,8 @@ #include -#include "src/vulkan/sbt.h" #include "src/vulkan/pipeline.h" +#include "src/vulkan/sbt.h" namespace amber { namespace vulkan { @@ -25,11 +25,13 @@ SBT::SBT(Device* device) : device_(device) {} Result SBT::Create(amber::SBT* sbt, VkPipeline pipeline) { uint32_t handles_count = 0; - for (auto& x : sbt->GetSBTRecords()) + for (auto& x : sbt->GetSBTRecords()) { handles_count += x->GetCount(); + } - if (handles_count == 0) + if (handles_count == 0) { return Result("SBT must contain at least one record"); + } const uint32_t handle_size = device_->GetRayTracingShaderGroupHandleSize(); const uint32_t buffer_size = handle_size * handles_count; @@ -41,8 +43,9 @@ Result SBT::Create(amber::SBT* sbt, VkPipeline pipeline) { VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); buffer_->AddAllocateFlags(VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT); Result r = buffer_->Initialize(); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } size_t start = 0; for (auto& x : sbt->GetSBTRecords()) { @@ -53,8 +56,9 @@ Result SBT::Create(amber::SBT* sbt, VkPipeline pipeline) { device_->GetVkDevice(), pipeline, index, count, count * handle_size, &handles[start * handle_size]); - if (vr != VK_SUCCESS) + if (vr != VK_SUCCESS) { return Result("vkGetRayTracingShaderGroupHandlesKHR has failed"); + } } start += count; diff --git a/src/vulkan/tlas.cc b/src/vulkan/tlas.cc index c0fe42290..b7125329e 100644 --- a/src/vulkan/tlas.cc +++ b/src/vulkan/tlas.cc @@ -25,8 +25,9 @@ static VkTransformMatrixKHR makeVkMatrix(const float* m) { {0.0f, 0.0f, 1.0f, 0.0f}}}; VkTransformMatrixKHR v; - if (m == nullptr) + if (m == nullptr) { return identityMatrix3x4; + } for (size_t i = 0; i < 12; i++) { const size_t r = i / 4; @@ -39,10 +40,10 @@ static VkTransformMatrixKHR makeVkMatrix(const float* m) { TLAS::TLAS(Device* device) : device_(device) {} -Result TLAS::CreateTLAS(amber::TLAS* tlas, - BlasesMap* blases) { - if (tlas_ != VK_NULL_HANDLE) +Result TLAS::CreateTLAS(amber::TLAS* tlas, BlasesMap* blases) { + if (tlas_ != VK_NULL_HANDLE) { return {}; + } assert(tlas != nullptr); @@ -65,8 +66,8 @@ Result TLAS::CreateTLAS(amber::TLAS* tlas, instance_buffer_->Initialize(); VkAccelerationStructureInstanceKHR* instances_ptr = - reinterpret_cast - (instance_buffer_->HostAccessibleMemoryPtr()); + reinterpret_cast( + instance_buffer_->HostAccessibleMemoryPtr()); for (auto& instance : tlas->GetInstances()) { auto blas = instance->GetUsedBLAS(); @@ -83,8 +84,9 @@ Result TLAS::CreateTLAS(amber::TLAS* tlas, Result r = blas_vulkan_ptr->CreateBLAS(blas); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } else { blas_vulkan_ptr = blas_vulkan_it->second.get(); } @@ -199,10 +201,12 @@ Result TLAS::CreateTLAS(amber::TLAS* tlas, } Result TLAS::BuildTLAS(VkCommandBuffer cmdBuffer) { - if (tlas_ == VK_NULL_HANDLE) + if (tlas_ == VK_NULL_HANDLE) { return Result("Acceleration structure should be created first"); - if (built_) + } + if (built_) { return {}; + } VkAccelerationStructureBuildRangeInfoKHR accelerationStructureBuildRangeInfoKHR = {instances_count_, 0, 0, 0}; diff --git a/src/vulkan/tlas_descriptor.cc b/src/vulkan/tlas_descriptor.cc index a1c7adf99..1a78409ec 100644 --- a/src/vulkan/tlas_descriptor.cc +++ b/src/vulkan/tlas_descriptor.cc @@ -43,8 +43,9 @@ Result TLASDescriptor::CreateResourceIfNeeded() { if (tlases_->find(amber_tlas) == tlases_->end()) { auto& vulkan_tlas = ((*tlases_)[amber_tlas] = MakeUnique(device_)); Result r = vulkan_tlas->CreateTLAS(amber_tlas, blases_); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } } } diff --git a/src/vulkan/transfer_buffer.cc b/src/vulkan/transfer_buffer.cc index 174c42b02..c17204e75 100644 --- a/src/vulkan/transfer_buffer.cc +++ b/src/vulkan/transfer_buffer.cc @@ -25,8 +25,9 @@ TransferBuffer::TransferBuffer(Device* device, uint32_t size_in_bytes, Format* format) : Resource(device, size_in_bytes) { - if (format) + if (format) { format_ = device->GetVkFormat(*format); + } } TransferBuffer::~TransferBuffer() { @@ -53,14 +54,16 @@ Result TransferBuffer::Initialize() { } Result r = CreateVkBuffer(&buffer_, usage_flags_); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } uint32_t memory_type_index = 0; r = AllocateAndBindMemoryToVkBuffer( buffer_, &memory_, GetMemoryPropertiesFlags(), true, &memory_type_index); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } // Create buffer view if (usage_flags_ & (VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT | diff --git a/src/vulkan/transfer_image.cc b/src/vulkan/transfer_image.cc index adfae62d1..cb032fea4 100644 --- a/src/vulkan/transfer_image.cc +++ b/src/vulkan/transfer_image.cc @@ -106,11 +106,13 @@ TransferImage::~TransferImage() { nullptr); } - if (image_ != VK_NULL_HANDLE) + if (image_ != VK_NULL_HANDLE) { device_->GetPtrs()->vkDestroyImage(device_->GetVkDevice(), image_, nullptr); + } - if (memory_ != VK_NULL_HANDLE) + if (memory_ != VK_NULL_HANDLE) { device_->GetPtrs()->vkFreeMemory(device_->GetVkDevice(), memory_, nullptr); + } if (host_accessible_memory_ != VK_NULL_HANDLE) { UnMapMemory(host_accessible_memory_); @@ -125,8 +127,9 @@ TransferImage::~TransferImage() { } Result TransferImage::Initialize() { - if (image_ != VK_NULL_HANDLE) + if (image_ != VK_NULL_HANDLE) { return Result("Vulkan::TransferImage was already initialized"); + } if (device_->GetPtrs()->vkCreateImage(device_->GetVkDevice(), &image_info_, nullptr, &image_) != VK_SUCCESS) { @@ -137,8 +140,9 @@ Result TransferImage::Initialize() { Result r = AllocateAndBindMemoryToVkImage(image_, &memory_, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, false, &memory_type_index); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } if (aspect_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) && !(image_info_.usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { @@ -149,8 +153,9 @@ Result TransferImage::Initialize() { r = CreateVkImageView(aspect_); } - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } // For images, we always make a secondary buffer. When the tiling of an image // is optimal, read/write data from CPU does not show correct values. We need @@ -159,8 +164,9 @@ Result TransferImage::Initialize() { r = CreateVkBuffer( &host_accessible_buffer_, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } memory_type_index = 0; r = AllocateAndBindMemoryToVkBuffer(host_accessible_buffer_, @@ -168,8 +174,9 @@ Result TransferImage::Initialize() { VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, true, &memory_type_index); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } return MapMemory(host_accessible_memory_); } @@ -254,8 +261,9 @@ void TransferImage::CopyToHost(CommandBuffer* command_buffer) { VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}; // Copy operations don't support multisample images. - if (samples_ > 1) + if (samples_ > 1) { return; + } std::vector copy_regions; uint32_t last_mip_level = used_mip_levels_ == VK_REMAINING_MIP_LEVELS @@ -279,8 +287,9 @@ void TransferImage::CopyToHost(CommandBuffer* command_buffer) { void TransferImage::CopyToDevice(CommandBuffer* command_buffer) { // Copy operations don't support multisample images. - if (samples_ > 1) + if (samples_ > 1) { return; + } const VkImageAspectFlagBits aspects[] = {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, @@ -308,8 +317,9 @@ void TransferImage::CopyToDevice(CommandBuffer* command_buffer) { void TransferImage::ImageBarrier(CommandBuffer* command_buffer, VkImageLayout to_layout, VkPipelineStageFlags to_stage) { - if (to_layout == layout_ && to_stage == stage_) + if (to_layout == layout_ && to_stage == stage_) { return; + } VkImageMemoryBarrier barrier = VkImageMemoryBarrier(); barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; @@ -396,10 +406,12 @@ Result TransferImage::AllocateAndBindMemoryToVkImage( *memory_type_index = 0; - if (image == VK_NULL_HANDLE) + if (image == VK_NULL_HANDLE) { return Result("Vulkan::Given VkImage is VK_NULL_HANDLE"); - if (memory == nullptr) + } + if (memory == nullptr) { return Result("Vulkan::Given VkDeviceMemory pointer is nullptr"); + } VkMemoryRequirements requirement; device_->GetPtrs()->vkGetImageMemoryRequirements(device_->GetVkDevice(), @@ -407,12 +419,14 @@ Result TransferImage::AllocateAndBindMemoryToVkImage( *memory_type_index = ChooseMemory(requirement.memoryTypeBits, flags, force_flags); - if (*memory_type_index == std::numeric_limits::max()) + if (*memory_type_index == std::numeric_limits::max()) { return Result("Vulkan::Find Proper Memory Fail"); + } Result r = AllocateMemory(memory, requirement.size, *memory_type_index); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } if (device_->GetPtrs()->vkBindImageMemory(device_->GetVkDevice(), image, *memory, 0) != VK_SUCCESS) { diff --git a/src/vulkan/vertex_buffer.cc b/src/vulkan/vertex_buffer.cc index 557b0a3d8..3b8199202 100644 --- a/src/vulkan/vertex_buffer.cc +++ b/src/vulkan/vertex_buffer.cc @@ -71,8 +71,9 @@ void VertexBuffer::BindToCommandBuffer(CommandBuffer* command) { } Result VertexBuffer::SendVertexData(CommandBuffer* command) { - if (!is_vertex_data_pending_) + if (!is_vertex_data_pending_) { return Result("Vulkan::Vertices data was already sent"); + } buffer_to_vk_buffer_.clear(); @@ -87,16 +88,18 @@ Result VertexBuffer::SendVertexData(CommandBuffer* command) { MakeUnique(device_, bytes, nullptr)); Result r = transfer_buffers_.back()->AddUsageFlags( VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } r = transfer_buffers_.back()->Initialize(); std::memcpy(transfer_buffers_.back()->HostAccessibleMemoryPtr(), buf->GetValues(), bytes); transfer_buffers_.back()->CopyToDevice(command); - if (!r.IsSuccess()) + if (!r.IsSuccess()) { return r; + } buffer_to_vk_buffer_[buf] = transfer_buffers_.back()->GetVkBuffer(); }