sdl3gpu
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm> // for max, min
|
||||
#include <cstring> // for memcpy
|
||||
#include <iostream> // for basic_ostream, operator<<, cout, endl
|
||||
#include <string> // for basic_string, char_traits, string
|
||||
|
||||
@@ -11,6 +12,10 @@
|
||||
#include "core/resources/asset.h" // for Asset
|
||||
#include "core/resources/resource.h"
|
||||
|
||||
#ifndef NO_SHADERS
|
||||
#include "core/rendering/sdl3gpu/sdl3gpu_shader.hpp" // for Rendering::SDL3GPUShader
|
||||
#endif
|
||||
|
||||
#ifdef __EMSCRIPTEN__
|
||||
#include <emscripten.h>
|
||||
#include <emscripten/html5.h>
|
||||
@@ -69,8 +74,23 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options
|
||||
// Define el color del borde para el modo de pantalla completa
|
||||
borderColor = {0x00, 0x00, 0x00};
|
||||
|
||||
// Crea la textura donde se dibujan los graficos del juego
|
||||
gameCanvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, gameCanvasWidth, gameCanvasHeight);
|
||||
// Establece el modo de video (fullscreen/ventana + logical presentation)
|
||||
// ANTES de crear la textura — SDL3 GPU necesita la logical presentation
|
||||
// del renderer ya aplicada al swapchain quan es reclama la ventana per a GPU.
|
||||
// Mirror del pattern de jaildoctors_dilemma (que usa exactament 256×192 i
|
||||
// funciona) on `initSDLVideo` configura la presentation abans de crear cap
|
||||
// textura.
|
||||
setVideoMode(options->videoMode != 0);
|
||||
|
||||
// Força al window manager a completar el resize/posicionat abans de passar
|
||||
// la ventana al dispositiu GPU. Sense açò en Linux/X11 hi ha un race
|
||||
// condition que deixa el swapchain en estat inestable i fa crashear el
|
||||
// driver Vulkan en `SDL_CreateGPUGraphicsPipeline`.
|
||||
SDL_SyncWindow(window);
|
||||
|
||||
// Crea la textura donde se dibujan los graficos del juego.
|
||||
// ARGB8888 per simplificar el readback cap al pipeline SDL3 GPU.
|
||||
gameCanvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, gameCanvasWidth, gameCanvasHeight);
|
||||
if (gameCanvas != nullptr) {
|
||||
SDL_SetTextureScaleMode(gameCanvas, options->filter == FILTER_NEAREST ? SDL_SCALEMODE_NEAREST : SDL_SCALEMODE_LINEAR);
|
||||
}
|
||||
@@ -80,11 +100,24 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options
|
||||
}
|
||||
}
|
||||
|
||||
// Establece el modo de video
|
||||
setVideoMode(options->videoMode != 0);
|
||||
#ifndef NO_SHADERS
|
||||
// Buffer de readback del gameCanvas (lo dimensionamos una vez)
|
||||
pixel_buffer_.resize(static_cast<size_t>(gameCanvasWidth) * static_cast<size_t>(gameCanvasHeight));
|
||||
#endif
|
||||
|
||||
// Inicializa el sistema de notificaciones (Text compartido de Resource)
|
||||
notificationText = Resource::get()->getText("8bithud");
|
||||
// Renderiza una vez la textura vacía al renderer abans d'inicialitzar els
|
||||
// shaders: jaildoctors_dilemma ho fa així i evita que el driver Vulkan
|
||||
// crashegi en la creació del pipeline gràfic. `initShaders()` es crida
|
||||
// després des de `Director` amb el swapchain ja estable.
|
||||
SDL_RenderTexture(renderer, gameCanvas, nullptr, nullptr);
|
||||
|
||||
// Estado inicial de las notificaciones. El Text real se enlaza después vía
|
||||
// `initNotifications()` quan `Resource` ja estigui inicialitzat. Dividim
|
||||
// això del constructor perquè `initShaders()` (GPU) ha de cridar-se ABANS
|
||||
// de carregar recursos: si el SDL_Renderer ha fet abans moltes
|
||||
// allocacions (carrega de textures), el driver Vulkan crasheja quan
|
||||
// després es reclama la ventana per al dispositiu GPU.
|
||||
notificationText = nullptr;
|
||||
notificationMessage = "";
|
||||
notificationTextColor = {0xFF, 0xFF, 0xFF};
|
||||
notificationOutlineColor = {0x00, 0x00, 0x00};
|
||||
@@ -95,9 +128,18 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options
|
||||
registerEmscriptenEventCallbacks();
|
||||
}
|
||||
|
||||
// Enllaça el Text de les notificacions amb el recurs compartit de `Resource`.
|
||||
// S'ha de cridar després de `Resource::init(...)`.
|
||||
void Screen::initNotifications() {
|
||||
notificationText = Resource::get()->getText("8bithud");
|
||||
}
|
||||
|
||||
// Destructor
|
||||
Screen::~Screen() {
|
||||
// notificationText es propiedad de Resource — no liberar.
|
||||
#ifndef NO_SHADERS
|
||||
shutdownShaders();
|
||||
#endif
|
||||
SDL_DestroyTexture(gameCanvas);
|
||||
}
|
||||
|
||||
@@ -118,6 +160,51 @@ void Screen::blit() {
|
||||
SDL_SetRenderTarget(renderer, gameCanvas);
|
||||
renderNotification();
|
||||
|
||||
#ifndef NO_SHADERS
|
||||
// Si el backend GPU està viu i accelerat, passem sempre per ell (tant amb
|
||||
// shaders com sense). Seguim el mateix pattern que aee_plus: quan shader
|
||||
// està desactivat, forcem POSTFX + params a zero només per a aquest frame
|
||||
// i restaurem el shader actiu, així CRTPI no aplica les seues scanlines
|
||||
// quan l'usuari ho ha desactivat.
|
||||
if (shader_backend_ && shader_backend_->isHardwareAccelerated()) {
|
||||
SDL_Surface *surface = SDL_RenderReadPixels(renderer, nullptr);
|
||||
if (surface != nullptr) {
|
||||
if (surface->format == SDL_PIXELFORMAT_ARGB8888) {
|
||||
std::memcpy(pixel_buffer_.data(), surface->pixels, pixel_buffer_.size() * sizeof(Uint32));
|
||||
} else {
|
||||
SDL_Surface *converted = SDL_ConvertSurface(surface, SDL_PIXELFORMAT_ARGB8888);
|
||||
if (converted != nullptr) {
|
||||
std::memcpy(pixel_buffer_.data(), converted->pixels, pixel_buffer_.size() * sizeof(Uint32));
|
||||
SDL_DestroySurface(converted);
|
||||
}
|
||||
}
|
||||
SDL_DestroySurface(surface);
|
||||
}
|
||||
SDL_SetRenderTarget(renderer, nullptr);
|
||||
|
||||
if (options->videoShaderEnabled) {
|
||||
// Ruta normal: shader amb els seus params.
|
||||
shader_backend_->uploadPixels(pixel_buffer_.data(), gameCanvasWidth, gameCanvasHeight);
|
||||
shader_backend_->render();
|
||||
} else {
|
||||
// Shader off: POSTFX amb params zero (passa-per-aquí). CRTPI no
|
||||
// val perque sempre aplica els seus efectes interns; salvem i
|
||||
// restaurem el shader actiu.
|
||||
const auto PREV_SHADER = shader_backend_->getActiveShader();
|
||||
if (PREV_SHADER != Rendering::ShaderType::POSTFX) {
|
||||
shader_backend_->setActiveShader(Rendering::ShaderType::POSTFX);
|
||||
}
|
||||
shader_backend_->setPostFXParams(Rendering::PostFXParams{});
|
||||
shader_backend_->uploadPixels(pixel_buffer_.data(), gameCanvasWidth, gameCanvasHeight);
|
||||
shader_backend_->render();
|
||||
if (PREV_SHADER != Rendering::ShaderType::POSTFX) {
|
||||
shader_backend_->setActiveShader(PREV_SHADER);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Vuelve a dejar el renderizador en modo normal
|
||||
SDL_SetRenderTarget(renderer, nullptr);
|
||||
|
||||
@@ -199,6 +286,11 @@ void Screen::toggleIntegerScale() {
|
||||
void Screen::setVSync(bool enabled) {
|
||||
options->vSync = enabled;
|
||||
SDL_SetRenderVSync(renderer, enabled ? 1 : SDL_RENDERER_VSYNC_DISABLED);
|
||||
#ifndef NO_SHADERS
|
||||
if (shader_backend_) {
|
||||
shader_backend_->setVSync(enabled);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// Alterna el V-Sync
|
||||
@@ -321,7 +413,7 @@ void Screen::clearNotification() {
|
||||
|
||||
// Dibuja la notificación activa (si la hay) sobre el gameCanvas
|
||||
void Screen::renderNotification() {
|
||||
if (SDL_GetTicks() >= notificationEndTime) {
|
||||
if (notificationText == nullptr || SDL_GetTicks() >= notificationEndTime) {
|
||||
return;
|
||||
}
|
||||
notificationText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE,
|
||||
@@ -367,3 +459,144 @@ void Screen::registerEmscriptenEventCallbacks() {
|
||||
emscripten_set_orientationchange_callback(nullptr, EM_TRUE, onEmOrientationChange);
|
||||
#endif
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// GPU / shaders (SDL3 GPU post-procesado). En builds con NO_SHADERS (Emscripten)
|
||||
// las operaciones son no-op; la ruta clásica sigue siendo la única disponible.
|
||||
// ============================================================================
|
||||
|
||||
#ifndef NO_SHADERS
|
||||
// Aplica al backend el preset del shader actiu segons options.
|
||||
// Només s'ha de cridar quan `videoShaderEnabled=true` (en cas contrari el
|
||||
// blit() ja força POSTFX+zero params per a desactivar els efectes sense
|
||||
// tocar els paràmetres emmagatzemats).
|
||||
void Screen::applyShaderParams() {
|
||||
if (!shader_backend_ || !shader_backend_->isHardwareAccelerated()) {
|
||||
return;
|
||||
}
|
||||
const Rendering::ShaderType ACTIVE = options->videoShaderType == 1
|
||||
? Rendering::ShaderType::CRTPI
|
||||
: Rendering::ShaderType::POSTFX;
|
||||
shader_backend_->setActiveShader(ACTIVE);
|
||||
|
||||
// Preset per defecte (carregador YAML pendent). Valors estil "CRT" de CCAE.
|
||||
Rendering::PostFXParams POSTFX;
|
||||
POSTFX.vignette = 0.15F;
|
||||
POSTFX.scanlines = 0.7F;
|
||||
POSTFX.chroma = 0.2F;
|
||||
shader_backend_->setPostFXParams(POSTFX);
|
||||
|
||||
// CrtPi: defaults del struct ja raonables (scanline_weight=6.0, bloom=3.5…).
|
||||
shader_backend_->setCrtPiParams(Rendering::CrtPiParams{});
|
||||
}
|
||||
#endif
|
||||
|
||||
void Screen::initShaders() {
|
||||
#ifndef NO_SHADERS
|
||||
if (!shader_backend_) {
|
||||
shader_backend_ = std::make_unique<Rendering::SDL3GPUShader>();
|
||||
const std::string FALLBACK_DRIVER = "none";
|
||||
shader_backend_->setPreferredDriver(
|
||||
options->videoGpuAcceleration ? options->videoGpuPreferredDriver : FALLBACK_DRIVER);
|
||||
}
|
||||
if (!shader_backend_->isHardwareAccelerated()) {
|
||||
const bool ok = shader_backend_->init(window, gameCanvas, "", "");
|
||||
if (options->console) {
|
||||
std::cout << "Screen::initShaders: SDL3GPUShader::init() = " << (ok ? "OK" : "FAILED") << '\n';
|
||||
}
|
||||
}
|
||||
if (shader_backend_->isHardwareAccelerated()) {
|
||||
shader_backend_->setScaleMode(options->integerScale);
|
||||
shader_backend_->setVSync(options->vSync);
|
||||
applyShaderParams(); // aplica preset del shader actiu
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void Screen::shutdownShaders() {
|
||||
#ifndef NO_SHADERS
|
||||
// Només es crida des del destructor de Screen. Els toggles runtime NO la
|
||||
// poden cridar: destruir + recrear el dispositiu SDL3 GPU amb la ventana
|
||||
// ja reclamada és inestable (Vulkan/Radeon crasheja en el següent claim).
|
||||
if (shader_backend_) {
|
||||
shader_backend_->cleanup();
|
||||
shader_backend_.reset();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void Screen::setGpuAcceleration(bool enabled) {
|
||||
if (options->videoGpuAcceleration == enabled) { return; }
|
||||
options->videoGpuAcceleration = enabled;
|
||||
// Soft toggle: el backend es manté viu (vegeu shutdownShaders). El canvi
|
||||
// s'aplica al proper arrencada. S'emet una notificació perquè l'usuari
|
||||
// sap que ha tocat la tecla però el canvi no és immediat.
|
||||
const color_t YELLOW = {0xFF, 0xFF, 0x00};
|
||||
const color_t BLACK = {0x00, 0x00, 0x00};
|
||||
const Uint32 DUR_MS = 2500;
|
||||
notify(enabled ? "GPU: ON (restart)" : "GPU: OFF (restart)", YELLOW, BLACK, DUR_MS);
|
||||
}
|
||||
|
||||
void Screen::toggleGpuAcceleration() {
|
||||
setGpuAcceleration(!options->videoGpuAcceleration);
|
||||
}
|
||||
|
||||
auto Screen::isGpuAccelerated() const -> bool {
|
||||
#ifndef NO_SHADERS
|
||||
return shader_backend_ && shader_backend_->isHardwareAccelerated();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void Screen::setShaderEnabled(bool enabled) {
|
||||
if (options->videoShaderEnabled == enabled) { return; }
|
||||
options->videoShaderEnabled = enabled;
|
||||
#ifndef NO_SHADERS
|
||||
if (enabled) {
|
||||
applyShaderParams(); // restaura preset del shader actiu
|
||||
}
|
||||
// Si enabled=false, blit() forçarà POSTFX+zero per frame — no cal tocar
|
||||
// res ara.
|
||||
#endif
|
||||
const color_t CYAN = {0x00, 0xFF, 0xFF};
|
||||
const color_t BLACK = {0x00, 0x00, 0x00};
|
||||
const Uint32 DUR_MS = 1500;
|
||||
notify(enabled ? "Shader: ON" : "Shader: OFF", CYAN, BLACK, DUR_MS);
|
||||
}
|
||||
|
||||
void Screen::toggleShaderEnabled() {
|
||||
setShaderEnabled(!options->videoShaderEnabled);
|
||||
}
|
||||
|
||||
auto Screen::isShaderEnabled() const -> bool {
|
||||
return options->videoShaderEnabled;
|
||||
}
|
||||
|
||||
#ifndef NO_SHADERS
|
||||
void Screen::setActiveShader(Rendering::ShaderType type) {
|
||||
options->videoShaderType = type == Rendering::ShaderType::CRTPI ? 1 : 0;
|
||||
if (options->videoShaderEnabled) {
|
||||
applyShaderParams();
|
||||
}
|
||||
const color_t MAGENTA = {0xFF, 0x00, 0xFF};
|
||||
const color_t BLACK = {0x00, 0x00, 0x00};
|
||||
const Uint32 DUR_MS = 1500;
|
||||
notify(type == Rendering::ShaderType::CRTPI ? "Shader: CRTPI" : "Shader: POSTFX", MAGENTA, BLACK, DUR_MS);
|
||||
}
|
||||
|
||||
auto Screen::getActiveShader() const -> Rendering::ShaderType {
|
||||
return options->videoShaderType == 1 ? Rendering::ShaderType::CRTPI : Rendering::ShaderType::POSTFX;
|
||||
}
|
||||
#endif
|
||||
|
||||
void Screen::toggleActiveShader() {
|
||||
#ifndef NO_SHADERS
|
||||
const Rendering::ShaderType NEXT = getActiveShader() == Rendering::ShaderType::POSTFX
|
||||
? Rendering::ShaderType::CRTPI
|
||||
: Rendering::ShaderType::POSTFX;
|
||||
setActiveShader(NEXT);
|
||||
#else
|
||||
options->videoShaderType = options->videoShaderType == 1 ? 0 : 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user