refactor renderer

This commit is contained in:
nmzik
2026-07-27 02:24:50 +02:00
parent a720b28b7f
commit a20cf5d298
112 changed files with 18269 additions and 18368 deletions
-29
View File
@@ -1,29 +0,0 @@
#ifndef EMULATOR_INCLUDE_EMULATOR_GRAPHICS_PRESENTATION_DISPLAYBUFFER_H_
#define EMULATOR_INCLUDE_EMULATOR_GRAPHICS_PRESENTATION_DISPLAYBUFFER_H_
#include "common/common.h"
namespace Libs::Graphics {
class CommandBuffer;
struct VideoOutVulkanImage;
} // namespace Libs::Graphics
namespace Libs::Presentation {
struct DisplayBufferImage {
Graphics::VideoOutVulkanImage* image = nullptr;
uint32_t index = static_cast<uint32_t>(-1);
uint64_t size = 0;
uint64_t pitch = 0;
};
DisplayBufferImage DisplayBufferFind(uint64_t addr, bool render_target = false);
int DisplayBufferSubmitFlipFromGpu(Graphics::CommandBuffer& buffer, int handle, int index,
int flip_mode, int64_t flip_arg, uint64_t& request_id);
uint64_t DisplayBufferPrepareNextFlipOnGpu(Graphics::CommandBuffer& buffer);
void DisplayBufferCompleteFlipFromGpu(uint64_t request_id);
void DisplayBufferWaitForFlipQueueSlot();
} // namespace Libs::Presentation
#endif // EMULATOR_INCLUDE_EMULATOR_GRAPHICS_PRESENTATION_DISPLAYBUFFER_H_
+38
View File
@@ -0,0 +1,38 @@
#ifndef EMULATOR_SRC_GRAPHICS_PRESENTATION_PRESENTER_H_
#define EMULATOR_SRC_GRAPHICS_PRESENTATION_PRESENTER_H_
#include "common/common.h"
#include <memory>
namespace Libs::Graphics {
class CommandBuffer;
class RenderContext;
struct ImageInfo;
struct WindowContext;
class Presenter final {
public:
struct Frame;
explicit Presenter(WindowContext& window);
~Presenter();
KYTY_CLASS_NO_COPY(Presenter);
[[nodiscard]] Frame& PrepareFrame(CommandBuffer& command, const ImageInfo& info);
[[nodiscard]] Frame& PrepareBlankFrame(uint32_t width, uint32_t height, bool opaque,
CommandBuffer* producer = nullptr);
[[nodiscard]] Frame* PrepareLastFrame();
[[nodiscard]] bool IsGuestPaused() const noexcept;
[[nodiscard]] RenderContext& Renderer() const noexcept;
void Present(Frame& frame, bool reuse = false);
void Discard(Frame& frame);
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
} // namespace Libs::Graphics
#endif // EMULATOR_SRC_GRAPHICS_PRESENTATION_PRESENTER_H_
File diff suppressed because it is too large Load Diff
+29 -8
View File
@@ -7,9 +7,11 @@
#include "common/abi.h"
#include "kernel/eventQueue.h"
#include <memory>
namespace Libs::Graphics {
// struct VulkanSwapchain;
struct VideoOutVulkanImage;
class CommandBuffer;
class Presenter;
} // namespace Libs::Graphics
namespace Libs::VideoOut {
@@ -22,8 +24,31 @@ struct VideoOutOutputOptions;
struct VideoOutBuffers;
struct VideoOutColorSettings;
void VideoOutInit(uint32_t width, uint32_t height);
void VideoOutWaitFlipDone(int handle, int index);
class VideoOutDriver final {
public:
struct Impl;
VideoOutDriver(uint32_t width, uint32_t height, Graphics::Presenter& presenter);
~VideoOutDriver();
KYTY_CLASS_NO_COPY(VideoOutDriver);
int SubmitFlipFromGpu(Graphics::CommandBuffer& buffer, int handle, int index, int flip_mode,
int64_t flip_arg, uint64_t& request_id);
void PrepareFlip(uint64_t request_id, Graphics::CommandBuffer& buffer);
void CompleteFlip(uint64_t request_id);
void SubmitFlipPreparation(uint64_t request_id);
void WaitForSubmitSlot();
void WaitFlipDone(int handle, int index);
[[nodiscard]] Impl& State() noexcept;
private:
std::unique_ptr<Impl> m_impl;
};
[[nodiscard]] VideoOutDriver& VideoOutInit(uint32_t width, uint32_t height,
Graphics::Presenter& presenter);
void VideoOutShutdown();
KYTY_SYSV_ABI int VideoOutOpen(int user_id, int bus_type, int index, const void* param);
KYTY_SYSV_ABI int VideoOutClose(int handle);
@@ -75,10 +100,6 @@ KYTY_SYSV_ABI int VideoOutLatencyMeasureSetStartPoint(int handle, uint32_t point
KYTY_SYSV_ABI int VideoOutColorSettingsSetGamma(VideoOutColorSettings* settings, float gamma);
KYTY_SYSV_ABI int VideoOutAdjustColor(int handle, const VideoOutColorSettings* settings);
void VideoOutBeginVblank();
void VideoOutEndVblank();
bool VideoOutFlipWindow(uint32_t micros);
} // namespace Libs::VideoOut
#endif /* EMULATOR_INCLUDE_EMULATOR_GRAPHICS_VIDEOOUT_H_ */
+4 -9
View File
@@ -6,16 +6,11 @@
namespace Libs::Graphics {
class CommandBuffer;
struct VideoOutVulkanImage;
struct PreparedFrame;
class Presenter;
void WindowInit(uint32_t width, uint32_t height);
void WindowRun();
PreparedFrame& WindowPrepareFrame(CommandBuffer& buffer, VideoOutVulkanImage& image);
PreparedFrame& WindowPrepareBlankFrame(CommandBuffer& buffer, uint32_t width, uint32_t height,
bool opaque);
void WindowPresentFrame(PreparedFrame& frame);
[[nodiscard]] Presenter& WindowInit(uint32_t width, uint32_t height);
void WindowRun();
void WindowShutdown();
} // namespace Libs::Graphics
File diff suppressed because it is too large Load Diff
+146 -80
View File
@@ -28,9 +28,11 @@
#include "common/timer.h"
#include "graphics/host_gpu/graphicContext.h"
#include "graphics/host_gpu/renderer/render.h"
#include "graphics/host_gpu/transfer.h"
#include "graphics/host_gpu/renderer/renderContext.h"
#include "graphics/host_gpu/vma.h"
#include "graphics/host_gpu/vulkanCommon.h"
#include "graphics/presentation/presenter.h"
#include "kernel/memory.h"
#include "graphics/presentation/renderDoc.h"
#include "graphics/presentation/videoOut.h"
#include "graphics/presentation/window.h"
@@ -40,7 +42,6 @@
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fmt/format.h>
#include <memory>
@@ -64,6 +65,14 @@ struct VulkanExtensions {
std::vector<vk::LayerProperties> available_layers;
};
vk::PhysicalDeviceVulkan13Features WindowContext::RequiredVulkan13Features() noexcept {
vk::PhysicalDeviceVulkan13Features features {};
features.sType = vk::StructureType::ePhysicalDeviceVulkan13Features;
features.dynamicRendering = VK_TRUE;
features.synchronization2 = VK_TRUE;
return features;
}
static bool HasExtension(const std::vector<vk::ExtensionProperties>& extensions, const char* name) {
return std::any_of(extensions.begin(), extensions.end(),
[name](const auto& ext) { return strcmp(ext.extensionName, name) == 0; });
@@ -79,8 +88,8 @@ static bool HasLayer(const std::vector<vk::LayerProperties>& layers, const char*
[name](const auto& layer) { return strcmp(layer.layerName, name) == 0; });
}
void VulkanGetSurfaceCapabilities(vk::PhysicalDevice physical_device, vk::SurfaceKHR surface,
SurfaceCapabilities& r) {
static void GetSurfaceCapabilities(vk::PhysicalDevice physical_device, vk::SurfaceKHR surface,
SurfaceCapabilities& r) {
RequireVulkanSuccess(physical_device.getSurfaceCapabilitiesKHR(surface, &r.capabilities),
"vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
@@ -96,22 +105,6 @@ void VulkanGetSurfaceCapabilities(vk::PhysicalDevice physical_device, vk::Surfac
return physical_device.getSurfacePresentModesKHR(surface, count, values);
});
EXIT_NOT_IMPLEMENTED(r.present_modes.empty());
r.format_srgb_bgra32 = false;
r.format_unorm_bgra32 = false;
for (const auto& f: r.formats) {
if (f.format == vk::Format::eB8G8R8A8Srgb &&
f.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) {
r.format_srgb_bgra32 = true;
}
if (f.format == vk::Format::eB8G8R8A8Unorm &&
f.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) {
r.format_unorm_bgra32 = true;
}
if (r.format_srgb_bgra32 && r.format_unorm_bgra32) {
break;
}
}
}
static bool CheckFormat(vk::PhysicalDevice device, vk::Format format, bool tile,
@@ -214,6 +207,7 @@ static void VulkanFindPhysicalDevice(vk::Instance instance, vk::SurfaceKHR surfa
device_features2.pNext = &features13;
device.getFeatures2(&device_features2);
const auto required_features13 = WindowContext::RequiredVulkan13Features();
const auto queue_family = VulkanFindQueueFamily(device, surface);
if (queue_family == static_cast<uint32_t>(-1)) {
@@ -239,10 +233,28 @@ static void VulkanFindPhysicalDevice(vk::Instance instance, vk::SurfaceKHR surfa
LOGF("samplerMirrorClampToEdge is not supported\n");
skip_device = true;
}
if (features12.timelineSemaphore != VK_TRUE) {
LOGF("timelineSemaphore is not supported\n");
skip_device = true;
}
if (features13.robustImageAccess != VK_TRUE) {
LOGF("robustImageAccess is not supported\n");
skip_device = true;
}
if (required_features13.dynamicRendering == VK_TRUE &&
features13.dynamicRendering != VK_TRUE) {
LOGF("dynamicRendering is not supported\n");
skip_device = true;
}
if (required_features13.synchronization2 == VK_TRUE &&
features13.synchronization2 != VK_TRUE) {
LOGF("synchronization2 is not supported\n");
skip_device = true;
}
if (device_features2.features.sampleRateShading != VK_TRUE) {
LOGF("sampleRateShading is not supported\n");
skip_device = true;
}
if (device_features2.features.fragmentStoresAndAtomics != VK_TRUE) {
LOGF("fragmentStoresAndAtomics is not supported\n");
@@ -309,7 +321,7 @@ static void VulkanFindPhysicalDevice(vk::Instance instance, vk::SurfaceKHR surfa
SurfaceCapabilities candidate_capabilities;
if (!skip_device) {
VulkanGetSurfaceCapabilities(device, surface, candidate_capabilities);
GetSurfaceCapabilities(device, surface, candidate_capabilities);
if (!(candidate_capabilities.capabilities.supportedUsageFlags &
vk::ImageUsageFlagBits::eTransferDst)) {
@@ -318,12 +330,6 @@ static void VulkanFindPhysicalDevice(vk::Instance instance, vk::SurfaceKHR surfa
}
}
if (!skip_device && !CheckFormat(device, vk::Format::eR8G8B8A8Srgb, false,
vk::FormatFeatureFlagBits::eBlitSrc)) {
LOGF("Format vk::Format::eR8G8B8A8Srgb cannot be used as transfer source\n");
skip_device = true;
}
if (!skip_device && !CheckFormat(device, vk::Format::eD32Sfloat, true,
vk::FormatFeatureFlagBits::eDepthStencilAttachment)) {
LOGF("Format vk::Format::eD32Sfloat cannot be used as depth buffer\n");
@@ -420,9 +426,9 @@ static void VulkanFindPhysicalDevice(vk::Instance instance, vk::SurfaceKHR surfa
}
}
static void VulkanInitSubgroupSizeControl(vk::PhysicalDevice physical_device) {
static void VulkanInitSubgroupSizeControl(vk::PhysicalDevice physical_device,
GraphicContext& graphics) {
EXIT_IF(physical_device == nullptr);
auto& graphics = g_window_ctx->graphic_ctx;
vk::PhysicalDeviceSubgroupSizeControlProperties subgroup_size_control {};
subgroup_size_control.sType = vk::StructureType::ePhysicalDeviceSubgroupSizeControlProperties;
@@ -463,10 +469,10 @@ static void VulkanInitSubgroupSizeControl(vk::PhysicalDevice physical_device) {
}
static vk::Device VulkanCreateDevice(vk::PhysicalDevice physical_device, const VulkanExtensions& r,
uint32_t queue_family,
const std::vector<const char*>& device_extensions) {
uint32_t queue_family,
const std::vector<const char*>& device_extensions,
GraphicContext& graphics) {
EXIT_IF(physical_device == nullptr);
auto& graphics = g_window_ctx->graphic_ctx;
EXIT_IF(queue_family == static_cast<uint32_t>(-1));
const float queue_priority = 1.0f;
@@ -502,7 +508,11 @@ static vk::Device VulkanCreateDevice(vk::PhysicalDevice physical_device, const V
vk::PhysicalDeviceVulkan13Features supported_features13 {};
supported_features13.sType = vk::StructureType::ePhysicalDeviceVulkan13Features;
supported_features13.pNext = nullptr;
vk::PhysicalDeviceVulkan12Features supported_features12 {};
supported_features12.sType = vk::StructureType::ePhysicalDeviceVulkan12Features;
supported_features12.pNext = nullptr;
supported_features13.pNext = &supported_features12;
const auto robustness2_ext_enabled =
HasExtension(device_extensions, VK_EXT_ROBUSTNESS_2_EXTENSION_NAME);
@@ -511,13 +521,21 @@ static vk::Device VulkanCreateDevice(vk::PhysicalDevice physical_device, const V
supported_robustness2.sType = vk::StructureType::ePhysicalDeviceRobustness2FeaturesEXT;
supported_robustness2.pNext = nullptr;
if (robustness2_ext_enabled) {
supported_features13.pNext = &supported_robustness2;
supported_features12.pNext = &supported_robustness2;
}
vk::PhysicalDeviceFeatures2 supported_features2 {};
supported_features2.sType = vk::StructureType::ePhysicalDeviceFeatures2;
supported_features2.pNext = &supported_features13;
physical_device.getFeatures2(&supported_features2);
const auto required_features13 = WindowContext::RequiredVulkan13Features();
EXIT_NOT_IMPLEMENTED(supported_features12.timelineSemaphore != VK_TRUE);
EXIT_NOT_IMPLEMENTED(required_features13.dynamicRendering == VK_TRUE &&
supported_features13.dynamicRendering != VK_TRUE);
EXIT_NOT_IMPLEMENTED(required_features13.synchronization2 == VK_TRUE &&
supported_features13.synchronization2 != VK_TRUE);
EXIT_NOT_IMPLEMENTED(supported_features2.features.sampleRateShading != VK_TRUE);
features12.timelineSemaphore = VK_TRUE;
vk::PhysicalDeviceFeatures device_features {};
device_features.fragmentStoresAndAtomics = VK_TRUE;
@@ -529,8 +547,8 @@ static vk::Device VulkanCreateDevice(vk::PhysicalDevice physical_device, const V
device_features.shaderImageGatherExtended = VK_TRUE;
device_features.independentBlend = VK_TRUE;
device_features.tessellationShader = VK_TRUE;
device_features.sampleRateShading = supported_features2.features.sampleRateShading;
graphics.sample_rate_shading_enabled = device_features.sampleRateShading == VK_TRUE;
device_features.sampleRateShading = VK_TRUE;
graphics.sample_rate_shading_enabled = true;
device_features.vertexPipelineStoresAndAtomics =
supported_features2.features.vertexPipelineStoresAndAtomics;
@@ -552,8 +570,7 @@ static vk::Device VulkanCreateDevice(vk::PhysicalDevice physical_device, const V
robustness2.nullDescriptor = supported_robustness2.nullDescriptor;
}
vk::PhysicalDeviceVulkan13Features features13 {};
features13.sType = vk::StructureType::ePhysicalDeviceVulkan13Features;
auto features13 = required_features13;
features13.pNext =
robustness2_ext_enabled ? &robustness2 : const_cast<void*>(base_feature_chain);
features13.robustImageAccess = supported_features13.robustImageAccess;
@@ -773,12 +790,12 @@ static void VulkanCheckInstanceVersion() {
}
}
void VulkanCreate(WindowContext& window) {
EXIT_IF(window.window == nullptr);
EXIT_IF(window.graphic_ctx.instance != nullptr);
EXIT_IF(window.graphic_ctx.physical_device != nullptr);
EXIT_IF(window.graphic_ctx.device != nullptr);
EXIT_IF(window.surface_capabilities != nullptr);
void WindowContext::CreateVulkan() {
EXIT_IF(window == nullptr);
EXIT_IF(graphic_ctx.instance != nullptr);
EXIT_IF(graphic_ctx.physical_device != nullptr);
EXIT_IF(graphic_ctx.device != nullptr);
EXIT_IF(surface != nullptr);
auto get_instance_proc_addr =
reinterpret_cast<PFN_vkGetInstanceProcAddr>(SDL_Vulkan_GetVkGetInstanceProcAddr());
@@ -788,7 +805,7 @@ void VulkanCreate(WindowContext& window) {
VULKAN_HPP_DEFAULT_DISPATCHER.init(get_instance_proc_addr);
VulkanExtensions r;
VulkanGetExtensions(window.window, r);
VulkanGetExtensions(window, r);
VulkanCheckInstanceVersion();
vk::ApplicationInfo app_info {};
@@ -852,36 +869,35 @@ void VulkanCreate(WindowContext& window) {
inst_info.ppEnabledLayerNames =
(r.enable_validation_layers ? r.required_layers.data() : nullptr);
const vk::Result result = vk::createInstance(&inst_info, nullptr, &window.graphic_ctx.instance);
const vk::Result result = vk::createInstance(&inst_info, nullptr, &graphic_ctx.instance);
switch (result) {
case vk::Result::eSuccess: break;
case vk::Result::eErrorIncompatibleDriver:
EXIT("Unable to find a compatible Vulkan Driver");
default: EXIT("Could not create a Vulkan instance (for unknown reasons)");
}
VULKAN_HPP_DEFAULT_DISPATCHER.init(window.graphic_ctx.instance);
VULKAN_HPP_DEFAULT_DISPATCHER.init(graphic_ctx.instance);
if (r.enable_validation_layers) {
dbg_create_info.pNext = nullptr;
if (VulkanCreateDebugUtilsMessengerEXT(window.graphic_ctx.instance, &dbg_create_info,
nullptr, &window.graphic_ctx.debug_messenger) !=
if (VulkanCreateDebugUtilsMessengerEXT(graphic_ctx.instance, &dbg_create_info, nullptr,
&graphic_ctx.debug_messenger) !=
vk::Result::eSuccess) {
EXIT("Could not create debug messenger");
}
}
vk::SurfaceKHR::CType native_surface = VK_NULL_HANDLE;
if (SDL_Vulkan_CreateSurface(window.window,
static_cast<vk::Instance::CType>(window.graphic_ctx.instance),
if (SDL_Vulkan_CreateSurface(window, static_cast<vk::Instance::CType>(graphic_ctx.instance),
&native_surface) == SDL_FALSE) {
EXIT("Could not create a Vulkan surface");
}
window.surface = native_surface;
surface = native_surface;
std::vector<const char*> device_extensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_EXT_DEPTH_CLIP_ENABLE_EXTENSION_NAME,
VK_EXT_DEPTH_CLIP_CONTROL_EXTENSION_NAME, VK_EXT_COLOR_WRITE_ENABLE_EXTENSION_NAME,
"VK_KHR_maintenance1"};
VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME, "VK_KHR_maintenance1"};
#ifdef KYTY_ENABLE_DEBUG_PRINTF
if (Config::SpirvDebugPrintfEnabled()) {
@@ -889,23 +905,18 @@ void VulkanCreate(WindowContext& window) {
}
#endif
window.surface_capabilities = new SurfaceCapabilities {};
uint32_t queue_family = static_cast<uint32_t>(-1);
VulkanFindPhysicalDevice(window.graphic_ctx.instance, window.surface, device_extensions,
*window.surface_capabilities, window.graphic_ctx.physical_device,
queue_family);
VulkanFindPhysicalDevice(graphic_ctx.instance, surface, device_extensions,
surface_capabilities, graphic_ctx.physical_device, queue_family);
if (window.graphic_ctx.physical_device == nullptr) {
if (graphic_ctx.physical_device == nullptr) {
EXIT("Could not find suitable device");
}
window.graphic_ctx.physical_device.getProperties(
&window.graphic_ctx.physical_device_properties);
window.graphic_ctx.physical_device.getMemoryProperties(
&window.graphic_ctx.physical_device_memory_properties);
const auto& device_properties = window.graphic_ctx.GetPhysicalDeviceProperties();
graphic_ctx.physical_device.getProperties(&graphic_ctx.physical_device_properties);
graphic_ctx.physical_device.getMemoryProperties(&graphic_ctx.physical_device_memory_properties);
const auto& device_properties = graphic_ctx.GetPhysicalDeviceProperties();
LOGF("Select device: %s\n", device_properties.deviceName.data());
@@ -913,41 +924,96 @@ void VulkanCreate(WindowContext& window) {
auto available_extensions = EnumerateVulkan<vk::ExtensionProperties>(
"vkEnumerateDeviceExtensionProperties",
[&](uint32_t* count, vk::ExtensionProperties* values) {
return window.graphic_ctx.physical_device.enumerateDeviceExtensionProperties(
nullptr, count, values);
return graphic_ctx.physical_device.enumerateDeviceExtensionProperties(nullptr,
count,
values);
});
if (HasExtension(available_extensions, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) {
device_extensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
window.graphic_ctx.memory_budget_ext_enabled = true;
graphic_ctx.memory_budget_ext_enabled = true;
}
if (HasExtension(available_extensions, VK_EXT_ROBUSTNESS_2_EXTENSION_NAME)) {
device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME);
}
}
memcpy(window.device_name, device_properties.deviceName, sizeof(window.device_name));
std::snprintf(window.processor_name, sizeof(window.processor_name), "%s",
memcpy(device_name, device_properties.deviceName, sizeof(device_name));
std::snprintf(processor_name, sizeof(processor_name), "%s",
Common::GetSystemInfo().ProcessorName.c_str());
VulkanInitSubgroupSizeControl(window.graphic_ctx.physical_device);
VulkanInitSubgroupSizeControl(graphic_ctx.physical_device, graphic_ctx);
window.graphic_ctx.device =
VulkanCreateDevice(window.graphic_ctx.physical_device, r, queue_family, device_extensions);
if (window.graphic_ctx.device == nullptr) {
graphic_ctx.device = VulkanCreateDevice(graphic_ctx.physical_device, r, queue_family,
device_extensions, graphic_ctx);
if (graphic_ctx.device == nullptr) {
EXIT("Could not create device");
}
VULKAN_HPP_DEFAULT_DISPATCHER.init(window.graphic_ctx.device);
window.graphic_ctx.queue_family = queue_family;
window.graphic_ctx.device.getQueue(queue_family, 0, &window.graphic_ctx.queue);
EXIT_IF(window.graphic_ctx.queue == nullptr);
VULKAN_HPP_DEFAULT_DISPATCHER.init(graphic_ctx.device);
graphic_ctx.queue_family = queue_family;
graphic_ctx.device.getQueue(queue_family, 0, &graphic_ctx.queue);
EXIT_IF(graphic_ctx.queue == nullptr);
if (!window.graphic_ctx.CreateAllocator()) {
if (!graphic_ctx.CreateAllocator()) {
EXIT("Could not create Vulkan memory allocator");
}
window.swapchain = VulkanCreateSwapchain(2);
RenderDocSetActiveWindow(window.graphic_ctx.instance, window.window);
render_context = std::make_unique<RenderContext>(graphic_ctx);
LibKernel::Memory::InstallGpuResources(&render_context->GetGpuResources());
presenter = std::make_unique<Presenter>(*this);
RenderDocSetActiveWindow(graphic_ctx.instance, window);
}
void WindowContext::RefreshSurfaceCapabilities() {
EXIT_IF(graphic_ctx.physical_device == nullptr || surface == nullptr);
GetSurfaceCapabilities(graphic_ctx.physical_device, surface, surface_capabilities);
}
void WindowContext::RecreateSurface() {
EXIT_IF(window == nullptr || graphic_ctx.instance == nullptr);
if (surface != nullptr) {
graphic_ctx.instance.destroySurfaceKHR(surface, nullptr);
surface = nullptr;
}
vk::SurfaceKHR::CType native_surface = VK_NULL_HANDLE;
if (SDL_Vulkan_CreateSurface(window, static_cast<vk::Instance::CType>(graphic_ctx.instance),
&native_surface) == SDL_FALSE) {
EXIT("Could not recreate the Vulkan surface: %s\n", SDL_GetError());
}
surface = native_surface;
RefreshSurfaceCapabilities();
}
WindowContext::~WindowContext() {
presenter.reset();
LibKernel::Memory::InstallGpuResources(nullptr);
render_context.reset();
if (graphic_ctx.device != nullptr) {
RequireVulkanSuccess(graphic_ctx.device.waitIdle(), "wait for Vulkan device shutdown");
graphic_ctx.DestroyAllocator();
graphic_ctx.device.destroy(nullptr);
graphic_ctx.device = nullptr;
graphic_ctx.queue = nullptr;
}
if (surface != nullptr) {
graphic_ctx.instance.destroySurfaceKHR(surface, nullptr);
surface = nullptr;
}
if (graphic_ctx.debug_messenger != nullptr) {
graphic_ctx.instance.destroyDebugUtilsMessengerEXT(graphic_ctx.debug_messenger, nullptr);
graphic_ctx.debug_messenger = nullptr;
}
if (graphic_ctx.instance != nullptr) {
graphic_ctx.instance.destroy(nullptr);
graphic_ctx.instance = nullptr;
graphic_ctx.physical_device = nullptr;
}
if (window != nullptr) {
SDL_DestroyWindow(window);
window = nullptr;
}
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER);
}
} // namespace Libs::Graphics
+126 -297
View File
@@ -24,24 +24,20 @@
#include "common/logging/log.h"
#include "common/profiler.h"
#include "common/stringUtils.h"
#include "common/subsystems.h"
#include "common/systemInfo.h"
#include "common/threads.h"
#include "common/timer.h"
#include "graphics/host_gpu/graphicContext.h"
#include "graphics/host_gpu/renderer/render.h"
#include "graphics/host_gpu/transfer.h"
#include "graphics/host_gpu/vma.h"
#include "graphics/host_gpu/vulkanCommon.h"
#include "graphics/presentation/renderDoc.h"
#include "graphics/presentation/videoOut.h"
#include "graphics/presentation/window/windowInternal.h"
#include "libs/controller.h"
#include "loader/systemContent.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
@@ -61,7 +57,6 @@
namespace Libs::Graphics {
constexpr float FPS_UPDATE_TIME = 1.0f;
constexpr int KEYBOARD_CONTROLLER_ID = -1000;
struct EventKeyboard {
@@ -213,163 +208,36 @@ constexpr uint32_t KYTY_SDL_BUTTON_RMASK = SDL_BUTTON_RMASK; // NOLINT(hicpp-s
constexpr uint32_t KYTY_SDL_BUTTON_X1MASK = SDL_BUTTON_X1MASK; // NOLINT(hicpp-signed-bitwise)
constexpr uint32_t KYTY_SDL_BUTTON_X2MASK = SDL_BUTTON_X2MASK; // NOLINT(hicpp-signed-bitwise)
struct WindowGame {
void* private_data = nullptr;
void* event = nullptr;
namespace {
bool m_game_need_exit = {false};
bool m_game_is_paused = {false};
uint32_t m_screen_width = {0};
uint32_t m_screen_height = {0};
double m_current_time_seconds = {0.0};
double m_previous_time_seconds = {0.0};
int m_update_num = {0};
int m_frame_num = {0};
double m_update_time_seconds = {0.0};
double m_current_fps = {0.0};
int m_max_updates_per_frame = {4};
double m_update_fixed_time = 1.0 / 60.0;
int m_fps_frames_num = {0};
double m_fps_start_time = {0};
};
std::unique_ptr<WindowContext> g_window;
struct WindowGamePrivate {
explicit WindowGamePrivate(GraphicContext& graphics): graphics(graphics) {}
Common::Mutex mutex;
int skip_frames = 0;
GraphicContext& graphics;
};
WindowContext* g_window_ctx = nullptr;
static WindowGame g_window_game;
} // namespace
constexpr const char* KYTY_SDL_WINDOW_CAPTION = "Game";
constexpr uint32_t KYTY_SDL_WINDOW_FLAGS =
(static_cast<uint32_t>(SDL_WINDOW_HIDDEN) | static_cast<uint32_t>(SDL_WINDOW_VULKAN));
constexpr int KYTY_SDL_WINDOWPOS_CENTERED = SDL_WINDOWPOS_CENTERED; /*NOLINT(hicpp-signed-bitwise)*/
static void CalcFrameTime(WindowGame& game, double game_time_s) {
game.m_previous_time_seconds = game.m_current_time_seconds;
game.m_current_time_seconds = game_time_s;
game.m_frame_num++;
game.m_fps_frames_num++;
const auto fps_time = game.m_current_time_seconds - game.m_fps_start_time;
if (fps_time > FPS_UPDATE_TIME) {
game.m_current_fps = static_cast<double>(game.m_fps_frames_num) / fps_time;
game.m_fps_frames_num = 0;
game.m_fps_start_time = game.m_current_time_seconds;
}
}
static bool Init(WindowGame& /*game*/) {
return true;
}
static bool Update(WindowGame& /*game*/) {
return true;
}
static bool Render(WindowGame& /*game*/) {
return true;
}
static bool Close(WindowGame& /*game*/) {
return true;
}
static void SetPause(WindowGame& game, bool flag) {
static void SetPause(WindowLoopState& game, bool flag) {
LOGF("Pause: %s\n", flag ? "true" : "false");
game.m_game_is_paused = flag;
game.paused.store(flag, std::memory_order_release);
}
static bool RenderAndUpdate(WindowGame& game) {
static double lag = 0.0;
lag += game.m_current_time_seconds - game.m_previous_time_seconds;
int num = 0;
bool ok = true;
while (lag >= game.m_update_fixed_time) {
if (num < game.m_max_updates_per_frame) {
ok = ok && Update(game);
game.m_update_num++;
num++;
game.m_update_time_seconds = game.m_update_num * game.m_update_fixed_time;
}
lag -= game.m_update_fixed_time;
}
ok = ok && Render(game);
return ok;
}
bool GameInit(WindowGame& game, const Common::Timer& timer) {
EXIT_IF(game.private_data || game.event);
auto& graphics = g_window_ctx->graphic_ctx;
EXIT_IF(graphics.screen_width == 0 || graphics.screen_height == 0);
auto* pdata = new WindowGamePrivate(graphics);
game.private_data = pdata;
game.event = new SDL_Event;
game.m_screen_width = graphics.screen_width;
game.m_screen_height = graphics.screen_height;
CalcFrameTime(game, timer.GetTimeS());
return Init(game);
}
bool GameClose(WindowGame& game) {
EXIT_IF(!game.private_data || !game.event);
delete (static_cast<WindowGamePrivate*>(game.private_data));
delete (static_cast<SDL_Event*>(game.event));
return Close(game);
}
void GameShowWindow(WindowGame& game, const Common::Timer& timer) {
auto* p = static_cast<WindowGamePrivate*>(game.private_data);
EXIT_IF(!p);
p->mutex.Lock();
{
if (p->skip_frames > 0) {
p->skip_frames--;
LOGF("skip frame %d\n", p->skip_frames);
} else {
VideoOut::VideoOutBeginVblank();
if (VideoOut::VideoOutFlipWindow(0)) {
CalcFrameTime(game, timer.GetTimeS());
}
VideoOut::VideoOutEndVblank();
}
}
p->mutex.Unlock();
}
void GameEventQuit(WindowGame& game) {
static void GameEventQuit(WindowLoopState& game) {
LOGF("Event: quit\n");
game.m_game_need_exit = true;
game.need_exit = true;
}
void GameEventTerminate(WindowGame& game) {
static void GameEventTerminate(WindowLoopState& game) {
LOGF("Event: terminate\n");
game.m_game_need_exit = true;
game.need_exit = true;
}
void GameEventKeyboard(WindowGame& game, const EventKeyboard& key) {
static void GameEventKeyboard(WindowLoopState& game, const EventKeyboard& key) {
#ifdef KYTY_DBG_INPUT
LOGF("Key: time = %.04f, %s%s, %s%s, %s, scan = %d, key = %d, mod = %04" PRIx16 "\n",
key.timestamp_seconds, (key.down ? "down" : ""), (key.up ? "up" : ""),
@@ -380,8 +248,10 @@ void GameEventKeyboard(WindowGame& game, const EventKeyboard& key) {
#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS || KYTY_PLATFORM == KYTY_PLATFORM_LINUX
if (key.down) {
switch (key.key_code) {
case SDLK_ESCAPE: game.m_game_need_exit = true; break;
case SDLK_SPACE: SetPause(game, !game.m_game_is_paused); break;
case SDLK_ESCAPE: game.need_exit = true; break;
case SDLK_SPACE:
SetPause(game, !game.paused.load(std::memory_order_acquire));
break;
case SDLK_F1:
if (!key.repeat) {
RenderDocRequestCapture();
@@ -403,7 +273,7 @@ void GameEventKeyboard(WindowGame& game, const EventKeyboard& key) {
#endif
}
void GameEventMouse([[maybe_unused]] WindowGame& game, [[maybe_unused]] const EventMouse& mb) {
static void GameEventMouse([[maybe_unused]] const EventMouse& mb) {
#ifdef KYTY_DBG_INPUT
if (mb.wheel) {
LOGF("Mouse wheel: time = %.04f, %s[%d, %d]\n", mb.timestamp_seconds,
@@ -424,7 +294,7 @@ void GameEventMouse([[maybe_unused]] WindowGame& game, [[maybe_unused]] const Ev
#endif
}
void GameEventFinger([[maybe_unused]] WindowGame& game, [[maybe_unused]] const EventFinger& f) {
static void GameEventFinger([[maybe_unused]] const EventFinger& f) {
#ifdef KYTY_DBG_INPUT
if (f.motion) {
LOGF("Finger motion: time = %.04f, %d, %d, (x,y) = [%f, %f], (dx,dy) = [%f, %f], pressure "
@@ -439,8 +309,7 @@ void GameEventFinger([[maybe_unused]] WindowGame& game, [[maybe_unused]] const E
#endif
}
void GameEventController([[maybe_unused]] WindowGame& game,
[[maybe_unused]] const EventController& f) {
static void GameEventController([[maybe_unused]] const EventController& f) {
EXIT_NOT_IMPLEMENTED(f.remapped);
#ifdef KYTY_DBG_INPUT
@@ -486,116 +355,104 @@ void GameEventController([[maybe_unused]] WindowGame& game,
}
}
void GameEventDisplay([[maybe_unused]] WindowGame& game) {
auto* p = static_cast<WindowGamePrivate*>(game.private_data);
p->mutex.Lock();
game.m_screen_width = p->graphics.screen_width;
game.m_screen_height = p->graphics.screen_height;
p->mutex.Unlock();
}
void GameEventLowMemory(WindowGame& /*game*/) {
static void GameEventLowMemory() {
LOGF("Event: low_memory\n");
}
void GameEventWillEnterBackground(WindowGame& game) {
static void GameEventWillEnterBackground(WindowLoopState& game) {
LOGF("Event: will_enter_background\n");
SetPause(game, true);
}
void GameEventDidEnterBackground(WindowGame& /*game*/) {
static void GameEventDidEnterBackground() {
LOGF("Event: did_enter_background\n");
}
void GameEventWillEnterForeground(WindowGame& /*game*/) {
static void GameEventWillEnterForeground() {
LOGF("Event: will_enter_foreground\n");
}
void GameEventDidEnterForeground(WindowGame& game) {
static void GameEventDidEnterForeground(WindowLoopState& game) {
LOGF("Event: did_enter_foreground\n");
SetPause(game, false);
}
void GameEventResize(WindowGame& game, uint32_t new_width, uint32_t new_height) {
void WindowContext::Resize(uint32_t new_width, uint32_t new_height) {
EXIT_IF(new_width == 0 || new_height == 0);
auto* p = static_cast<WindowGamePrivate*>(game.private_data);
EXIT_IF(p == nullptr);
p->mutex.Lock();
{
p->skip_frames++;
p->graphics.screen_width = new_width;
p->graphics.screen_height = new_height;
game.m_screen_width = p->graphics.screen_width;
game.m_screen_height = p->graphics.screen_height;
}
p->mutex.Unlock();
graphic_ctx.screen_width = new_width;
graphic_ctx.screen_height = new_height;
}
static void ProcessWindowEvent(WindowGame& game, SDL_WindowEvent window) {
switch (window.event) {
case SDL_WINDOWEVENT_SHOWN: LOGF("Window %" PRIu32 " shown\n", window.windowID); break;
void WindowContext::ProcessWindowEvent(const SDL_WindowEvent& event) {
const auto& window_event = event;
switch (window_event.event) {
case SDL_WINDOWEVENT_SHOWN: LOGF("Window %" PRIu32 " shown\n", window_event.windowID); break;
case SDL_WINDOWEVENT_HIDDEN: LOGF("Window %" PRIu32 " hidden\n", window.windowID); break;
case SDL_WINDOWEVENT_HIDDEN:
LOGF("Window %" PRIu32 " hidden\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_EXPOSED: LOGF("Window %" PRIu32 " exposed\n", window.windowID); break;
case SDL_WINDOWEVENT_EXPOSED:
LOGF("Window %" PRIu32 " exposed\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_MOVED:
LOGF("Window %" PRIu32 " moved to %" PRId32 ",%" PRId32 "\n", window.windowID,
window.data1, window.data2);
LOGF("Window %" PRIu32 " moved to %" PRId32 ",%" PRId32 "\n",
window_event.windowID, window_event.data1, window_event.data2);
break;
case SDL_WINDOWEVENT_RESIZED:
LOGF("Window %" PRIu32 " resized to %" PRId32 "x%" PRId32 "\n", window.windowID,
window.data1, window.data2);
LOGF("Window %" PRIu32 " resized to %" PRId32 "x%" PRId32 "\n",
window_event.windowID, window_event.data1, window_event.data2);
LOGF("m: %d\n", static_cast<int>(SDL_ThreadID()));
GameEventResize(game, window.data1, window.data2);
Resize(window_event.data1, window_event.data2);
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
LOGF("Window %" PRIu32 " size changed to %" PRId32 "x%" PRId32 "\n", window.windowID,
window.data1, window.data2);
LOGF("Window %" PRIu32 " size changed to %" PRId32 "x%" PRId32 "\n",
window_event.windowID, window_event.data1, window_event.data2);
LOGF("m: %d\n", static_cast<int>(SDL_ThreadID()));
GameEventResize(game, window.data1, window.data2);
Resize(window_event.data1, window_event.data2);
break;
case SDL_WINDOWEVENT_MINIMIZED:
LOGF("Window %" PRIu32 " minimized\n", window.windowID);
LOGF("Window %" PRIu32 " minimized\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_MAXIMIZED:
LOGF("Window %" PRIu32 " maximized\n", window.windowID);
LOGF("Window %" PRIu32 " maximized\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_RESTORED:
LOGF("Window %" PRIu32 " restored\n", window.windowID);
LOGF("Window %" PRIu32 " restored\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_ENTER:
LOGF("Mouse entered window %" PRIu32 "\n", window.windowID);
LOGF("Mouse entered window %" PRIu32 "\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_LEAVE:
LOGF("Mouse left window %" PRIu32 "\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_LEAVE: LOGF("Mouse left window %" PRIu32 "\n", window.windowID); break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
LOGF("Window %" PRIu32 " gained keyboard focus\n", window.windowID);
LOGF("Window %" PRIu32 " gained keyboard focus\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
LOGF("Window %" PRIu32 " lost keyboard focus\n", window.windowID);
LOGF("Window %" PRIu32 " lost keyboard focus\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_CLOSE:
LOGF("Window %" PRIu32 " closed\n", window_event.windowID);
break;
case SDL_WINDOWEVENT_CLOSE: LOGF("Window %" PRIu32 " closed\n", window.windowID); break;
default:
LOGF("Window %" PRIu32 " got unknown event %" PRIu8 "\n", window.windowID,
window.event);
LOGF("Window %" PRIu32 " got unknown event %" PRIu8 "\n", window_event.windowID,
window_event.event);
break;
}
}
static void ProcessDisplayEvent(WindowGame& game, SDL_DisplayEvent display) {
void WindowContext::ProcessDisplayEvent(const SDL_DisplayEvent& display) {
bool sdl = false;
switch (display.event) {
@@ -613,10 +470,6 @@ static void ProcessDisplayEvent(WindowGame& game, SDL_DisplayEvent display) {
default: LOGF("???\n");
}
if (!sdl) {
GameEventDisplay(game);
}
break;
}
default:
@@ -626,27 +479,9 @@ static void ProcessDisplayEvent(WindowGame& game, SDL_DisplayEvent display) {
}
}
int GamePollEvent(WindowGame& game) {
auto* event = static_cast<SDL_Event*>(game.event);
EXIT_IF(!event);
return SDL_PollEvent(event);
}
int GameWaitEvent(WindowGame& game) {
auto* event = static_cast<SDL_Event*>(game.event);
EXIT_IF(!event);
return SDL_WaitEvent(event);
}
void GameProcessEvent(WindowGame& game, double time_s) {
auto* event = static_cast<SDL_Event*>(game.event);
EXIT_IF(!event);
void WindowContext::ProcessEvent(double time_s) {
auto& game = loop;
auto* event = &game.event;
EXIT_IF(SDL_GetEventState(SDL_DISPLAYEVENT) != SDL_ENABLE);
switch (event->type) {
@@ -654,13 +489,13 @@ void GameProcessEvent(WindowGame& game, double time_s) {
case SDL_APP_TERMINATING: GameEventTerminate(game); break;
case SDL_APP_LOWMEMORY: GameEventLowMemory(game); break;
case SDL_APP_LOWMEMORY: GameEventLowMemory(); break;
case SDL_APP_WILLENTERBACKGROUND: GameEventWillEnterBackground(game); break;
case SDL_APP_DIDENTERBACKGROUND: GameEventDidEnterBackground(game); break;
case SDL_APP_DIDENTERBACKGROUND: GameEventDidEnterBackground(); break;
case SDL_APP_WILLENTERFOREGROUND: GameEventWillEnterForeground(game); break;
case SDL_APP_WILLENTERFOREGROUND: GameEventWillEnterForeground(); break;
case SDL_APP_DIDENTERFOREGROUND: GameEventDidEnterForeground(game); break;
@@ -683,9 +518,9 @@ void GameProcessEvent(WindowGame& game, double time_s) {
break;
}
case SDL_WINDOWEVENT: ProcessWindowEvent(game, event->window); break;
case SDL_WINDOWEVENT: ProcessWindowEvent(event->window); break;
case SDL_DISPLAYEVENT: ProcessDisplayEvent(game, event->display); break;
case SDL_DISPLAYEVENT: ProcessDisplayEvent(event->display); break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP: {
@@ -710,7 +545,7 @@ void GameProcessEvent(WindowGame& game, double time_s) {
mb.motion_y = 0;
mb.timestamp_seconds = time_s;
GameEventMouse(game, mb);
GameEventMouse(mb);
break;
}
@@ -737,7 +572,7 @@ void GameProcessEvent(WindowGame& game, double time_s) {
mb.motion_y = 0;
mb.timestamp_seconds = time_s;
GameEventMouse(game, mb);
GameEventMouse(mb);
break;
}
@@ -764,7 +599,7 @@ void GameProcessEvent(WindowGame& game, double time_s) {
mb.motion_y = event->motion.yrel;
mb.timestamp_seconds = time_s;
GameEventMouse(game, mb);
GameEventMouse(mb);
break;
}
@@ -786,7 +621,7 @@ void GameProcessEvent(WindowGame& game, double time_s) {
f.pressure = event->tfinger.pressure;
f.timestamp_seconds = time_s;
GameEventFinger(game, f);
GameEventFinger(f);
break;
}
@@ -808,7 +643,7 @@ void GameProcessEvent(WindowGame& game, double time_s) {
c.released = false;
c.timestamp_seconds = time_s;
GameEventController(game, c);
GameEventController(c);
break;
}
@@ -831,7 +666,7 @@ void GameProcessEvent(WindowGame& game, double time_s) {
c.released = (event->cbutton.state == SDL_RELEASED);
c.timestamp_seconds = time_s;
GameEventController(game, c);
GameEventController(c);
break;
}
@@ -855,67 +690,43 @@ void GameProcessEvent(WindowGame& game, double time_s) {
c.released = false;
c.timestamp_seconds = time_s;
GameEventController(game, c);
GameEventController(c);
break;
}
}
}
void GameMainLoop(WindowGame& game) {
bool need_exit = false;
void WindowContext::Run() {
Common::Timer timer;
timer.Start();
if (!GameInit(game, timer)) {
need_exit = true;
}
loop.event = {};
loop.need_exit = false;
loop.paused.store(false, std::memory_order_release);
for (;;) {
if (need_exit) {
break;
}
if (GamePollEvent(game) != 0) {
GameProcessEvent(game, timer.GetTimeS());
while (!loop.need_exit) {
if (SDL_PollEvent(&loop.event) != 0) {
ProcessEvent(timer.GetTimeS());
continue;
}
if (game.m_game_is_paused) {
if (loop.paused.load(std::memory_order_acquire)) {
if (!timer.IsPaused()) {
timer.Pause();
}
GameWaitEvent(game);
GameProcessEvent(game, timer.GetTimeS());
need_exit = game.m_game_need_exit;
if (SDL_WaitEvent(&loop.event) == 0) {
EXIT("%s\n", SDL_GetError());
}
ProcessEvent(timer.GetTimeS());
continue;
}
need_exit = game.m_game_need_exit;
if (game.m_game_is_paused) {
if (!timer.IsPaused()) {
timer.Pause();
}
} else {
if (timer.IsPaused()) {
timer.Resume();
}
if (!need_exit) {
need_exit = !RenderAndUpdate(game);
}
if (!need_exit) {
GameShowWindow(game, timer);
}
if (timer.IsPaused()) {
timer.Resume();
}
Common::Thread::SleepMicro(1000);
}
GameClose(game);
}
static void WindowCreate(WindowContext& context) {
@@ -949,29 +760,33 @@ static void WindowCreate(WindowContext& context) {
SDL_SetWindowResizable(context.window, SDL_FALSE);
}
void WindowInit(uint32_t width, uint32_t height) {
Presenter& WindowInit(uint32_t width, uint32_t height) {
EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread());
EXIT_IF(g_window_ctx != nullptr);
EXIT_IF(g_window != nullptr);
g_window_ctx = new WindowContext;
auto window = std::make_unique<WindowContext>();
g_window_ctx->graphic_ctx.screen_width = width;
g_window_ctx->graphic_ctx.screen_height = height;
window->graphic_ctx.screen_width = width;
window->graphic_ctx.screen_height = height;
WindowCreate(*g_window_ctx);
VulkanCreate(*g_window_ctx);
GraphicsRenderInit(g_window_ctx->graphic_ctx);
WindowCreate(*window);
window->CreateVulkan();
auto& presenter = *window->presenter;
g_window = std::move(window);
return presenter;
}
void WindowRun() {
KYTY_PROFILER_THREAD("Thread_Window");
EXIT_IF(g_window == nullptr);
GameMainLoop(g_window_game);
g_window->Run();
}
// TODO: replace std::_Exit shutdown with full Vulkan teardown, then destroy
// the VMA allocator immediately before vkDestroyDevice.
Common::SubsystemsListSingleton::Instance()->ShutdownAll();
std::_Exit(0);
void WindowShutdown() {
if (g_window != nullptr) {
g_window.reset();
}
}
static int WindowIconRead(void* user, char* data, int size) {
@@ -1033,7 +848,7 @@ static void WindowLoadPngIcon(const std::string& path, WindowIcon* icon) {
EXIT_NOT_IMPLEMENTED(icon->surface == nullptr);
}
void WindowUpdateIcon() {
void WindowContext::UpdateIcon() {
static WindowIcon icon;
static bool icon_loaded = false;
@@ -1046,11 +861,11 @@ void WindowUpdateIcon() {
}
if (icon.surface != nullptr) {
SDL_SetWindowIcon(g_window_ctx->window, icon.surface);
SDL_SetWindowIcon(window, icon.surface);
}
}
void WindowUpdateTitle() {
void WindowContext::UpdateTitle() {
static char title[128];
static char title_id[12];
static char app_ver[12];
@@ -1059,15 +874,29 @@ void WindowUpdateTitle() {
Loader::SystemContentParamSfoGetString("TITLE_ID", title_id, sizeof(title_id));
static bool has_app_ver =
Loader::SystemContentParamSfoGetString("APP_VER", app_ver, sizeof(app_ver));
static uint64_t fps_start = Common::Timer::QueryPerformanceCounter();
static uint64_t frame_num = 0;
static uint64_t fps_frames = 0;
static double current_fps = 0.0;
const auto now = Common::Timer::QueryPerformanceCounter();
const auto frequency = Common::Timer::QueryPerformanceFrequency();
frame_num++;
fps_frames++;
if (now - fps_start >= frequency) {
current_fps = static_cast<double>(fps_frames) * static_cast<double>(frequency) /
static_cast<double>(now - fps_start);
fps_start = now;
fps_frames = 0;
}
auto fps = fmt::format("{}{}{}{}{}{}[{}] [{}], frame: {}, fps: {:f}", (has_title ? title : ""),
(has_title ? ", " : ""), (has_title_id ? title_id : ""),
(has_title_id ? ", " : ""), (has_app_ver ? app_ver : ""),
(has_app_ver ? " " : ""), g_window_ctx->device_name,
g_window_ctx->processor_name, g_window_game.m_frame_num,
g_window_game.m_current_fps);
(has_app_ver ? " " : ""), device_name, processor_name,
frame_num, current_fps);
SDL_SetWindowTitle(g_window_ctx->window, fps.c_str());
SDL_SetWindowTitle(window, fps.c_str());
}
} // namespace Libs::Graphics
@@ -1,31 +1,60 @@
#ifndef EMULATOR_SRC_GRAPHICS_PRESENTATION_WINDOW_WINDOWINTERNAL_H_
#define EMULATOR_SRC_GRAPHICS_PRESENTATION_WINDOW_WINDOWINTERNAL_H_
#include "SDL_events.h"
#include "SDL_video.h"
#include "common/threads.h"
#include "graphics/host_gpu/graphicContext.h"
#include "graphics/host_gpu/vulkanCommon.h"
#include <atomic>
#include <cstdint>
#include <memory>
#include <vector>
namespace Libs::Graphics {
class Presenter;
class RenderContext;
struct SurfaceCapabilities {
vk::SurfaceCapabilitiesKHR capabilities {};
std::vector<vk::SurfaceFormatKHR> formats;
std::vector<vk::PresentModeKHR> present_modes;
bool format_srgb_bgra32 = false;
bool format_unorm_bgra32 = false;
};
struct WindowLoopState {
SDL_Event event {};
bool need_exit = false;
std::atomic_bool paused = false;
};
struct WindowContext {
GraphicContext graphic_ctx;
VulkanSwapchain* swapchain = nullptr;
SDL_Window* window = nullptr;
bool window_hidden = true;
vk::SurfaceKHR surface = nullptr;
SurfaceCapabilities* surface_capabilities = nullptr;
WindowContext();
~WindowContext();
KYTY_CLASS_NO_COPY(WindowContext);
[[nodiscard]] static vk::PhysicalDeviceVulkan13Features
RequiredVulkan13Features() noexcept;
void CreateVulkan();
void RecreateSurface();
void RefreshSurfaceCapabilities();
void UpdateIcon();
void UpdateTitle();
void Resize(uint32_t width, uint32_t height);
void ProcessWindowEvent(const SDL_WindowEvent& event);
void ProcessDisplayEvent(const SDL_DisplayEvent& event);
void ProcessEvent(double time_seconds);
void Run();
GraphicContext graphic_ctx;
SDL_Window* window = nullptr;
bool window_hidden = true;
vk::SurfaceKHR surface = nullptr;
SurfaceCapabilities surface_capabilities;
std::unique_ptr<RenderContext> render_context;
std::unique_ptr<Presenter> presenter;
WindowLoopState loop;
char device_name[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE] = {0};
char processor_name[64] = {0};
@@ -33,16 +62,6 @@ struct WindowContext {
Common::Mutex mutex;
};
extern WindowContext* g_window_ctx;
void VulkanGetSurfaceCapabilities(vk::PhysicalDevice physical_device, vk::SurfaceKHR surface,
SurfaceCapabilities& capabilities);
VulkanSwapchain* VulkanCreateSwapchain(uint32_t image_count);
void VulkanCreate(WindowContext& window);
void WindowUpdateIcon();
void WindowUpdateTitle();
} // namespace Libs::Graphics
#endif // EMULATOR_SRC_GRAPHICS_PRESENTATION_WINDOW_WINDOWINTERNAL_H_