Debian Codegraph @

Source/Core/VideoCommon/UberShaderPixel.cpp

raw symbols SCIP
1 // Copyright 2015 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/UberShaderPixel.h"
5
6 #include "Common/Assert.h"
7
8 #include "VideoCommon/BPMemory.h"
9 #include "VideoCommon/DriverDetails.h"
10 #include "VideoCommon/PixelShaderGen.h"
11 #include "VideoCommon/ShaderGenCommon.h"
12 #include "VideoCommon/UberShaderCommon.h"
13 #include "VideoCommon/VideoCommon.h"
14 #include "VideoCommon/VideoConfig.h"
15 #include "VideoCommon/XFMemory.h"
16
17 namespace UberShader
18 {
19 PixelShaderUid GetPixelShaderUid()
20 {
21 PixelShaderUid out;
22
23 pixel_ubershader_uid_data* const uid_data = out.GetUidData();
24 uid_data->num_texgens = xfmem.numTexGen.numTexGens;
25 uid_data->early_depth = bpmem.GetEmulatedZ() == EmulatedZ::Early &&
26 (g_ActiveConfig.bFastDepthCalc ||
27 bpmem.alpha_test.TestResult() == AlphaTestResult::Undetermined) &&
28 !(bpmem.zmode.test_enable && bpmem.genMode.zfreeze);
29 uid_data->per_pixel_depth =
30 (bpmem.ztex2.op != ZTexOp::Disabled && bpmem.GetEmulatedZ() == EmulatedZ::Late) ||
31 (!g_ActiveConfig.bFastDepthCalc && bpmem.zmode.test_enable && !uid_data->early_depth) ||
32 (bpmem.zmode.test_enable && bpmem.genMode.zfreeze);
33 uid_data->uint_output = bpmem.blendmode.UseLogicOp();
34
35 return out;
36 }
37
38 void ClearUnusedPixelShaderUidBits(APIType api_type, const ShaderHostConfig& host_config,
39 PixelShaderUid* uid)
40 {
41 pixel_ubershader_uid_data* const uid_data = uid->GetUidData();
42
43 // With fbfetch, ubershaders always blend using that and don't use dual src
44 if (host_config.backend_shader_framebuffer_fetch || !host_config.backend_dual_source_blend)
45 uid_data->no_dual_src = 1;
46 // Dual source is always enabled in the shader if this bug is not present
47 else if (!DriverDetails::HasBug(DriverDetails::BUG_BROKEN_DUAL_SOURCE_BLENDING))
48 uid_data->no_dual_src = 0;
49
50 // OpenGL and Vulkan convert implicitly normalized color outputs to their uint representation.
51 // Therefore, it is not necessary to use a uint output on these backends. We also disable the
52 // uint output when logic op is not supported (i.e. driver/device does not support D3D11.1).
53 if (api_type != APIType::D3D || !host_config.backend_logic_op)
54 uid_data->uint_output = 0;
55 }
56
57 ShaderCode GenPixelShader(APIType api_type, const ShaderHostConfig& host_config,
58 const pixel_ubershader_uid_data* uid_data)
59 {
60 const bool per_pixel_lighting = host_config.per_pixel_lighting;
61 const bool msaa = host_config.msaa;
62 const bool ssaa = host_config.ssaa;
63 const bool stereo = host_config.stereo;
64 const bool use_framebuffer_fetch = host_config.backend_shader_framebuffer_fetch;
65 const bool use_dual_source = host_config.backend_dual_source_blend && !uid_data->no_dual_src;
66 const bool early_depth = uid_data->early_depth != 0;
67 const bool per_pixel_depth = uid_data->per_pixel_depth != 0;
68 const bool bounding_box = host_config.bounding_box;
69 const u32 numTexgen = uid_data->num_texgens;
70 ShaderCode out;
71
72 ASSERT_MSG(VIDEO, !(use_dual_source && use_framebuffer_fetch),
73 "If you're using framebuffer fetch, you shouldn't need dual source blend!");
74
75 out.Write("// {}\n", *uid_data);
76 WriteBitfieldExtractHeader(out, api_type, host_config);
77 WritePixelShaderCommonHeader(out, api_type, host_config, bounding_box);
78 if (per_pixel_lighting)
79 WriteLightingFunction(out);
80
81 #ifdef __APPLE__
82 // Framebuffer fetch is only supported by Metal, so ensure that we're running Vulkan (MoltenVK)
83 // if we want to use it.
84 if (api_type == APIType::Vulkan || api_type == APIType::Metal)
85 {
86 if (use_dual_source)
87 {
88 out.Write("FRAGMENT_OUTPUT_LOCATION_INDEXED(0, 0) out vec4 ocol0;\n"
89 "FRAGMENT_OUTPUT_LOCATION_INDEXED(0, 1) out vec4 ocol1;\n");
90 }
91 else
92 {
93 // Metal doesn't support a single unified variable for both input and output,
94 // so when using framebuffer fetch, we declare the input separately below.
95 out.Write("FRAGMENT_OUTPUT_LOCATION(0) out vec4 {};\n",
96 use_framebuffer_fetch ? "real_ocol0" : "ocol0");
97 }
98
99 if (use_framebuffer_fetch)
100 {
101 // Subpass inputs will be converted to framebuffer fetch by SPIRV-Cross.
102 out.Write("INPUT_ATTACHMENT_BINDING(0, 0, 0) uniform subpassInput in_ocol0;\n");
103 }
104 }
105 else
106 #endif
107 {
108 if (use_framebuffer_fetch)
109 {
110 out.Write("FRAGMENT_OUTPUT_LOCATION(0) FRAGMENT_INOUT vec4 real_ocol0;\n");
111 }
112 else
113 {
114 out.Write("FRAGMENT_OUTPUT_LOCATION_INDEXED(0, 0) out {} ocol0;\n",
115 uid_data->uint_output ? "uvec4" : "vec4");
116 }
117
118 if (use_dual_source)
119 {
120 out.Write("{} out {} ocol1;\n", "FRAGMENT_OUTPUT_LOCATION_INDEXED(0, 1)",
121 uid_data->uint_output ? "uvec4" : "vec4");
122 }
123 }
124
125 if (per_pixel_depth)
126 out.Write("#define depth gl_FragDepth\n");
127
128 if (host_config.backend_geometry_shaders)
129 {
130 out.Write("VARYING_LOCATION(0) in VertexData {{\n");
131 GenerateVSOutputMembers(out, api_type, numTexgen, host_config,
132 GetInterpolationQualifier(msaa, ssaa, true, true), ShaderStage::Pixel);
133
134 out.Write("}};\n\n");
135 if (stereo && !host_config.backend_gl_layer_in_fs)
136 out.Write("flat in int layer;");
137 }
138 else
139 {
140 // Let's set up attributes
141 u32 counter = 0;
142 out.Write("VARYING_LOCATION({}) {} in float4 colors_0;\n", counter++,
143 GetInterpolationQualifier(msaa, ssaa));
144 out.Write("VARYING_LOCATION({}) {} in float4 colors_1;\n", counter++,
145 GetInterpolationQualifier(msaa, ssaa));
146 for (u32 i = 0; i < numTexgen; ++i)
147 {
148 out.Write("VARYING_LOCATION({}) {} in float3 tex{};\n", counter++,
149 GetInterpolationQualifier(msaa, ssaa), i);
150 }
151 if (!host_config.fast_depth_calc)
152 {
153 out.Write("VARYING_LOCATION({}) {} in float4 clipPos;\n", counter++,
154 GetInterpolationQualifier(msaa, ssaa));
155 }
156 if (per_pixel_lighting)
157 {
158 out.Write("VARYING_LOCATION({}) {} in float3 Normal;\n", counter++,
159 GetInterpolationQualifier(msaa, ssaa));
160 out.Write("VARYING_LOCATION({}) {} in float3 WorldPos;\n", counter++,
161 GetInterpolationQualifier(msaa, ssaa));
162 }
163 }
164
165 // Uniform index -> texture coordinates
166 // Quirk: when the tex coord is not less than the number of tex gens (i.e. the tex coord does
167 // not exist), then tex coord 0 is used (though sometimes glitchy effects happen on console).
168 // This affects the Mario portrait in Luigi's Mansion, where the developers forgot to set
169 // the number of tex gens to 2 (bug 11462).
170 if (numTexgen > 0)
171 {
172 out.Write("int2 selectTexCoord(uint index");
173 for (u32 i = 0; i < numTexgen; i++)
174 out.Write(", int2 fixpoint_uv{}", i);
175 out.Write(") {{\n");
176
177 if (api_type == APIType::D3D)
178 {
179 out.Write(" switch (index) {{\n");
180 for (u32 i = 0; i < numTexgen; i++)
181 {
182 out.Write(" case {}u:\n"
183 " return fixpoint_uv{};\n",
184 i, i);
185 }
186 out.Write(" default:\n"
187 " return fixpoint_uv0;\n"
188 " }}\n");
189 }
190 else
191 {
192 out.Write(" if (index >= {}u) {{\n", numTexgen);
193 out.Write(" return fixpoint_uv0;\n"
194 " }}\n");
195 if (numTexgen > 4)
196 out.Write(" if (index < 4u) {{\n");
197 if (numTexgen > 2)
198 out.Write(" if (index < 2u) {{\n");
199 if (numTexgen > 1)
200 out.Write(" return (index == 0u) ? fixpoint_uv0 : fixpoint_uv1;\n");
201 else
202 out.Write(" return fixpoint_uv0;\n");
203 if (numTexgen > 2)
204 {
205 out.Write(" }} else {{\n"); // >= 2 < min(4, numTexgen)
206 if (numTexgen > 3)
207 out.Write(" return (index == 2u) ? fixpoint_uv2 : fixpoint_uv3;\n");
208 else
209 out.Write(" return fixpoint_uv2;\n");
210 out.Write(" }}\n");
211 }
212 if (numTexgen > 4)
213 {
214 out.Write(" }} else {{\n"); // >= 4 < min(8, numTexgen)
215 if (numTexgen > 6)
216 out.Write(" if (index < 6u) {{\n");
217 if (numTexgen > 5)
218 out.Write(" return (index == 4u) ? fixpoint_uv4 : fixpoint_uv5;\n");
219 else
220 out.Write(" return fixpoint_uv4;\n");
221 if (numTexgen > 6)
222 {
223 out.Write(" }} else {{\n"); // >= 6 < min(8, numTexgen)
224 if (numTexgen > 7)
225 out.Write(" return (index == 6u) ? fixpoint_uv6 : fixpoint_uv7;\n");
226 else
227 out.Write(" return fixpoint_uv6;\n");
228 out.Write(" }}\n");
229 }
230 out.Write(" }}\n");
231 }
232 }
233
234 out.Write("}}\n\n");
235
236 out.Write("uint selectTexCoordIndex(uint texmap)");
237 out.Write("{{\n");
238
239 if (api_type == APIType::D3D)
240 {
241 out.Write(" switch (texmap) {{\n");
242 for (u32 i = 0; i < numTexgen; i++)
243 {
244 out.Write(" case {}u:\n"
245 " return {}u;\n",
246 i, i);
247 }
248 out.Write(" default:\n"
249 " return 0u;\n"
250 " }}\n");
251 }
252 else
253 {
254 out.Write(" if (texmap >= {}u) {{\n", numTexgen);
255 out.Write(" return 0u;\n"
256 " }}\n");
257 if (numTexgen > 4)
258 out.Write(" if (texmap < 4u) {{\n");
259 if (numTexgen > 2)
260 out.Write(" if (texmap < 2u) {{\n");
261 if (numTexgen > 1)
262 out.Write(" return (texmap == 0u) ? 0u : 1u;\n");
263 else
264 out.Write(" return 0u;\n");
265 if (numTexgen > 2)
266 {
267 out.Write(" }} else {{\n"); // >= 2 < min(4, numTexgen)
268 if (numTexgen > 3)
269 out.Write(" return (texmap == 2u) ? 2u : 3u;\n");
270 else
271 out.Write(" return 2u;\n");
272 out.Write(" }}\n");
273 }
274 if (numTexgen > 4)
275 {
276 out.Write(" }} else {{\n"); // >= 4 < min(8, numTexgen)
277 if (numTexgen > 6)
278 out.Write(" if (texmap < 6u) {{\n");
279 if (numTexgen > 5)
280 out.Write(" return (texmap == 4u) ? 4u : 5u;\n");
281 else
282 out.Write(" return 4u;\n");
283 if (numTexgen > 6)
284 {
285 out.Write(" }} else {{\n"); // >= 6 < min(8, numTexgen)
286 if (numTexgen > 7)
287 out.Write(" return (texmap == 6u) ? 6u : 7u;\n");
288 else
289 out.Write(" return 6u;\n");
290 out.Write(" }}\n");
291 }
292 out.Write(" }}\n");
293 }
294 }
295
296 out.Write("}}\n\n");
297 }
298
299 // =====================
300 // Texture Sampling
301 // =====================
302
303 if (host_config.backend_dynamic_sampler_indexing)
304 {
305 // Doesn't look like DirectX supports this. Oh well the code path is here just in case it
306 // supports this in the future.
307 out.Write("int4 sampleTextureWrapper(uint texmap, int2 uv, int layer) {{\n");
308 out.Write(" return sampleTexture(texmap, samp[texmap], uv, layer);\n");
309 out.Write("}}\n\n");
310 }
311 else
312 {
313 out.Write("int4 sampleTextureWrapper(uint sampler_num, int2 uv, int layer) {{\n"
314 " // This is messy, but DirectX, OpenGL 3.3, and OpenGL ES 3.0 don't support "
315 "dynamic indexing of the sampler array\n"
316 " // With any luck the shader compiler will optimise this if the hardware supports "
317 "dynamic indexing.\n"
318 " switch(sampler_num) {{\n");
319 for (int i = 0; i < 8; i++)
320 {
321 out.Write(" case {0}u: return sampleTexture({0}u, samp[{0}u], uv, layer);\n", i);
322 }
323 out.Write(" }}\n"
324 "}}\n\n");
325 }
326
327 // ======================
328 // Arbitrary Swizzling
329 // ======================
330
331 out.Write("int4 Swizzle(uint s, int4 color) {{\n"
332 " // AKA: Color Channel Swapping\n"
333 "\n"
334 " int4 ret;\n");
335 out.Write(" ret.r = color[{}];\n", BitfieldExtract<&TevKSel::swap_rb>("bpmem_tevksel(s * 2u)"));
336 out.Write(" ret.g = color[{}];\n", BitfieldExtract<&TevKSel::swap_ga>("bpmem_tevksel(s * 2u)"));
337 out.Write(" ret.b = color[{}];\n",
338 BitfieldExtract<&TevKSel::swap_rb>("bpmem_tevksel(s * 2u + 1u)"));
339 out.Write(" ret.a = color[{}];\n",
340 BitfieldExtract<&TevKSel::swap_ga>("bpmem_tevksel(s * 2u + 1u)"));
341 out.Write(" return ret;\n"
342 "}}\n\n");
343
344 // ======================
345 // Indirect Wrapping
346 // ======================
347 out.Write("int Wrap(int coord, uint mode) {{\n"
348 " if (mode == 0u) // ITW_OFF\n"
349 " return coord;\n"
350 " else if (mode < 6u) // ITW_256 to ITW_16\n"
351 " return coord & (0xfffe >> mode);\n"
352 " else // ITW_0\n"
353 " return 0;\n"
354 "}}\n\n");
355
356 // ======================
357 // Indirect Lookup
358 // ======================
359 const auto LookupIndirectTexture = [&out](std::string_view out_var_name,
360 std::string_view in_index_name) {
361 // in_index_name is the indirect stage, not the tev stage
362 // bpmem_iref is packed differently from RAS1_IREF
363 // This function assumes bpmem_iref is nonzero (i.e. matrix is not off, and the
364 // indirect texture stage is enabled).
365 out.Write("{{\n"
366 " uint iref = bpmem_iref({});\n"
367 " uint texcoord = bitfieldExtract(iref, 0, 3);\n"
368 " uint texmap = bitfieldExtract(iref, 8, 3);\n"
369 " int2 fixedPoint_uv = getTexCoord(texcoord);\n"
370 "\n"
371 " if (({} & 1u) == 0u)\n"
372 " fixedPoint_uv = fixedPoint_uv >> " I_INDTEXSCALE "[{} >> 1].xy;\n"
373 " else\n"
374 " fixedPoint_uv = fixedPoint_uv >> " I_INDTEXSCALE "[{} >> 1].zw;\n"
375 "\n"
376 " {} = sampleTextureWrapper(texmap, fixedPoint_uv, layer).abg;\n"
377 "}}\n",
378 in_index_name, in_index_name, in_index_name, in_index_name, out_var_name);
379 };
380
381 // ======================
382 // TEV's Special Lerp
383 // ======================
384 const auto WriteTevLerp = [&out](std::string_view components) {
385 out.Write("// TEV's Linear Interpolate, plus bias, add/subtract and scale\n"
386 "int{0} tevLerp{0}(int{0} A, int{0} B, int{0} C, int{0} D, uint bias, bool op, "
387 "uint scale) {{\n"
388 " // Scale C from 0..255 to 0..256\n"
389 " C += C >> 7;\n"
390 "\n"
391 " // Add bias to D\n"
392 " if (bias == 1u) D += 128;\n"
393 " else if (bias == 2u) D -= 128;\n"
394 "\n"
395 " int{0} lerp = (A << 8) + (B - A)*C;\n"
396 " if (scale != 3u) {{\n"
397 " lerp = lerp << scale;\n"
398 " D = D << scale;\n"
399 " }}\n"
400 "\n"
401 " // This rounding bias is not added when the scale is divide by 2\n"
402 " if (scale != 3u)\n"
403 " lerp = lerp + (op ? 127 : 128);\n"
404 "\n"
405 " int{0} result = lerp >> 8;\n"
406 "\n"
407 " // Add/Subtract D\n"
408 " if (op) // Subtract\n"
409 " result = D - result;\n"
410 " else // Add\n"
411 " result = D + result;\n"
412 "\n"
413 " // Most of the Scale was moved inside the lerp for improved precision\n"
414 " // But we still do the divide by 2 here\n"
415 " if (scale == 3u)\n"
416 " result = result >> 1;\n"
417 " return result;\n"
418 "}}\n\n",
419 components);
420 };
421 WriteTevLerp(""); // int
422 WriteTevLerp("3"); // int3
423
424 // =======================
425 // TEV's Color Compare
426 // =======================
427
428 out.Write(
429 "// Implements operations 0-5 of TEV's compare mode,\n"
430 "// which are common to both color and alpha channels\n"
431 "bool tevCompare(uint op, int3 color_A, int3 color_B) {{\n"
432 " switch (op) {{\n"
433 " case 0u: // TevCompareMode::R8, TevComparison::GT\n"
434 " return (color_A.r > color_B.r);\n"
435 " case 1u: // TevCompareMode::R8, TevComparison::EQ\n"
436 " return (color_A.r == color_B.r);\n"
437 " case 2u: // TevCompareMode::GR16, TevComparison::GT\n"
438 " int A_16 = (color_A.r | (color_A.g << 8));\n"
439 " int B_16 = (color_B.r | (color_B.g << 8));\n"
440 " return A_16 > B_16;\n"
441 " case 3u: // TevCompareMode::GR16, TevComparison::EQ\n"
442 " return (color_A.r == color_B.r && color_A.g == color_B.g);\n"
443 " case 4u: // TevCompareMode::BGR24, TevComparison::GT\n"
444 " int A_24 = (color_A.r | (color_A.g << 8) | (color_A.b << 16));\n"
445 " int B_24 = (color_B.r | (color_B.g << 8) | (color_B.b << 16));\n"
446 " return A_24 > B_24;\n"
447 " case 5u: // TevCompareMode::BGR24, TevComparison::EQ\n"
448 " return (color_A.r == color_B.r && color_A.g == color_B.g && color_A.b == color_B.b);\n"
449 " default:\n"
450 " return false;\n"
451 " }}\n"
452 "}}\n\n");
453
454 // =================
455 // Input Selects
456 // =================
457
458 out.Write("struct State {{\n"
459 " int4 Reg[4];\n"
460 " int4 RawTexColor;\n"
461 " int4 TexColor;\n"
462 " int AlphaBump;\n"
463 "}};\n"
464 "struct StageState {{\n"
465 " uint stage;\n"
466 " uint order;\n"
467 " uint cc;\n"
468 " uint ac;\n"
469 "}};\n"
470 "\n"
471 "int4 getRasColor(State s, StageState ss, float4 colors_0, float4 colors_1);\n"
472 "int4 getKonstColor(State s, StageState ss);\n"
473 "\n");
474
475 static constexpr Common::EnumMap<std::string_view, CompareMode::Always> tev_alpha_funcs_table{
476 "return false;", // CompareMode::Never
477 "return a < b;", // CompareMode::Less
478 "return a == b;", // CompareMode::Equal
479 "return a <= b;", // CompareMode::LEqual
480 "return a > b;", // CompareMode::Greater
481 "return a != b;", // CompareMode::NEqual
482 "return a >= b;", // CompareMode::GEqual
483 "return true;" // CompareMode::Always
484 };
485
486 static constexpr Common::EnumMap<std::string_view, TevColorArg::Zero> tev_c_input_table{
487 "return s.Reg[0].rgb;", // CPREV,
488 "return s.Reg[0].aaa;", // APREV,
489 "return s.Reg[1].rgb;", // C0,
490 "return s.Reg[1].aaa;", // A0,
491 "return s.Reg[2].rgb;", // C1,
492 "return s.Reg[2].aaa;", // A1,
493 "return s.Reg[3].rgb;", // C2,
494 "return s.Reg[3].aaa;", // A2,
495 "return s.TexColor.rgb;", // TEXC,
496 "return s.TexColor.aaa;", // TEXA,
497 "return getRasColor(s, ss, colors_0, colors_1).rgb;", // RASC,
498 "return getRasColor(s, ss, colors_0, colors_1).aaa;", // RASA,
499 "return int3(255, 255, 255);", // ONE
500 "return int3(128, 128, 128);", // HALF
501 "return getKonstColor(s, ss).rgb;", // KONST
502 "return int3(0, 0, 0);", // ZERO
503 };
504
505 static constexpr Common::EnumMap<std::string_view, TevAlphaArg::Zero> tev_a_input_table{
506 "return s.Reg[0].a;", // APREV,
507 "return s.Reg[1].a;", // A0,
508 "return s.Reg[2].a;", // A1,
509 "return s.Reg[3].a;", // A2,
510 "return s.TexColor.a;", // TEXA,
511 "return getRasColor(s, ss, colors_0, colors_1).a;", // RASA,
512 "return getKonstColor(s, ss).a;", // KONST, (hw1 had quarter)
513 "return 0;", // ZERO
514 };
515
516 static constexpr Common::EnumMap<std::string_view, TevOutput::Color2> tev_regs_lookup_table{
517 "return s.Reg[0];",
518 "return s.Reg[1];",
519 "return s.Reg[2];",
520 "return s.Reg[3];",
521 };
522
523 static constexpr Common::EnumMap<std::string_view, TevOutput::Color2> tev_c_set_table{
524 "s.Reg[0].rgb = color;",
525 "s.Reg[1].rgb = color;",
526 "s.Reg[2].rgb = color;",
527 "s.Reg[3].rgb = color;",
528 };
529
530 static constexpr Common::EnumMap<std::string_view, TevOutput::Color2> tev_a_set_table{
531 "s.Reg[0].a = alpha;",
532 "s.Reg[1].a = alpha;",
533 "s.Reg[2].a = alpha;",
534 "s.Reg[3].a = alpha;",
535 };
536
537 out.Write("// Helper function for Alpha Test\n"
538 "bool alphaCompare(int a, int b, uint compare) {{\n");
539 WriteSwitch(out, api_type, "compare", tev_alpha_funcs_table, 2, false);
540 out.Write("}}\n"
541 "\n"
542 "int3 selectColorInput(State s, StageState ss, float4 colors_0, float4 colors_1, "
543 "uint index) {{\n");
544 WriteSwitch(out, api_type, "index", tev_c_input_table, 2, false);
545 out.Write("}}\n"
546 "\n"
547 "int selectAlphaInput(State s, StageState ss, float4 colors_0, float4 colors_1, "
548 "uint index) {{\n");
549 WriteSwitch(out, api_type, "index", tev_a_input_table, 2, false);
550 out.Write("}}\n"
551 "\n"
552 "int4 getTevReg(in State s, uint index) {{\n");
553 WriteSwitch(out, api_type, "index", tev_regs_lookup_table, 2, false);
554 out.Write("}}\n"
555 "\n");
556
557 // Since the fixed-point texture coordinate variables aren't global, we need to pass
558 // them to the select function. This applies to all backends.
559 if (numTexgen > 0)
560 {
561 out.Write("#define getTexCoord(index) selectTexCoord((index)");
562 for (u32 i = 0; i < numTexgen; i++)
563 out.Write(", fixpoint_uv{}", i);
564 out.Write(")\n\n");
565 }
566
567 if (early_depth && host_config.backend_early_z)
568 out.Write("FORCE_EARLY_Z;\n");
569
570 out.Write("void main()\n{{\n");
571 out.Write(" float4 rawpos = gl_FragCoord;\n");
572
573 out.Write(" uint num_stages = {};\n\n",
574 BitfieldExtract<&GenMode::numtevstages>("bpmem_genmode"));
575
576 if (use_framebuffer_fetch)
577 {
578 // Store off a copy of the initial framebuffer value.
579 //
580 // If FB_FETCH_VALUE isn't defined (i.e. no special keyword for fetching from the
581 // framebuffer), we read from real_ocol0.
582 out.Write("#ifdef FB_FETCH_VALUE\n"
583 " float4 initial_ocol0 = FB_FETCH_VALUE;\n"
584 "#else\n"
585 " float4 initial_ocol0 = real_ocol0;\n"
586 "#endif\n");
587
588 // QComm's Adreno driver doesn't seem to like using the framebuffer_fetch value as an
589 // intermediate value with multiple reads & modifications, so we pull out the "real" output
590 // value above and use a temporary for calculations, then set the output value once at the
591 // end of the shader.
592 out.Write(" float4 ocol0;\n"
593 " float4 ocol1;\n");
594 }
595
596 if (host_config.backend_geometry_shaders && stereo)
597 {
598 if (host_config.backend_gl_layer_in_fs)
599 out.Write("\tint layer = gl_Layer;\n");
600 }
601 else
602 {
603 out.Write("\tint layer = 0;\n");
604 }
605
606 out.Write(" int3 tevcoord = int3(0, 0, 0);\n"
607 " State s;\n"
608 " s.TexColor = int4(0, 0, 0, 0);\n"
609 " s.RawTexColor = int4(0, 0, 0, 0);\n"
610 " s.AlphaBump = 0;\n"
611 "\n");
612 for (int i = 0; i < 4; i++)
613 out.Write(" s.Reg[{}] = " I_COLORS "[{}];\n", i, i);
614
615 const char* color_input_prefix = "";
616 if (per_pixel_lighting)
617 {
618 out.Write(" float4 lit_colors_0 = colors_0;\n"
619 " float4 lit_colors_1 = colors_1;\n"
620 " float3 lit_normal = normalize(Normal.xyz);\n"
621 " float3 lit_pos = WorldPos.xyz;\n");
622 WriteVertexLighting(out, api_type, "lit_pos", "lit_normal", "colors_0", "colors_1",
623 "lit_colors_0", "lit_colors_1");
624 color_input_prefix = "lit_";
625 out.Write(" // The number of colors available to TEV is determined by numColorChans.\n"
626 " // Normally this is performed in the vertex shader after lighting,\n"
627 " // but with per-pixel lighting, we need to perform it here.\n"
628 " // TODO: Actually implement this for ubershaders\n"
629 " // if (xfmem_numColorChans == 0u)\n"
630 " // o.colors_0 = float4(0.0, 0.0, 0.0, 0.0);\n"
631 " // if (xfmem_numColorChans <= 1u)\n"
632 " // o.colors_1 = float4(0.0, 0.0, 0.0, 0.0);\n");
633 }
634
635 out.Write(" // Main tev loop\n");
636
637 out.Write(" for(uint stage = 0u; stage <= num_stages; stage++)\n"
638 " {{\n"
639 " StageState ss;\n"
640 " ss.stage = stage;\n"
641 " ss.cc = bpmem_combiners(stage).x;\n"
642 " ss.ac = bpmem_combiners(stage).y;\n"
643 " ss.order = bpmem_tevorder(stage>>1);\n"
644 " if ((stage & 1u) == 1u)\n"
645 " ss.order = ss.order >> {};\n\n",
646 int(TwoTevStageOrders().enable_tex_odd.StartBit() -
647 TwoTevStageOrders().enable_tex_even.StartBit()));
648
649 // Disable texturing when there are no texgens (for now)
650 if (numTexgen != 0)
651 {
652 for (u32 i = 0; i < numTexgen; i++)
653 {
654 out.Write(" int2 fixpoint_uv{} = int2(", i);
655 out.Write("(tex{}.z == 0.0 ? tex{}.xy : tex{}.xy / tex{}.z)", i, i, i, i);
656 out.Write(" * float2(" I_TEXDIMS "[{}].zw * 128));\n", i);
657 // TODO: S24 overflows here?
658 }
659
660 out.Write("\n"
661 " uint tex_coord = {};\n",
662 BitfieldExtract<&TwoTevStageOrders::texcoord_even>("ss.order"));
663 out.Write(" int2 fixedPoint_uv = getTexCoord(tex_coord);\n"
664 "\n"
665 " bool texture_enabled = (ss.order & {}u) != 0u;\n",
666 1 << TwoTevStageOrders().enable_tex_even.StartBit());
667 out.Write("\n"
668 " // Indirect textures\n"
669 " uint tevind = bpmem_tevind(stage);\n"
670 " if (tevind != 0u)\n"
671 " {{\n"
672 " uint bs = {};\n",
673 BitfieldExtract<&TevStageIndirect::bs>("tevind"));
674 out.Write(" uint fmt = {};\n", BitfieldExtract<&TevStageIndirect::fmt>("tevind"));
675 out.Write(" uint bias = {};\n", BitfieldExtract<&TevStageIndirect::bias>("tevind"));
676 out.Write(" uint bt = {};\n", BitfieldExtract<&TevStageIndirect::bt>("tevind"));
677 out.Write(" uint matrix_index = {};\n",
678 BitfieldExtract<&TevStageIndirect::matrix_index>("tevind"));
679 out.Write(" uint matrix_id = {};\n",
680 BitfieldExtract<&TevStageIndirect::matrix_id>("tevind"));
681 out.Write(" int2 indtevtrans = int2(0, 0);\n"
682 "\n");
683 // There is always a bit set in bpmem_iref if the data is valid (matrix is not off, and the
684 // indirect texture stage is enabled). If the matrix is off, the result doesn't matter; if the
685 // indirect texture stage is disabled, the result is undefined (and produces a glitchy pattern
686 // on hardware, different from this).
687 // For the undefined case, we just skip applying the indirect operation, which is close
688 // enough. Viewtiful Joe hits the undefined case (bug 12525). Wrapping and add to previous
689 // still apply in this case (and when the stage is disabled).
690 out.Write(" if (bpmem_iref(bt) != 0u) {{\n");
691 out.Write(" int3 indcoord;\n");
692 LookupIndirectTexture("indcoord", "bt");
693 out.Write(" if (bs != 0u)\n"
694 " s.AlphaBump = indcoord[bs - 1u];\n"
695 " switch(fmt)\n"
696 " {{\n"
697 " case {:s}:\n",
698 IndTexFormat::ITF_8);
699 out.Write(" indcoord.x = indcoord.x + ((bias & 1u) != 0u ? -128 : 0);\n"
700 " indcoord.y = indcoord.y + ((bias & 2u) != 0u ? -128 : 0);\n"
701 " indcoord.z = indcoord.z + ((bias & 4u) != 0u ? -128 : 0);\n"
702 " s.AlphaBump = s.AlphaBump & 0xf8;\n"
703 " break;\n"
704 " case {:s}:\n",
705 IndTexFormat::ITF_5);
706 out.Write(" indcoord.x = (indcoord.x >> 3) + ((bias & 1u) != 0u ? 1 : 0);\n"
707 " indcoord.y = (indcoord.y >> 3) + ((bias & 2u) != 0u ? 1 : 0);\n"
708 " indcoord.z = (indcoord.z >> 3) + ((bias & 4u) != 0u ? 1 : 0);\n"
709 " s.AlphaBump = s.AlphaBump << 5;\n"
710 " break;\n"
711 " case {:s}:\n",
712 IndTexFormat::ITF_4);
713 out.Write(" indcoord.x = (indcoord.x >> 4) + ((bias & 1u) != 0u ? 1 : 0);\n"
714 " indcoord.y = (indcoord.y >> 4) + ((bias & 2u) != 0u ? 1 : 0);\n"
715 " indcoord.z = (indcoord.z >> 4) + ((bias & 4u) != 0u ? 1 : 0);\n"
716 " s.AlphaBump = s.AlphaBump << 4;\n"
717 " break;\n"
718 " case {:s}:\n",
719 IndTexFormat::ITF_3);
720 out.Write(" indcoord.x = (indcoord.x >> 5) + ((bias & 1u) != 0u ? 1 : 0);\n"
721 " indcoord.y = (indcoord.y >> 5) + ((bias & 2u) != 0u ? 1 : 0);\n"
722 " indcoord.z = (indcoord.z >> 5) + ((bias & 4u) != 0u ? 1 : 0);\n"
723 " s.AlphaBump = s.AlphaBump << 3;\n"
724 " break;\n"
725 " }}\n"
726 "\n"
727 " // Matrix multiply\n"
728 " if (matrix_index != 0u)\n"
729 " {{\n"
730 " uint mtxidx = 2u * (matrix_index - 1u);\n"
731 " int shift = " I_INDTEXMTX "[mtxidx].w;\n"
732 "\n"
733 " switch (matrix_id)\n"
734 " {{\n"
735 " case 0u: // 3x2 S0.10 matrix\n"
736 " indtevtrans = int2(idot(" I_INDTEXMTX
737 "[mtxidx].xyz, indcoord), idot(" I_INDTEXMTX "[mtxidx + 1u].xyz, indcoord)) >> 3;\n"
738 " break;\n"
739 " case 1u: // S matrix, S17.7 format\n"
740 " indtevtrans = (fixedPoint_uv * indcoord.xx) >> 8;\n"
741 " break;\n"
742 " case 2u: // T matrix, S17.7 format\n"
743 " indtevtrans = (fixedPoint_uv * indcoord.yy) >> 8;\n"
744 " break;\n"
745 " }}\n"
746 "\n"
747 " if (shift >= 0)\n"
748 " indtevtrans = indtevtrans >> shift;\n"
749 " else\n"
750 " indtevtrans = indtevtrans << ((-shift) & 31);\n"
751 " }}\n"
752 " }}\n"
753 "\n"
754 " // Wrapping\n"
755 " uint sw = {};\n",
756 BitfieldExtract<&TevStageIndirect::sw>("tevind"));
757 out.Write(" uint tw = {}; \n", BitfieldExtract<&TevStageIndirect::tw>("tevind"));
758 out.Write(
759 " int2 wrapped_coord = int2(Wrap(fixedPoint_uv.x, sw), Wrap(fixedPoint_uv.y, tw));\n"
760 "\n"
761 " if ((tevind & {}u) != 0u) // add previous tevcoord\n",
762 1 << TevStageIndirect().fb_addprev.StartBit());
763 out.Write(" tevcoord.xy += wrapped_coord + indtevtrans;\n"
764 " else\n"
765 " tevcoord.xy = wrapped_coord + indtevtrans;\n"
766 "\n"
767 " // Emulate s24 overflows\n"
768 " tevcoord.xy = (tevcoord.xy << 8) >> 8;\n"
769 " }}\n"
770 " else\n"
771 " {{\n"
772 " tevcoord.xy = fixedPoint_uv;\n"
773 " }}\n"
774 "\n"
775 " // Sample texture for stage\n"
776 " if (texture_enabled) {{\n"
777 " uint sampler_num = {};\n",
778 BitfieldExtract<&TwoTevStageOrders::texmap_even>("ss.order"));
779 out.Write("\n"
780 " s.RawTexColor = sampleTextureWrapper(sampler_num, tevcoord.xy, layer);\n"
781 " uint swap = {};\n",
782 BitfieldExtract<&TevStageCombiner::AlphaCombiner::tswap>("ss.ac"));
783 out.Write(" s.TexColor = Swizzle(swap, s.RawTexColor);\n");
784 out.Write(" }} else {{\n"
785 " // Texture is disabled\n"
786 " s.TexColor = int4(255, 255, 255, 255);\n"
787 " }}\n"
788 "\n");
789 }
790
791 out.Write(" // This is the Meat of TEV\n"
792 " {{\n"
793 " // Color Combiner\n");
794 out.Write(" uint color_a = {};\n",
795 BitfieldExtract<&TevStageCombiner::ColorCombiner::a>("ss.cc"));
796 out.Write(" uint color_b = {};\n",
797 BitfieldExtract<&TevStageCombiner::ColorCombiner::b>("ss.cc"));
798 out.Write(" uint color_c = {};\n",
799 BitfieldExtract<&TevStageCombiner::ColorCombiner::c>("ss.cc"));
800 out.Write(" uint color_d = {};\n",
801 BitfieldExtract<&TevStageCombiner::ColorCombiner::d>("ss.cc"));
802
803 out.Write(" uint color_bias = {};\n",
804 BitfieldExtract<&TevStageCombiner::ColorCombiner::bias>("ss.cc"));
805 out.Write(" bool color_op = bool({});\n",
806 BitfieldExtract<&TevStageCombiner::ColorCombiner::op>("ss.cc"));
807 out.Write(" bool color_clamp = bool({});\n",
808 BitfieldExtract<&TevStageCombiner::ColorCombiner::clamp>("ss.cc"));
809 out.Write(" uint color_scale = {};\n",
810 BitfieldExtract<&TevStageCombiner::ColorCombiner::scale>("ss.cc"));
811 out.Write(" uint color_dest = {};\n",
812 BitfieldExtract<&TevStageCombiner::ColorCombiner::dest>("ss.cc"));
813
814 out.Write(
815 " uint color_compare_op = color_scale << 1 | uint(color_op);\n"
816 "\n"
817 " int3 color_A = selectColorInput(s, ss, {0}colors_0, {0}colors_1, color_a) & "
818 "int3(255, 255, 255);\n"
819 " int3 color_B = selectColorInput(s, ss, {0}colors_0, {0}colors_1, color_b) & "
820 "int3(255, 255, 255);\n"
821 " int3 color_C = selectColorInput(s, ss, {0}colors_0, {0}colors_1, color_c) & "
822 "int3(255, 255, 255);\n"
823 " int3 color_D = selectColorInput(s, ss, {0}colors_0, {0}colors_1, color_d); // 10 "
824 "bits + sign\n"
825 "\n", // TODO: do we need to sign extend?
826 color_input_prefix);
827 out.Write(
828 " int3 color;\n"
829 " if (color_bias != 3u) {{ // Normal mode\n"
830 " color = tevLerp3(color_A, color_B, color_C, color_D, color_bias, color_op, "
831 "color_scale);\n"
832 " }} else {{ // Compare mode\n"
833 " // op 6 and 7 do a select per color channel\n"
834 " if (color_compare_op == 6u) {{\n"
835 " // TevCompareMode::RGB8, TevComparison::GT\n"
836 " color.r = (color_A.r > color_B.r) ? color_C.r : 0;\n"
837 " color.g = (color_A.g > color_B.g) ? color_C.g : 0;\n"
838 " color.b = (color_A.b > color_B.b) ? color_C.b : 0;\n"
839 " }} else if (color_compare_op == 7u) {{\n"
840 " // TevCompareMode::RGB8, TevComparison::EQ\n"
841 " color.r = (color_A.r == color_B.r) ? color_C.r : 0;\n"
842 " color.g = (color_A.g == color_B.g) ? color_C.g : 0;\n"
843 " color.b = (color_A.b == color_B.b) ? color_C.b : 0;\n"
844 " }} else {{\n"
845 " // The remaining ops do one compare which selects all 3 channels\n"
846 " color = tevCompare(color_compare_op, color_A, color_B) ? color_C : int3(0, 0, "
847 "0);\n"
848 " }}\n"
849 " color = color_D + color;\n"
850 " }}\n"
851 "\n"
852 " // Clamp result\n"
853 " if (color_clamp)\n"
854 " color = clamp(color, 0, 255);\n"
855 " else\n"
856 " color = clamp(color, -1024, 1023);\n"
857 "\n"
858 " // Write result to the correct input register of the next stage\n");
859 WriteSwitch(out, api_type, "color_dest", tev_c_set_table, 6, true);
860 out.Write("\n");
861
862 // Alpha combiner
863 out.Write(" // Alpha Combiner\n");
864 out.Write(" uint alpha_a = {};\n",
865 BitfieldExtract<&TevStageCombiner::AlphaCombiner::a>("ss.ac"));
866 out.Write(" uint alpha_b = {};\n",
867 BitfieldExtract<&TevStageCombiner::AlphaCombiner::b>("ss.ac"));
868 out.Write(" uint alpha_c = {};\n",
869 BitfieldExtract<&TevStageCombiner::AlphaCombiner::c>("ss.ac"));
870 out.Write(" uint alpha_d = {};\n",
871 BitfieldExtract<&TevStageCombiner::AlphaCombiner::d>("ss.ac"));
872
873 out.Write(" uint alpha_bias = {};\n",
874 BitfieldExtract<&TevStageCombiner::AlphaCombiner::bias>("ss.ac"));
875 out.Write(" bool alpha_op = bool({});\n",
876 BitfieldExtract<&TevStageCombiner::AlphaCombiner::op>("ss.ac"));
877 out.Write(" bool alpha_clamp = bool({});\n",
878 BitfieldExtract<&TevStageCombiner::AlphaCombiner::clamp>("ss.ac"));
879 out.Write(" uint alpha_scale = {};\n",
880 BitfieldExtract<&TevStageCombiner::AlphaCombiner::scale>("ss.ac"));
881 out.Write(" uint alpha_dest = {};\n",
882 BitfieldExtract<&TevStageCombiner::AlphaCombiner::dest>("ss.ac"));
883
884 out.Write(
885 " uint alpha_compare_op = alpha_scale << 1 | uint(alpha_op);\n"
886 "\n"
887 " int alpha_A = 0;\n"
888 " int alpha_B = 0;\n"
889 " if (alpha_bias != 3u || alpha_compare_op > 5u) {{\n"
890 " // Small optimisation here: alpha_A and alpha_B are unused by compare ops 0-5\n"
891 " alpha_A = selectAlphaInput(s, ss, {0}colors_0, {0}colors_1, alpha_a) & 255;\n"
892 " alpha_B = selectAlphaInput(s, ss, {0}colors_0, {0}colors_1, alpha_b) & 255;\n"
893 " }};\n"
894 " int alpha_C = selectAlphaInput(s, ss, {0}colors_0, {0}colors_1, alpha_c) & 255;\n"
895 " int alpha_D = selectAlphaInput(s, ss, {0}colors_0, {0}colors_1, alpha_d); // 10 "
896 "bits "
897 "+ sign\n"
898 "\n", // TODO: do we need to sign extend?
899 color_input_prefix);
900 out.Write("\n"
901 " int alpha;\n"
902 " if (alpha_bias != 3u) {{ // Normal mode\n"
903 " alpha = tevLerp(alpha_A, alpha_B, alpha_C, alpha_D, alpha_bias, alpha_op, "
904 "alpha_scale);\n"
905 " }} else {{ // Compare mode\n"
906 " if (alpha_compare_op == 6u) {{\n"
907 " // TevCompareMode::A8, TevComparison::GT\n"
908 " alpha = (alpha_A > alpha_B) ? alpha_C : 0;\n"
909 " }} else if (alpha_compare_op == 7u) {{\n"
910 " // TevCompareMode::A8, TevComparison::EQ\n"
911 " alpha = (alpha_A == alpha_B) ? alpha_C : 0;\n"
912 " }} else {{\n"
913 " // All remaining alpha compare ops actually compare the color channels\n"
914 " alpha = tevCompare(alpha_compare_op, color_A, color_B) ? alpha_C : 0;\n"
915 " }}\n"
916 " alpha = alpha_D + alpha;\n"
917 " }}\n"
918 "\n"
919 " // Clamp result\n"
920 " if (alpha_clamp)\n"
921 " alpha = clamp(alpha, 0, 255);\n"
922 " else\n"
923 " alpha = clamp(alpha, -1024, 1023);\n"
924 "\n"
925 " // Write result to the correct input register of the next stage\n");
926 WriteSwitch(out, api_type, "alpha_dest", tev_a_set_table, 6, true);
927 out.Write(" }}\n");
928 out.Write(" }} // Main TEV loop\n");
929 out.Write("\n");
930
931 // Select the output color and alpha registers from the last stage.
932 out.Write(" int4 TevResult;\n");
933 out.Write(
934 " TevResult.xyz = getTevReg(s, {}).xyz;\n",
935 BitfieldExtract<&TevStageCombiner::ColorCombiner::dest>("bpmem_combiners(num_stages).x"));
936 out.Write(
937 " TevResult.w = getTevReg(s, {}).w;\n",
938 BitfieldExtract<&TevStageCombiner::AlphaCombiner::dest>("bpmem_combiners(num_stages).y"));
939
940 out.Write(" TevResult &= 255;\n\n");
941
942 if (host_config.fast_depth_calc)
943 {
944 if (!host_config.backend_reversed_depth_range)
945 out.Write(" int zCoord = int((1.0 - rawpos.z) * 16777216.0);\n");
946 else
947 out.Write(" int zCoord = int(rawpos.z * 16777216.0);\n");
948 out.Write(" zCoord = clamp(zCoord, 0, 0xFFFFFF);\n"
949 "\n");
950 }
951 else
952 {
953 out.Write("\tint zCoord = " I_ZBIAS "[1].x + int((clipPos.z / clipPos.w) * float(" I_ZBIAS
954 "[1].y));\n");
955 }
956
957 // ===========
958 // ZFreeze
959 // ===========
960
961 if (per_pixel_depth)
962 {
963 // Zfreeze forces early depth off
964 out.Write(" // ZFreeze\n"
965 " if ((bpmem_genmode & {}u) != 0u) {{\n",
966 1 << GenMode().zfreeze.StartBit());
967 out.Write(" float2 screenpos = rawpos.xy * " I_EFBSCALE ".xy;\n");
968 if (api_type == APIType::OpenGL)
969 {
970 out.Write(" // OpenGL has reversed vertical screenspace coordinates\n"
971 " screenpos.y = 528.0 - screenpos.y;\n");
972 }
973 out.Write(" zCoord = int(" I_ZSLOPE ".z + " I_ZSLOPE ".x * screenpos.x + " I_ZSLOPE
974 ".y * screenpos.y);\n"
975 " }}\n"
976 "\n");
977 }
978
979 // =================
980 // Depth Texture
981 // =================
982
983 out.Write(" // Depth Texture\n"
984 " int early_zCoord = zCoord;\n"
985 " if (bpmem_ztex_op != 0u) {{\n"
986 " int ztex = int(" I_ZBIAS "[1].w); // fixed bias\n"
987 "\n"
988 " // Whatever texture was in our last stage, it's now our depth texture\n"
989 " ztex += idot(s.RawTexColor.xyzw, " I_ZBIAS "[0].xyzw);\n"
990 " ztex += (bpmem_ztex_op == 1u) ? zCoord : 0;\n"
991 " zCoord = ztex & 0xFFFFFF;\n"
992 " }}\n"
993 "\n");
994
995 if (per_pixel_depth)
996 {
997 out.Write(" // If early depth is enabled, write to zbuffer before depth textures\n"
998 " // If early depth isn't enabled, we write to the zbuffer here\n"
999 " int zbuffer_zCoord = bpmem_late_ztest ? zCoord : early_zCoord;\n");
1000 if (!host_config.backend_reversed_depth_range)
1001 out.Write(" depth = 1.0 - float(zbuffer_zCoord) / 16777216.0;\n");
1002 else
1003 out.Write(" depth = float(zbuffer_zCoord) / 16777216.0;\n");
1004 }
1005
1006 out.Write(" // Alpha Test\n");
1007
1008 if (early_depth && DriverDetails::HasBug(DriverDetails::BUG_BROKEN_DISCARD_WITH_EARLY_Z) &&
1009 host_config.backend_shader_framebuffer_fetch)
1010 {
1011 // Instead of using discard, fetch the framebuffer's color value and use it as the output
1012 // for this fragment.
1013 out.Write(" #define discard_fragment {{ real_ocol0 = float4(initial_ocol0.xyz, 1.0); "
1014 "return; }}\n");
1015 }
1016 else
1017 {
1018 out.Write(" #define discard_fragment discard\n");
1019 }
1020
1021 out.Write(" if (bpmem_alphaTest != 0u) {{\n"
1022 " bool comp0 = alphaCompare(TevResult.a, " I_ALPHA ".r, {});\n",
1023 BitfieldExtract<&AlphaTest::comp0>("bpmem_alphaTest"));
1024 out.Write(" bool comp1 = alphaCompare(TevResult.a, " I_ALPHA ".g, {});\n",
1025 BitfieldExtract<&AlphaTest::comp1>("bpmem_alphaTest"));
1026 out.Write("\n"
1027 " // These if statements are written weirdly to work around intel and Qualcomm "
1028 "bugs with handling booleans.\n"
1029 " switch ({}) {{\n",
1030 BitfieldExtract<&AlphaTest::logic>("bpmem_alphaTest"));
1031 out.Write(" case 0u: // AND\n"
1032 " if (comp0 && comp1) break; else discard_fragment; break;\n"
1033 " case 1u: // OR\n"
1034 " if (comp0 || comp1) break; else discard_fragment; break;\n"
1035 " case 2u: // XOR\n"
1036 " if (comp0 != comp1) break; else discard_fragment; break;\n"
1037 " case 3u: // XNOR\n"
1038 " if (comp0 == comp1) break; else discard_fragment; break;\n"
1039 " }}\n"
1040 " }}\n"
1041 "\n");
1042
1043 out.Write(" // Hardware testing indicates that an alpha of 1 can pass an alpha test,\n"
1044 " // but doesn't do anything in blending\n"
1045 " if (TevResult.a == 1) TevResult.a = 0;\n");
1046 // =========
1047 // Dithering
1048 // =========
1049 out.Write(" if (bpmem_dither) {{\n"
1050 " // Flipper uses a standard 2x2 Bayer Matrix for 6 bit dithering\n"
1051 " // Here the matrix is encoded into the two factor constants\n"
1052 " int2 dither = int2(rawpos.xy) & 1;\n"
1053 " TevResult.rgb = (TevResult.rgb - (TevResult.rgb >> 6)) + (dither.x ^ dither.y) * "
1054 "2 + dither.y;\n"
1055 " }}\n\n");
1056
1057 // =========
1058 // Fog
1059 // =========
1060
1061 // FIXME: Fog is implemented the same as ShaderGen, but ShaderGen's fog is all hacks.
1062 // Should be fixed point, and should not make guesses about Range-Based adjustments.
1063 out.Write(" // Fog\n"
1064 " uint fog_function = {};\n",
1065 BitfieldExtract<&FogParam3::fsel>("bpmem_fogParam3"));
1066 out.Write(" if (fog_function != {:s}) {{\n", FogType::Off);
1067 out.Write(" // TODO: This all needs to be converted from float to fixed point\n"
1068 " float ze;\n"
1069 " if ({} == 0u) {{\n",
1070 BitfieldExtract<&FogParam3::proj>("bpmem_fogParam3"));
1071 out.Write(" // perspective\n"
1072 " // ze = A/(B - (Zs >> B_SHF)\n"
1073 " ze = (" I_FOGF ".x * 16777216.0) / float(" I_FOGI ".y - (zCoord >> " I_FOGI
1074 ".w));\n"
1075 " }} else {{\n"
1076 " // orthographic\n"
1077 " // ze = a*Zs (here, no B_SHF)\n"
1078 " ze = " I_FOGF ".x * float(zCoord) / 16777216.0;\n"
1079 " }}\n"
1080 "\n"
1081 " if (bool({})) {{\n",
1082 BitfieldExtract<&FogRangeParams::RangeBase::Enabled>("bpmem_fogRangeBase"));
1083 out.Write(" // x_adjust = sqrt((x-center)^2 + k^2)/k\n"
1084 " // ze *= x_adjust\n"
1085 " float offset = (2.0 * (rawpos.x / " I_FOGF ".w)) - 1.0 - " I_FOGF ".z;\n"
1086 " float floatindex = clamp(9.0 - abs(offset) * 9.0, 0.0, 9.0);\n"
1087 " uint indexlower = uint(floatindex);\n"
1088 " uint indexupper = indexlower + 1u;\n"
1089 " float klower = " I_FOGRANGE "[indexlower >> 2u][indexlower & 3u];\n"
1090 " float kupper = " I_FOGRANGE "[indexupper >> 2u][indexupper & 3u];\n"
1091 " float k = lerp(klower, kupper, frac(floatindex));\n"
1092 " float x_adjust = sqrt(offset * offset + k * k) / k;\n"
1093 " ze *= x_adjust;\n"
1094 " }}\n"
1095 "\n"
1096 " float fog = clamp(ze - " I_FOGF ".y, 0.0, 1.0);\n"
1097 "\n");
1098 out.Write(" if (fog_function >= {:s}) {{\n", FogType::Exp);
1099 out.Write(" switch (fog_function) {{\n"
1100 " case {:s}:\n"
1101 " fog = 1.0 - exp2(-8.0 * fog);\n"
1102 " break;\n",
1103 FogType::Exp);
1104 out.Write(" case {:s}:\n"
1105 " fog = 1.0 - exp2(-8.0 * fog * fog);\n"
1106 " break;\n",
1107 FogType::ExpSq);
1108 out.Write(" case {:s}:\n"
1109 " fog = exp2(-8.0 * (1.0 - fog));\n"
1110 " break;\n",
1111 FogType::BackwardsExp);
1112 out.Write(" case {:s}:\n"
1113 " fog = 1.0 - fog;\n"
1114 " fog = exp2(-8.0 * fog * fog);\n"
1115 " break;\n",
1116 FogType::BackwardsExpSq);
1117 out.Write(" }}\n"
1118 " }}\n"
1119 "\n"
1120 " int ifog = iround(fog * 256.0);\n"
1121 " TevResult.rgb = (TevResult.rgb * (256 - ifog) + " I_FOGCOLOR ".rgb * ifog) >> 8;\n"
1122 " }}\n"
1123 "\n");
1124
1125 if (use_framebuffer_fetch)
1126 {
1127 static constexpr std::array<const char*, 16> logic_op_mode{
1128 "int4(0, 0, 0, 0)", // CLEAR
1129 "TevResult & fb_value", // AND
1130 "TevResult & ~fb_value", // AND_REVERSE
1131 "TevResult", // COPY
1132 "~TevResult & fb_value", // AND_INVERTED
1133 "fb_value", // NOOP
1134 "TevResult ^ fb_value", // XOR
1135 "TevResult | fb_value", // OR
1136 "~(TevResult | fb_value)", // NOR
1137 "~(TevResult ^ fb_value)", // EQUIV
1138 "~fb_value", // INVERT
1139 "TevResult | ~fb_value", // OR_REVERSE
1140 "~TevResult", // COPY_INVERTED
1141 "~TevResult | fb_value", // OR_INVERTED
1142 "~(TevResult & fb_value)", // NAND
1143 "int4(255, 255, 255, 255)", // SET
1144 };
1145
1146 out.Write(" // Logic Ops\n"
1147 " if (logic_op_enable) {{\n"
1148 " int4 fb_value = iround(initial_ocol0 * 255.0);"
1149 " switch (logic_op_mode) {{\n");
1150 for (size_t i = 0; i < logic_op_mode.size(); i++)
1151 {
1152 out.Write(" case {}u: TevResult = {}; break;\n", i, logic_op_mode[i]);
1153 }
1154
1155 out.Write(" }}\n"
1156 " TevResult &= 0xff;\n"
1157 " }}\n");
1158 }
1159 else if (!host_config.backend_logic_op)
1160 {
1161 out.Write(" // Helpers for logic op blending approximations\n"
1162 " if (logic_op_enable) {{\n"
1163 " switch (logic_op_mode) {{\n");
1164 out.Write(" case {}: // Clear\n", static_cast<u32>(LogicOp::Clear));
1165 out.Write(" TevResult = int4(0, 0, 0, 0);\n"
1166 " break;\n");
1167 out.Write(" case {}: // Copy Inverted\n", static_cast<u32>(LogicOp::CopyInverted));
1168 out.Write(" TevResult ^= 0xff;\n"
1169 " break;\n");
1170 out.Write(" case {}: // Set\n", static_cast<u32>(LogicOp::Set));
1171 out.Write(" case {}: // Invert\n", static_cast<u32>(LogicOp::Invert));
1172 out.Write(" TevResult = int4(255, 255, 255, 255);\n"
1173 " break;\n");
1174 out.Write(" default:\n"
1175 " break;\n"
1176 " }}\n"
1177 " }}\n");
1178 }
1179
1180 // Some backends require that the shader outputs be uint when writing to a uint render target
1181 // for logic op.
1182 if (uid_data->uint_output)
1183 {
1184 out.Write(" if (bpmem_rgba6_format)\n"
1185 " ocol0 = uint4(TevResult & 0xFC);\n"
1186 " else\n"
1187 " ocol0 = uint4(TevResult);\n"
1188 "\n");
1189 }
1190 else
1191 {
1192 out.Write(" if (bpmem_rgba6_format)\n"
1193 " ocol0.rgb = float3(TevResult.rgb >> 2) / 63.0;\n"
1194 " else\n"
1195 " ocol0.rgb = float3(TevResult.rgb) / 255.0;\n"
1196 "\n"
1197 " if (bpmem_dstalpha != 0u)\n");
1198 out.Write(" ocol0.a = float({} >> 2) / 63.0;\n",
1199 BitfieldExtract<&ConstantAlpha::alpha>("bpmem_dstalpha"));
1200 out.Write(" else\n"
1201 " ocol0.a = float(TevResult.a >> 2) / 63.0;\n"
1202 " \n");
1203
1204 if (use_dual_source || use_framebuffer_fetch)
1205 {
1206 out.Write(" // Dest alpha override (dual source blending)\n"
1207 " // Colors will be blended against the alpha from ocol1 and\n"
1208 " // the alpha from ocol0 will be written to the framebuffer.\n"
1209 " ocol1 = float4(0.0, 0.0, 0.0, float(TevResult.a) / 255.0);\n");
1210 }
1211 }
1212
1213 if (bounding_box)
1214 {
1215 out.Write(" if (bpmem_bounding_box) {{\n"
1216 " UpdateBoundingBox(rawpos.xy);\n"
1217 " }}\n");
1218 }
1219
1220 if (use_framebuffer_fetch)
1221 {
1222 using Common::EnumMap;
1223
1224 static constexpr EnumMap<std::string_view, SrcBlendFactor::InvDstAlpha> blendSrcFactor{
1225 "blend_src.rgb = float3(0,0,0);", // ZERO
1226 "blend_src.rgb = float3(1,1,1);", // ONE
1227 "blend_src.rgb = initial_ocol0.rgb;", // DSTCLR
1228 "blend_src.rgb = float3(1,1,1) - initial_ocol0.rgb;", // INVDSTCLR
1229 "blend_src.rgb = src_color.aaa;", // SRCALPHA
1230 "blend_src.rgb = float3(1,1,1) - src_color.aaa;", // INVSRCALPHA
1231 "blend_src.rgb = initial_ocol0.aaa;", // DSTALPHA
1232 "blend_src.rgb = float3(1,1,1) - initial_ocol0.aaa;", // INVDSTALPHA
1233 };
1234 static constexpr EnumMap<std::string_view, SrcBlendFactor::InvDstAlpha> blendSrcFactorAlpha{
1235 "blend_src.a = 0.0;", // ZERO
1236 "blend_src.a = 1.0;", // ONE
1237 "blend_src.a = initial_ocol0.a;", // DSTCLR
1238 "blend_src.a = 1.0 - initial_ocol0.a;", // INVDSTCLR
1239 "blend_src.a = src_color.a;", // SRCALPHA
1240 "blend_src.a = 1.0 - src_color.a;", // INVSRCALPHA
1241 "blend_src.a = initial_ocol0.a;", // DSTALPHA
1242 "blend_src.a = 1.0 - initial_ocol0.a;", // INVDSTALPHA
1243 };
1244 static constexpr EnumMap<std::string_view, DstBlendFactor::InvDstAlpha> blendDstFactor{
1245 "blend_dst.rgb = float3(0,0,0);", // ZERO
1246 "blend_dst.rgb = float3(1,1,1);", // ONE
1247 "blend_dst.rgb = ocol0.rgb;", // SRCCLR
1248 "blend_dst.rgb = float3(1,1,1) - ocol0.rgb;", // INVSRCCLR
1249 "blend_dst.rgb = src_color.aaa;", // SRCALHA
1250 "blend_dst.rgb = float3(1,1,1) - src_color.aaa;", // INVSRCALPHA
1251 "blend_dst.rgb = initial_ocol0.aaa;", // DSTALPHA
1252 "blend_dst.rgb = float3(1,1,1) - initial_ocol0.aaa;", // INVDSTALPHA
1253 };
1254 static constexpr EnumMap<std::string_view, DstBlendFactor::InvDstAlpha> blendDstFactorAlpha{
1255 "blend_dst.a = 0.0;", // ZERO
1256 "blend_dst.a = 1.0;", // ONE
1257 "blend_dst.a = ocol0.a;", // SRCCLR
1258 "blend_dst.a = 1.0 - ocol0.a;", // INVSRCCLR
1259 "blend_dst.a = src_color.a;", // SRCALPHA
1260 "blend_dst.a = 1.0 - src_color.a;", // INVSRCALPHA
1261 "blend_dst.a = initial_ocol0.a;", // DSTALPHA
1262 "blend_dst.a = 1.0 - initial_ocol0.a;", // INVDSTALPHA
1263 };
1264
1265 out.Write(" if (blend_enable) {{\n"
1266 " float4 src_color;\n"
1267 " if (bpmem_dstalpha != 0u) {{\n"
1268 " src_color = ocol1;\n"
1269 " }} else {{\n"
1270 " src_color = ocol0;\n"
1271 " }}"
1272 " float4 blend_src;\n");
1273 WriteSwitch(out, api_type, "blend_src_factor", blendSrcFactor, 4, true);
1274 WriteSwitch(out, api_type, "blend_src_factor_alpha", blendSrcFactorAlpha, 4, true);
1275
1276 out.Write(" float4 blend_dst;\n");
1277 WriteSwitch(out, api_type, "blend_dst_factor", blendDstFactor, 4, true);
1278 WriteSwitch(out, api_type, "blend_dst_factor_alpha", blendDstFactorAlpha, 4, true);
1279
1280 out.Write(" float4 blend_result;\n"
1281 " if (blend_subtract)\n"
1282 " blend_result.rgb = initial_ocol0.rgb * blend_dst.rgb - ocol0.rgb * "
1283 "blend_src.rgb;\n"
1284 " else\n"
1285 " blend_result.rgb = initial_ocol0.rgb * blend_dst.rgb + ocol0.rgb * "
1286 "blend_src.rgb;\n");
1287
1288 out.Write(" if (blend_subtract_alpha)\n"
1289 " blend_result.a = initial_ocol0.a * blend_dst.a - ocol0.a * blend_src.a;\n"
1290 " else\n"
1291 " blend_result.a = initial_ocol0.a * blend_dst.a + ocol0.a * blend_src.a;\n");
1292
1293 out.Write(" real_ocol0 = blend_result;\n");
1294
1295 out.Write(" }} else {{\n"
1296 " real_ocol0 = ocol0;\n"
1297 " }}\n");
1298 }
1299
1300 out.Write("}}\n"
1301 "\n"
1302 "int4 getRasColor(State s, StageState ss, float4 colors_0, float4 colors_1) {{\n"
1303 " // Select Ras for stage\n"
1304 " uint ras = {};\n",
1305 BitfieldExtract<&TwoTevStageOrders::colorchan_even>("ss.order"));
1306 out.Write(" if (ras < 2u) {{ // Lighting Channel 0 or 1\n"
1307 " int4 color = iround(((ras == 0u) ? colors_0 : colors_1) * 255.0);\n"
1308 " uint swap = {};\n",
1309 BitfieldExtract<&TevStageCombiner::AlphaCombiner::rswap>("ss.ac"));
1310 out.Write(" return Swizzle(swap, color);\n");
1311 out.Write(" }} else if (ras == 5u) {{ // Alpha Bump\n"
1312 " return int4(s.AlphaBump, s.AlphaBump, s.AlphaBump, s.AlphaBump);\n"
1313 " }} else if (ras == 6u) {{ // Normalzied Alpha Bump\n"
1314 " int normalized = s.AlphaBump | s.AlphaBump >> 5;\n"
1315 " return int4(normalized, normalized, normalized, normalized);\n"
1316 " }} else {{\n"
1317 " return int4(0, 0, 0, 0);\n"
1318 " }}\n"
1319 "}}\n"
1320 "\n"
1321 "int4 getKonstColor(State s, StageState ss) {{\n"
1322 " // Select Konst for stage\n"
1323 " // TODO: a switch case might be better here than an dynamically"
1324 " // indexed uniform lookup\n"
1325 " uint tevksel = bpmem_tevksel(ss.stage>>1);\n"
1326 " if ((ss.stage & 1u) == 0u)\n"
1327 " return int4(konstLookup[{}].rgb, konstLookup[{}].a);\n",
1328 BitfieldExtract<&TevKSel::kcsel_even>("tevksel"),
1329 BitfieldExtract<&TevKSel::kasel_even>("tevksel"));
1330 out.Write(" else\n"
1331 " return int4(konstLookup[{}].rgb, konstLookup[{}].a);\n",
1332 BitfieldExtract<&TevKSel::kcsel_odd>("tevksel"),
1333 BitfieldExtract<&TevKSel::kasel_odd>("tevksel"));
1334 out.Write("}}\n");
1335
1336 return out;
1337 }
1338
1339 void EnumeratePixelShaderUids(const std::function<void(const PixelShaderUid&)>& callback)
1340 {
1341 PixelShaderUid uid;
1342
1343 for (u32 texgens = 0; texgens <= 8; texgens++)
1344 {
1345 pixel_ubershader_uid_data* const puid = uid.GetUidData();
1346 puid->num_texgens = texgens;
1347
1348 for (u32 early_depth = 0; early_depth < 2; early_depth++)
1349 {
1350 puid->early_depth = early_depth != 0;
1351 for (u32 per_pixel_depth = 0; per_pixel_depth < 2; per_pixel_depth++)
1352 {
1353 // Don't generate shaders where we have early depth tests enabled, and write gl_FragDepth.
1354 if (early_depth && per_pixel_depth)
1355 continue;
1356
1357 puid->per_pixel_depth = per_pixel_depth != 0;
1358 for (u32 uint_output = 0; uint_output < 2; uint_output++)
1359 {
1360 puid->uint_output = uint_output;
1361 for (u32 no_dual_src = 0; no_dual_src < 2; no_dual_src++)
1362 {
1363 puid->no_dual_src = no_dual_src;
1364 callback(uid);
1365 }
1366 }
1367 }
1368 }
1369 }
1370 }
1371 } // namespace UberShader