| 1 | // Copyright 2008 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "VideoCommon/PixelShaderGen.h" |
| 5 | |
| 6 | #include "Common/Assert.h" |
| 7 | #include "Common/CommonTypes.h" |
| 8 | #include "Common/EnumMap.h" |
| 9 | #include "Common/Logging/Log.h" |
| 10 | #include "VideoCommon/BPMemory.h" |
| 11 | #include "VideoCommon/BoundingBox.h" |
| 12 | #include "VideoCommon/DriverDetails.h" |
| 13 | #include "VideoCommon/LightingShaderGen.h" |
| 14 | #include "VideoCommon/RenderState.h" |
| 15 | #include "VideoCommon/VideoCommon.h" |
| 16 | #include "VideoCommon/VideoConfig.h" |
| 17 | #include "VideoCommon/XFMemory.h" // for texture projection mode |
| 18 | |
| 19 | // TODO: Get rid of these |
| 20 | enum : u32 |
| 21 | { |
| 22 | C_COLORMATRIX = 0, // 0 |
| 23 | C_COLORS = 0, // 0 |
| 24 | C_KCOLORS = C_COLORS + 4, // 4 |
| 25 | C_ALPHA = C_KCOLORS + 4, // 8 |
| 26 | C_TEXDIMS = C_ALPHA + 1, // 9 |
| 27 | C_ZBIAS = C_TEXDIMS + 8, // 17 |
| 28 | C_INDTEXSCALE = C_ZBIAS + 2, // 19 |
| 29 | C_INDTEXMTX = C_INDTEXSCALE + 2, // 21 |
| 30 | C_FOGCOLOR = C_INDTEXMTX + 6, // 27 |
| 31 | C_FOGI = C_FOGCOLOR + 1, // 28 |
| 32 | C_FOGF = C_FOGI + 1, // 29 |
| 33 | C_ZSLOPE = C_FOGF + 2, // 31 |
| 34 | C_EFBSCALE = C_ZSLOPE + 1, // 32 |
| 35 | C_PENVCONST_END = C_EFBSCALE + 1 |
| 36 | }; |
| 37 | |
| 38 | constexpr Common::EnumMap<const char*, KonstSel::K3_A> tev_ksel_table_c{ |
| 39 | "255,255,255", // 1 = 0x00 |
| 40 | "223,223,223", // 7_8 = 0x01 |
| 41 | "191,191,191", // 3_4 = 0x02 |
| 42 | "159,159,159", // 5_8 = 0x03 |
| 43 | "128,128,128", // 1_2 = 0x04 |
| 44 | "96,96,96", // 3_8 = 0x05 |
| 45 | "64,64,64", // 1_4 = 0x06 |
| 46 | "32,32,32", // 1_8 = 0x07 |
| 47 | "0,0,0", // INVALID = 0x08 |
| 48 | "0,0,0", // INVALID = 0x09 |
| 49 | "0,0,0", // INVALID = 0x0a |
| 50 | "0,0,0", // INVALID = 0x0b |
| 51 | I_KCOLORS "[0].rgb", // K0 = 0x0C |
| 52 | I_KCOLORS "[1].rgb", // K1 = 0x0D |
| 53 | I_KCOLORS "[2].rgb", // K2 = 0x0E |
| 54 | I_KCOLORS "[3].rgb", // K3 = 0x0F |
| 55 | I_KCOLORS "[0].rrr", // K0_R = 0x10 |
| 56 | I_KCOLORS "[1].rrr", // K1_R = 0x11 |
| 57 | I_KCOLORS "[2].rrr", // K2_R = 0x12 |
| 58 | I_KCOLORS "[3].rrr", // K3_R = 0x13 |
| 59 | I_KCOLORS "[0].ggg", // K0_G = 0x14 |
| 60 | I_KCOLORS "[1].ggg", // K1_G = 0x15 |
| 61 | I_KCOLORS "[2].ggg", // K2_G = 0x16 |
| 62 | I_KCOLORS "[3].ggg", // K3_G = 0x17 |
| 63 | I_KCOLORS "[0].bbb", // K0_B = 0x18 |
| 64 | I_KCOLORS "[1].bbb", // K1_B = 0x19 |
| 65 | I_KCOLORS "[2].bbb", // K2_B = 0x1A |
| 66 | I_KCOLORS "[3].bbb", // K3_B = 0x1B |
| 67 | I_KCOLORS "[0].aaa", // K0_A = 0x1C |
| 68 | I_KCOLORS "[1].aaa", // K1_A = 0x1D |
| 69 | I_KCOLORS "[2].aaa", // K2_A = 0x1E |
| 70 | I_KCOLORS "[3].aaa", // K3_A = 0x1F |
| 71 | }; |
| 72 | |
| 73 | constexpr Common::EnumMap<const char*, KonstSel::K3_A> tev_ksel_table_a{ |
| 74 | "255", // 1 = 0x00 |
| 75 | "223", // 7_8 = 0x01 |
| 76 | "191", // 3_4 = 0x02 |
| 77 | "159", // 5_8 = 0x03 |
| 78 | "128", // 1_2 = 0x04 |
| 79 | "96", // 3_8 = 0x05 |
| 80 | "64", // 1_4 = 0x06 |
| 81 | "32", // 1_8 = 0x07 |
| 82 | "0", // INVALID = 0x08 |
| 83 | "0", // INVALID = 0x09 |
| 84 | "0", // INVALID = 0x0a |
| 85 | "0", // INVALID = 0x0b |
| 86 | "0", // INVALID = 0x0c |
| 87 | "0", // INVALID = 0x0d |
| 88 | "0", // INVALID = 0x0e |
| 89 | "0", // INVALID = 0x0f |
| 90 | I_KCOLORS "[0].r", // K0_R = 0x10 |
| 91 | I_KCOLORS "[1].r", // K1_R = 0x11 |
| 92 | I_KCOLORS "[2].r", // K2_R = 0x12 |
| 93 | I_KCOLORS "[3].r", // K3_R = 0x13 |
| 94 | I_KCOLORS "[0].g", // K0_G = 0x14 |
| 95 | I_KCOLORS "[1].g", // K1_G = 0x15 |
| 96 | I_KCOLORS "[2].g", // K2_G = 0x16 |
| 97 | I_KCOLORS "[3].g", // K3_G = 0x17 |
| 98 | I_KCOLORS "[0].b", // K0_B = 0x18 |
| 99 | I_KCOLORS "[1].b", // K1_B = 0x19 |
| 100 | I_KCOLORS "[2].b", // K2_B = 0x1A |
| 101 | I_KCOLORS "[3].b", // K3_B = 0x1B |
| 102 | I_KCOLORS "[0].a", // K0_A = 0x1C |
| 103 | I_KCOLORS "[1].a", // K1_A = 0x1D |
| 104 | I_KCOLORS "[2].a", // K2_A = 0x1E |
| 105 | I_KCOLORS "[3].a", // K3_A = 0x1F |
| 106 | }; |
| 107 | |
| 108 | constexpr Common::EnumMap<const char*, TevColorArg::Zero> tev_c_input_table{ |
| 109 | "prev.rgb", // CPREV, |
| 110 | "prev.aaa", // APREV, |
| 111 | "c0.rgb", // C0, |
| 112 | "c0.aaa", // A0, |
| 113 | "c1.rgb", // C1, |
| 114 | "c1.aaa", // A1, |
| 115 | "c2.rgb", // C2, |
| 116 | "c2.aaa", // A2, |
| 117 | "textemp.rgb", // TEXC, |
| 118 | "textemp.aaa", // TEXA, |
| 119 | "rastemp.rgb", // RASC, |
| 120 | "rastemp.aaa", // RASA, |
| 121 | "int3(255,255,255)", // ONE |
| 122 | "int3(128,128,128)", // HALF |
| 123 | "konsttemp.rgb", // KONST |
| 124 | "int3(0,0,0)", // ZERO |
| 125 | }; |
| 126 | |
| 127 | constexpr Common::EnumMap<const char*, TevAlphaArg::Zero> tev_a_input_table{ |
| 128 | "prev.a", // APREV, |
| 129 | "c0.a", // A0, |
| 130 | "c1.a", // A1, |
| 131 | "c2.a", // A2, |
| 132 | "textemp.a", // TEXA, |
| 133 | "rastemp.a", // RASA, |
| 134 | "konsttemp.a", // KONST, (hw1 had quarter) |
| 135 | "0", // ZERO |
| 136 | }; |
| 137 | |
| 138 | constexpr Common::EnumMap<const char*, RasColorChan::Zero> tev_ras_table{ |
| 139 | "iround(col0 * 255.0)", |
| 140 | "iround(col1 * 255.0)", |
| 141 | "ERROR13", // 2 |
| 142 | "ERROR14", // 3 |
| 143 | "ERROR15", // 4 |
| 144 | "(int4(1, 1, 1, 1) * alphabump)", // bump alpha (0..248) |
| 145 | "(int4(1, 1, 1, 1) * (alphabump | (alphabump >> 5)))", // normalized bump alpha (0..255) |
| 146 | "int4(0, 0, 0, 0)", // zero |
| 147 | }; |
| 148 | |
| 149 | constexpr Common::EnumMap<const char*, TevOutput::Color2> tev_c_output_table{ |
| 150 | "prev.rgb", |
| 151 | "c0.rgb", |
| 152 | "c1.rgb", |
| 153 | "c2.rgb", |
| 154 | }; |
| 155 | |
| 156 | constexpr Common::EnumMap<const char*, TevOutput::Color2> tev_a_output_table{ |
| 157 | "prev.a", |
| 158 | "c0.a", |
| 159 | "c1.a", |
| 160 | "c2.a", |
| 161 | }; |
| 162 | |
| 163 | constexpr Common::EnumMap<char, ColorChannel::Alpha> rgba_swizzle{'r', 'g', 'b', 'a'}; |
| 164 | |
| 165 | PixelShaderUid GetPixelShaderUid() |
| 166 | { |
| 167 | PixelShaderUid out; |
| 168 | |
| 169 | pixel_shader_uid_data* const uid_data = out.GetUidData(); |
| 170 | uid_data->useDstAlpha = bpmem.dstalpha.enable && bpmem.blendmode.alpha_update && |
| 171 | bpmem.zcontrol.pixel_format == PixelFormat::RGBA6_Z24; |
| 172 | |
| 173 | uid_data->genMode_numindstages = bpmem.genMode.numindstages; |
| 174 | uid_data->genMode_numtevstages = bpmem.genMode.numtevstages; |
| 175 | uid_data->genMode_numtexgens = bpmem.genMode.numtexgens; |
| 176 | uid_data->bounding_box = g_ActiveConfig.bBBoxEnable && g_bounding_box->IsEnabled(); |
| 177 | uid_data->rgba6_format = |
| 178 | bpmem.zcontrol.pixel_format == PixelFormat::RGBA6_Z24 && !g_ActiveConfig.bForceTrueColor; |
| 179 | uid_data->dither = bpmem.blendmode.dither && uid_data->rgba6_format; |
| 180 | uid_data->uint_output = bpmem.blendmode.UseLogicOp(); |
| 181 | |
| 182 | u32 numStages = uid_data->genMode_numtevstages + 1; |
| 183 | |
| 184 | uid_data->Pretest = bpmem.alpha_test.TestResult(); |
| 185 | uid_data->ztest = bpmem.GetEmulatedZ(); |
| 186 | if (uid_data->ztest == EmulatedZ::Early && |
| 187 | (g_ActiveConfig.bFastDepthCalc || |
| 188 | bpmem.alpha_test.TestResult() == AlphaTestResult::Undetermined) |
| 189 | // We can't allow early_ztest for zfreeze because depth is overridden per-pixel. |
| 190 | // This means it's impossible for zcomploc to be emulated on a zfrozen polygon. |
| 191 | && !bpmem.genMode.zfreeze) |
| 192 | { |
| 193 | uid_data->ztest = EmulatedZ::ForcedEarly; |
| 194 | } |
| 195 | |
| 196 | const bool forced_early_z = uid_data->ztest == EmulatedZ::ForcedEarly; |
| 197 | const bool per_pixel_depth = |
| 198 | (bpmem.ztex2.op != ZTexOp::Disabled && uid_data->ztest == EmulatedZ::Late) || |
| 199 | (!g_ActiveConfig.bFastDepthCalc && bpmem.zmode.test_enable && !forced_early_z) || |
| 200 | (bpmem.zmode.test_enable && bpmem.genMode.zfreeze); |
| 201 | |
| 202 | uid_data->per_pixel_depth = per_pixel_depth; |
| 203 | |
| 204 | if (g_ActiveConfig.bEnablePixelLighting) |
| 205 | { |
| 206 | uid_data->numColorChans = xfmem.numChan.numColorChans; |
| 207 | GetLightingShaderUid(uid_data->lighting); |
| 208 | } |
| 209 | |
| 210 | if (uid_data->genMode_numtexgens > 0) |
| 211 | { |
| 212 | for (unsigned int i = 0; i < uid_data->genMode_numtexgens; ++i) |
| 213 | { |
| 214 | // optional perspective divides |
| 215 | uid_data->texMtxInfo_n_projection |= static_cast<u32>(xfmem.texMtxInfo[i].projection.Value()) |
| 216 | << i; |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // indirect texture map lookup |
| 221 | int nIndirectStagesUsed = 0; |
| 222 | for (unsigned int i = 0; i < numStages; ++i) |
| 223 | { |
| 224 | if (bpmem.tevind[i].IsActive()) |
| 225 | nIndirectStagesUsed |= 1 << bpmem.tevind[i].bt; |
| 226 | } |
| 227 | |
| 228 | uid_data->nIndirectStagesUsed = nIndirectStagesUsed; |
| 229 | for (u32 i = 0; i < uid_data->genMode_numindstages; ++i) |
| 230 | { |
| 231 | if (uid_data->nIndirectStagesUsed & (1 << i)) |
| 232 | uid_data->SetTevindrefValues(i, bpmem.tevindref.getTexCoord(i), bpmem.tevindref.getTexMap(i)); |
| 233 | } |
| 234 | |
| 235 | for (unsigned int n = 0; n < numStages; n++) |
| 236 | { |
| 237 | uid_data->stagehash[n].tevorders_texcoord = bpmem.tevorders[n / 2].getTexCoord(n & 1); |
| 238 | uid_data->stagehash[n].tevind = bpmem.tevind[n].hex; |
| 239 | |
| 240 | TevStageCombiner::ColorCombiner& cc = bpmem.combiners[n].colorC; |
| 241 | TevStageCombiner::AlphaCombiner& ac = bpmem.combiners[n].alphaC; |
| 242 | uid_data->stagehash[n].cc = cc.hex & 0xFFFFFF; |
| 243 | uid_data->stagehash[n].ac = ac.hex & 0xFFFFF0; // Storing rswap and tswap later |
| 244 | |
| 245 | if (cc.a == TevColorArg::RasAlpha || cc.a == TevColorArg::RasColor || |
| 246 | cc.b == TevColorArg::RasAlpha || cc.b == TevColorArg::RasColor || |
| 247 | cc.c == TevColorArg::RasAlpha || cc.c == TevColorArg::RasColor || |
| 248 | cc.d == TevColorArg::RasAlpha || cc.d == TevColorArg::RasColor || |
| 249 | ac.a == TevAlphaArg::RasAlpha || ac.b == TevAlphaArg::RasAlpha || |
| 250 | ac.c == TevAlphaArg::RasAlpha || ac.d == TevAlphaArg::RasAlpha) |
| 251 | { |
| 252 | const auto ras_swap_table = bpmem.tevksel.GetSwapTable(bpmem.combiners[n].alphaC.rswap); |
| 253 | uid_data->stagehash[n].ras_swap_r = ras_swap_table[ColorChannel::Red]; |
| 254 | uid_data->stagehash[n].ras_swap_g = ras_swap_table[ColorChannel::Green]; |
| 255 | uid_data->stagehash[n].ras_swap_b = ras_swap_table[ColorChannel::Blue]; |
| 256 | uid_data->stagehash[n].ras_swap_a = ras_swap_table[ColorChannel::Alpha]; |
| 257 | uid_data->stagehash[n].tevorders_colorchan = bpmem.tevorders[n / 2].getColorChan(n & 1); |
| 258 | } |
| 259 | |
| 260 | uid_data->stagehash[n].tevorders_enable = bpmem.tevorders[n / 2].getEnable(n & 1); |
| 261 | if (uid_data->stagehash[n].tevorders_enable) |
| 262 | { |
| 263 | const auto tex_swap_table = bpmem.tevksel.GetSwapTable(bpmem.combiners[n].alphaC.tswap); |
| 264 | uid_data->stagehash[n].tex_swap_r = tex_swap_table[ColorChannel::Red]; |
| 265 | uid_data->stagehash[n].tex_swap_g = tex_swap_table[ColorChannel::Green]; |
| 266 | uid_data->stagehash[n].tex_swap_b = tex_swap_table[ColorChannel::Blue]; |
| 267 | uid_data->stagehash[n].tex_swap_a = tex_swap_table[ColorChannel::Alpha]; |
| 268 | uid_data->stagehash[n].tevorders_texmap = bpmem.tevorders[n / 2].getTexMap(n & 1); |
| 269 | } |
| 270 | |
| 271 | if (cc.a == TevColorArg::Konst || cc.b == TevColorArg::Konst || cc.c == TevColorArg::Konst || |
| 272 | cc.d == TevColorArg::Konst || ac.a == TevAlphaArg::Konst || ac.b == TevAlphaArg::Konst || |
| 273 | ac.c == TevAlphaArg::Konst || ac.d == TevAlphaArg::Konst) |
| 274 | { |
| 275 | uid_data->stagehash[n].tevksel_kc = bpmem.tevksel.GetKonstColor(n); |
| 276 | uid_data->stagehash[n].tevksel_ka = bpmem.tevksel.GetKonstAlpha(n); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | #define MY_STRUCT_OFFSET(str, elem) ((u32)((u64) & (str).elem - (u64) & (str))) |
| 281 | uid_data->num_values = (g_ActiveConfig.bEnablePixelLighting) ? |
| 282 | sizeof(*uid_data) : |
| 283 | MY_STRUCT_OFFSET(*uid_data, stagehash[numStages]); |
| 284 | |
| 285 | // NOTE: Fragment may not be discarded if alpha test always fails and early depth test is enabled |
| 286 | // (in this case we need to write a depth value if depth test passes regardless of the alpha |
| 287 | // testing result) |
| 288 | if (uid_data->Pretest == AlphaTestResult::Undetermined || |
| 289 | (uid_data->Pretest == AlphaTestResult::Fail && uid_data->ztest == EmulatedZ::Late)) |
| 290 | { |
| 291 | uid_data->alpha_test_comp0 = bpmem.alpha_test.comp0; |
| 292 | uid_data->alpha_test_comp1 = bpmem.alpha_test.comp1; |
| 293 | uid_data->alpha_test_logic = bpmem.alpha_test.logic; |
| 294 | } |
| 295 | |
| 296 | uid_data->zfreeze = bpmem.genMode.zfreeze; |
| 297 | uid_data->ztex_op = bpmem.ztex2.op; |
| 298 | |
| 299 | uid_data->fog_fsel = bpmem.fog.c_proj_fsel.fsel; |
| 300 | uid_data->fog_proj = bpmem.fog.c_proj_fsel.proj; |
| 301 | uid_data->fog_RangeBaseEnabled = bpmem.fogRange.Base.Enabled; |
| 302 | |
| 303 | return out; |
| 304 | } |
| 305 | |
| 306 | void ClearUnusedPixelShaderUidBits(APIType api_type, const ShaderHostConfig& host_config, |
| 307 | PixelShaderUid* uid) |
| 308 | { |
| 309 | pixel_shader_uid_data* const uid_data = uid->GetUidData(); |
| 310 | |
| 311 | // OpenGL and Vulkan convert implicitly normalized color outputs to their uint representation. |
| 312 | // Therefore, it is not necessary to use a uint output on these backends. We also disable the |
| 313 | // uint output when logic op is not supported (i.e. driver/device does not support D3D11.1). |
| 314 | if (api_type != APIType::D3D || !host_config.backend_logic_op) |
| 315 | uid_data->uint_output = 0; |
| 316 | |
| 317 | // If bounding box is enabled when a UID cache is created, then later disabled, we shouldn't |
| 318 | // emit the bounding box portion of the shader. |
| 319 | uid_data->bounding_box &= host_config.bounding_box && host_config.backend_bbox; |
| 320 | } |
| 321 | |
| 322 | void WritePixelShaderCommonHeader(ShaderCode& out, APIType api_type, |
| 323 | const ShaderHostConfig& host_config, bool bounding_box) |
| 324 | { |
| 325 | // dot product for integer vectors |
| 326 | out.Write("int idot(int3 x, int3 y)\n" |
| 327 | "{{\n" |
| 328 | "\tint3 tmp = x * y;\n" |
| 329 | "\treturn tmp.x + tmp.y + tmp.z;\n" |
| 330 | "}}\n"); |
| 331 | |
| 332 | out.Write("int idot(int4 x, int4 y)\n" |
| 333 | "{{\n" |
| 334 | "\tint4 tmp = x * y;\n" |
| 335 | "\treturn tmp.x + tmp.y + tmp.z + tmp.w;\n" |
| 336 | "}}\n\n"); |
| 337 | |
| 338 | // rounding + casting to integer at once in a single function |
| 339 | out.Write("int iround(float x) {{ return int (round(x)); }}\n" |
| 340 | "int2 iround(float2 x) {{ return int2(round(x)); }}\n" |
| 341 | "int3 iround(float3 x) {{ return int3(round(x)); }}\n" |
| 342 | "int4 iround(float4 x) {{ return int4(round(x)); }}\n\n"); |
| 343 | |
| 344 | out.Write("SAMPLER_BINDING(0) uniform sampler2DArray samp[8];\n"); |
| 345 | out.Write("\n"); |
| 346 | |
| 347 | out.Write("UBO_BINDING(std140, 1) uniform PSBlock {{\n"); |
| 348 | |
| 349 | out.Write("\tint4 " I_COLORS "[4];\n" |
| 350 | "\tint4 " I_KCOLORS "[4];\n" |
| 351 | "\tint4 " I_ALPHA ";\n" |
| 352 | "\tint4 " I_TEXDIMS "[8];\n" |
| 353 | "\tint4 " I_ZBIAS "[2];\n" |
| 354 | "\tint4 " I_INDTEXSCALE "[2];\n" |
| 355 | "\tint4 " I_INDTEXMTX "[6];\n" |
| 356 | "\tint4 " I_FOGCOLOR ";\n" |
| 357 | "\tint4 " I_FOGI ";\n" |
| 358 | "\tfloat4 " I_FOGF ";\n" |
| 359 | "\tfloat4 " I_FOGRANGE "[3];\n" |
| 360 | "\tfloat4 " I_ZSLOPE ";\n" |
| 361 | "\tfloat2 " I_EFBSCALE ";\n" |
| 362 | "\tuint bpmem_genmode;\n" |
| 363 | "\tuint bpmem_alphaTest;\n" |
| 364 | "\tuint bpmem_fogParam3;\n" |
| 365 | "\tuint bpmem_fogRangeBase;\n" |
| 366 | "\tuint bpmem_dstalpha;\n" |
| 367 | "\tuint bpmem_ztex_op;\n" |
| 368 | "\tbool bpmem_late_ztest;\n" |
| 369 | "\tbool bpmem_rgba6_format;\n" |
| 370 | "\tbool bpmem_dither;\n" |
| 371 | "\tbool bpmem_bounding_box;\n" |
| 372 | "\tuint4 bpmem_pack1[16];\n" // .xy - combiners, .z - tevind |
| 373 | "\tuint4 bpmem_pack2[8];\n" // .x - tevorder, .y - tevksel, .zw - SamplerState tm0/tm1 |
| 374 | "\tint4 konstLookup[32];\n" |
| 375 | "\tbool blend_enable;\n" |
| 376 | "\tuint blend_src_factor;\n" |
| 377 | "\tuint blend_src_factor_alpha;\n" |
| 378 | "\tuint blend_dst_factor;\n" |
| 379 | "\tuint blend_dst_factor_alpha;\n" |
| 380 | "\tbool blend_subtract;\n" |
| 381 | "\tbool blend_subtract_alpha;\n" |
| 382 | "\tbool logic_op_enable;\n" |
| 383 | "\tuint logic_op_mode;\n" |
| 384 | "\tuint time_ms;\n" |
| 385 | "}};\n\n"); |
| 386 | out.Write("#define bpmem_combiners(i) (bpmem_pack1[(i)].xy)\n" |
| 387 | "#define bpmem_tevind(i) (bpmem_pack1[(i)].z)\n" |
| 388 | "#define bpmem_iref(i) (bpmem_pack1[(i)].w)\n" |
| 389 | "#define bpmem_tevorder(i) (bpmem_pack2[(i)].x)\n" |
| 390 | "#define bpmem_tevksel(i) (bpmem_pack2[(i)].y)\n" |
| 391 | "#define samp_texmode0(i) (bpmem_pack2[(i)].z)\n" |
| 392 | "#define samp_texmode1(i) (bpmem_pack2[(i)].w)\n\n"); |
| 393 | |
| 394 | if (host_config.per_pixel_lighting) |
| 395 | { |
| 396 | out.Write("{}", s_lighting_struct); |
| 397 | |
| 398 | out.Write("UBO_BINDING(std140, 2) uniform VSBlock {{\n"); |
| 399 | |
| 400 | out.Write("{}", s_shader_uniforms); |
| 401 | out.Write("}};\n"); |
| 402 | } |
| 403 | |
| 404 | if (bounding_box) |
| 405 | { |
| 406 | out.Write("SSBO_BINDING(0) coherent buffer BBox {{\n" |
| 407 | " int bbox_data[4];\n" |
| 408 | "}};"); |
| 409 | |
| 410 | out.Write(R"( |
| 411 | #define bbox_left bbox_data[0] |
| 412 | #define bbox_right bbox_data[1] |
| 413 | #define bbox_top bbox_data[2] |
| 414 | #define bbox_bottom bbox_data[3] |
| 415 | |
| 416 | void UpdateBoundingBoxBuffer(int2 min_pos, int2 max_pos) {{ |
| 417 | if (bbox_left > min_pos.x) |
| 418 | atomicMin(bbox_left, min_pos.x); |
| 419 | if (bbox_right < max_pos.x) |
| 420 | atomicMax(bbox_right, max_pos.x); |
| 421 | if (bbox_top > min_pos.y) |
| 422 | atomicMin(bbox_top, min_pos.y); |
| 423 | if (bbox_bottom < max_pos.y) |
| 424 | atomicMax(bbox_bottom, max_pos.y); |
| 425 | }} |
| 426 | |
| 427 | void UpdateBoundingBox(float2 rawpos) {{ |
| 428 | // We only want to include coordinates for pixels aligned with the native resolution pixel centers. |
| 429 | // This makes bounding box sizes more accurate (though not perfect) at higher resolutions, |
| 430 | // avoiding EFB copy buffer overflow in affected games. |
| 431 | // |
| 432 | // For a more detailed explanation, see https://dolp.in/pr9801 |
| 433 | int2 int_efb_scale = iround(1.0 / {efb_scale}.xy); |
| 434 | if (int(rawpos.x) % int_efb_scale.x != int_efb_scale.x >> 1 || |
| 435 | int(rawpos.y) % int_efb_scale.y != int_efb_scale.y >> 1) // right shift for fast divide by two |
| 436 | {{ |
| 437 | return; |
| 438 | }} |
| 439 | |
| 440 | // The rightmost shaded pixel is not included in the right bounding box register, |
| 441 | // such that width = right - left + 1. This has been verified on hardware. |
| 442 | int2 pos = int2(rawpos * {efb_scale}.xy); |
| 443 | |
| 444 | #ifdef API_OPENGL |
| 445 | // We need to invert the Y coordinate due to OpenGL's lower-left origin |
| 446 | pos.y = {efb_height} - pos.y - 1; |
| 447 | #endif |
| 448 | |
| 449 | // The GC/Wii GPU rasterizes in 2x2 pixel groups, so bounding box values will be rounded to the |
| 450 | // extents of these groups, rather than the exact pixel. |
| 451 | int2 pos_tl = pos & ~1; // round down to even |
| 452 | int2 pos_br = pos | 1; // round up to odd |
| 453 | |
| 454 | #if defined(SUPPORTS_SUBGROUP_REDUCTION) && !defined(BROKEN_SUBGROUP_WITH_DISCARD) |
| 455 | if (!IS_HELPER_INVOCATION) |
| 456 | {{ |
| 457 | SUBGROUP_MIN(pos_tl); |
| 458 | SUBGROUP_MAX(pos_br); |
| 459 | if (IS_FIRST_ACTIVE_INVOCATION) |
| 460 | UpdateBoundingBoxBuffer(pos_tl, pos_br); |
| 461 | }} |
| 462 | #else |
| 463 | UpdateBoundingBoxBuffer(pos_tl, pos_br); |
| 464 | #endif |
| 465 | }} |
| 466 | |
| 467 | )", |
| 468 | fmt::arg("efb_height", EFB_HEIGHT), fmt::arg("efb_scale", I_EFBSCALE)); |
| 469 | } |
| 470 | |
| 471 | if (host_config.manual_texture_sampling) |
| 472 | { |
| 473 | out.Write(R"( |
| 474 | int4 readTexture(in sampler2DArray tex, uint u, uint v, int layer, int lod) {{ |
| 475 | return iround(texelFetch(tex, int3(u, v, layer), lod) * 255.0); |
| 476 | }} |
| 477 | |
| 478 | int4 readTextureLinear(in sampler2DArray tex, uint2 uv1, uint2 uv2, int layer, int lod, int2 frac_uv) {{)"); |
| 479 | |
| 480 | out.Write(R"( |
| 481 | int4 result = |
| 482 | readTexture(tex, uv1.x, uv1.y, layer, lod) * (128 - frac_uv.x) * (128 - frac_uv.y) + |
| 483 | readTexture(tex, uv2.x, uv1.y, layer, lod) * ( frac_uv.x) * (128 - frac_uv.y) + |
| 484 | readTexture(tex, uv1.x, uv2.y, layer, lod) * (128 - frac_uv.x) * ( frac_uv.y) + |
| 485 | readTexture(tex, uv2.x, uv2.y, layer, lod) * ( frac_uv.x) * ( frac_uv.y); |
| 486 | return result >> 14; |
| 487 | }} |
| 488 | )"); |
| 489 | |
| 490 | if (host_config.manual_texture_sampling_custom_texture_sizes) |
| 491 | { |
| 492 | // This is slower, and doesn't result in the same odd behavior that happens on console when |
| 493 | // wrapping with non-power-of-2 sizes, but it's fine for custom textures to have non-console |
| 494 | // behavior. |
| 495 | out.Write(R"( |
| 496 | // Both GLSL and HLSL produce undefined values when the modulo operator (%) is used with a negative |
| 497 | // dividend and a positive divisor. We want a positive value such that SafeModulo(-1, 3) is 2. |
| 498 | int SafeModulo(int dividend, int divisor) {{ |
| 499 | if (dividend >= 0) {{ |
| 500 | return dividend % divisor; |
| 501 | }} else {{ |
| 502 | // This works because ~x is the same as -x - 1. |
| 503 | // `~x % 5` over -5 to -1 gives 4, 3, 2, 1, 0. `4 - (~x % 5)` gives 0, 1, 2, 3, 4. |
| 504 | return (divisor - 1) - (~dividend % divisor); |
| 505 | }} |
| 506 | }} |
| 507 | |
| 508 | uint WrapCoord(int coord, uint wrap, int size) {{ |
| 509 | switch (wrap) {{ |
| 510 | case {:s}: |
| 511 | default: // confirmed that clamp is used for invalid (3) via hardware test |
| 512 | return uint(clamp(coord, 0, size - 1)); |
| 513 | case {:s}: |
| 514 | return uint(SafeModulo(coord, size)); // coord % size |
| 515 | case {:s}: |
| 516 | if (SafeModulo(coord, 2 * size) >= size) {{ // coord % (2 * size) |
| 517 | coord = ~coord; |
| 518 | }} |
| 519 | return uint(SafeModulo(coord, size)); // coord % size |
| 520 | }} |
| 521 | }} |
| 522 | )", |
| 523 | WrapMode::Clamp, WrapMode::Repeat, WrapMode::Mirror); |
| 524 | } |
| 525 | else |
| 526 | { |
| 527 | out.Write(R"( |
| 528 | uint WrapCoord(int coord, uint wrap, int size) {{ |
| 529 | switch (wrap) {{ |
| 530 | case {:s}: |
| 531 | default: // confirmed that clamp is used for invalid (3) via hardware test |
| 532 | return uint(clamp(coord, 0, size - 1)); |
| 533 | case {:s}: |
| 534 | return uint(coord & (size - 1)); |
| 535 | case {:s}: |
| 536 | if ((coord & size) != 0) {{ |
| 537 | coord = ~coord; |
| 538 | }} |
| 539 | return uint(coord & (size - 1)); |
| 540 | }} |
| 541 | }} |
| 542 | )", |
| 543 | WrapMode::Clamp, WrapMode::Repeat, WrapMode::Mirror); |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | out.Write("\nint4 sampleTexture(uint texmap, in sampler2DArray tex, int2 uv, int layer) {{\n"); |
| 548 | |
| 549 | if (!host_config.manual_texture_sampling) |
| 550 | { |
| 551 | out.Write(" float size_s = float(" I_TEXDIMS "[texmap].x * 128);\n" |
| 552 | " float size_t = float(" I_TEXDIMS "[texmap].y * 128);\n" |
| 553 | " float3 coords = float3(float(uv.x) / size_s, float(uv.y) / size_t, layer);\n"); |
| 554 | if (!host_config.backend_sampler_lod_bias) |
| 555 | { |
| 556 | out.Write(" uint texmode0 = samp_texmode0(texmap);\n" |
| 557 | " float lod_bias = float({}) / 256.0f;\n" |
| 558 | " return iround(255.0 * texture(tex, coords, lod_bias));\n", |
| 559 | BitfieldExtract<&SamplerState::TM0::lod_bias>("texmode0")); |
| 560 | } |
| 561 | else |
| 562 | { |
| 563 | out.Write(" return iround(255.0 * texture(tex, coords));\n"); |
| 564 | } |
| 565 | |
| 566 | out.Write("}}\n"); |
| 567 | } |
| 568 | else |
| 569 | { |
| 570 | out.Write(R"( |
| 571 | uint texmode0 = samp_texmode0(texmap); |
| 572 | uint texmode1 = samp_texmode1(texmap); |
| 573 | |
| 574 | uint wrap_s = {}; |
| 575 | uint wrap_t = {}; |
| 576 | bool mag_linear = {} != 0u; |
| 577 | bool mipmap_linear = {} != 0u; |
| 578 | bool min_linear = {} != 0u; |
| 579 | bool diag_lod = {} != 0u; |
| 580 | int lod_bias = {}; |
| 581 | // uint max_aniso = TODO; |
| 582 | bool lod_clamp = {} != 0u; |
| 583 | int min_lod = int({}); |
| 584 | int max_lod = int({}); |
| 585 | )", |
| 586 | BitfieldExtract<&SamplerState::TM0::wrap_u>("texmode0"), |
| 587 | BitfieldExtract<&SamplerState::TM0::wrap_v>("texmode0"), |
| 588 | BitfieldExtract<&SamplerState::TM0::mag_filter>("texmode0"), |
| 589 | BitfieldExtract<&SamplerState::TM0::mipmap_filter>("texmode0"), |
| 590 | BitfieldExtract<&SamplerState::TM0::min_filter>("texmode0"), |
| 591 | BitfieldExtract<&SamplerState::TM0::diag_lod>("texmode0"), |
| 592 | BitfieldExtract<&SamplerState::TM0::lod_bias>("texmode0"), |
| 593 | // BitfieldExtract<&SamplerState::TM0::max_aniso>("texmode0"), |
| 594 | BitfieldExtract<&SamplerState::TM0::lod_clamp>("texmode0"), |
| 595 | BitfieldExtract<&SamplerState::TM1::min_lod>("texmode1"), |
| 596 | BitfieldExtract<&SamplerState::TM1::max_lod>("texmode1")); |
| 597 | |
| 598 | if (host_config.manual_texture_sampling_custom_texture_sizes) |
| 599 | { |
| 600 | out.Write(R"( |
| 601 | int native_size_s = )" I_TEXDIMS R"([texmap].x; |
| 602 | int native_size_t = )" I_TEXDIMS R"([texmap].y; |
| 603 | )"); |
| 604 | |
| 605 | out.Write(R"( |
| 606 | int3 size = textureSize(tex, 0); |
| 607 | int size_s = size.x; |
| 608 | int size_t = size.y; |
| 609 | int num_layers = size.z; |
| 610 | )"); |
| 611 | if (g_backend_info.bSupportsTextureQueryLevels) |
| 612 | { |
| 613 | out.Write(" int number_of_levels = textureQueryLevels(tex);\n"); |
| 614 | } |
| 615 | else |
| 616 | { |
| 617 | out.Write(" int number_of_levels = 256; // textureQueryLevels is not supported\n"); |
| 618 | ERROR_LOG_FMT(VIDEO, "textureQueryLevels is not supported! Odd graphical results may " |
| 619 | "occur if custom textures are in use!"); |
| 620 | } |
| 621 | |
| 622 | out.Write(R"( |
| 623 | // Prevent out-of-bounds LOD values when using custom textures |
| 624 | max_lod = min(max_lod, (number_of_levels - 1) << 4); |
| 625 | // Rescale uv to account for the new texture size |
| 626 | uv.x = (uv.x * size_s) / native_size_s; |
| 627 | uv.y = (uv.y * size_t) / native_size_t; |
| 628 | // Clamp layer as well (texture() automatically clamps, but texelFetch() doesn't) |
| 629 | layer = clamp(layer, 0, num_layers - 1); |
| 630 | )"); |
| 631 | } |
| 632 | else |
| 633 | { |
| 634 | out.Write(R"( |
| 635 | int size_s = )" I_TEXDIMS R"([texmap].x; |
| 636 | int size_t = )" I_TEXDIMS R"([texmap].y; |
| 637 | )"); |
| 638 | } |
| 639 | |
| 640 | if (g_backend_info.bSupportsCoarseDerivatives) |
| 641 | { |
| 642 | // The software renderer uses the equivalent of coarse derivatives, so use them here for |
| 643 | // consistency. This hasn't been hardware tested. |
| 644 | // Note that bSupportsCoarseDerivatives being false only means dFdxCoarse and dFdxFine don't |
| 645 | // exist. The GPU may still implement dFdx using coarse derivatives; we just don't have the |
| 646 | // ability to specifically require it. |
| 647 | out.Write(R"( |
| 648 | float2 uv_delta_x = abs(dFdxCoarse(float2(uv))); |
| 649 | float2 uv_delta_y = abs(dFdyCoarse(float2(uv))); |
| 650 | )"); |
| 651 | } |
| 652 | else |
| 653 | { |
| 654 | out.Write(R"( |
| 655 | float2 uv_delta_x = abs(dFdx(float2(uv))); |
| 656 | float2 uv_delta_y = abs(dFdy(float2(uv))); |
| 657 | )"); |
| 658 | } |
| 659 | |
| 660 | // TODO: LOD bias is normally S2.5 (Dolphin uses S7.8 for arbitrary mipmap detection and higher |
| 661 | // IRs), but (at least per the software renderer) actual LOD is S28.4. How does this work? |
| 662 | // Also, note that we can make some assumptions due to use of a SamplerState version of the BP |
| 663 | // configuration, which tidies things compared to whatever nonsense games can put in. |
| 664 | out.Write(R"( |
| 665 | float2 uv_delta = diag_lod ? uv_delta_x + uv_delta_y : max(uv_delta_x, uv_delta_y); |
| 666 | float max_delta = max(uv_delta.x / 128.0, uv_delta.y / 128.0); |
| 667 | // log2(x) is undefined if x <= 0, but in practice it seems log2(0) is -infinity, which becomes INT_MIN. |
| 668 | // If lod_bias is negative, adding it to INT_MIN causes an underflow, resulting in a large positive value. |
| 669 | // Hardware testing indicates that min_lod should be used when the derivative is 0. |
| 670 | int lod = max_delta == 0.0 ? min_lod : int(floor(log2(max_delta) * 16.0)) + (lod_bias >> 4); |
| 671 | |
| 672 | bool is_linear = (lod > 0) ? min_linear : mag_linear; |
| 673 | lod = clamp(lod, min_lod, max_lod); |
| 674 | int base_lod = lod >> 4; |
| 675 | int frac_lod = lod & 15; |
| 676 | if (!mipmap_linear && frac_lod >= 8) {{ |
| 677 | // Round to nearest LOD in point mode |
| 678 | base_lod++; |
| 679 | }} |
| 680 | |
| 681 | if (is_linear) {{ |
| 682 | uint2 texuv1 = uint2( |
| 683 | WrapCoord(((uv.x >> base_lod) - 64) >> 7, wrap_s, size_s >> base_lod), |
| 684 | WrapCoord(((uv.y >> base_lod) - 64) >> 7, wrap_t, size_t >> base_lod)); |
| 685 | uint2 texuv2 = uint2( |
| 686 | WrapCoord(((uv.x >> base_lod) + 64) >> 7, wrap_s, size_s >> base_lod), |
| 687 | WrapCoord(((uv.y >> base_lod) + 64) >> 7, wrap_t, size_t >> base_lod)); |
| 688 | int2 frac_uv = int2(((uv.x >> base_lod) - 64) & 0x7f, ((uv.y >> base_lod) - 64) & 0x7f); |
| 689 | |
| 690 | int4 result = readTextureLinear(tex, texuv1, texuv2, layer, base_lod, frac_uv); |
| 691 | |
| 692 | if (frac_lod != 0 && mipmap_linear) {{ |
| 693 | texuv1 = uint2( |
| 694 | WrapCoord(((uv.x >> (base_lod + 1)) - 64) >> 7, wrap_s, size_s >> (base_lod + 1)), |
| 695 | WrapCoord(((uv.y >> (base_lod + 1)) - 64) >> 7, wrap_t, size_t >> (base_lod + 1))); |
| 696 | texuv2 = uint2( |
| 697 | WrapCoord(((uv.x >> (base_lod + 1)) + 64) >> 7, wrap_s, size_s >> (base_lod + 1)), |
| 698 | WrapCoord(((uv.y >> (base_lod + 1)) + 64) >> 7, wrap_t, size_t >> (base_lod + 1))); |
| 699 | frac_uv = int2(((uv.x >> (base_lod + 1)) - 64) & 0x7f, ((uv.y >> (base_lod + 1)) - 64) & 0x7f); |
| 700 | |
| 701 | result *= 16 - frac_lod; |
| 702 | result += readTextureLinear(tex, texuv1, texuv2, layer, base_lod + 1, frac_uv) * frac_lod; |
| 703 | result >>= 4; |
| 704 | }} |
| 705 | |
| 706 | return result; |
| 707 | }} else {{ |
| 708 | uint2 texuv = uint2( |
| 709 | WrapCoord(uv.x >> (7 + base_lod), wrap_s, size_s >> base_lod), |
| 710 | WrapCoord(uv.y >> (7 + base_lod), wrap_t, size_t >> base_lod)); |
| 711 | |
| 712 | int4 result = readTexture(tex, texuv.x, texuv.y, layer, base_lod); |
| 713 | |
| 714 | if (frac_lod != 0 && mipmap_linear) {{ |
| 715 | texuv = uint2( |
| 716 | WrapCoord(uv.x >> (7 + base_lod + 1), wrap_s, size_s >> (base_lod + 1)), |
| 717 | WrapCoord(uv.y >> (7 + base_lod + 1), wrap_t, size_t >> (base_lod + 1))); |
| 718 | |
| 719 | result *= 16 - frac_lod; |
| 720 | result += readTexture(tex, texuv.x, texuv.y, layer, base_lod + 1) * frac_lod; |
| 721 | result >>= 4; |
| 722 | }} |
| 723 | return result; |
| 724 | }} |
| 725 | }} |
| 726 | )"); |
| 727 | } |
| 728 | } |
| 729 | |
| 730 | static void WriteStage(ShaderCode& out, const pixel_shader_uid_data* uid_data, int n, |
| 731 | APIType api_type, bool stereo); |
| 732 | static void WriteTevRegular(ShaderCode& out, std::string_view components, TevBias bias, TevOp op, |
| 733 | bool clamp, TevScale scale); |
| 734 | static void WriteAlphaTest(ShaderCode& out, const pixel_shader_uid_data* uid_data, APIType api_type, |
| 735 | bool per_pixel_depth, bool use_dual_source); |
| 736 | static void WriteFog(ShaderCode& out, const pixel_shader_uid_data* uid_data); |
| 737 | static void WriteLogicOp(ShaderCode& out, const pixel_shader_uid_data* uid_data); |
| 738 | static void WriteLogicOpBlend(ShaderCode& out, const pixel_shader_uid_data* uid_data); |
| 739 | static void WriteColor(ShaderCode& out, APIType api_type, const pixel_shader_uid_data* uid_data, |
| 740 | bool use_dual_source); |
| 741 | static void WriteBlend(ShaderCode& out, const pixel_shader_uid_data* uid_data); |
| 742 | |
| 743 | static void WriteEmulatedFragmentBodyHeader(APIType api_type, const ShaderHostConfig& host_config, |
| 744 | const pixel_shader_uid_data* uid_data, ShaderCode& out); |
| 745 | static void WriteFragmentDefinitions(APIType api_type, const ShaderHostConfig& host_config, |
| 746 | const pixel_shader_uid_data* uid_data, ShaderCode& out); |
| 747 | |
| 748 | ShaderCode GeneratePixelShaderCode(APIType api_type, const ShaderHostConfig& host_config, |
| 749 | const pixel_shader_uid_data* uid_data, |
| 750 | CustomPixelContents custom_contents) |
| 751 | { |
| 752 | ShaderCode out; |
| 753 | |
| 754 | const bool per_pixel_lighting = g_ActiveConfig.bEnablePixelLighting; |
| 755 | const bool msaa = host_config.msaa; |
| 756 | const bool ssaa = host_config.ssaa; |
| 757 | const bool stereo = host_config.stereo; |
| 758 | const u32 numStages = uid_data->genMode_numtevstages + 1; |
| 759 | |
| 760 | out.Write("// Pixel Shader for TEV stages\n"); |
| 761 | out.Write("// {} TEV stages, {} texgens, {} IND stages\n", numStages, |
| 762 | uid_data->genMode_numtexgens, uid_data->genMode_numindstages); |
| 763 | |
| 764 | // Stuff that is shared between ubershaders and pixelgen. |
| 765 | WriteBitfieldExtractHeader(out, api_type, host_config); |
| 766 | |
| 767 | WritePixelShaderCommonHeader(out, api_type, host_config, uid_data->bounding_box); |
| 768 | |
| 769 | out.Write("\n#define sampleTextureWrapper(texmap, uv, layer) " |
| 770 | "sampleTexture(texmap, samp[texmap], uv, layer)\n"); |
| 771 | |
| 772 | if (uid_data->ztest == EmulatedZ::ForcedEarly) |
| 773 | { |
| 774 | // Zcomploc (aka early_ztest) is a way to control whether depth test is done before |
| 775 | // or after texturing and alpha test. PC graphics APIs used to provide no way to emulate |
| 776 | // this feature properly until 2012: Depth tests were always done after alpha testing. |
| 777 | // Most importantly, it was not possible to write to the depth buffer without also writing |
| 778 | // a color value (unless color writing was disabled altogether). |
| 779 | |
| 780 | // OpenGL 4.2 actually provides two extensions which can force an early z test: |
| 781 | // * ARB_image_load_store has 'layout(early_fragment_tests)' which forces the driver to do z |
| 782 | // and stencil tests early. |
| 783 | // * ARB_conservative_depth has 'layout(depth_unchanged) which signals to the driver that it |
| 784 | // can make optimisations |
| 785 | // which assume the pixel shader won't update the depth buffer. |
| 786 | |
| 787 | // early_fragment_tests is the best option, as it requires the driver to do early-z and defines |
| 788 | // early-z exactly as |
| 789 | // we expect, with discard causing the shader to exit with only the depth buffer updated. |
| 790 | |
| 791 | // Conservative depth's 'depth_unchanged' only hints to the driver that an early-z optimisation |
| 792 | // can be made and |
| 793 | // doesn't define what will happen if we discard the fragment. But the way modern graphics |
| 794 | // hardware is implemented |
| 795 | // means it is not unreasonable to expect the same behaviour as early_fragment_tests. |
| 796 | // We can also assume that if a driver has gone out of its way to support conservative depth and |
| 797 | // not image_load_store |
| 798 | // as required by OpenGL 4.2 that it will be doing the optimisation. |
| 799 | // If the driver doesn't actually do an early z optimisation, ZCompLoc will be broken and depth |
| 800 | // will only be written |
| 801 | // if the alpha test passes. |
| 802 | |
| 803 | // We support Conservative as a fallback, because many drivers based on Mesa haven't implemented |
| 804 | // all of the |
| 805 | // ARB_image_load_store extension yet. |
| 806 | |
| 807 | // This is a #define which signals whatever early-z method the driver supports. |
| 808 | out.Write("FORCE_EARLY_Z; \n"); |
| 809 | } |
| 810 | |
| 811 | const bool use_framebuffer_fetch = uid_data->blend_enable || uid_data->logic_op_enable || |
| 812 | uid_data->ztest == EmulatedZ::EarlyWithFBFetch; |
| 813 | |
| 814 | #ifdef __APPLE__ |
| 815 | // Framebuffer fetch is only supported by Metal, so ensure that we're running Vulkan (MoltenVK) |
| 816 | // if we want to use it. |
| 817 | if (api_type == APIType::Vulkan || api_type == APIType::Metal) |
| 818 | { |
| 819 | if (!uid_data->no_dual_src) |
| 820 | { |
| 821 | out.Write("FRAGMENT_OUTPUT_LOCATION_INDEXED(0, 0) out vec4 {};\n" |
| 822 | "FRAGMENT_OUTPUT_LOCATION_INDEXED(0, 1) out vec4 ocol1;\n", |
| 823 | use_framebuffer_fetch ? "real_ocol0" : "ocol0"); |
| 824 | } |
| 825 | else |
| 826 | { |
| 827 | // Metal doesn't support a single unified variable for both input and output, |
| 828 | // so when using framebuffer fetch, we declare the input separately below. |
| 829 | out.Write("FRAGMENT_OUTPUT_LOCATION(0) out vec4 {};\n", |
| 830 | use_framebuffer_fetch ? "real_ocol0" : "ocol0"); |
| 831 | } |
| 832 | |
| 833 | if (use_framebuffer_fetch) |
| 834 | { |
| 835 | // Subpass inputs will be converted to framebuffer fetch by SPIRV-Cross. |
| 836 | out.Write("INPUT_ATTACHMENT_BINDING(0, 0, 0) uniform subpassInput in_ocol0;\n"); |
| 837 | } |
| 838 | } |
| 839 | else |
| 840 | #endif |
| 841 | { |
| 842 | if (use_framebuffer_fetch) |
| 843 | { |
| 844 | out.Write("FRAGMENT_OUTPUT_LOCATION(0) FRAGMENT_INOUT vec4 real_ocol0;\n"); |
| 845 | } |
| 846 | else |
| 847 | { |
| 848 | out.Write("FRAGMENT_OUTPUT_LOCATION_INDEXED(0, 0) out {} ocol0;\n", |
| 849 | uid_data->uint_output ? "uvec4" : "vec4"); |
| 850 | } |
| 851 | |
| 852 | if (!uid_data->no_dual_src) |
| 853 | { |
| 854 | out.Write("{} out {} ocol1;\n", "FRAGMENT_OUTPUT_LOCATION_INDEXED(0, 1)", |
| 855 | uid_data->uint_output ? "uvec4" : "vec4"); |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | if (uid_data->per_pixel_depth) |
| 860 | out.Write("#define depth gl_FragDepth\n"); |
| 861 | |
| 862 | if (host_config.backend_geometry_shaders) |
| 863 | { |
| 864 | out.Write("VARYING_LOCATION(0) in VertexData {{\n"); |
| 865 | GenerateVSOutputMembers(out, api_type, uid_data->genMode_numtexgens, host_config, |
| 866 | GetInterpolationQualifier(msaa, ssaa, true, true), ShaderStage::Pixel); |
| 867 | |
| 868 | out.Write("}};\n"); |
| 869 | if (stereo && !host_config.backend_gl_layer_in_fs) |
| 870 | out.Write("flat in int layer;"); |
| 871 | } |
| 872 | else |
| 873 | { |
| 874 | // Let's set up attributes |
| 875 | u32 counter = 0; |
| 876 | out.Write("VARYING_LOCATION({}) {} in float4 colors_0;\n", counter++, |
| 877 | GetInterpolationQualifier(msaa, ssaa)); |
| 878 | out.Write("VARYING_LOCATION({}) {} in float4 colors_1;\n", counter++, |
| 879 | GetInterpolationQualifier(msaa, ssaa)); |
| 880 | for (u32 i = 0; i < uid_data->genMode_numtexgens; ++i) |
| 881 | { |
| 882 | out.Write("VARYING_LOCATION({}) {} in float3 tex{};\n", counter++, |
| 883 | GetInterpolationQualifier(msaa, ssaa), i); |
| 884 | } |
| 885 | if (!host_config.fast_depth_calc) |
| 886 | { |
| 887 | out.Write("VARYING_LOCATION({}) {} in float4 clipPos;\n", counter++, |
| 888 | GetInterpolationQualifier(msaa, ssaa)); |
| 889 | } |
| 890 | if (per_pixel_lighting) |
| 891 | { |
| 892 | out.Write("VARYING_LOCATION({}) {} in float3 Normal;\n", counter++, |
| 893 | GetInterpolationQualifier(msaa, ssaa)); |
| 894 | out.Write("VARYING_LOCATION({}) {} in float3 WorldPos;\n", counter++, |
| 895 | GetInterpolationQualifier(msaa, ssaa)); |
| 896 | } |
| 897 | } |
| 898 | |
| 899 | if (!custom_contents.uniforms.empty()) |
| 900 | { |
| 901 | out.Write("UBO_BINDING(std140, 3) uniform CustomShaderBlock {{\n"); |
| 902 | out.Write("{}", custom_contents.uniforms); |
| 903 | out.Write("}} custom_uniforms;\n"); |
| 904 | } |
| 905 | |
| 906 | if (per_pixel_lighting) |
| 907 | { |
| 908 | GenerateLightingShaderHeader(out, uid_data->lighting); |
| 909 | } |
| 910 | |
| 911 | WriteFragmentDefinitions(api_type, host_config, uid_data, out); |
| 912 | WriteEmulatedFragmentBodyHeader(api_type, host_config, uid_data, out); |
| 913 | |
| 914 | if (custom_contents.shader.empty()) |
| 915 | { |
| 916 | out.Write("void process_fragment(in DolphinFragmentInput frag_input, out DolphinFragmentOutput " |
| 917 | "frag_output)\n"); |
| 918 | out.Write("{{\n"); |
| 919 | |
| 920 | out.Write("\tdolphin_process_emulated_fragment(frag_input, frag_output);\n"); |
| 921 | |
| 922 | out.Write("}}\n"); |
| 923 | } |
| 924 | else |
| 925 | { |
| 926 | out.Write("{}\n", custom_contents.shader); |
| 927 | } |
| 928 | |
| 929 | out.Write("void main()\n{{\n"); |
| 930 | out.Write("\tfloat4 rawpos = gl_FragCoord;\n"); |
| 931 | |
| 932 | if (use_framebuffer_fetch) |
| 933 | { |
| 934 | // Store off a copy of the initial framebuffer value. |
| 935 | // |
| 936 | // If FB_FETCH_VALUE isn't defined (i.e. no special keyword for fetching from the |
| 937 | // framebuffer), we read from real_ocol0. |
| 938 | out.Write("#ifdef FB_FETCH_VALUE\n" |
| 939 | "\tfloat4 initial_ocol0 = FB_FETCH_VALUE;\n" |
| 940 | "#else\n" |
| 941 | "\tfloat4 initial_ocol0 = real_ocol0;\n" |
| 942 | "#endif\n"); |
| 943 | |
| 944 | // QComm's Adreno driver doesn't seem to like using the framebuffer_fetch value as an |
| 945 | // intermediate value with multiple reads & modifications, so we pull out the "real" output |
| 946 | // value above and use a temporary for calculations, then set the output value once at the |
| 947 | // end of the shader. |
| 948 | out.Write("\tfloat4 ocol0;\n"); |
| 949 | } |
| 950 | |
| 951 | if (uid_data->blend_enable) |
| 952 | { |
| 953 | out.Write("\tfloat4 ocol1;\n"); |
| 954 | } |
| 955 | |
| 956 | if (host_config.backend_geometry_shaders && stereo) |
| 957 | { |
| 958 | if (host_config.backend_gl_layer_in_fs) |
| 959 | out.Write("\tint layer = gl_Layer;\n"); |
| 960 | } |
| 961 | else |
| 962 | { |
| 963 | out.Write("\tint layer = 0;\n"); |
| 964 | } |
| 965 | |
| 966 | out.Write("\tDolphinFragmentInput frag_input;\n"); |
| 967 | out.Write("\tfrag_input.color_0 = colors_0;\n"); |
| 968 | out.Write("\tfrag_input.color_1 = colors_1;\n"); |
| 969 | out.Write("\tfrag_input.layer = layer;\n"); |
| 970 | if (per_pixel_lighting) |
| 971 | { |
| 972 | out.Write("\tfrag_input.normal = normalize(Normal);\n"); |
| 973 | out.Write("\tfrag_input.position = WorldPos;\n"); |
| 974 | } |
| 975 | else |
| 976 | { |
| 977 | out.Write("\tfrag_input.normal = vec3(0, 0, 0);\n"); |
| 978 | out.Write("\tfrag_input.position = vec3(0, 0, 0);\n"); |
| 979 | } |
| 980 | for (u32 i = 0; i < uid_data->genMode_numtexgens; i++) |
| 981 | { |
| 982 | out.Write("\tfrag_input.tex{0} = tex{0};\n", i); |
| 983 | } |
| 984 | |
| 985 | // Initialize other texture coordinates that are unused |
| 986 | for (u32 i = uid_data->genMode_numtexgens; i < 8; i++) |
| 987 | { |
| 988 | out.Write("\tfrag_input.tex{0} = vec3(0, 0, 0);\n", i); |
| 989 | } |
| 990 | |
| 991 | if (!custom_contents.shader.empty()) |
| 992 | GenerateCustomLighting(&out, uid_data->lighting); |
| 993 | |
| 994 | out.Write("\tDolphinFragmentOutput frag_output;\n"); |
| 995 | out.Write("\tprocess_fragment(frag_input, frag_output);\n"); |
| 996 | out.Write("\tivec4 prev = frag_output.main & 255;\n"); |
| 997 | |
| 998 | // NOTE: Fragment may not be discarded if alpha test always fails and early depth test is enabled |
| 999 | // (in this case we need to write a depth value if depth test passes regardless of the alpha |
| 1000 | // testing result) |
| 1001 | if (uid_data->Pretest == AlphaTestResult::Undetermined || |
| 1002 | (uid_data->Pretest == AlphaTestResult::Fail && uid_data->ztest == EmulatedZ::Late)) |
| 1003 | { |
| 1004 | WriteAlphaTest(out, uid_data, api_type, uid_data->per_pixel_depth, |
| 1005 | !uid_data->no_dual_src || uid_data->blend_enable); |
| 1006 | } |
| 1007 | |
| 1008 | // This situation is important for Mario Kart Wii's menus (they will render incorrectly if the |
| 1009 | // alpha test for the FMV in the background fails, since they depend on depth for drawing a yellow |
| 1010 | // border) and Fortune Street's gameplay (where a rectangle with an alpha value of 1 is drawn over |
| 1011 | // the center of the screen several times, but those rectangles shouldn't be visible). |
| 1012 | // Blending seems to result in no changes to the output with an alpha of 1, even if the input |
| 1013 | // color is white. |
| 1014 | // TODO: Investigate this further: we might be handling blending incorrectly in general (though |
| 1015 | // there might not be any good way of changing blending behavior) |
| 1016 | out.Write("\t// Hardware testing indicates that an alpha of 1 can pass an alpha test,\n" |
| 1017 | "\t// but doesn't do anything in blending\n" |
| 1018 | "\tif (prev.a == 1) prev.a = 0;\n"); |
| 1019 | |
| 1020 | if (uid_data->zfreeze) |
| 1021 | { |
| 1022 | out.SetConstantsUsed(C_ZSLOPE, C_ZSLOPE); |
| 1023 | out.SetConstantsUsed(C_EFBSCALE, C_EFBSCALE); |
| 1024 | |
| 1025 | out.Write("\tfloat2 screenpos = rawpos.xy * " I_EFBSCALE ".xy;\n"); |
| 1026 | |
| 1027 | // Opengl has reversed vertical screenspace coordinates |
| 1028 | if (api_type == APIType::OpenGL) |
| 1029 | out.Write("\tscreenpos.y = {}.0 - screenpos.y;\n", EFB_HEIGHT); |
| 1030 | |
| 1031 | out.Write("\tint zCoord = int(" I_ZSLOPE ".z + " I_ZSLOPE ".x * screenpos.x + " I_ZSLOPE |
| 1032 | ".y * screenpos.y);\n"); |
| 1033 | } |
| 1034 | else if (!host_config.fast_depth_calc) |
| 1035 | { |
| 1036 | // FastDepth means to trust the depth generated in perspective division. |
| 1037 | // It should be correct, but it seems not to be as accurate as required. TODO: Find out why! |
| 1038 | // For disabled FastDepth we just calculate the depth value again. |
| 1039 | // The performance impact of this additional calculation doesn't matter, but it prevents |
| 1040 | // the host GPU driver from performing any early depth test optimizations. |
| 1041 | out.SetConstantsUsed(C_ZBIAS + 1, C_ZBIAS + 1); |
| 1042 | // the screen space depth value = far z + (clip z / clip w) * z range |
| 1043 | out.Write("\tint zCoord = " I_ZBIAS "[1].x + int((clipPos.z / clipPos.w) * float(" I_ZBIAS |
| 1044 | "[1].y));\n"); |
| 1045 | } |
| 1046 | else |
| 1047 | { |
| 1048 | if (!host_config.backend_reversed_depth_range) |
| 1049 | out.Write("\tint zCoord = int((1.0 - rawpos.z) * 16777216.0);\n"); |
| 1050 | else |
| 1051 | out.Write("\tint zCoord = int(rawpos.z * 16777216.0);\n"); |
| 1052 | } |
| 1053 | out.Write("\tzCoord = clamp(zCoord, 0, 0xFFFFFF);\n"); |
| 1054 | |
| 1055 | // depth texture can safely be ignored if the result won't be written to the depth buffer |
| 1056 | // (early_ztest) and isn't used for fog either |
| 1057 | const bool skip_ztexture = !uid_data->per_pixel_depth && uid_data->fog_fsel == FogType::Off; |
| 1058 | |
| 1059 | // Note: z-textures are not written to depth buffer if early depth test is used |
| 1060 | const bool early_ztest = uid_data->ztest == EmulatedZ::Early || |
| 1061 | uid_data->ztest == EmulatedZ::EarlyWithFBFetch || |
| 1062 | uid_data->ztest == EmulatedZ::EarlyWithZComplocHack; |
| 1063 | if (uid_data->per_pixel_depth && early_ztest) |
| 1064 | { |
| 1065 | if (!host_config.backend_reversed_depth_range) |
| 1066 | out.Write("\tdepth = 1.0 - float(zCoord) / 16777216.0;\n"); |
| 1067 | else |
| 1068 | out.Write("\tdepth = float(zCoord) / 16777216.0;\n"); |
| 1069 | } |
| 1070 | |
| 1071 | // Note: depth texture output is only written to depth buffer if late depth test is used |
| 1072 | // theoretical final depth value is used for fog calculation, though, so we have to emulate |
| 1073 | // ztextures anyway |
| 1074 | if (uid_data->ztex_op != ZTexOp::Disabled && !skip_ztexture) |
| 1075 | { |
| 1076 | // use the texture input of the last texture stage, hopefully this has been read and |
| 1077 | // is in correct format... |
| 1078 | out.SetConstantsUsed(C_ZBIAS, C_ZBIAS + 1); |
| 1079 | out.Write("\tzCoord = idot(" I_ZBIAS "[0].xyzw, frag_output.last_texture.xyzw) + " I_ZBIAS |
| 1080 | "[1].w {};\n", |
| 1081 | (uid_data->ztex_op == ZTexOp::Add) ? "+ zCoord" : ""); |
| 1082 | out.Write("\tzCoord = zCoord & 0xFFFFFF;\n"); |
| 1083 | } |
| 1084 | |
| 1085 | if (uid_data->per_pixel_depth && uid_data->ztest == EmulatedZ::Late) |
| 1086 | { |
| 1087 | if (!host_config.backend_reversed_depth_range) |
| 1088 | out.Write("\tdepth = 1.0 - float(zCoord) / 16777216.0;\n"); |
| 1089 | else |
| 1090 | out.Write("\tdepth = float(zCoord) / 16777216.0;\n"); |
| 1091 | } |
| 1092 | |
| 1093 | // No dithering for RGB8 mode |
| 1094 | if (uid_data->dither) |
| 1095 | { |
| 1096 | // Flipper uses a standard 2x2 Bayer Matrix for 6 bit dithering |
| 1097 | out.Write("\tint2 dither = int2(rawpos.xy) & 1;\n"); |
| 1098 | out.Write( |
| 1099 | "\tprev.rgb = (prev.rgb - (prev.rgb >> 6)) + (dither.x ^ dither.y) * 2 + dither.y;\n"); |
| 1100 | } |
| 1101 | |
| 1102 | WriteFog(out, uid_data); |
| 1103 | |
| 1104 | if (uid_data->logic_op_enable) |
| 1105 | WriteLogicOp(out, uid_data); |
| 1106 | else if (uid_data->emulate_logic_op_with_blend) |
| 1107 | WriteLogicOpBlend(out, uid_data); |
| 1108 | |
| 1109 | // Write the color and alpha values to the framebuffer |
| 1110 | // If using shader blend, we still use the separate alpha |
| 1111 | const bool use_dual_source = !uid_data->no_dual_src || uid_data->blend_enable; |
| 1112 | WriteColor(out, api_type, uid_data, use_dual_source); |
| 1113 | |
| 1114 | if (uid_data->blend_enable) |
| 1115 | WriteBlend(out, uid_data); |
| 1116 | else if (use_framebuffer_fetch) |
| 1117 | out.Write("\treal_ocol0 = ocol0;\n"); |
| 1118 | |
| 1119 | if (uid_data->bounding_box) |
| 1120 | out.Write("\tUpdateBoundingBox(rawpos.xy);\n"); |
| 1121 | |
| 1122 | out.Write("}}\n"); |
| 1123 | |
| 1124 | return out; |
| 1125 | } |
| 1126 | |
| 1127 | static void WriteStage(ShaderCode& out, const pixel_shader_uid_data* uid_data, int n, |
| 1128 | APIType api_type, bool stereo) |
| 1129 | { |
| 1130 | using Common::EnumMap; |
| 1131 | |
| 1132 | const auto& stage = uid_data->stagehash[n]; |
| 1133 | out.Write("\n\t// TEV stage {}\n", n); |
| 1134 | |
| 1135 | // Quirk: when the tex coord is not less than the number of tex gens (i.e. the tex coord does not |
| 1136 | // exist), then tex coord 0 is used (though sometimes glitchy effects happen on console). |
| 1137 | u32 texcoord = stage.tevorders_texcoord; |
| 1138 | const bool has_tex_coord = texcoord < uid_data->genMode_numtexgens; |
| 1139 | if (!has_tex_coord) |
| 1140 | texcoord = 0; |
| 1141 | |
| 1142 | { |
| 1143 | const TevStageIndirect tevind{.hex = stage.tevind}; |
| 1144 | out.Write("\t// indirect op\n"); |
| 1145 | |
| 1146 | // Quirk: Referencing a stage above the number of ind stages is undefined behavior, |
| 1147 | // and on console produces a noise pattern (details unknown). |
| 1148 | // Instead, just skip applying the indirect operation, which is close enough. |
| 1149 | // We need to do *something*, as there won't be an iindtex variable otherwise. |
| 1150 | // Viewtiful Joe hits this case (bug 12525). |
| 1151 | // Wrapping and add to previous still apply in this case (and when the stage is disabled). |
| 1152 | const bool has_ind_stage = tevind.bt < uid_data->genMode_numindstages; |
| 1153 | |
| 1154 | // Perform the indirect op on the incoming regular coordinates |
| 1155 | // using iindtex{} as the offset coords |
| 1156 | if (has_ind_stage && tevind.bs != IndTexBumpAlpha::Off) |
| 1157 | { |
| 1158 | static constexpr EnumMap<const char*, IndTexBumpAlpha::U> tev_ind_alpha_sel{ |
| 1159 | "", |
| 1160 | "x", |
| 1161 | "y", |
| 1162 | "z", |
| 1163 | }; |
| 1164 | |
| 1165 | // According to libogc, the bump alpha value is 5 bits, and comes from the bottom bits of the |
| 1166 | // component byte, except in the case of ITF_8, which presumably uses the top bits with a |
| 1167 | // mask. |
| 1168 | // https://github.com/devkitPro/libogc/blob/bd24a9b3f59502f9b30d6bac0ae35fc485045f78/gc/ogc/gx.h#L3038-L3041 |
| 1169 | // https://github.com/devkitPro/libogc/blob/bd24a9b3f59502f9b30d6bac0ae35fc485045f78/gc/ogc/gx.h#L790-L800 |
| 1170 | |
| 1171 | static constexpr EnumMap<char, IndTexFormat::ITF_3> tev_ind_alpha_shift{ |
| 1172 | '0', // ITF_8: 0bXXXXXYYY -> 0bXXXXX000? No shift? |
| 1173 | '5', // ITF_5: 0bIIIIIAAA -> 0bAAA00000, shift of 5 |
| 1174 | '4', // ITF_4: 0bIIIIAAAA -> 0bAAAA0000, shift of 4 |
| 1175 | '3', // ITF_3: 0bIIIAAAAA -> 0bAAAAA000, shift of 3 |
| 1176 | }; |
| 1177 | |
| 1178 | out.Write("\talphabump = (iindtex{}.{} << {}) & 248;\n", tevind.bt, |
| 1179 | tev_ind_alpha_sel[tevind.bs], tev_ind_alpha_shift[tevind.fmt]); |
| 1180 | } |
| 1181 | else |
| 1182 | { |
| 1183 | // TODO: Should we reset alphabump to 0 here? |
| 1184 | } |
| 1185 | |
| 1186 | if (has_ind_stage && tevind.matrix_index != IndMtxIndex::Off) |
| 1187 | { |
| 1188 | // format |
| 1189 | static constexpr EnumMap<char, IndTexFormat::ITF_3> tev_ind_fmt_shift{ |
| 1190 | '0', // ITF_8: 0bXXXXXXXX -> 0bXXXXXXXX, no shift |
| 1191 | '3', // ITF_5: 0bIIIIIAAA -> 0b000IIIII, shift of 3 |
| 1192 | '4', // ITF_4: 0bIIIIAAAA -> 0b0000IIII, shift of 4 |
| 1193 | '5', // ITF_3: 0bIIIAAAAA -> 0b00000III, shift of 5 |
| 1194 | }; |
| 1195 | out.Write("\tint3 iindtevcrd{} = iindtex{} >> {};\n", n, tevind.bt, |
| 1196 | tev_ind_fmt_shift[tevind.fmt]); |
| 1197 | |
| 1198 | // bias - TODO: Check if this needs to be this complicated... |
| 1199 | // indexed by bias |
| 1200 | static constexpr EnumMap<const char*, IndTexBias::STU> tev_ind_bias_field{ |
| 1201 | "", "x", "y", "xy", "z", "xz", "yz", "xyz", |
| 1202 | }; |
| 1203 | |
| 1204 | // indexed by fmt |
| 1205 | static constexpr EnumMap<const char*, IndTexFormat::ITF_3> tev_ind_bias_add{ |
| 1206 | "-128", |
| 1207 | "1", |
| 1208 | "1", |
| 1209 | "1", |
| 1210 | }; |
| 1211 | |
| 1212 | if (tevind.bias == IndTexBias::S || tevind.bias == IndTexBias::T || |
| 1213 | tevind.bias == IndTexBias::U) |
| 1214 | { |
| 1215 | out.Write("\tiindtevcrd{}.{} += int({});\n", n, tev_ind_bias_field[tevind.bias], |
| 1216 | tev_ind_bias_add[tevind.fmt]); |
| 1217 | } |
| 1218 | else if (tevind.bias == IndTexBias::ST || tevind.bias == IndTexBias::SU || |
| 1219 | tevind.bias == IndTexBias::TU_) |
| 1220 | { |
| 1221 | out.Write("\tiindtevcrd{0}.{1} += int2({2}, {2});\n", n, tev_ind_bias_field[tevind.bias], |
| 1222 | tev_ind_bias_add[tevind.fmt]); |
| 1223 | } |
| 1224 | else if (tevind.bias == IndTexBias::STU) |
| 1225 | { |
| 1226 | out.Write("\tiindtevcrd{0}.{1} += int3({2}, {2}, {2});\n", n, |
| 1227 | tev_ind_bias_field[tevind.bias], tev_ind_bias_add[tevind.fmt]); |
| 1228 | } |
| 1229 | |
| 1230 | // Multiplied by 2 because each matrix has two rows. |
| 1231 | // Note also that the 4th column of the matrix contains the scale factor. |
| 1232 | const u32 mtxidx = 2 * (static_cast<u32>(tevind.matrix_index.Value()) - 1); |
| 1233 | |
| 1234 | // multiply by offset matrix and scale - calculations are likely to overflow badly, |
| 1235 | // yet it works out since we only care about the lower 23 bits (+1 sign bit) of the result |
| 1236 | if (tevind.matrix_id == IndMtxId::Indirect) |
| 1237 | { |
| 1238 | out.SetConstantsUsed(C_INDTEXMTX + mtxidx, C_INDTEXMTX + mtxidx); |
| 1239 | |
| 1240 | out.Write("\tint2 indtevtrans{} = int2(idot(" I_INDTEXMTX |
| 1241 | "[{}].xyz, iindtevcrd{}), idot(" I_INDTEXMTX "[{}].xyz, iindtevcrd{})) >> 3;\n", |
| 1242 | n, mtxidx, n, mtxidx + 1, n); |
| 1243 | |
| 1244 | // TODO: should use a shader uid branch for this for better performance |
| 1245 | if (DriverDetails::HasBug(DriverDetails::BUG_BROKEN_BITWISE_OP_NEGATION)) |
| 1246 | { |
| 1247 | out.Write("\tint indtexmtx_w_inverse_{} = -" I_INDTEXMTX "[{}].w;\n", n, mtxidx); |
| 1248 | out.Write("\tif (" I_INDTEXMTX "[{}].w >= 0) indtevtrans{} >>= " I_INDTEXMTX "[{}].w;\n", |
| 1249 | mtxidx, n, mtxidx); |
| 1250 | out.Write("\telse indtevtrans{} <<= indtexmtx_w_inverse_{};\n", n, n); |
| 1251 | } |
| 1252 | else |
| 1253 | { |
| 1254 | out.Write("\tif (" I_INDTEXMTX "[{}].w >= 0) indtevtrans{} >>= " I_INDTEXMTX "[{}].w;\n", |
| 1255 | mtxidx, n, mtxidx); |
| 1256 | out.Write("\telse indtevtrans{} <<= (-" I_INDTEXMTX "[{}].w);\n", n, mtxidx); |
| 1257 | } |
| 1258 | } |
| 1259 | else if (tevind.matrix_id == IndMtxId::S) |
| 1260 | { |
| 1261 | ASSERT(has_tex_coord); |
| 1262 | out.SetConstantsUsed(C_INDTEXMTX + mtxidx, C_INDTEXMTX + mtxidx); |
| 1263 | |
| 1264 | out.Write("\tint2 indtevtrans{} = int2(fixpoint_uv{} * iindtevcrd{}.xx) >> 8;\n", n, |
| 1265 | texcoord, n); |
| 1266 | if (DriverDetails::HasBug(DriverDetails::BUG_BROKEN_BITWISE_OP_NEGATION)) |
| 1267 | { |
| 1268 | out.Write("\tint indtexmtx_w_inverse_{} = -" I_INDTEXMTX "[{}].w;\n", n, mtxidx); |
| 1269 | out.Write("\tif (" I_INDTEXMTX "[{}].w >= 0) indtevtrans{} >>= " I_INDTEXMTX "[{}].w;\n", |
| 1270 | mtxidx, n, mtxidx); |
| 1271 | out.Write("\telse indtevtrans{} <<= (indtexmtx_w_inverse_{});\n", n, n); |
| 1272 | } |
| 1273 | else |
| 1274 | { |
| 1275 | out.Write("\tif (" I_INDTEXMTX "[{}].w >= 0) indtevtrans{} >>= " I_INDTEXMTX "[{}].w;\n", |
| 1276 | mtxidx, n, mtxidx); |
| 1277 | out.Write("\telse indtevtrans{} <<= (-" I_INDTEXMTX "[{}].w);\n", n, mtxidx); |
| 1278 | } |
| 1279 | } |
| 1280 | else if (tevind.matrix_id == IndMtxId::T) |
| 1281 | { |
| 1282 | ASSERT(has_tex_coord); |
| 1283 | out.SetConstantsUsed(C_INDTEXMTX + mtxidx, C_INDTEXMTX + mtxidx); |
| 1284 | |
| 1285 | out.Write("\tint2 indtevtrans{} = int2(fixpoint_uv{} * iindtevcrd{}.yy) >> 8;\n", n, |
| 1286 | texcoord, n); |
| 1287 | |
| 1288 | if (DriverDetails::HasBug(DriverDetails::BUG_BROKEN_BITWISE_OP_NEGATION)) |
| 1289 | { |
| 1290 | out.Write("\tint indtexmtx_w_inverse_{} = -" I_INDTEXMTX "[{}].w;\n", n, mtxidx); |
| 1291 | out.Write("\tif (" I_INDTEXMTX "[{}].w >= 0) indtevtrans{} >>= " I_INDTEXMTX "[{}].w;\n", |
| 1292 | mtxidx, n, mtxidx); |
| 1293 | out.Write("\telse indtevtrans{} <<= (indtexmtx_w_inverse_{});\n", n, n); |
| 1294 | } |
| 1295 | else |
| 1296 | { |
| 1297 | out.Write("\tif (" I_INDTEXMTX "[{}].w >= 0) indtevtrans{} >>= " I_INDTEXMTX "[{}].w;\n", |
| 1298 | mtxidx, n, mtxidx); |
| 1299 | out.Write("\telse indtevtrans{} <<= (-" I_INDTEXMTX "[{}].w);\n", n, mtxidx); |
| 1300 | } |
| 1301 | } |
| 1302 | else |
| 1303 | { |
| 1304 | out.Write("\tint2 indtevtrans{} = int2(0, 0);\n", n); |
| 1305 | ASSERT(false); // Unknown value for matrix_id |
| 1306 | } |
| 1307 | } |
| 1308 | else |
| 1309 | { |
| 1310 | out.Write("\tint2 indtevtrans{} = int2(0, 0);\n", n); |
| 1311 | if (tevind.matrix_index == IndMtxIndex::Off) |
| 1312 | { |
| 1313 | // If matrix_index is Off (0), matrix_id should be Indirect (0) |
| 1314 | ASSERT(tevind.matrix_id == IndMtxId::Indirect); |
| 1315 | } |
| 1316 | } |
| 1317 | |
| 1318 | // --------- |
| 1319 | // Wrapping |
| 1320 | // --------- |
| 1321 | |
| 1322 | static constexpr std::array<const char*, 5> tev_ind_wrap_start{ |
| 1323 | "(256<<7)", "(128<<7)", "(64<<7)", "(32<<7)", "(16<<7)", |
| 1324 | }; |
| 1325 | |
| 1326 | // wrap S |
| 1327 | if (tevind.sw == IndTexWrap::ITW_OFF) |
| 1328 | { |
| 1329 | out.Write("\twrappedcoord.x = fixpoint_uv{}.x;\n", texcoord); |
| 1330 | } |
| 1331 | else if (tevind.sw >= IndTexWrap::ITW_0) // 7 (Invalid) appears to behave the same as 6 (ITW_0) |
| 1332 | { |
| 1333 | out.Write("\twrappedcoord.x = 0;\n"); |
| 1334 | } |
| 1335 | else |
| 1336 | { |
| 1337 | out.Write("\twrappedcoord.x = fixpoint_uv{}.x & ({} - 1);\n", texcoord, |
| 1338 | tev_ind_wrap_start[u32(tevind.sw.Value()) - u32(IndTexWrap::ITW_256)]); |
| 1339 | } |
| 1340 | |
| 1341 | // wrap T |
| 1342 | if (tevind.tw == IndTexWrap::ITW_OFF) |
| 1343 | { |
| 1344 | out.Write("\twrappedcoord.y = fixpoint_uv{}.y;\n", texcoord); |
| 1345 | } |
| 1346 | else if (tevind.tw >= IndTexWrap::ITW_0) // 7 (Invalid) appears to behave the same as 6 (ITW_0) |
| 1347 | { |
| 1348 | out.Write("\twrappedcoord.y = 0;\n"); |
| 1349 | } |
| 1350 | else |
| 1351 | { |
| 1352 | out.Write("\twrappedcoord.y = fixpoint_uv{}.y & ({} - 1);\n", texcoord, |
| 1353 | tev_ind_wrap_start[u32(tevind.tw.Value()) - u32(IndTexWrap::ITW_256)]); |
| 1354 | } |
| 1355 | |
| 1356 | if (tevind.fb_addprev) // add previous tevcoord |
| 1357 | out.Write("\ttevcoord.xy += wrappedcoord + indtevtrans{};\n", n); |
| 1358 | else |
| 1359 | out.Write("\ttevcoord.xy = wrappedcoord + indtevtrans{};\n", n); |
| 1360 | |
| 1361 | // Emulate s24 overflows |
| 1362 | out.Write("\ttevcoord.xy = (tevcoord.xy << 8) >> 8;\n"); |
| 1363 | } |
| 1364 | |
| 1365 | TevStageCombiner::ColorCombiner cc; |
| 1366 | TevStageCombiner::AlphaCombiner ac; |
| 1367 | cc.hex = stage.cc; |
| 1368 | ac.hex = stage.ac; |
| 1369 | |
| 1370 | if (cc.a == TevColorArg::RasAlpha || cc.a == TevColorArg::RasColor || |
| 1371 | cc.b == TevColorArg::RasAlpha || cc.b == TevColorArg::RasColor || |
| 1372 | cc.c == TevColorArg::RasAlpha || cc.c == TevColorArg::RasColor || |
| 1373 | cc.d == TevColorArg::RasAlpha || cc.d == TevColorArg::RasColor || |
| 1374 | ac.a == TevAlphaArg::RasAlpha || ac.b == TevAlphaArg::RasAlpha || |
| 1375 | ac.c == TevAlphaArg::RasAlpha || ac.d == TevAlphaArg::RasAlpha) |
| 1376 | { |
| 1377 | // Generate swizzle string to represent the Ras color channel swapping |
| 1378 | out.Write("\trastemp = {}.{}{}{}{};\n", tev_ras_table[stage.tevorders_colorchan], |
| 1379 | rgba_swizzle[stage.ras_swap_r], rgba_swizzle[stage.ras_swap_g], |
| 1380 | rgba_swizzle[stage.ras_swap_b], rgba_swizzle[stage.ras_swap_a]); |
| 1381 | } |
| 1382 | |
| 1383 | if (stage.tevorders_enable && uid_data->genMode_numtexgens > 0) |
| 1384 | { |
| 1385 | // Generate swizzle string to represent the texture color channel swapping |
| 1386 | out.Write("\trawtextemp = sampleTextureWrapper({}u, tevcoord.xy, layer);\n", |
| 1387 | stage.tevorders_texmap); |
| 1388 | out.Write("\ttextemp = rawtextemp.{}{}{}{};\n", rgba_swizzle[stage.tex_swap_r], |
| 1389 | rgba_swizzle[stage.tex_swap_g], rgba_swizzle[stage.tex_swap_b], |
| 1390 | rgba_swizzle[stage.tex_swap_a]); |
| 1391 | } |
| 1392 | else if (uid_data->genMode_numtexgens == 0) |
| 1393 | { |
| 1394 | // It seems like the result is always black when no tex coords are enabled, but further testing |
| 1395 | // is needed. |
| 1396 | out.Write("\ttextemp = int4(0, 0, 0, 0);\n"); |
| 1397 | } |
| 1398 | else |
| 1399 | { |
| 1400 | out.Write("\ttextemp = int4(255, 255, 255, 255);\n"); |
| 1401 | } |
| 1402 | |
| 1403 | if (cc.a == TevColorArg::Konst || cc.b == TevColorArg::Konst || cc.c == TevColorArg::Konst || |
| 1404 | cc.d == TevColorArg::Konst || ac.a == TevAlphaArg::Konst || ac.b == TevAlphaArg::Konst || |
| 1405 | ac.c == TevAlphaArg::Konst || ac.d == TevAlphaArg::Konst) |
| 1406 | { |
| 1407 | out.Write("\tkonsttemp = int4({}, {});\n", tev_ksel_table_c[stage.tevksel_kc], |
| 1408 | tev_ksel_table_a[stage.tevksel_ka]); |
| 1409 | |
| 1410 | if (u32(stage.tevksel_kc) > 7) |
| 1411 | { |
| 1412 | out.SetConstantsUsed(C_KCOLORS + ((u32(stage.tevksel_kc) - 0xc) % 4), |
| 1413 | C_KCOLORS + ((u32(stage.tevksel_kc) - 0xc) % 4)); |
| 1414 | } |
| 1415 | if (u32(stage.tevksel_ka) > 7) |
| 1416 | { |
| 1417 | out.SetConstantsUsed(C_KCOLORS + ((u32(stage.tevksel_ka) - 0xc) % 4), |
| 1418 | C_KCOLORS + ((u32(stage.tevksel_ka) - 0xc) % 4)); |
| 1419 | } |
| 1420 | } |
| 1421 | |
| 1422 | if (cc.d == TevColorArg::Color0 || cc.d == TevColorArg::Alpha0 || ac.d == TevAlphaArg::Alpha0) |
| 1423 | out.SetConstantsUsed(C_COLORS + 1, C_COLORS + 1); |
| 1424 | |
| 1425 | if (cc.d == TevColorArg::Color1 || cc.d == TevColorArg::Alpha1 || ac.d == TevAlphaArg::Alpha1) |
| 1426 | out.SetConstantsUsed(C_COLORS + 2, C_COLORS + 2); |
| 1427 | |
| 1428 | if (cc.d == TevColorArg::Color2 || cc.d == TevColorArg::Alpha2 || ac.d == TevAlphaArg::Alpha2) |
| 1429 | out.SetConstantsUsed(C_COLORS + 3, C_COLORS + 3); |
| 1430 | |
| 1431 | if (cc.dest >= TevOutput::Color0) |
| 1432 | out.SetConstantsUsed(C_COLORS + u32(cc.dest.Value()), C_COLORS + u32(cc.dest.Value())); |
| 1433 | |
| 1434 | if (ac.dest >= TevOutput::Color0) |
| 1435 | out.SetConstantsUsed(C_COLORS + u32(ac.dest.Value()), C_COLORS + u32(ac.dest.Value())); |
| 1436 | |
| 1437 | if (DriverDetails::HasBug(DriverDetails::BUG_BROKEN_VECTOR_BITWISE_AND)) |
| 1438 | { |
| 1439 | out.Write("\ttevin_a = int4({} & 255, {} & 255);\n", tev_c_input_table[cc.a], |
| 1440 | tev_a_input_table[ac.a]); |
| 1441 | out.Write("\ttevin_b = int4({} & 255, {} & 255);\n", tev_c_input_table[cc.b], |
| 1442 | tev_a_input_table[ac.b]); |
| 1443 | out.Write("\ttevin_c = int4({} & 255, {} & 255);\n", tev_c_input_table[cc.c], |
| 1444 | tev_a_input_table[ac.c]); |
| 1445 | } |
| 1446 | else |
| 1447 | { |
| 1448 | out.Write("\ttevin_a = int4({}, {})&int4(255, 255, 255, 255);\n", tev_c_input_table[cc.a], |
| 1449 | tev_a_input_table[ac.a]); |
| 1450 | out.Write("\ttevin_b = int4({}, {})&int4(255, 255, 255, 255);\n", tev_c_input_table[cc.b], |
| 1451 | tev_a_input_table[ac.b]); |
| 1452 | out.Write("\ttevin_c = int4({}, {})&int4(255, 255, 255, 255);\n", tev_c_input_table[cc.c], |
| 1453 | tev_a_input_table[ac.c]); |
| 1454 | } |
| 1455 | out.Write("\ttevin_d = int4({}, {});\n", tev_c_input_table[cc.d], tev_a_input_table[ac.d]); |
| 1456 | |
| 1457 | out.Write("\t// color combine\n"); |
| 1458 | out.Write("\t{} = clamp(", tev_c_output_table[cc.dest]); |
| 1459 | if (cc.bias != TevBias::Compare) |
| 1460 | { |
| 1461 | WriteTevRegular(out, "rgb", cc.bias, cc.op, cc.clamp, cc.scale); |
| 1462 | } |
| 1463 | else |
| 1464 | { |
| 1465 | static constexpr EnumMap<const char*, TevCompareMode::RGB8> tev_rgb_comparison_gt{ |
| 1466 | "((tevin_a.r > tevin_b.r) ? tevin_c.rgb : int3(0,0,0))", // TevCompareMode::R8 |
| 1467 | "((idot(tevin_a.rgb, comp16) > idot(tevin_b.rgb, comp16)) ? tevin_c.rgb : int3(0,0,0))", // GR16 |
| 1468 | "((idot(tevin_a.rgb, comp24) > idot(tevin_b.rgb, comp24)) ? tevin_c.rgb : int3(0,0,0))", // BGR24 |
| 1469 | "(max(sign(tevin_a.rgb - tevin_b.rgb), int3(0,0,0)) * tevin_c.rgb)", // RGB8 |
| 1470 | }; |
| 1471 | |
| 1472 | static constexpr EnumMap<const char*, TevCompareMode::RGB8> tev_rgb_comparison_eq{ |
| 1473 | "((tevin_a.r == tevin_b.r) ? tevin_c.rgb : int3(0,0,0))", // TevCompareMode::R8 |
| 1474 | "((idot(tevin_a.rgb,comp16) == idot(tevin_b.rgb,comp16)) ? tevin_c.rgb : int3(0,0,0))", // GR16 |
| 1475 | "((idot(tevin_a.rgb,comp24) == idot(tevin_b.rgb,comp24)) ? tevin_c.rgb : int3(0,0,0))", // BGR24 |
| 1476 | "((int3(1,1,1) - sign(abs(tevin_a.rgb - tevin_b.rgb))) * tevin_c.rgb)" // RGB8 |
| 1477 | }; |
| 1478 | |
| 1479 | if (cc.comparison == TevComparison::EQ) |
| 1480 | out.Write(" tevin_d.rgb + {}", tev_rgb_comparison_eq[cc.compare_mode]); |
| 1481 | else |
| 1482 | out.Write(" tevin_d.rgb + {}", tev_rgb_comparison_gt[cc.compare_mode]); |
| 1483 | } |
| 1484 | if (cc.clamp) |
| 1485 | out.Write(", int3(0,0,0), int3(255,255,255))"); |
| 1486 | else |
| 1487 | out.Write(", int3(-1024,-1024,-1024), int3(1023,1023,1023))"); |
| 1488 | out.Write(";\n"); |
| 1489 | |
| 1490 | out.Write("\t// alpha combine\n"); |
| 1491 | out.Write("\t{} = clamp(", tev_a_output_table[ac.dest]); |
| 1492 | if (ac.bias != TevBias::Compare) |
| 1493 | { |
| 1494 | WriteTevRegular(out, "a", ac.bias, ac.op, ac.clamp, ac.scale); |
| 1495 | } |
| 1496 | else |
| 1497 | { |
| 1498 | static constexpr EnumMap<const char*, TevCompareMode::A8> tev_a_comparison_gt{ |
| 1499 | "((tevin_a.r > tevin_b.r) ? tevin_c.a : 0)", // TevCompareMode::R8 |
| 1500 | "((idot(tevin_a.rgb, comp16) > idot(tevin_b.rgb, comp16)) ? tevin_c.a : 0)", // GR16 |
| 1501 | "((idot(tevin_a.rgb, comp24) > idot(tevin_b.rgb, comp24)) ? tevin_c.a : 0)", // BGR24 |
| 1502 | "((tevin_a.a > tevin_b.a) ? tevin_c.a : 0)", // A8 |
| 1503 | }; |
| 1504 | |
| 1505 | static constexpr EnumMap<const char*, TevCompareMode::A8> tev_a_comparison_eq{ |
| 1506 | "((tevin_a.r == tevin_b.r) ? tevin_c.a : 0)", // TevCompareMode::R8 |
| 1507 | "((idot(tevin_a.rgb, comp16) == idot(tevin_b.rgb, comp16)) ? tevin_c.a : 0)", // GR16, |
| 1508 | "((idot(tevin_a.rgb, comp24) == idot(tevin_b.rgb, comp24)) ? tevin_c.a : 0)", // BGR24, |
| 1509 | "((tevin_a.a == tevin_b.a) ? tevin_c.a : 0)", // A8 |
| 1510 | }; |
| 1511 | |
| 1512 | if (ac.comparison == TevComparison::EQ) |
| 1513 | out.Write(" tevin_d.a + {}", tev_a_comparison_eq[ac.compare_mode]); |
| 1514 | else |
| 1515 | out.Write(" tevin_d.a + {}", tev_a_comparison_gt[ac.compare_mode]); |
| 1516 | } |
| 1517 | if (ac.clamp) |
| 1518 | out.Write(", 0, 255)"); |
| 1519 | else |
| 1520 | out.Write(", -1024, 1023)"); |
| 1521 | |
| 1522 | out.Write(";\n"); |
| 1523 | } |
| 1524 | |
| 1525 | static void WriteTevRegular(ShaderCode& out, std::string_view components, TevBias bias, TevOp op, |
| 1526 | bool clamp, TevScale scale) |
| 1527 | { |
| 1528 | static constexpr Common::EnumMap<const char*, TevScale::Divide2> tev_scale_table_left{ |
| 1529 | "", // Scale1 |
| 1530 | " << 1", // Scale2 |
| 1531 | " << 2", // Scale4 |
| 1532 | "", // Divide2 |
| 1533 | }; |
| 1534 | |
| 1535 | static constexpr Common::EnumMap<const char*, TevScale::Divide2> tev_scale_table_right{ |
| 1536 | "", // Scale1 |
| 1537 | "", // Scale2 |
| 1538 | "", // Scale4 |
| 1539 | " >> 1", // Divide2 |
| 1540 | }; |
| 1541 | |
| 1542 | static constexpr Common::EnumMap<const char*, TevOp::Sub> tev_lerp_bias{ |
| 1543 | " + 128", |
| 1544 | " + 127", |
| 1545 | }; |
| 1546 | |
| 1547 | static constexpr Common::EnumMap<const char*, TevBias::Compare> tev_bias_table{ |
| 1548 | "", // Zero, |
| 1549 | " + 128", // AddHalf, |
| 1550 | " - 128", // SubHalf, |
| 1551 | "", |
| 1552 | }; |
| 1553 | |
| 1554 | static constexpr Common::EnumMap<char, TevOp::Sub> tev_op_table{ |
| 1555 | '+', // TevOp::Add = 0, |
| 1556 | '-', // TevOp::Sub = 1, |
| 1557 | }; |
| 1558 | |
| 1559 | // Regular TEV stage: (d + bias + lerp(a,b,c)) * scale |
| 1560 | // The GameCube/Wii GPU uses a very sophisticated algorithm for scale-lerping: |
| 1561 | // - c is scaled from 0..255 to 0..256, which allows dividing the result by 256 instead of 255 |
| 1562 | // - if scale is bigger than one, it is moved inside the lerp calculation for increased accuracy |
| 1563 | // - a rounding bias is added before dividing by 256 |
| 1564 | // TODO: Is the rounding bias still added when the scale is divide by 2? Currently we do not |
| 1565 | // apply it. |
| 1566 | out.Write("(((tevin_d.{}{}){})", components, tev_bias_table[bias], tev_scale_table_left[scale]); |
| 1567 | out.Write(" {} ", tev_op_table[op]); |
| 1568 | out.Write("(((((tevin_a.{0}<<8) + " |
| 1569 | "(tevin_b.{0}-tevin_a.{0})*(tevin_c.{0}+(tevin_c.{0}>>7))){1}){2})>>8)", |
| 1570 | components, tev_scale_table_left[scale], |
| 1571 | (scale != TevScale::Divide2) ? tev_lerp_bias[op] : ""); |
| 1572 | out.Write("){}", tev_scale_table_right[scale]); |
| 1573 | } |
| 1574 | |
| 1575 | constexpr Common::EnumMap<const char*, CompareMode::Always> tev_alpha_funcs_table{ |
| 1576 | "(false)", // CompareMode::Never |
| 1577 | "(prev.a < {})", // CompareMode::Less |
| 1578 | "(prev.a == {})", // CompareMode::Equal |
| 1579 | "(prev.a <= {})", // CompareMode::LEqual |
| 1580 | "(prev.a > {})", // CompareMode::Greater |
| 1581 | "(prev.a != {})", // CompareMode::NEqual |
| 1582 | "(prev.a >= {})", // CompareMode::GEqual |
| 1583 | "(true)" // CompareMode::Always |
| 1584 | }; |
| 1585 | |
| 1586 | constexpr Common::EnumMap<const char*, AlphaTestOp::Xnor> tev_alpha_funclogic_table{ |
| 1587 | " && ", // and |
| 1588 | " || ", // or |
| 1589 | " != ", // xor |
| 1590 | " == " // xnor |
| 1591 | }; |
| 1592 | |
| 1593 | static void WriteAlphaTest(ShaderCode& out, const pixel_shader_uid_data* uid_data, APIType api_type, |
| 1594 | bool per_pixel_depth, bool use_dual_source) |
| 1595 | { |
| 1596 | static constexpr std::array<std::string_view, 2> alpha_ref{ |
| 1597 | I_ALPHA ".r", |
| 1598 | I_ALPHA ".g", |
| 1599 | }; |
| 1600 | |
| 1601 | const auto write_alpha_func = [&out](CompareMode mode, std::string_view ref) { |
| 1602 | const bool has_no_arguments = mode == CompareMode::Never || mode == CompareMode::Always; |
| 1603 | if (has_no_arguments) |
| 1604 | out.Write("{}", tev_alpha_funcs_table[mode]); |
| 1605 | else |
| 1606 | out.Write(fmt::runtime(tev_alpha_funcs_table[mode]), ref); |
| 1607 | }; |
| 1608 | |
| 1609 | out.SetConstantsUsed(C_ALPHA, C_ALPHA); |
| 1610 | |
| 1611 | if (DriverDetails::HasBug(DriverDetails::BUG_BROKEN_NEGATED_BOOLEAN)) |
| 1612 | out.Write("\tif(( "); |
| 1613 | else |
| 1614 | out.Write("\tif(!( "); |
| 1615 | |
| 1616 | // Lookup the first component from the alpha function table |
| 1617 | write_alpha_func(uid_data->alpha_test_comp0, alpha_ref[0]); |
| 1618 | |
| 1619 | // Lookup the logic op |
| 1620 | out.Write("{}", tev_alpha_funclogic_table[uid_data->alpha_test_logic]); |
| 1621 | |
| 1622 | // Lookup the second component from the alpha function table |
| 1623 | write_alpha_func(uid_data->alpha_test_comp1, alpha_ref[1]); |
| 1624 | |
| 1625 | if (DriverDetails::HasBug(DriverDetails::BUG_BROKEN_NEGATED_BOOLEAN)) |
| 1626 | out.Write(") == false) {{\n"); |
| 1627 | else |
| 1628 | out.Write(")) {{\n"); |
| 1629 | |
| 1630 | if (uid_data->uint_output) |
| 1631 | out.Write("\t\tocol0 = uint4(0, 0, 0, 0);\n"); |
| 1632 | else |
| 1633 | out.Write("\t\tocol0 = float4(0.0, 0.0, 0.0, 0.0);\n"); |
| 1634 | if (use_dual_source) |
| 1635 | { |
| 1636 | if (uid_data->uint_output) |
| 1637 | out.Write("\t\tocol1 = uint4(0, 0, 0, 0);\n"); |
| 1638 | else |
| 1639 | out.Write("\t\tocol1 = float4(0.0, 0.0, 0.0, 0.0);\n"); |
| 1640 | } |
| 1641 | if (per_pixel_depth) |
| 1642 | { |
| 1643 | out.Write("\t\tdepth = {};\n", !g_backend_info.bSupportsReversedDepthRange ? "0.0" : "1.0"); |
| 1644 | } |
| 1645 | |
| 1646 | // ZCOMPLOC HACK: |
| 1647 | if (uid_data->ztest != EmulatedZ::EarlyWithZComplocHack) |
| 1648 | { |
| 1649 | #ifdef __APPLE__ |
| 1650 | if (uid_data->ztest == EmulatedZ::EarlyWithFBFetch) |
| 1651 | { |
| 1652 | // Instead of using discard, fetch the framebuffer's color value and use it as the output |
| 1653 | // for this fragment. |
| 1654 | out.Write("\t\t{} = float4(initial_ocol0.xyz, 1.0);\n", |
| 1655 | use_dual_source ? "real_ocol0" : "ocol0"); |
| 1656 | out.Write("\t\treturn;\n"); |
| 1657 | } |
| 1658 | else |
| 1659 | #endif |
| 1660 | { |
| 1661 | out.Write("\t\tdiscard;\n"); |
| 1662 | if (api_type == APIType::D3D) |
| 1663 | out.Write("\t\treturn;\n"); |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | out.Write("\t}}\n"); |
| 1668 | } |
| 1669 | |
| 1670 | constexpr Common::EnumMap<const char*, FogType::BackwardsExpSq> tev_fog_funcs_table{ |
| 1671 | "", // No Fog |
| 1672 | "", // ? |
| 1673 | "", // Linear |
| 1674 | "", // ? |
| 1675 | "\tfog = 1.0 - exp2(-8.0 * fog);\n", // exp |
| 1676 | "\tfog = 1.0 - exp2(-8.0 * fog * fog);\n", // exp2 |
| 1677 | "\tfog = exp2(-8.0 * (1.0 - fog));\n", // backward exp |
| 1678 | "\tfog = 1.0 - fog;\n fog = exp2(-8.0 * fog * fog);\n" // backward exp2 |
| 1679 | }; |
| 1680 | |
| 1681 | static void WriteFog(ShaderCode& out, const pixel_shader_uid_data* uid_data) |
| 1682 | { |
| 1683 | if (uid_data->fog_fsel == FogType::Off) |
| 1684 | return; // no Fog |
| 1685 | |
| 1686 | out.SetConstantsUsed(C_FOGCOLOR, C_FOGCOLOR); |
| 1687 | out.SetConstantsUsed(C_FOGI, C_FOGI); |
| 1688 | out.SetConstantsUsed(C_FOGF, C_FOGF + 1); |
| 1689 | if (uid_data->fog_proj == FogProjection::Perspective) |
| 1690 | { |
| 1691 | // perspective |
| 1692 | // ze = A/(B - (Zs >> B_SHF) |
| 1693 | // TODO: Verify that we want to drop lower bits here! (currently taken over from software |
| 1694 | // renderer) |
| 1695 | // Maybe we want to use "ze = (A << B_SHF)/((B << B_SHF) - Zs)" instead? |
| 1696 | // That's equivalent, but keeps the lower bits of Zs. |
| 1697 | out.Write("\tfloat ze = (" I_FOGF ".x * 16777216.0) / float(" I_FOGI ".y - (zCoord >> " I_FOGI |
| 1698 | ".w));\n"); |
| 1699 | } |
| 1700 | else |
| 1701 | { |
| 1702 | // orthographic |
| 1703 | // ze = a*Zs (here, no B_SHF) |
| 1704 | out.Write("\tfloat ze = " I_FOGF ".x * float(zCoord) / 16777216.0;\n"); |
| 1705 | } |
| 1706 | |
| 1707 | // x_adjust = sqrt((x-center)^2 + k^2)/k |
| 1708 | // ze *= x_adjust |
| 1709 | if (uid_data->fog_RangeBaseEnabled) |
| 1710 | { |
| 1711 | out.SetConstantsUsed(C_FOGF, C_FOGF); |
| 1712 | out.Write("\tfloat offset = (2.0 * (rawpos.x / " I_FOGF ".w)) - 1.0 - " I_FOGF ".z;\n" |
| 1713 | "\tfloat floatindex = clamp(9.0 - abs(offset) * 9.0, 0.0, 9.0);\n" |
| 1714 | "\tuint indexlower = uint(floatindex);\n" |
| 1715 | "\tuint indexupper = indexlower + 1u;\n" |
| 1716 | "\tfloat klower = " I_FOGRANGE "[indexlower >> 2u][indexlower & 3u];\n" |
| 1717 | "\tfloat kupper = " I_FOGRANGE "[indexupper >> 2u][indexupper & 3u];\n" |
| 1718 | "\tfloat k = lerp(klower, kupper, frac(floatindex));\n" |
| 1719 | "\tfloat x_adjust = sqrt(offset * offset + k * k) / k;\n" |
| 1720 | "\tze *= x_adjust;\n"); |
| 1721 | } |
| 1722 | |
| 1723 | out.Write("\tfloat fog = clamp(ze - " I_FOGF ".y, 0.0, 1.0);\n"); |
| 1724 | |
| 1725 | if (uid_data->fog_fsel >= FogType::Exp) |
| 1726 | { |
| 1727 | out.Write("{}", tev_fog_funcs_table[uid_data->fog_fsel]); |
| 1728 | } |
| 1729 | else |
| 1730 | { |
| 1731 | if (uid_data->fog_fsel != FogType::Linear) |
| 1732 | WARN_LOG_FMT(VIDEO, "Unknown Fog Type! {}", uid_data->fog_fsel); |
| 1733 | } |
| 1734 | |
| 1735 | out.Write("\tint ifog = iround(fog * 256.0);\n"); |
| 1736 | out.Write("\tprev.rgb = (prev.rgb * (256 - ifog) + " I_FOGCOLOR ".rgb * ifog) >> 8;\n"); |
| 1737 | } |
| 1738 | |
| 1739 | static void WriteLogicOp(ShaderCode& out, const pixel_shader_uid_data* uid_data) |
| 1740 | { |
| 1741 | static constexpr std::array<const char*, 16> logic_op_mode{ |
| 1742 | "int4(0, 0, 0, 0)", // CLEAR |
| 1743 | "prev & fb_value", // AND |
| 1744 | "prev & ~fb_value", // AND_REVERSE |
| 1745 | "prev", // COPY |
| 1746 | "~prev & fb_value", // AND_INVERTED |
| 1747 | "fb_value", // NOOP |
| 1748 | "prev ^ fb_value", // XOR |
| 1749 | "prev | fb_value", // OR |
| 1750 | "~(prev | fb_value)", // NOR |
| 1751 | "~(prev ^ fb_value)", // EQUIV |
| 1752 | "~fb_value", // INVERT |
| 1753 | "prev | ~fb_value", // OR_REVERSE |
| 1754 | "~prev", // COPY_INVERTED |
| 1755 | "~prev | fb_value", // OR_INVERTED |
| 1756 | "~(prev & fb_value)", // NAND |
| 1757 | "int4(255, 255, 255, 255)", // SET |
| 1758 | }; |
| 1759 | |
| 1760 | out.Write("\tint4 fb_value = iround(initial_ocol0 * 255.0);\n"); |
| 1761 | out.Write("\tprev = ({}) & 0xff;\n", logic_op_mode[uid_data->logic_op_mode]); |
| 1762 | } |
| 1763 | |
| 1764 | static void WriteLogicOpBlend(ShaderCode& out, const pixel_shader_uid_data* uid_data) |
| 1765 | { |
| 1766 | switch (static_cast<LogicOp>(uid_data->logic_op_mode)) |
| 1767 | { |
| 1768 | case LogicOp::Clear: |
| 1769 | case LogicOp::NoOp: |
| 1770 | out.Write("\tprev = int4(0, 0, 0, 0);\n"); |
| 1771 | break; |
| 1772 | case LogicOp::Copy: |
| 1773 | // Do nothing! |
| 1774 | break; |
| 1775 | case LogicOp::CopyInverted: |
| 1776 | out.Write("\tprev ^= 255;\n"); |
| 1777 | break; |
| 1778 | case LogicOp::Set: |
| 1779 | case LogicOp::Invert: // In cooperation with blend |
| 1780 | out.Write("\tprev = int4(255, 255, 255, 255);\n"); |
| 1781 | break; |
| 1782 | default: |
| 1783 | break; |
| 1784 | } |
| 1785 | } |
| 1786 | |
| 1787 | static void WriteColor(ShaderCode& out, APIType api_type, const pixel_shader_uid_data* uid_data, |
| 1788 | bool use_dual_source) |
| 1789 | { |
| 1790 | // Some backends require the shader outputs be uint when writing to a uint render target for logic |
| 1791 | // op. |
| 1792 | if (uid_data->uint_output) |
| 1793 | { |
| 1794 | if (uid_data->rgba6_format) |
| 1795 | out.Write("\tocol0 = uint4(prev & 0xFC);\n"); |
| 1796 | else |
| 1797 | out.Write("\tocol0 = uint4(prev);\n"); |
| 1798 | return; |
| 1799 | } |
| 1800 | |
| 1801 | if (uid_data->rgba6_format) |
| 1802 | out.Write("\tocol0.rgb = float3(prev.rgb >> 2) / 63.0;\n"); |
| 1803 | else |
| 1804 | out.Write("\tocol0.rgb = float3(prev.rgb) / 255.0;\n"); |
| 1805 | |
| 1806 | // Colors will be blended against the 8-bit alpha from ocol1 and |
| 1807 | // the 6-bit alpha from ocol0 will be written to the framebuffer |
| 1808 | if (uid_data->useDstAlpha) |
| 1809 | { |
| 1810 | out.SetConstantsUsed(C_ALPHA, C_ALPHA); |
| 1811 | out.Write("\tocol0.a = float(" I_ALPHA ".a >> 2) / 63.0;\n"); |
| 1812 | |
| 1813 | // Use dual-source color blending to perform dst alpha in a single pass |
| 1814 | if (use_dual_source) |
| 1815 | out.Write("\tocol1 = float4(0.0, 0.0, 0.0, float(prev.a) / 255.0);\n"); |
| 1816 | } |
| 1817 | else |
| 1818 | { |
| 1819 | out.Write("\tocol0.a = float(prev.a >> 2) / 63.0;\n"); |
| 1820 | if (use_dual_source) |
| 1821 | out.Write("\tocol1 = float4(0.0, 0.0, 0.0, float(prev.a) / 255.0);\n"); |
| 1822 | } |
| 1823 | } |
| 1824 | |
| 1825 | static void WriteBlend(ShaderCode& out, const pixel_shader_uid_data* uid_data) |
| 1826 | { |
| 1827 | if (uid_data->blend_enable) |
| 1828 | { |
| 1829 | using Common::EnumMap; |
| 1830 | static constexpr EnumMap<const char*, SrcBlendFactor::InvDstAlpha> blend_src_factor{ |
| 1831 | "float3(0,0,0);", // ZERO |
| 1832 | "float3(1,1,1);", // ONE |
| 1833 | "initial_ocol0.rgb;", // DSTCLR |
| 1834 | "float3(1,1,1) - initial_ocol0.rgb;", // INVDSTCLR |
| 1835 | "src_color.aaa;", // SRCALPHA |
| 1836 | "float3(1,1,1) - src_color.aaa;", // INVSRCALPHA |
| 1837 | "initial_ocol0.aaa;", // DSTALPHA |
| 1838 | "float3(1,1,1) - initial_ocol0.aaa;", // INVDSTALPHA |
| 1839 | }; |
| 1840 | static constexpr EnumMap<const char*, SrcBlendFactor::InvDstAlpha> blend_src_factor_alpha{ |
| 1841 | "0.0;", // ZERO |
| 1842 | "1.0;", // ONE |
| 1843 | "initial_ocol0.a;", // DSTCLR |
| 1844 | "1.0 - initial_ocol0.a;", // INVDSTCLR |
| 1845 | "src_color.a;", // SRCALPHA |
| 1846 | "1.0 - src_color.a;", // INVSRCALPHA |
| 1847 | "initial_ocol0.a;", // DSTALPHA |
| 1848 | "1.0 - initial_ocol0.a;", // INVDSTALPHA |
| 1849 | }; |
| 1850 | static constexpr EnumMap<const char*, DstBlendFactor::InvDstAlpha> blend_dst_factor{ |
| 1851 | "float3(0,0,0);", // ZERO |
| 1852 | "float3(1,1,1);", // ONE |
| 1853 | "ocol0.rgb;", // SRCCLR |
| 1854 | "float3(1,1,1) - ocol0.rgb;", // INVSRCCLR |
| 1855 | "src_color.aaa;", // SRCALHA |
| 1856 | "float3(1,1,1) - src_color.aaa;", // INVSRCALPHA |
| 1857 | "initial_ocol0.aaa;", // DSTALPHA |
| 1858 | "float3(1,1,1) - initial_ocol0.aaa;", // INVDSTALPHA |
| 1859 | }; |
| 1860 | static constexpr EnumMap<const char*, DstBlendFactor::InvDstAlpha> blend_dst_factor_alpha{ |
| 1861 | "0.0;", // ZERO |
| 1862 | "1.0;", // ONE |
| 1863 | "ocol0.a;", // SRCCLR |
| 1864 | "1.0 - ocol0.a;", // INVSRCCLR |
| 1865 | "src_color.a;", // SRCALPHA |
| 1866 | "1.0 - src_color.a;", // INVSRCALPHA |
| 1867 | "initial_ocol0.a;", // DSTALPHA |
| 1868 | "1.0 - initial_ocol0.a;", // INVDSTALPHA |
| 1869 | }; |
| 1870 | out.Write("\tfloat4 src_color = {};\n" |
| 1871 | "\tfloat4 blend_src;", |
| 1872 | uid_data->useDstAlpha ? "ocol1" : "ocol0"); |
| 1873 | out.Write("\tblend_src.rgb = {}\n", blend_src_factor[uid_data->blend_src_factor]); |
| 1874 | out.Write("\tblend_src.a = {}\n", blend_src_factor_alpha[uid_data->blend_src_factor_alpha]); |
| 1875 | out.Write("\tfloat4 blend_dst;\n"); |
| 1876 | out.Write("\tblend_dst.rgb = {}\n", blend_dst_factor[uid_data->blend_dst_factor]); |
| 1877 | out.Write("\tblend_dst.a = {}\n", blend_dst_factor_alpha[uid_data->blend_dst_factor_alpha]); |
| 1878 | |
| 1879 | out.Write("\tfloat4 blend_result;\n"); |
| 1880 | if (uid_data->blend_subtract) |
| 1881 | { |
| 1882 | out.Write("\tblend_result.rgb = initial_ocol0.rgb * blend_dst.rgb - ocol0.rgb * " |
| 1883 | "blend_src.rgb;\n"); |
| 1884 | } |
| 1885 | else |
| 1886 | { |
| 1887 | out.Write( |
| 1888 | "\tblend_result.rgb = initial_ocol0.rgb * blend_dst.rgb + ocol0.rgb * blend_src.rgb;\n"); |
| 1889 | } |
| 1890 | |
| 1891 | if (uid_data->blend_subtract_alpha) |
| 1892 | out.Write("\tblend_result.a = initial_ocol0.a * blend_dst.a - ocol0.a * blend_src.a;\n"); |
| 1893 | else |
| 1894 | out.Write("\tblend_result.a = initial_ocol0.a * blend_dst.a + ocol0.a * blend_src.a;\n"); |
| 1895 | } |
| 1896 | else |
| 1897 | { |
| 1898 | out.Write("\tfloat4 blend_result = ocol0;\n"); |
| 1899 | } |
| 1900 | |
| 1901 | out.Write("\treal_ocol0 = blend_result;\n"); |
| 1902 | } |
| 1903 | |
| 1904 | void WriteFragmentBody(APIType api_type, const ShaderHostConfig& host_config, |
| 1905 | const pixel_shader_uid_data* uid_data, ShaderCode& out) |
| 1906 | { |
| 1907 | const bool per_pixel_lighting = host_config.per_pixel_lighting; |
| 1908 | const bool stereo = host_config.stereo; |
| 1909 | const u32 numStages = uid_data->genMode_numtevstages + 1; |
| 1910 | |
| 1911 | out.Write("\tvec4 col0 = frag_input.color_0;\n"); |
| 1912 | out.Write("\tvec4 col1 = frag_input.color_1;\n"); |
| 1913 | out.Write("\tint layer = frag_input.layer;\n"); |
| 1914 | |
| 1915 | out.Write("\tint4 c0 = " I_COLORS "[1], c1 = " I_COLORS "[2], c2 = " I_COLORS |
| 1916 | "[3], prev = " I_COLORS "[0];\n" |
| 1917 | "\tint4 rastemp = int4(0, 0, 0, 0), rawtextemp = int4(0, 0, 0, 0), " |
| 1918 | "textemp = int4(0, 0, 0, 0), konsttemp = int4(0, 0, 0, 0);\n" |
| 1919 | "\tint3 comp16 = int3(1, 256, 0), comp24 = int3(1, 256, 256*256);\n" |
| 1920 | "\tint alphabump=0;\n" |
| 1921 | "\tint3 tevcoord=int3(0, 0, 0);\n" |
| 1922 | "\tint2 wrappedcoord=int2(0,0), tempcoord=int2(0,0);\n" |
| 1923 | "\tint4 " |
| 1924 | "tevin_a=int4(0,0,0,0),tevin_b=int4(0,0,0,0),tevin_c=int4(0,0,0,0),tevin_d=int4(0,0,0," |
| 1925 | "0);\n\n"); // tev combiner inputs |
| 1926 | |
| 1927 | if (per_pixel_lighting) |
| 1928 | { |
| 1929 | if (uid_data->numColorChans > 0) |
| 1930 | { |
| 1931 | out.Write("\tcol0 = dolphin_calculate_lighting_chn0(col0, frag_input.position, " |
| 1932 | "frag_input.normal);\n"); |
| 1933 | } |
| 1934 | else |
| 1935 | { |
| 1936 | // The number of colors available to TEV is determined by numColorChans. |
| 1937 | // We have to provide the fields to match the interface, so set to zero if it's not enabled. |
| 1938 | out.Write("\tcol0 = vec4(0.0, 0.0, 0.0, 0.0);\n"); |
| 1939 | } |
| 1940 | |
| 1941 | if (uid_data->numColorChans == 2) |
| 1942 | { |
| 1943 | out.Write("\tcol1 = dolphin_calculate_lighting_chn1(col1, frag_input.position, " |
| 1944 | "frag_input.normal);\n"); |
| 1945 | } |
| 1946 | else |
| 1947 | { |
| 1948 | // The number of colors available to TEV is determined by numColorChans. |
| 1949 | // We have to provide the fields to match the interface, so set to zero if it's not enabled. |
| 1950 | out.Write("\tcol1 = vec4(0.0, 0.0, 0.0, 0.0);\n"); |
| 1951 | } |
| 1952 | } |
| 1953 | |
| 1954 | if (uid_data->genMode_numtexgens == 0) |
| 1955 | { |
| 1956 | // TODO: This is a hack to ensure that shaders still compile when setting out of bounds tex |
| 1957 | // coord indices to 0. Ideally, it shouldn't exist at all, but the exact behavior hasn't been |
| 1958 | // tested. |
| 1959 | out.Write("\tint2 fixpoint_uv0 = int2(0, 0);\n\n"); |
| 1960 | } |
| 1961 | else |
| 1962 | { |
| 1963 | out.SetConstantsUsed(C_TEXDIMS, C_TEXDIMS + uid_data->genMode_numtexgens - 1); |
| 1964 | for (u32 i = 0; i < uid_data->genMode_numtexgens; ++i) |
| 1965 | { |
| 1966 | out.Write("\tint2 fixpoint_uv{} = int2(", i); |
| 1967 | out.Write("(frag_input.tex{}.z == 0.0 ? frag_input.tex{}.xy : frag_input.tex{}.xy / " |
| 1968 | "frag_input.tex{}.z)", |
| 1969 | i, i, i, i); |
| 1970 | out.Write(" * float2(" I_TEXDIMS "[{}].zw * 128));\n", i); |
| 1971 | // TODO: S24 overflows here? |
| 1972 | } |
| 1973 | } |
| 1974 | |
| 1975 | for (u32 i = 0; i < uid_data->genMode_numindstages; ++i) |
| 1976 | { |
| 1977 | if ((uid_data->nIndirectStagesUsed & (1U << i)) != 0) |
| 1978 | { |
| 1979 | u32 texcoord = uid_data->GetTevindirefCoord(i); |
| 1980 | const u32 texmap = uid_data->GetTevindirefMap(i); |
| 1981 | |
| 1982 | // Quirk: when the tex coord is not less than the number of tex gens (i.e. the tex coord |
| 1983 | // does not exist), then tex coord 0 is used (though sometimes glitchy effects happen on |
| 1984 | // console). This affects the Mario portrait in Luigi's Mansion, where the developers forgot |
| 1985 | // to set the number of tex gens to 2 (bug 11462). |
| 1986 | if (texcoord >= uid_data->genMode_numtexgens) |
| 1987 | texcoord = 0; |
| 1988 | |
| 1989 | out.SetConstantsUsed(C_INDTEXSCALE + i / 2, C_INDTEXSCALE + i / 2); |
| 1990 | out.Write("\ttempcoord = fixpoint_uv{} >> " I_INDTEXSCALE "[{}].{};\n", texcoord, i / 2, |
| 1991 | (i & 1) ? "zw" : "xy"); |
| 1992 | |
| 1993 | out.Write("\tint3 iindtex{0} = sampleTextureWrapper({1}u, tempcoord, layer).abg;\n", i, |
| 1994 | texmap); |
| 1995 | } |
| 1996 | } |
| 1997 | |
| 1998 | for (u32 i = 0; i < numStages; i++) |
| 1999 | { |
| 2000 | // Build the equation for this stage |
| 2001 | WriteStage(out, uid_data, i, api_type, stereo); |
| 2002 | } |
| 2003 | |
| 2004 | { |
| 2005 | // The results of the last texenv stage are put onto the screen, |
| 2006 | // regardless of the used destination register |
| 2007 | TevStageCombiner::ColorCombiner last_cc; |
| 2008 | TevStageCombiner::AlphaCombiner last_ac; |
| 2009 | last_cc.hex = uid_data->stagehash[uid_data->genMode_numtevstages].cc; |
| 2010 | last_ac.hex = uid_data->stagehash[uid_data->genMode_numtevstages].ac; |
| 2011 | if (last_cc.dest != TevOutput::Prev) |
| 2012 | { |
| 2013 | out.Write("\tprev.rgb = {};\n", tev_c_output_table[last_cc.dest]); |
| 2014 | } |
| 2015 | if (last_ac.dest != TevOutput::Prev) |
| 2016 | { |
| 2017 | out.Write("\tprev.a = {};\n", tev_a_output_table[last_ac.dest]); |
| 2018 | } |
| 2019 | } |
| 2020 | |
| 2021 | out.Write("\tfrag_output.last_texture = rawtextemp;\n"); |
| 2022 | out.Write("\tfrag_output.main = prev;\n"); |
| 2023 | } |
| 2024 | |
| 2025 | static void WriteFragmentDefinitions(APIType api_type, const ShaderHostConfig& host_config, |
| 2026 | const pixel_shader_uid_data* uid_data, ShaderCode& out) |
| 2027 | { |
| 2028 | out.Write("struct DolphinLightData\n"); |
| 2029 | out.Write("{{\n"); |
| 2030 | out.Write("\tfloat3 position;\n"); |
| 2031 | out.Write("\tfloat3 direction;\n"); |
| 2032 | out.Write("\tfloat3 color;\n"); |
| 2033 | out.Write("\tuint attenuation_type;\n"); |
| 2034 | out.Write("\tfloat4 cosatt;\n"); |
| 2035 | out.Write("\tfloat4 distatt;\n"); |
| 2036 | out.Write("}};\n\n"); |
| 2037 | |
| 2038 | out.Write("struct DolphinFragmentInput\n"); |
| 2039 | out.Write("{{\n"); |
| 2040 | out.Write("\tvec4 color_0;\n"); |
| 2041 | out.Write("\tvec4 color_1;\n"); |
| 2042 | out.Write("\tint layer;\n"); |
| 2043 | out.Write("\tvec3 normal;\n"); |
| 2044 | out.Write("\tvec3 position;\n"); |
| 2045 | for (u32 i = 0; i < 8; i++) |
| 2046 | { |
| 2047 | out.Write("\tvec3 tex{};\n", i); |
| 2048 | } |
| 2049 | out.Write("\n"); |
| 2050 | |
| 2051 | out.Write("\tDolphinLightData[8] lights_chan0_color;\n"); |
| 2052 | out.Write("\tDolphinLightData[8] lights_chan0_alpha;\n"); |
| 2053 | out.Write("\tDolphinLightData[8] lights_chan1_color;\n"); |
| 2054 | out.Write("\tDolphinLightData[8] lights_chan1_alpha;\n"); |
| 2055 | out.Write("\tfloat4[2] ambient_lighting;\n"); |
| 2056 | out.Write("\tfloat4[2] base_material;\n"); |
| 2057 | out.Write("\tuint light_chan0_color_count;\n"); |
| 2058 | out.Write("\tuint light_chan0_alpha_count;\n"); |
| 2059 | out.Write("\tuint light_chan1_color_count;\n"); |
| 2060 | out.Write("\tuint light_chan1_alpha_count;\n"); |
| 2061 | |
| 2062 | out.Write("}};\n\n"); |
| 2063 | |
| 2064 | out.Write("struct DolphinFragmentOutput\n"); |
| 2065 | out.Write("{{\n"); |
| 2066 | out.Write("\tivec4 main;\n"); |
| 2067 | out.Write("\tivec4 last_texture;\n"); |
| 2068 | out.Write("}};\n\n"); |
| 2069 | |
| 2070 | // CUSTOM_SHADER_LIGHTING_ATTENUATION_TYPE "enum" values |
| 2071 | out.Write("const uint CUSTOM_SHADER_LIGHTING_ATTENUATION_TYPE_NONE = {}u;\n", |
| 2072 | static_cast<u32>(AttenuationFunc::None)); |
| 2073 | out.Write("const uint CUSTOM_SHADER_LIGHTING_ATTENUATION_TYPE_POINT = {}u;\n", |
| 2074 | static_cast<u32>(AttenuationFunc::Spec)); |
| 2075 | out.Write("const uint CUSTOM_SHADER_LIGHTING_ATTENUATION_TYPE_DIR = {}u;\n", |
| 2076 | static_cast<u32>(AttenuationFunc::Dir)); |
| 2077 | out.Write("const uint CUSTOM_SHADER_LIGHTING_ATTENUATION_TYPE_SPOT = {}u;\n", |
| 2078 | static_cast<u32>(AttenuationFunc::Spot)); |
| 2079 | } |
| 2080 | |
| 2081 | static void WriteEmulatedFragmentBodyHeader(APIType api_type, const ShaderHostConfig& host_config, |
| 2082 | const pixel_shader_uid_data* uid_data, ShaderCode& out) |
| 2083 | { |
| 2084 | constexpr std::string_view emulated_fragment_definition = |
| 2085 | "void dolphin_process_emulated_fragment(in DolphinFragmentInput frag_input, out " |
| 2086 | "DolphinFragmentOutput frag_output)"; |
| 2087 | out.Write("{}\n", emulated_fragment_definition); |
| 2088 | out.Write("{{\n"); |
| 2089 | |
| 2090 | WriteFragmentBody(api_type, host_config, uid_data, out); |
| 2091 | |
| 2092 | out.Write("}}\n"); |
| 2093 | } |