Path: blob/master/GPU/Common/FragmentShaderGenerator.cpp
3186 views
// Copyright (c) 2012- PPSSPP Project.12// This program is free software: you can redistribute it and/or modify3// it under the terms of the GNU General Public License as published by4// the Free Software Foundation, version 2.0 or later versions.56// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License 2.0 for more details.1011// A copy of the GPL 2.0 should have been included with the program.12// If not, see http://www.gnu.org/licenses/1314// Official git repository and contact information can be found at15// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.1617#include <cstdio>18#include <sstream>1920#include "Common/Log.h"21#include "Common/StringUtils.h"22#include "Common/GPU/OpenGL/GLFeatures.h"23#include "Common/GPU/ShaderWriter.h"24#include "Common/GPU/thin3d.h"25#include "Core/Compatibility.h"26#include "Core/Config.h"27#include "Core/System.h"28#include "GPU/Common/GPUStateUtils.h"29#include "GPU/Common/ShaderId.h"30#include "GPU/Common/ShaderUniforms.h"31#include "GPU/Common/FragmentShaderGenerator.h"32#include "GPU/Vulkan/DrawEngineVulkan.h"33#include "GPU/ge_constants.h"34#include "GPU/GPUState.h"3536#define WRITE(p, ...) p.F(__VA_ARGS__)3738static const SamplerDef samplersMono[3] = {39{ 0, "tex" },40{ 1, "fbotex", SamplerFlags::ARRAY_ON_VULKAN },41{ 2, "pal" },42};4344static const SamplerDef samplersStereo[3] = {45{ 0, "tex", SamplerFlags::ARRAY_ON_VULKAN },46{ 1, "fbotex", SamplerFlags::ARRAY_ON_VULKAN },47{ 2, "pal" },48};4950bool GenerateFragmentShader(const FShaderID &id, char *buffer, const ShaderLanguageDesc &compat, Draw::Bugs bugs, uint64_t *uniformMask, FragmentShaderFlags *fragmentShaderFlags, std::string *errorString) {51*uniformMask = 0;52*fragmentShaderFlags = (FragmentShaderFlags)0;53errorString->clear();5455bool useStereo = id.Bit(FS_BIT_STEREO);56bool highpFog = false;57bool highpTexcoord = false;58bool enableFragmentTestCache = gstate_c.Use(GPU_USE_FRAGMENT_TEST_CACHE);5960if (compat.gles) {61// PowerVR needs highp to do the fog in MHU correctly.62// Others don't, and some can't handle highp in the fragment shader.63highpFog = (gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) ? true : false;64highpTexcoord = highpFog;65}6667bool texture3D = id.Bit(FS_BIT_3D_TEXTURE);68bool arrayTexture = id.Bit(FS_BIT_SAMPLE_ARRAY_TEXTURE);6970ReplaceAlphaType stencilToAlpha = static_cast<ReplaceAlphaType>(id.Bits(FS_BIT_STENCIL_TO_ALPHA, 2));7172std::vector<const char*> extensions;73if (ShaderLanguageIsOpenGL(compat.shaderLanguage)) {74if (stencilToAlpha == REPLACE_ALPHA_DUALSOURCE && gl_extensions.EXT_blend_func_extended) {75extensions.push_back("#extension GL_EXT_blend_func_extended : require");76}77if (gl_extensions.EXT_gpu_shader4) {78extensions.push_back("#extension GL_EXT_gpu_shader4 : enable");79}80if (compat.framebufferFetchExtension) {81extensions.push_back(compat.framebufferFetchExtension);82}83if (gl_extensions.OES_texture_3D && texture3D) {84extensions.push_back("#extension GL_OES_texture_3D: enable");85}86}8788ShaderWriterFlags flags = ShaderWriterFlags::NONE;89if (useStereo) {90flags |= ShaderWriterFlags::FS_AUTO_STEREO;91}9293ShaderWriter p(buffer, compat, ShaderStage::Fragment, extensions, flags);94p.F("// %s\n", FragmentShaderDesc(id).c_str());9596p.ApplySamplerMetadata(arrayTexture ? samplersStereo : samplersMono);9798bool lmode = id.Bit(FS_BIT_LMODE);99bool doTexture = id.Bit(FS_BIT_DO_TEXTURE);100bool enableFog = id.Bit(FS_BIT_ENABLE_FOG);101bool enableAlphaTest = id.Bit(FS_BIT_ALPHA_TEST);102103bool alphaTestAgainstZero = id.Bit(FS_BIT_ALPHA_AGAINST_ZERO);104bool testForceToZero = id.Bit(FS_BIT_TEST_DISCARD_TO_ZERO);105bool enableColorTest = id.Bit(FS_BIT_COLOR_TEST);106bool colorTestAgainstZero = id.Bit(FS_BIT_COLOR_AGAINST_ZERO);107bool doTextureProjection = id.Bit(FS_BIT_DO_TEXTURE_PROJ);108109bool ubershader = id.Bit(FS_BIT_UBERSHADER);110// ubershader-controlled bits. If ubershader is on, these will not be used below (and will be false).111bool useTexAlpha = id.Bit(FS_BIT_TEXALPHA);112bool enableColorDouble = id.Bit(FS_BIT_DOUBLE_COLOR);113114if (texture3D && arrayTexture) {115*errorString = "Invalid combination of 3D texture and array texture, shouldn't happen";116return false;117}118if (compat.shaderLanguage != ShaderLanguage::GLSL_VULKAN && arrayTexture) {119*errorString = "We only do array textures for framebuffers in Vulkan.";120return false;121}122123bool flatBug = bugs.Has(Draw::Bugs::BROKEN_FLAT_IN_SHADER) && g_Config.bVendorBugChecksEnabled;124125bool doFlatShading = id.Bit(FS_BIT_FLATSHADE) && !flatBug;126if (doFlatShading) {127*fragmentShaderFlags |= FragmentShaderFlags::USES_FLAT_SHADING;128}129130ShaderDepalMode shaderDepalMode = (ShaderDepalMode)id.Bits(FS_BIT_SHADER_DEPAL_MODE, 2);131if (texture3D) {132shaderDepalMode = ShaderDepalMode::OFF;133}134if (!compat.bitwiseOps && shaderDepalMode != ShaderDepalMode::OFF) {135*errorString = "depal requires bitwise ops";136return false;137}138bool bgraTexture = id.Bit(FS_BIT_BGRA_TEXTURE);139bool colorWriteMask = id.Bit(FS_BIT_COLOR_WRITEMASK) && compat.bitwiseOps;140141GEComparison alphaTestFunc = (GEComparison)id.Bits(FS_BIT_ALPHA_TEST_FUNC, 3);142GEComparison colorTestFunc = (GEComparison)id.Bits(FS_BIT_COLOR_TEST_FUNC, 2);143bool needShaderTexClamp = id.Bit(FS_BIT_SHADER_TEX_CLAMP);144145GETexFunc texFunc = (GETexFunc)id.Bits(FS_BIT_TEXFUNC, 3);146147ReplaceBlendType replaceBlend = static_cast<ReplaceBlendType>(id.Bits(FS_BIT_REPLACE_BLEND, 3));148149bool blueToAlpha = false;150if (replaceBlend == ReplaceBlendType::REPLACE_BLEND_BLUE_TO_ALPHA) {151blueToAlpha = true;152}153154bool isModeClear = id.Bit(FS_BIT_CLEARMODE);155156const char *shading = "";157if (compat.glslES30 || compat.shaderLanguage == ShaderLanguage::GLSL_VULKAN) {158shading = doFlatShading ? "flat" : "";159}160161bool forceDepthWritesOff = id.Bit(FS_BIT_DEPTH_TEST_NEVER);162163bool useDiscardStencilBugWorkaround = id.Bit(FS_BIT_NO_DEPTH_CANNOT_DISCARD_STENCIL) && !forceDepthWritesOff;164165GEBlendSrcFactor replaceBlendFuncA = (GEBlendSrcFactor)id.Bits(FS_BIT_BLENDFUNC_A, 4);166GEBlendDstFactor replaceBlendFuncB = (GEBlendDstFactor)id.Bits(FS_BIT_BLENDFUNC_B, 4);167GEBlendMode replaceBlendEq = (GEBlendMode)id.Bits(FS_BIT_BLENDEQ, 3);168StencilValueType replaceAlphaWithStencilType = (StencilValueType)id.Bits(FS_BIT_REPLACE_ALPHA_WITH_STENCIL_TYPE, 4);169170// Distinct from the logic op simulation support.171GELogicOp replaceLogicOpType = isModeClear ? GE_LOGIC_COPY : (GELogicOp)id.Bits(FS_BIT_REPLACE_LOGIC_OP, 4);172bool replaceLogicOp = replaceLogicOpType != GE_LOGIC_COPY && compat.bitwiseOps;173174bool needFramebufferRead = replaceBlend == REPLACE_BLEND_READ_FRAMEBUFFER || colorWriteMask || replaceLogicOp;175176bool fetchFramebuffer = needFramebufferRead && id.Bit(FS_BIT_USE_FRAMEBUFFER_FETCH);177bool readFramebufferTex = needFramebufferRead && !id.Bit(FS_BIT_USE_FRAMEBUFFER_FETCH);178179if (fetchFramebuffer && (compat.shaderLanguage != GLSL_3xx || !compat.lastFragData)) {180*errorString = "framebuffer fetch requires GLSL 3xx";181return false;182}183184bool needFragCoord = readFramebufferTex || gstate_c.Use(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT);185bool writeDepth = gstate_c.Use(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT) && !forceDepthWritesOff;186187// TODO: We could have a separate mechanism to support more ops using the shader blending mechanism,188// on hardware that can do proper bit math in fragment shaders.189SimulateLogicOpType simulateLogicOpType = (SimulateLogicOpType)id.Bits(FS_BIT_SIMULATE_LOGIC_OP_TYPE, 2);190191if (shaderDepalMode != ShaderDepalMode::OFF && !doTexture) {192*errorString = "depal requires a texture";193return false;194}195196// Currently only used by Vulkan.197std::vector<SamplerDef> samplers;198199if (compat.shaderLanguage == ShaderLanguage::GLSL_VULKAN) {200if (useDiscardStencilBugWorkaround && !writeDepth) {201WRITE(p, "layout (depth_unchanged) out float gl_FragDepth;\n");202}203204WRITE(p, "layout (std140, set = 0, binding = %d) uniform baseUBO {\n%s};\n", DRAW_BINDING_DYNUBO_BASE, ub_baseStr);205if (doTexture) {206WRITE(p, "layout (set = 0, binding = %d) uniform %s%s tex;\n", DRAW_BINDING_TEXTURE, texture3D ? "sampler3D" : "sampler2D", arrayTexture ? "Array" : "");207}208209if (readFramebufferTex) {210// The framebuffer texture is always bound as an array.211p.F("layout (set = 0, binding = %d) uniform sampler2DArray fbotex;\n", DRAW_BINDING_2ND_TEXTURE);212}213214if (shaderDepalMode != ShaderDepalMode::OFF) {215WRITE(p, "layout (set = 0, binding = %d) uniform sampler2D pal;\n", DRAW_BINDING_DEPAL_TEXTURE);216}217218// Note: the precision qualifiers must match the vertex shader!219WRITE(p, "layout (location = 1) %s in lowp vec4 v_color0;\n", shading);220if (lmode) {221WRITE(p, "layout (location = 2) %s in lowp vec3 v_color1;\n", shading);222}223WRITE(p, "layout (location = 3) in highp float v_fogdepth;\n");224if (doTexture) {225WRITE(p, "layout (location = 0) in highp vec3 v_texcoord;\n");226}227228if (enableAlphaTest && !alphaTestAgainstZero) {229WRITE(p, "int roundAndScaleTo255i(in highp float x) { return int(floor(x * 255.0 + 0.5)); }\n");230}231if (enableColorTest && !colorTestAgainstZero) {232WRITE(p, "uint roundAndScaleTo8x4(in highp vec3 x) { uvec3 u = uvec3(floor(x * 255.0 + 0.5)); return u.r | (u.g << 8) | (u.b << 16); }\n");233WRITE(p, "uint packFloatsTo8x4(in vec3 x) { uvec3 u = uvec3(x); return u.r | (u.g << 8) | (u.b << 16); }\n");234}235236WRITE(p, "layout (location = 0, index = 0) out vec4 fragColor0;\n");237if (stencilToAlpha == REPLACE_ALPHA_DUALSOURCE) {238WRITE(p, "layout (location = 0, index = 1) out vec4 fragColor1;\n");239}240} else if (compat.shaderLanguage == HLSL_D3D11) {241{242WRITE(p, "SamplerState texSamp : register(s0);\n");243if (texture3D) {244WRITE(p, "Texture3D<vec4> tex : register(t0);\n");245} else {246WRITE(p, "Texture2D<vec4> tex : register(t0);\n");247}248if (readFramebufferTex) {249// No sampler required, we Load250WRITE(p, "Texture2D<vec4> fbotex : register(t1);\n");251}252253if (shaderDepalMode != ShaderDepalMode::OFF) {254WRITE(p, "SamplerState palSamp : register(s3);\n");255WRITE(p, "Texture2D<vec4> pal : register(t3);\n");256WRITE(p, "float2 textureSize(Texture2D<float4> tex, int mip) { float2 size; tex.GetDimensions(size.x, size.y); return size; }\n");257}258259WRITE(p, "cbuffer base : register(b0) {\n%s};\n", ub_baseStr);260}261262if (enableAlphaTest) {263if (compat.shaderLanguage == HLSL_D3D11) {264WRITE(p, "int roundAndScaleTo255i(float x) { return int(floor(x * 255.0f + 0.5f)); }\n");265} else {266// D3D11 level 9 gets to take this path.267WRITE(p, "float roundAndScaleTo255f(float x) { return floor(x * 255.0f + 0.5f); }\n");268}269}270if (enableColorTest) {271if (compat.shaderLanguage == HLSL_D3D11) {272WRITE(p, "uint roundAndScaleTo8x4(float3 x) { uvec3 u = (floor(x * 255.0f + 0.5f)); return u.r | (u.g << 8) | (u.b << 16); }\n");273WRITE(p, "uint packFloatsTo8x4(in vec3 x) { uvec3 u = uvec3(x); return u.r | (u.g << 8) | (u.b << 16); }\n");274} else {275WRITE(p, "vec3 roundAndScaleTo255v(float3 x) { return floor(x * 255.0f + 0.5f); }\n");276}277}278279WRITE(p, "struct PS_IN {\n");280if (doTexture || compat.shaderLanguage == HLSL_D3D11) {281// In D3D11, if we always have a texcoord in the VS, we always need it in the PS too for the structs to match.282WRITE(p, " vec3 v_texcoord: TEXCOORD0;\n");283}284const char *colorInterpolation = doFlatShading && compat.shaderLanguage == HLSL_D3D11 ? "nointerpolation " : "";285WRITE(p, " %svec4 v_color0: COLOR0;\n", colorInterpolation);286if (lmode) {287WRITE(p, " vec3 v_color1: COLOR1;\n");288}289WRITE(p, " float v_fogdepth: TEXCOORD1;\n");290if (needFragCoord) {291if (compat.shaderLanguage == HLSL_D3D11) {292WRITE(p, " vec4 pixelPos : SV_POSITION;\n");293}294}295WRITE(p, "};\n");296297if (compat.shaderLanguage == HLSL_D3D11) {298WRITE(p, "struct PS_OUT {\n");299if (stencilToAlpha == REPLACE_ALPHA_DUALSOURCE) {300WRITE(p, " vec4 target : SV_Target0;\n");301WRITE(p, " vec4 target1 : SV_Target1;\n");302} else {303WRITE(p, " vec4 target : SV_Target;\n");304}305if (writeDepth) {306WRITE(p, " float depth : SV_Depth;\n");307}308WRITE(p, "};\n");309}310} else if (ShaderLanguageIsOpenGL(compat.shaderLanguage)) {311if ((shaderDepalMode != ShaderDepalMode::OFF || colorWriteMask) && gl_extensions.IsGLES) {312WRITE(p, "precision highp int;\n");313}314315if (doTexture) {316if (texture3D) {317// For whatever reason, a precision specifier is required here.318WRITE(p, "uniform lowp sampler3D tex;\n");319} else {320WRITE(p, "uniform sampler2D tex;\n");321}322*uniformMask |= DIRTY_TEX_ALPHA_MUL;323if (ubershader) {324WRITE(p, "uniform vec2 u_texNoAlphaMul;\n");325}326}327328if (readFramebufferTex) {329if (!compat.texelFetch) {330WRITE(p, "uniform vec2 u_fbotexSize;\n");331}332WRITE(p, "uniform sampler2D fbotex;\n");333}334335if (!isModeClear && replaceBlend > REPLACE_BLEND_STANDARD) {336*uniformMask |= DIRTY_SHADERBLEND;337if (replaceBlendFuncA >= GE_SRCBLEND_FIXA) {338WRITE(p, "uniform vec3 u_blendFixA;\n");339}340if (replaceBlendFuncB >= GE_DSTBLEND_FIXB) {341WRITE(p, "uniform vec3 u_blendFixB;\n");342}343}344345if (needShaderTexClamp && doTexture) {346*uniformMask |= DIRTY_TEXCLAMP;347WRITE(p, "uniform vec4 u_texclamp;\n");348WRITE(p, "uniform vec2 u_texclampoff;\n");349}350351// TODO: Can get rid of some of this in the != 0 cases.352if (enableAlphaTest || enableColorTest) {353if (enableFragmentTestCache) {354WRITE(p, "uniform sampler2D testtex;\n");355} else {356*uniformMask |= DIRTY_ALPHACOLORREF;357if (compat.bitwiseOps) {358WRITE(p, "uniform uint u_alphacolorref;\n");359} else {360WRITE(p, "uniform vec4 u_alphacolorref;\n");361}362if (compat.bitwiseOps && ((enableColorTest && !colorTestAgainstZero) || (enableAlphaTest && !alphaTestAgainstZero))) {363*uniformMask |= DIRTY_ALPHACOLORMASK;364WRITE(p, "uniform uint u_alphacolormask;\n");365}366}367}368369if (shaderDepalMode != ShaderDepalMode::OFF) {370WRITE(p, "uniform sampler2D pal;\n");371WRITE(p, "uniform uint u_depal_mask_shift_off_fmt;\n");372*uniformMask |= DIRTY_DEPAL;373}374375if (colorWriteMask) {376WRITE(p, "uniform uint u_colorWriteMask;\n");377*uniformMask |= DIRTY_COLORWRITEMASK;378}379380if (stencilToAlpha && replaceAlphaWithStencilType == STENCIL_VALUE_UNIFORM) {381*uniformMask |= DIRTY_STENCILREPLACEVALUE;382WRITE(p, "uniform float u_stencilReplaceValue;\n");383}384if (doTexture && texFunc == GE_TEXFUNC_BLEND) {385*uniformMask |= DIRTY_TEXENV;386WRITE(p, "uniform vec3 u_texenv;\n");387}388389if (texture3D) {390*uniformMask |= DIRTY_MIPBIAS;391WRITE(p, "uniform float u_mipBias;\n");392}393394WRITE(p, "%s %s lowp vec4 v_color0;\n", shading, compat.varying_fs);395if (lmode) {396WRITE(p, "%s %s lowp vec3 v_color1;\n", shading, compat.varying_fs);397}398if (enableFog) {399*uniformMask |= DIRTY_FOGCOLOR;400WRITE(p, "uniform vec3 u_fogcolor;\n");401}402WRITE(p, "%s %s float v_fogdepth;\n", compat.varying_fs, highpFog ? "highp" : "mediump");403if (doTexture) {404WRITE(p, "%s %s vec3 v_texcoord;\n", compat.varying_fs, highpTexcoord ? "highp" : "mediump");405}406407if (!enableFragmentTestCache) {408if (enableAlphaTest && !alphaTestAgainstZero) {409if (compat.bitwiseOps) {410WRITE(p, "int roundAndScaleTo255i(in float x) { return int(floor(x * 255.0 + 0.5)); }\n");411} else if (gl_extensions.gpuVendor == GPU_VENDOR_IMGTEC) {412WRITE(p, "float roundTo255thf(in mediump float x) { mediump float y = x + (0.5/255.0); return y - fract(y * 255.0) * (1.0 / 255.0); }\n");413} else {414WRITE(p, "float roundAndScaleTo255f(in float x) { return floor(x * 255.0 + 0.5); }\n");415}416}417if (enableColorTest && !colorTestAgainstZero) {418if (compat.bitwiseOps) {419WRITE(p, "uint roundAndScaleTo8x4(in vec3 x) { uvec3 u = uvec3(floor(x * 255.92)); return u.r | (u.g << 0x8u) | (u.b << 0x10u); }\n");420WRITE(p, "uint packFloatsTo8x4(in vec3 x) { uvec3 u = uvec3(x); return u.r | (u.g << 0x8u) | (u.b << 0x10u); }\n");421} else if (gl_extensions.gpuVendor == GPU_VENDOR_IMGTEC) {422WRITE(p, "vec3 roundTo255thv(in vec3 x) { vec3 y = x + (0.5/255.0); return y - fract(y * 255.0) * (1.0 / 255.0); }\n");423} else {424WRITE(p, "vec3 roundAndScaleTo255v(in vec3 x) { return floor(x * 255.0 + 0.5); }\n");425}426}427}428429if (!strcmp(compat.fragColor0, "fragColor0")) {430const char *qualifierColor0 = "out";431if (fetchFramebuffer && compat.lastFragData && !strcmp(compat.lastFragData, compat.fragColor0)) {432qualifierColor0 = "inout";433}434// Output the output color definitions.435if (stencilToAlpha == REPLACE_ALPHA_DUALSOURCE) {436WRITE(p, "%s vec4 fragColor0;\n", qualifierColor0);437WRITE(p, "out vec4 fragColor1;\n");438} else {439WRITE(p, "%s vec4 fragColor0;\n", qualifierColor0);440}441}442}443444bool hasPackUnorm4x8 = false;445if (compat.shaderLanguage == GLSL_VULKAN) {446hasPackUnorm4x8 = true;447} else if (ShaderLanguageIsOpenGL(compat.shaderLanguage)) {448if (compat.gles) {449hasPackUnorm4x8 = compat.glslVersionNumber >= 310;450} else {451hasPackUnorm4x8 = compat.glslVersionNumber >= 400;452}453}454455const char *packSuffix = "";456if (!hasPackUnorm4x8) {457packSuffix = "R";458}459460// Provide implementations of packUnorm4x8 and unpackUnorm4x8 if not available.461if ((colorWriteMask || replaceLogicOp) && !hasPackUnorm4x8) {462WRITE(p, "uint packUnorm4x8%s(%svec4 v) {\n", packSuffix, compat.shaderLanguage == GLSL_VULKAN ? "highp " : "");463WRITE(p, " highp vec4 f = clamp(v, 0.0, 1.0);\n");464WRITE(p, " uvec4 u = uvec4(255.0 * f);\n");465WRITE(p, " return u.x | (u.y << 0x8u) | (u.z << 0x10u) | (u.w << 0x18u);\n");466WRITE(p, "}\n");467468WRITE(p, "vec4 unpackUnorm4x8%s(highp uint x) {\n", packSuffix);469WRITE(p, " highp uvec4 u = uvec4(x & 0xFFu, (x >> 0x8u) & 0xFFu, (x >> 0x10u) & 0xFFu, (x >> 0x18u) & 0xFFu);\n");470WRITE(p, " highp vec4 f = vec4(u);\n");471WRITE(p, " return f * (1.0 / 255.0);\n");472WRITE(p, "}\n");473}474475if (compat.bitwiseOps && enableColorTest) {476p.C("uvec3 unpackUVec3(highp uint x) {\n");477p.C(" return uvec3(x & 0xFFu, (x >> 0x8u) & 0xFFu, (x >> 0x10u) & 0xFFu);\n");478p.C("}\n");479}480481// PowerVR needs a custom modulo function. For some reason, this has far higher precision than the builtin one.482if ((gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) && needShaderTexClamp) {483WRITE(p, "float mymod(float a, float b) { return a - b * floor(a / b); }\n");484}485486if (compat.shaderLanguage == HLSL_D3D11) {487WRITE(p, "PS_OUT main( PS_IN In ) {\n");488WRITE(p, " PS_OUT outfragment;\n");489if (needFragCoord) {490WRITE(p, " vec4 gl_FragCoord = In.pixelPos;\n");491}492if (writeDepth) {493WRITE(p, " float gl_FragDepth;\n");494}495} else {496WRITE(p, "void main() {\n");497}498499if (compat.shaderLanguage == HLSL_D3D11) {500WRITE(p, " vec4 v_color0 = In.v_color0;\n");501if (lmode) {502WRITE(p, " vec3 v_color1 = In.v_color1;\n");503}504if (enableFog) {505WRITE(p, " float v_fogdepth = In.v_fogdepth;\n");506}507if (doTexture) {508WRITE(p, " vec3 v_texcoord = In.v_texcoord;\n");509}510}511512// Two things read from the old framebuffer - shader replacement blending and bit-level masking.513if (readFramebufferTex) {514if (compat.shaderLanguage == HLSL_D3D11) {515WRITE(p, " vec4 destColor = fbotex.Load(int3((int)gl_FragCoord.x, (int)gl_FragCoord.y, 0));\n");516} else if (compat.shaderLanguage == GLSL_VULKAN) {517WRITE(p, " lowp vec4 destColor = %s(fbotex, ivec3(gl_FragCoord.x, gl_FragCoord.y, %s), 0);\n", compat.texelFetch, useStereo ? "float(gl_ViewIndex)" : "0");518} else if (!compat.texelFetch) {519WRITE(p, " lowp vec4 destColor = %s(fbotex, gl_FragCoord.xy * u_fbotexSize.xy);\n", compat.texture);520} else {521WRITE(p, " lowp vec4 destColor = %s(fbotex, ivec2(gl_FragCoord.x, gl_FragCoord.y), 0);\n", compat.texelFetch);522}523} else if (fetchFramebuffer) {524// If we have EXT_shader_framebuffer_fetch / ARM_shader_framebuffer_fetch, we skip the blit.525// We can just read the prev value more directly.526if (compat.shaderLanguage == GLSL_3xx) {527WRITE(p, " lowp vec4 destColor = %s;\n", compat.lastFragData);528} else if (compat.shaderLanguage == GLSL_VULKAN) {529WRITE(p, " lowp vec4 destColor = subpassLoad(inputColor);\n");530} else {531_assert_msg_(false, "Need fetch destColor, but not a compatible language");532}533}534535if (isModeClear) {536// Clear mode does not allow any fancy shading.537WRITE(p, " vec4 v = v_color0;\n");538} else {539const char *secondary = "";540// Secondary color for specular on top of texture541if (lmode) {542WRITE(p, " vec4 s = vec4(v_color1, 0.0);\n");543secondary = " + s";544}545546if (doTexture) {547char texcoord[64] = "v_texcoord";548// TODO: Not sure the right way to do this for projection.549// This path destroys resolution on older PowerVR no matter what I do if projection is needed,550// so we disable it on SGX 540 and lesser, and live with the consequences.551bool terriblePrecision = (gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_TERRIBLE) != 0;552bool clampDisabled = doTextureProjection && terriblePrecision;553// Also with terrible precision we can't do wrapping without destroying the image. See #9189554if (terriblePrecision && (!id.Bit(FS_BIT_CLAMP_S) || !id.Bit(FS_BIT_CLAMP_T))) {555clampDisabled = true;556}557if (needShaderTexClamp && !clampDisabled) {558// We may be clamping inside a larger surface (tex = 64x64, buffer=480x272).559// We may also be wrapping in such a surface, or either one in a too-small surface.560// Obviously, clamping to a smaller surface won't work. But better to clamp to something.561std::string ucoord = "v_texcoord.x";562std::string vcoord = "v_texcoord.y";563if (doTextureProjection) {564ucoord = "(v_texcoord.x / v_texcoord.z)";565vcoord = "(v_texcoord.y / v_texcoord.z)";566}567568std::string modulo = (gl_extensions.bugs & BUG_PVR_SHADER_PRECISION_BAD) ? "mymod" : "mod";569570if (id.Bit(FS_BIT_CLAMP_S)) {571ucoord = "clamp(" + ucoord + ", u_texclamp.z, u_texclamp.x - u_texclamp.z)";572} else {573ucoord = modulo + "(" + ucoord + ", u_texclamp.x)";574}575if (id.Bit(FS_BIT_CLAMP_T)) {576vcoord = "clamp(" + vcoord + ", u_texclamp.w, u_texclamp.y - u_texclamp.w)";577} else {578vcoord = modulo + "(" + vcoord + ", u_texclamp.y)";579}580ucoord = "(" + ucoord + " + u_texclampoff.x)";581vcoord = "(" + vcoord + " + u_texclampoff.y)";582583WRITE(p, " vec2 fixedcoord = vec2(%s, %s);\n", ucoord.c_str(), vcoord.c_str());584truncate_cpy(texcoord, "fixedcoord");585// We already projected it.586doTextureProjection = false;587}588589switch (shaderDepalMode) {590case ShaderDepalMode::OFF:591if (compat.shaderLanguage == HLSL_D3D11) {592if (texture3D) {593if (doTextureProjection) {594WRITE(p, " vec4 t = tex.Sample(texSamp, vec3(v_texcoord.xy / v_texcoord.z, u_mipBias))%s;\n", bgraTexture ? ".bgra" : "");595} else {596WRITE(p, " vec4 t = tex.Sample(texSamp, vec3(%s.xy, u_mipBias))%s;\n", texcoord, bgraTexture ? ".bgra" : "");597}598} else {599if (doTextureProjection) {600WRITE(p, " vec4 t = tex.Sample(texSamp, v_texcoord.xy / v_texcoord.z)%s;\n", bgraTexture ? ".bgra" : "");601} else {602WRITE(p, " vec4 t = tex.Sample(texSamp, %s.xy)%s;\n", texcoord, bgraTexture ? ".bgra" : "");603}604}605} else {606// Note that here we're relying on the filter to be linear. We would have to otherwise to do two samples and manually filter in Z.607// Let's add that if we run into a case...608if (texture3D) {609if (doTextureProjection) {610WRITE(p, " vec4 t = %sProj(tex, vec4(%s.xy, u_mipBias, %s.z));\n", compat.texture3D, texcoord, texcoord);611} else {612WRITE(p, " vec4 t = %s(tex, vec3(%s.xy, u_mipBias));\n", compat.texture3D, texcoord);613}614} else if (arrayTexture) {615_dbg_assert_(compat.shaderLanguage == GLSL_VULKAN);616// Used for stereo rendering.617const char *arrayIndex = useStereo ? "float(gl_ViewIndex)" : "0.0";618if (doTextureProjection) {619// There's no textureProj for array textures, so we need to emulate it.620// Should be fine on any Vulkan-compatible hardware.621WRITE(p, " vec2 uv_proj = (%s.xy) / (%s.z);\n", texcoord, texcoord);622WRITE(p, " vec4 t = %s(tex, vec3(uv_proj, %s));\n", compat.texture, texcoord, arrayIndex);623} else {624WRITE(p, " vec4 t = %s(tex, vec3(%s.xy, %s));\n", compat.texture, texcoord, arrayIndex);625}626} else {627if (doTextureProjection) {628WRITE(p, " vec4 t = %sProj(tex, %s);\n", compat.texture, texcoord);629} else {630WRITE(p, " vec4 t = %s(tex, %s.xy);\n", compat.texture, texcoord);631}632}633}634break;635case ShaderDepalMode::SMOOTHED:636// Specific mode for Test Drive. Fixes the banding.637if (doTextureProjection) {638// We don't use textureProj because we need better control and it's probably not much of a savings anyway.639// However it is good for precision on older hardware like PowerVR.640p.F(" vec2 uv = %s.xy/%s.z;\n vec2 uv_round;\n", texcoord, texcoord);641} else {642p.F(" vec2 uv = %s.xy;\n vec2 uv_round;\n", texcoord);643}644// Restrictions on this are checked before setting the smoothed flag.645// Only RGB565 and RGBA5551 are supported, and only the specific shifts hitting the646// channels directly.647// Also, since we know the CLUT is smooth, we do not need to do the bilinear filter manually, we can just648// lookup with the filtered value once.649p.F(" vec4 t = ").SampleTexture2D("tex", "uv").C(";\n");650p.C(" uint depalShift = (u_depal_mask_shift_off_fmt >> 0x8u) & 0xFFu;\n");651p.C(" uint depalOffset = ((u_depal_mask_shift_off_fmt >> 0x10u) & 0xFFu) << 0x4u;\n");652p.C(" uint depalFmt = (u_depal_mask_shift_off_fmt >> 0x18u) & 0x3u;\n");653p.C(" float index0 = t.r;\n");654p.C(" float factor = 31.0 / 256.0;\n");655p.C(" if (depalFmt == 0x0u) {\n"); // yes, different versions of Test Drive use different formats. Could do compile time by adding more compat flags but meh.656p.C(" if (depalShift == 0x5u) { index0 = t.g; factor = 63.0 / 256.0; }\n");657p.C(" else if (depalShift == 0xBu) { index0 = t.b; }\n");658p.C(" } else {\n");659p.C(" if (depalShift == 0x5u) { index0 = t.g; }\n");660p.C(" else if (depalShift == 0xAu) { index0 = t.b; }\n");661p.C(" }\n");662p.C(" float offset = float(depalOffset) / 256.0;\n");663p.F(" t = ").SampleTexture2D("pal", "vec2((index0 * factor + offset) * 0.5 + 0.5 / 512.0, 0.0)").C(";\n"); // 0.5 for 512-entry CLUT.664break;665case ShaderDepalMode::NORMAL:666if (doTextureProjection) {667// We don't use textureProj because we need better control and it's probably not much of a savings anyway.668// However it is good for precision on older hardware like PowerVR.669WRITE(p, " vec2 uv = %s.xy/%s.z;\n vec2 uv_round;\n", texcoord, texcoord);670} else {671WRITE(p, " vec2 uv = %s.xy;\n vec2 uv_round;\n", texcoord);672}673WRITE(p, " vec2 tsize = vec2(textureSize(tex, 0).xy);\n");674WRITE(p, " vec2 fraction;\n");675WRITE(p, " bool bilinear = (u_depal_mask_shift_off_fmt >> 0x2Fu) != 0x0u;\n");676WRITE(p, " if (bilinear) {\n");677WRITE(p, " uv_round = uv * tsize - vec2(0.5, 0.5);\n");678WRITE(p, " fraction = fract(uv_round);\n");679WRITE(p, " uv_round = (uv_round - fraction + vec2(0.5, 0.5)) / tsize;\n"); // We want to take our four point samples at pixel centers.680WRITE(p, " } else {\n");681WRITE(p, " uv_round = uv;\n");682WRITE(p, " }\n");683p.C(" highp vec4 t = ").SampleTexture2D("tex", "uv_round").C(";\n");684p.C(" highp vec4 t1 = ").SampleTexture2DOffset("tex", "uv_round", 1, 0).C(";\n");685p.C(" highp vec4 t2 = ").SampleTexture2DOffset("tex", "uv_round", 0, 1).C(";\n");686p.C(" highp vec4 t3 = ").SampleTexture2DOffset("tex", "uv_round", 1, 1).C(";\n");687WRITE(p, " uint depalMask = (u_depal_mask_shift_off_fmt & 0xFFu);\n");688WRITE(p, " uint depalShift = (u_depal_mask_shift_off_fmt >> 0x8u) & 0xFFu;\n");689WRITE(p, " uint depalOffset = ((u_depal_mask_shift_off_fmt >> 0x10u) & 0xFFu) << 0x4u;\n");690WRITE(p, " uint depalFmt = (u_depal_mask_shift_off_fmt >> 0x18u) & 0x3u;\n");691WRITE(p, " uvec4 col; uint index0; uint index1; uint index2; uint index3;\n");692WRITE(p, " switch (int(depalFmt)) {\n"); // We might want to include fmt in the shader ID if this is a performance issue.693WRITE(p, " case 0:\n"); // 565694WRITE(p, " col = uvec4(t.rgb * vec3(31.99, 63.99, 31.99), 0);\n");695WRITE(p, " index0 = (col.b << 0xBu) | (col.g << 0x5u) | (col.r);\n");696WRITE(p, " if (bilinear) {\n");697WRITE(p, " col = uvec4(t1.rgb * vec3(31.99, 63.99, 31.99), 0);\n");698WRITE(p, " index1 = (col.b << 0xBu) | (col.g << 0x5u) | (col.r);\n");699WRITE(p, " col = uvec4(t2.rgb * vec3(31.99, 63.99, 31.99), 0);\n");700WRITE(p, " index2 = (col.b << 0xBu) | (col.g << 0x5u) | (col.r);\n");701WRITE(p, " col = uvec4(t3.rgb * vec3(31.99, 63.99, 31.99), 0);\n");702WRITE(p, " index3 = (col.b << 0xBu) | (col.g << 0x5u) | (col.r);\n");703WRITE(p, " }\n");704WRITE(p, " break;\n");705WRITE(p, " case 1:\n"); // 5551706WRITE(p, " col = uvec4(t.rgba * vec4(31.99, 31.99, 31.99, 1.0));\n");707WRITE(p, " index0 = (col.a << 0xFu) | (col.b << 0xAu) | (col.g << 0x5u) | (col.r);\n");708WRITE(p, " if (bilinear) {\n");709WRITE(p, " col = uvec4(t1.rgba * vec4(31.99, 31.99, 31.99, 1.0));\n");710WRITE(p, " index1 = (col.a << 0xFu) | (col.b << 0xAu) | (col.g << 0x5u) | (col.r);\n");711WRITE(p, " col = uvec4(t2.rgba * vec4(31.99, 31.99, 31.99, 1.0));\n");712WRITE(p, " index2 = (col.a << 0xFu) | (col.b << 0xAu) | (col.g << 0x5u) | (col.r);\n");713WRITE(p, " col = uvec4(t3.rgba * vec4(31.99, 31.99, 31.99, 1.0));\n");714WRITE(p, " index3 = (col.a << 0xFu) | (col.b << 0xAu) | (col.g << 0x5u) | (col.r);\n");715WRITE(p, " }\n");716WRITE(p, " break;\n");717WRITE(p, " case 2:\n"); // 4444718WRITE(p, " col = uvec4(t.rgba * 15.99);\n");719WRITE(p, " index0 = (col.a << 0xCu) | (col.b << 0x8u) | (col.g << 0x4u) | (col.r);\n");720WRITE(p, " if (bilinear) {\n");721WRITE(p, " col = uvec4(t1.rgba * 15.99);\n");722WRITE(p, " index1 = (col.a << 0xCu) | (col.b << 0x8u) | (col.g << 0x4u) | (col.r);\n");723WRITE(p, " col = uvec4(t2.rgba * 15.99);\n");724WRITE(p, " index2 = (col.a << 0xCu) | (col.b << 0x8u) | (col.g << 0x4u) | (col.r);\n");725WRITE(p, " col = uvec4(t3.rgba * 15.99);\n");726WRITE(p, " index3 = (col.a << 0xCu) | (col.b << 0x8u) | (col.g << 0x4u) | (col.r);\n");727WRITE(p, " }\n");728WRITE(p, " break;\n");729WRITE(p, " case 3:\n"); // 8888730WRITE(p, " col = uvec4(t.rgba * 255.99);\n");731WRITE(p, " index0 = (col.a << 0x18u) | (col.b << 0x10u) | (col.g << 0x8u) | (col.r);\n");732WRITE(p, " if (bilinear) {\n");733WRITE(p, " col = uvec4(t1.rgba * 255.99);\n");734WRITE(p, " index1 = (col.a << 0x18u) | (col.b << 0x10u) | (col.g << 0x8u) | (col.r);\n");735WRITE(p, " col = uvec4(t2.rgba * 255.99);\n");736WRITE(p, " index2 = (col.a << 0x18u) | (col.b << 0x10u) | (col.g << 0x8u) | (col.r);\n");737WRITE(p, " col = uvec4(t3.rgba * 255.99);\n");738WRITE(p, " index3 = (col.a << 0x18u) | (col.b << 0x10u) | (col.g << 0x8u) | (col.r);\n");739WRITE(p, " }\n");740WRITE(p, " break;\n");741WRITE(p, " };\n");742WRITE(p, " index0 = ((index0 >> depalShift) & depalMask) | depalOffset;\n");743p.C(" t = ").LoadTexture2D("pal", "ivec2(index0, 0)", 0).C(";\n");744WRITE(p, " if (bilinear && !(index0 == index1 && index1 == index2 && index2 == index3)) {\n");745WRITE(p, " index1 = ((index1 >> depalShift) & depalMask) | depalOffset;\n");746WRITE(p, " index2 = ((index2 >> depalShift) & depalMask) | depalOffset;\n");747WRITE(p, " index3 = ((index3 >> depalShift) & depalMask) | depalOffset;\n");748p.C(" t1 = ").LoadTexture2D("pal", "ivec2(index1, 0)", 0).C(";\n");749p.C(" t2 = ").LoadTexture2D("pal", "ivec2(index2, 0)", 0).C(";\n");750p.C(" t3 = ").LoadTexture2D("pal", "ivec2(index3, 0)", 0).C(";\n");751WRITE(p, " t = mix(t, t1, fraction.x);\n");752WRITE(p, " t2 = mix(t2, t3, fraction.x);\n");753WRITE(p, " t = mix(t, t2, fraction.y);\n");754WRITE(p, " }\n");755break;756case ShaderDepalMode::CLUT8_8888:757if (doTextureProjection) {758// We don't use textureProj because we need better control and it's probably not much of a savings anyway.759// However it is good for precision on older hardware like PowerVR.760p.F(" vec2 uv = %s.xy/%s.z;\n vec2 uv_round;\n", texcoord, texcoord);761} else {762p.F(" vec2 uv = %s.xy;\n vec2 uv_round;\n", texcoord);763}764p.C(" vec2 tsize = vec2(textureSize(tex, 0).xy);\n");765p.C(" uv_round = floor(uv * tsize);\n");766p.C(" int component = int(uv_round.x) & 3;\n");767p.C(" uv_round.x *= 0.25;\n");768p.C(" uv_round /= tsize;\n");769p.C(" vec4 t = ").SampleTexture2D("tex", "uv_round").C(";\n");770p.C(" int index;\n");771p.C(" switch (component) {\n");772p.C(" case 0: index = int(t.x * 254.99); break;\n"); // TODO: Not sure why 254.99 instead of 255.99, but it's currently needed.773p.C(" case 1: index = int(t.y * 254.99); break;\n");774p.C(" case 2: index = int(t.z * 254.99); break;\n");775p.C(" case 3: index = int(t.w * 254.99); break;\n");776p.C(" }\n");777p.C(" t = ").LoadTexture2D("pal", "ivec2(index, 0)", 0).C(";\n");778break;779}780781WRITE(p, " vec4 p = v_color0;\n");782783if (texFunc != GE_TEXFUNC_REPLACE) {784if (ubershader) {785WRITE(p, " t.a = max(t.a, u_texNoAlphaMul.x);\n");786} else if (!useTexAlpha) {787WRITE(p, " t.a = 1.0;\n");788}789}790791switch (texFunc) {792case GE_TEXFUNC_MODULATE:793WRITE(p, " vec4 v = p * t%s;\n", secondary);794break;795case GE_TEXFUNC_DECAL:796WRITE(p, " vec4 v = vec4(mix(p.rgb, t.rgb, t.a), p.a)%s;\n", secondary);797break;798case GE_TEXFUNC_BLEND:799WRITE(p, " vec4 v = vec4(mix(p.rgb, u_texenv.rgb, t.rgb), p.a * t.a)%s;\n", secondary);800break;801case GE_TEXFUNC_REPLACE:802WRITE(p, " vec4 r = t;\n");803if (ubershader) {804WRITE(p, " r.a = mix(r.a, p.a, u_texNoAlphaMul.x);\n");805} else if (!useTexAlpha) {806WRITE(p, " r.a = p.a;\n");807}808WRITE(p, " vec4 v = r%s;\n", secondary);809break;810case GE_TEXFUNC_ADD:811case GE_TEXFUNC_UNKNOWN1:812case GE_TEXFUNC_UNKNOWN2:813case GE_TEXFUNC_UNKNOWN3:814WRITE(p, " vec4 v = vec4(p.rgb + t.rgb, p.a * t.a)%s;\n", secondary);815break;816default:817// Doesn't happen818WRITE(p, " vec4 v = p%s;\n", secondary); break;819break;820}821822// This happens before fog is applied.823*uniformMask |= DIRTY_TEX_ALPHA_MUL;824825// We only need a clamp if the color will be further processed. Otherwise the hardware color conversion will clamp for us.826if (ubershader) {827if (enableFog || enableColorTest || replaceBlend != REPLACE_BLEND_NO || simulateLogicOpType != LOGICOPTYPE_NORMAL || colorWriteMask || blueToAlpha) {828WRITE(p, " v.rgb = clamp(v.rgb * u_texNoAlphaMul.y, 0.0, 1.0);\n");829} else {830WRITE(p, " v.rgb *= u_texNoAlphaMul.y;\n");831}832} else if (enableColorDouble) {833p.C(" v.rgb = clamp(v.rgb * 2.0, 0.0, 1.0);\n");834}835} else {836// No texture mapping837WRITE(p, " vec4 v = v_color0%s;\n", secondary);838}839840if (enableFog) {841WRITE(p, " float fogCoef = clamp(v_fogdepth, 0.0, 1.0);\n");842WRITE(p, " v = mix(vec4(u_fogcolor, v.a), v, fogCoef);\n");843}844845// Texture access is at half texels [0.5/256, 255.5/256], but colors are normalized [0, 255].846// So we have to scale to account for the difference.847char alphaTestXCoord[64] = "0";848if (enableFragmentTestCache) {849if (enableColorTest && !colorTestAgainstZero) {850WRITE(p, " vec4 vScale256 = v * %f + %f;\n", 255.0 / 256.0, 0.5 / 256.0);851truncate_cpy(alphaTestXCoord, "vScale256.a");852} else if (enableAlphaTest && !alphaTestAgainstZero) {853snprintf(alphaTestXCoord, sizeof(alphaTestXCoord), "v.a * %f + %f", 255.0 / 256.0, 0.5 / 256.0);854}855}856857const char *discardStatement = testForceToZero ? "v.a = 0.0;" : "DISCARD;";858if (enableAlphaTest) {859*fragmentShaderFlags |= FragmentShaderFlags::USES_DISCARD;860861if (alphaTestAgainstZero) {862// When testing against 0 (extremely common), we can avoid some math.863// 0.002 is approximately half of 1.0 / 255.0.864if (alphaTestFunc == GE_COMP_NOTEQUAL || alphaTestFunc == GE_COMP_GREATER) {865WRITE(p, " if (v.a < 0.002) %s\n", discardStatement);866} else if (alphaTestFunc != GE_COMP_NEVER) {867// Anything else is a test for == 0. Happens sometimes, actually...868WRITE(p, " if (v.a > 0.002) %s\n", discardStatement);869} else {870// NEVER has been logged as used by games, although it makes little sense - statically failing.871// Maybe we could discard the drawcall, but it's pretty rare. Let's just statically discard here.872WRITE(p, " %s\n", discardStatement);873}874} else if (enableFragmentTestCache) {875WRITE(p, " float aResult = %s(testtex, vec2(%s, 0)).a;\n", compat.texture, alphaTestXCoord);876WRITE(p, " if (aResult < 0.5) %s\n", discardStatement);877} else {878const char *alphaTestFuncs[] = { "#", "#", " != ", " == ", " >= ", " > ", " <= ", " < " };879if (alphaTestFuncs[alphaTestFunc][0] != '#') {880if (compat.bitwiseOps) {881WRITE(p, " if ((roundAndScaleTo255i(v.a) & int(u_alphacolormask >> 0x18u)) %s int(u_alphacolorref >> 0x18u)) %s\n", alphaTestFuncs[alphaTestFunc], discardStatement);882} else if (gl_extensions.gpuVendor == GPU_VENDOR_IMGTEC) {883// Work around bad PVR driver problem where equality check + discard just doesn't work.884if (alphaTestFunc != GE_COMP_NOTEQUAL) {885WRITE(p, " if (roundTo255thf(v.a) %s u_alphacolorref.a) %s\n", alphaTestFuncs[alphaTestFunc], discardStatement);886}887} else {888WRITE(p, " if (roundAndScaleTo255f(v.a) %s u_alphacolorref.a) %s\n", alphaTestFuncs[alphaTestFunc], discardStatement);889}890} else {891// This means NEVER. See above.892WRITE(p, " %s\n", discardStatement);893}894}895}896897if (enableColorTest) {898*fragmentShaderFlags |= FragmentShaderFlags::USES_DISCARD;899900if (colorTestAgainstZero) {901// When testing against 0 (common), we can avoid some math.902// 0.002 is approximately half of 1.0 / 255.0.903if (colorTestFunc == GE_COMP_NOTEQUAL) {904if (compat.shaderLanguage == GLSL_VULKAN) {905// Old workaround for Adreno driver bug. We could make this the main path actually906// since the math is roughly equivalent given the non-negative inputs.907WRITE(p, " if (v.r + v.g + v.b < 0.002) %s\n", discardStatement);908} else {909WRITE(p, " if (v.r < 0.002 && v.g < 0.002 && v.b < 0.002) %s\n", discardStatement);910}911} else if (colorTestFunc != GE_COMP_NEVER) {912if (compat.shaderLanguage == GLSL_VULKAN) {913// See the GE_COMP_NOTEQUAL case.914WRITE(p, " if (v.r + v.g + v.b > 0.002) %s\n", discardStatement);915} else {916// Anything else is a test for == 0.917WRITE(p, " if (v.r > 0.002 || v.g > 0.002 || v.b > 0.002) %s\n", discardStatement);918}919} else {920// NEVER has been logged as used by games, although it makes little sense - statically failing.921// Maybe we could discard the drawcall, but it's pretty rare. Let's just statically discard here.922WRITE(p, " %s\n", discardStatement);923}924} else if (enableFragmentTestCache) {925WRITE(p, " float rResult = %s(testtex, vec2(vScale256.r, 0)).r;\n", compat.texture);926WRITE(p, " float gResult = %s(testtex, vec2(vScale256.g, 0)).g;\n", compat.texture);927WRITE(p, " float bResult = %s(testtex, vec2(vScale256.b, 0)).b;\n", compat.texture);928if (colorTestFunc == GE_COMP_EQUAL) {929// Equal means all parts must be equal (so discard if any is not.)930WRITE(p, " if (rResult < 0.5 || gResult < 0.5 || bResult < 0.5) %s\n", discardStatement);931} else {932// Not equal means any part must be not equal.933WRITE(p, " if (rResult < 0.5 && gResult < 0.5 && bResult < 0.5) %s\n", discardStatement);934}935} else {936const char *colorTestFuncs[] = { "#", "#", " != ", " == " };937const char *test = colorTestFuncs[colorTestFunc];938if (test[0] != '#') {939// TODO: Unify these paths better.940if (compat.bitwiseOps) {941WRITE(p, " uint v_uint = roundAndScaleTo8x4(v.rgb);\n");942WRITE(p, " uint v_masked = v_uint & u_alphacolormask;\n");943WRITE(p, " uint colorTestRef = (u_alphacolorref & u_alphacolormask) & 0xFFFFFFu;\n");944WRITE(p, " if (v_masked %s colorTestRef) %s\n", test, discardStatement);945} else if (gl_extensions.gpuVendor == GPU_VENDOR_IMGTEC) {946WRITE(p, " if (roundTo255thv(v.rgb) %s u_alphacolorref.rgb) %s\n", test, discardStatement);947} else {948WRITE(p, " if (roundAndScaleTo255v(v.rgb) %s u_alphacolorref.rgb) %s\n", test, discardStatement);949}950} else {951WRITE(p, " %s\n", discardStatement);952}953}954}955956if (replaceBlend == REPLACE_BLEND_2X_SRC) {957WRITE(p, " v.rgb = v.rgb * 2.0;\n");958}959960// In some cases we need to replicate the first half of the blend equation here.961// In case of blue-to-alpha, it's since we overwrite alpha with blue before the actual blend equation runs.962if (replaceBlend == REPLACE_BLEND_PRE_SRC || replaceBlend == REPLACE_BLEND_PRE_SRC_2X_ALPHA || replaceBlend == REPLACE_BLEND_BLUE_TO_ALPHA) {963const char *srcFactor = "ERROR";964switch (replaceBlendFuncA) {965case GE_SRCBLEND_DSTCOLOR: srcFactor = "ERROR"; break;966case GE_SRCBLEND_INVDSTCOLOR: srcFactor = "ERROR"; break;967case GE_SRCBLEND_SRCALPHA: srcFactor = "splat3(v.a)"; break;968case GE_SRCBLEND_INVSRCALPHA: srcFactor = "splat3(1.0 - v.a)"; break;969case GE_SRCBLEND_DSTALPHA: srcFactor = "ERROR"; break;970case GE_SRCBLEND_INVDSTALPHA: srcFactor = "ERROR"; break;971case GE_SRCBLEND_DOUBLESRCALPHA: srcFactor = "splat3(v.a * 2.0)"; break;972case GE_SRCBLEND_DOUBLEINVSRCALPHA: srcFactor = "splat3(1.0 - v.a * 2.0)"; break;973// PRE_SRC for REPLACE_BLEND_PRE_SRC_2X_ALPHA means "double the src."974// It's close to the same, but clamping can still be an issue.975case GE_SRCBLEND_DOUBLEDSTALPHA: srcFactor = "splat3(2.0)"; break;976case GE_SRCBLEND_DOUBLEINVDSTALPHA: srcFactor = "ERROR"; break;977case GE_SRCBLEND_FIXA: srcFactor = "u_blendFixA"; break;978default: srcFactor = "u_blendFixA"; break;979}980981if (!strcmp(srcFactor, "ERROR")) {982*errorString = "Bad replaceblend src factor";983return false;984}985986WRITE(p, " v.rgb = v.rgb * %s;\n", srcFactor);987}988989if (replaceBlend == REPLACE_BLEND_READ_FRAMEBUFFER) {990const char *srcFactor = nullptr;991const char *dstFactor = nullptr;992993switch (replaceBlendFuncA) {994case GE_SRCBLEND_DSTCOLOR: srcFactor = "destColor.rgb"; break;995case GE_SRCBLEND_INVDSTCOLOR: srcFactor = "(splat3(1.0) - destColor.rgb)"; break;996case GE_SRCBLEND_SRCALPHA: srcFactor = "v.aaa"; break;997case GE_SRCBLEND_INVSRCALPHA: srcFactor = "splat3(1.0 - v.a)"; break;998case GE_SRCBLEND_DSTALPHA: srcFactor = "destColor.aaa"; break;999case GE_SRCBLEND_INVDSTALPHA: srcFactor = "(splat3(1.0) - destColor.aaa)"; break;1000case GE_SRCBLEND_DOUBLESRCALPHA: srcFactor = "v.aaa * 2.0"; break;1001case GE_SRCBLEND_DOUBLEINVSRCALPHA: srcFactor = "(splat3(1.0) - v.aaa * 2.0)"; break;1002case GE_SRCBLEND_DOUBLEDSTALPHA: srcFactor = "destColor.aaa * 2.0"; break;1003case GE_SRCBLEND_DOUBLEINVDSTALPHA: srcFactor = "(splat3(1.0) - destColor.aaa * 2.0)"; break;1004case GE_SRCBLEND_FIXA: srcFactor = "u_blendFixA"; break;1005default: srcFactor = "u_blendFixA"; break;1006}1007switch (replaceBlendFuncB) {1008case GE_DSTBLEND_SRCCOLOR: dstFactor = "v.rgb"; break;1009case GE_DSTBLEND_INVSRCCOLOR: dstFactor = "(splat3(1.0) - v.rgb)"; break;1010case GE_DSTBLEND_SRCALPHA: dstFactor = "v.aaa"; break;1011case GE_DSTBLEND_INVSRCALPHA: dstFactor = "(splat3(1.0) - v.aaa)"; break;1012case GE_DSTBLEND_DSTALPHA: dstFactor = "destColor.aaa"; break;1013case GE_DSTBLEND_INVDSTALPHA: dstFactor = "(splat3(1.0) - destColor.aaa)"; break;1014case GE_DSTBLEND_DOUBLESRCALPHA: dstFactor = "v.aaa * 2.0"; break;1015case GE_DSTBLEND_DOUBLEINVSRCALPHA: dstFactor = "(splat3(1.0) - v.aaa * 2.0)"; break;1016case GE_DSTBLEND_DOUBLEDSTALPHA: dstFactor = "destColor.aaa * 2.0"; break;1017case GE_DSTBLEND_DOUBLEINVDSTALPHA: dstFactor = "(splat3(1.0) - destColor.aaa * 2.0)"; break;1018case GE_DSTBLEND_FIXB: dstFactor = "u_blendFixB"; break;1019default: dstFactor = "u_blendFixB"; break;1020}10211022switch (replaceBlendEq) {1023case GE_BLENDMODE_MUL_AND_ADD:1024WRITE(p, " v.rgb = v.rgb * %s + destColor.rgb * %s;\n", srcFactor, dstFactor);1025break;1026case GE_BLENDMODE_MUL_AND_SUBTRACT:1027WRITE(p, " v.rgb = v.rgb * %s - destColor.rgb * %s;\n", srcFactor, dstFactor);1028break;1029case GE_BLENDMODE_MUL_AND_SUBTRACT_REVERSE:1030WRITE(p, " v.rgb = destColor.rgb * %s - v.rgb * %s;\n", dstFactor, srcFactor);1031break;1032case GE_BLENDMODE_MIN:1033WRITE(p, " v.rgb = min(v.rgb, destColor.rgb);\n");1034break;1035case GE_BLENDMODE_MAX:1036WRITE(p, " v.rgb = max(v.rgb, destColor.rgb);\n");1037break;1038case GE_BLENDMODE_ABSDIFF:1039WRITE(p, " v.rgb = abs(v.rgb - destColor.rgb);\n");1040break;1041default:1042*errorString = StringFromFormat("Bad replace blend eq: %d", (int)replaceBlendEq);1043return false;1044}1045}10461047if (replaceBlend == REPLACE_BLEND_2X_ALPHA || replaceBlend == REPLACE_BLEND_PRE_SRC_2X_ALPHA) {1048WRITE(p, " v.a *= 2.0;\n");1049}1050}10511052char replacedAlpha[64] = "0.0";1053if (stencilToAlpha != REPLACE_ALPHA_NO) {1054switch (replaceAlphaWithStencilType) {1055case STENCIL_VALUE_UNIFORM:1056truncate_cpy(replacedAlpha, "u_stencilReplaceValue");1057break;10581059case STENCIL_VALUE_ZERO:1060truncate_cpy(replacedAlpha, "0.0");1061break;10621063case STENCIL_VALUE_ONE:1064case STENCIL_VALUE_INVERT:1065// In invert, we subtract by one, but we want to output one here.1066truncate_cpy(replacedAlpha, "1.0");1067break;10681069case STENCIL_VALUE_INCR_4:1070case STENCIL_VALUE_DECR_4:1071// We're adding/subtracting, just by the smallest value in 4-bit.1072snprintf(replacedAlpha, sizeof(replacedAlpha), "%f", 1.0 / 15.0);1073break;10741075case STENCIL_VALUE_INCR_8:1076case STENCIL_VALUE_DECR_8:1077// We're adding/subtracting, just by the smallest value in 8-bit.1078snprintf(replacedAlpha, sizeof(replacedAlpha), "%f", 1.0 / 255.0);1079break;10801081case STENCIL_VALUE_KEEP:1082// Do nothing. We'll mask out the alpha using color mask.1083break;1084}1085}10861087switch (stencilToAlpha) {1088case REPLACE_ALPHA_DUALSOURCE:1089WRITE(p, " %s = vec4(v.rgb, %s);\n", compat.fragColor0, replacedAlpha);1090WRITE(p, " %s = vec4(0.0, 0.0, 0.0, v.a);\n", compat.fragColor1);1091break;10921093case REPLACE_ALPHA_YES:1094WRITE(p, " %s = vec4(v.rgb, %s);\n", compat.fragColor0, replacedAlpha);1095break;10961097case REPLACE_ALPHA_NO:1098WRITE(p, " %s = v;\n", compat.fragColor0);1099break;11001101default:1102*errorString = "Bad stencil-to-alpha type, corrupt ID?";1103return false;1104}11051106switch (simulateLogicOpType) {1107case LOGICOPTYPE_ONE:1108WRITE(p, " %s.rgb = splat3(1.0);\n", compat.fragColor0);1109break;1110case LOGICOPTYPE_INVERT:1111WRITE(p, " %s.rgb = splat3(1.0) - %s.rgb;\n", compat.fragColor0, compat.fragColor0);1112break;1113case LOGICOPTYPE_NORMAL:1114break;11151116default:1117*errorString = "Bad logic op type, corrupt ID?";1118return false;1119}11201121// Final color computed - apply logic ops and bitwise color write mask, through shader blending, if specified.1122if (colorWriteMask || replaceLogicOp) {1123WRITE(p, " highp uint v32 = packUnorm4x8%s(%s);\n", packSuffix, compat.fragColor0);1124WRITE(p, " highp uint d32 = packUnorm4x8%s(destColor);\n", packSuffix);11251126// v32 is both the "s" to the logical operation, and the value that we'll merge to the destination with masking later.1127// d32 is the "d" to the logical operation.1128// NOTE: Alpha of v32 needs to be preserved. Same equations as in the software renderer.1129switch (replaceLogicOpType) {1130case GE_LOGIC_CLEAR: p.C(" v32 &= 0xFF000000u;\n"); break;1131case GE_LOGIC_AND: p.C(" v32 = v32 & (d32 | 0xFF000000u);\n"); break;1132case GE_LOGIC_AND_REVERSE: p.C(" v32 = v32 & (~d32 | 0xFF000000u);\n"); break;1133case GE_LOGIC_COPY: break; // source to dest, do nothing. Will be set to this, if not used.1134case GE_LOGIC_AND_INVERTED: p.C(" v32 = (~v32 & (d32 & 0x00FFFFFFu)) | (v32 & 0xFF000000u);\n"); break;1135case GE_LOGIC_NOOP: p.C(" v32 = (d32 & 0x00FFFFFFu) | (v32 & 0xFF000000u);\n"); break;1136case GE_LOGIC_XOR: p.C(" v32 = v32 ^ (d32 & 0x00FFFFFFu);\n"); break;1137case GE_LOGIC_OR: p.C(" v32 = v32 | (d32 & 0x00FFFFFFu);\n"); break;1138case GE_LOGIC_NOR: p.C(" v32 = (~(v32 | d32) & 0x00FFFFFFu) | (v32 & 0xFF000000u);\n"); break;1139case GE_LOGIC_EQUIV: p.C(" v32 = (~(v32 ^ d32) & 0x00FFFFFFu) | (v32 & 0xFF000000u);\n"); break;1140case GE_LOGIC_INVERTED: p.C(" v32 = (~d32 & 0x00FFFFFFu) | (v32 & 0xFF000000u);\n"); break;1141case GE_LOGIC_OR_REVERSE: p.C(" v32 = v32 | (~d32 & 0x00FFFFFFu);\n"); break;1142case GE_LOGIC_COPY_INVERTED: p.C(" v32 = (~v32 & 0x00FFFFFFu) | (v32 & 0xFF000000u);\n"); break;1143case GE_LOGIC_OR_INVERTED: p.C(" v32 = ((~v32 | d32) & 0x00FFFFFFu) | (v32 & 0xFF000000u);\n"); break;1144case GE_LOGIC_NAND: p.C(" v32 = (~(v32 & d32) & 0x00FFFFFFu) | (v32 & 0xFF000000u);\n"); break;1145case GE_LOGIC_SET: p.C(" v32 |= 0x00FFFFFFu;\n"); break;1146}11471148// Note that the mask has already been flipped to the PC way - 1 means write.1149if (colorWriteMask) {1150if (stencilToAlpha != REPLACE_ALPHA_NO)1151WRITE(p, " v32 = (v32 & u_colorWriteMask) | (d32 & ~u_colorWriteMask);\n");1152else1153WRITE(p, " v32 = (v32 & u_colorWriteMask & 0x00FFFFFFu) | (d32 & (~u_colorWriteMask | 0xFF000000u));\n");1154}1155WRITE(p, " %s = unpackUnorm4x8%s(v32);\n", compat.fragColor0, packSuffix);1156}11571158if (blueToAlpha) {1159WRITE(p, " %s = vec4(0.0, 0.0, 0.0, %s.z); // blue to alpha\n", compat.fragColor0, compat.fragColor0);1160}11611162if (gstate_c.Use(GPU_ROUND_FRAGMENT_DEPTH_TO_16BIT)) {1163DepthScaleFactors depthScale = GetDepthScaleFactors(gstate_c.UseFlags());11641165const double scale = depthScale.ScaleU16();11661167WRITE(p, " highp float z = gl_FragCoord.z;\n");1168if (gstate_c.Use(GPU_USE_ACCURATE_DEPTH)) {1169// We center the depth with an offset, but only its fraction matters.1170// When (DepthSliceFactor() - 1) is odd, it will be 0.5, otherwise 0.1171if (((int)(depthScale.Scale() - 1.0f) & 1) == 1) {1172WRITE(p, " z = (floor((z * %f) - (1.0 / 2.0)) + (1.0 / 2.0)) * (1.0 / %f);\n", scale, scale);1173} else {1174WRITE(p, " z = floor(z * %f) * (1.0 / %f);\n", scale, scale);1175}1176} else {1177WRITE(p, " z = (1.0 / 65535.0) * floor(z * 65535.0);\n");1178}1179WRITE(p, " gl_FragDepth = z;\n");1180} else if (useDiscardStencilBugWorkaround) {1181// Adreno and some Mali drivers apply early frag tests even with discard in the shader,1182// when only stencil is used. The exact situation seems to vary by driver.1183// Writing depth prevents the bug for both vendors, even with depth_unchanged specified.1184// This doesn't make a ton of sense, but empirically does work.1185WRITE(p, " gl_FragDepth = gl_FragCoord.z;\n");1186}11871188if (compat.shaderLanguage == HLSL_D3D11) {1189if (writeDepth) {1190WRITE(p, " outfragment.depth = gl_FragDepth;\n");1191}1192WRITE(p, " return outfragment;\n");1193}11941195WRITE(p, "}\n");11961197return true;1198}1199120012011202