From 04a8b03cf33168ef6f7a0775ba087bee0962b403 Mon Sep 17 00:00:00 2001 From: SirLynix Date: Sat, 5 Nov 2022 00:29:25 +0100 Subject: [PATCH] Graphics/TextureLoader: Add support for alpha-test and alpha-blending --- src/Nazara/Graphics/Formats/TextureLoader.cpp | 43 +++++++++++++++++-- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/src/Nazara/Graphics/Formats/TextureLoader.cpp b/src/Nazara/Graphics/Formats/TextureLoader.cpp index 9c10af640..9aefc5396 100644 --- a/src/Nazara/Graphics/Formats/TextureLoader.cpp +++ b/src/Nazara/Graphics/Formats/TextureLoader.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -24,12 +25,27 @@ namespace Nz { TextureParams texParams; texParams.renderDevice = Graphics::Instance()->GetRenderDevice(); + // TODO: Set format as sRGB - std::shared_ptr texture = Texture::LoadFromStream(stream, texParams); - if (!texture) + std::shared_ptr image = Image::LoadFromStream(stream, texParams); + if (!image) return Err(ResourceLoadingError::Unrecognized); - bool hasAlphaTest = parameters.custom.GetBooleanParameter("EnableAlphaTest").GetValueOr(false); + std::shared_ptr texture = Texture::CreateFromImage(*image, texParams); + if (!texture) + return Err(ResourceLoadingError::Internal); + + bool enableAlphaTest = parameters.custom.GetBooleanParameter("EnableAlphaTest").GetValueOr(false); + bool enableAlphaBlending = parameters.custom.GetBooleanParameter("EnableAlphaBlending").GetValueOr(false); + + bool hasAlpha; + if (enableAlphaTest || enableAlphaBlending) + hasAlpha = image->HasAlpha(); + else + hasAlpha = false; + + // Delete image to free memory + image.reset(); std::shared_ptr materialInstance; switch (parameters.lightingType) @@ -49,9 +65,28 @@ namespace Nz if (!materialInstance) materialInstance = Graphics::Instance()->GetDefaultMaterials().basicMaterial->Instantiate(); - if (hasAlphaTest && PixelFormatInfo::HasAlpha(texture->GetFormat())) + if (enableAlphaTest && hasAlpha) materialInstance->SetValueProperty("AlphaTest", true); + if (enableAlphaBlending && hasAlpha) + { + materialInstance->DisablePass("DepthPass"); + materialInstance->UpdatePassStates("ForwardPass", [](RenderStates& renderStates) + { + renderStates.depthBuffer = true; + renderStates.depthWrite = false; + renderStates.blending = true; + renderStates.blend.modeColor = BlendEquation::Add; + renderStates.blend.modeAlpha = BlendEquation::Add; + renderStates.blend.srcColor = BlendFunc::SrcAlpha; + renderStates.blend.dstColor = BlendFunc::InvSrcAlpha; + renderStates.blend.srcAlpha = BlendFunc::One; + renderStates.blend.dstAlpha = BlendFunc::One; + + return true; + }); + } + materialInstance->SetTextureProperty("BaseColorMap", std::move(texture)); return materialInstance;