summaryrefslogtreecommitdiff
path: root/src/video_core/swrasterizer/rasterizer.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/video_core/swrasterizer/rasterizer.cpp')
-rw-r--r--src/video_core/swrasterizer/rasterizer.cpp853
1 files changed, 0 insertions, 853 deletions
diff --git a/src/video_core/swrasterizer/rasterizer.cpp b/src/video_core/swrasterizer/rasterizer.cpp
deleted file mode 100644
index 862135614..000000000
--- a/src/video_core/swrasterizer/rasterizer.cpp
+++ /dev/null
@@ -1,853 +0,0 @@
1// Copyright 2014 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6#include <array>
7#include <cmath>
8#include <tuple>
9#include "common/assert.h"
10#include "common/bit_field.h"
11#include "common/color.h"
12#include "common/common_types.h"
13#include "common/logging/log.h"
14#include "common/math_util.h"
15#include "common/microprofile.h"
16#include "common/quaternion.h"
17#include "common/vector_math.h"
18#include "core/hw/gpu.h"
19#include "core/memory.h"
20#include "video_core/debug_utils/debug_utils.h"
21#include "video_core/pica_state.h"
22#include "video_core/pica_types.h"
23#include "video_core/regs_framebuffer.h"
24#include "video_core/regs_rasterizer.h"
25#include "video_core/regs_texturing.h"
26#include "video_core/shader/shader.h"
27#include "video_core/swrasterizer/framebuffer.h"
28#include "video_core/swrasterizer/lighting.h"
29#include "video_core/swrasterizer/proctex.h"
30#include "video_core/swrasterizer/rasterizer.h"
31#include "video_core/swrasterizer/texturing.h"
32#include "video_core/texture/texture_decode.h"
33#include "video_core/utils.h"
34
35namespace Pica {
36namespace Rasterizer {
37
38// NOTE: Assuming that rasterizer coordinates are 12.4 fixed-point values
39struct Fix12P4 {
40 Fix12P4() {}
41 Fix12P4(u16 val) : val(val) {}
42
43 static u16 FracMask() {
44 return 0xF;
45 }
46 static u16 IntMask() {
47 return (u16)~0xF;
48 }
49
50 operator u16() const {
51 return val;
52 }
53
54 bool operator<(const Fix12P4& oth) const {
55 return (u16) * this < (u16)oth;
56 }
57
58private:
59 u16 val;
60};
61
62/**
63 * Calculate signed area of the triangle spanned by the three argument vertices.
64 * The sign denotes an orientation.
65 *
66 * @todo define orientation concretely.
67 */
68static int SignedArea(const Math::Vec2<Fix12P4>& vtx1, const Math::Vec2<Fix12P4>& vtx2,
69 const Math::Vec2<Fix12P4>& vtx3) {
70 const auto vec1 = Math::MakeVec(vtx2 - vtx1, 0);
71 const auto vec2 = Math::MakeVec(vtx3 - vtx1, 0);
72 // TODO: There is a very small chance this will overflow for sizeof(int) == 4
73 return Math::Cross(vec1, vec2).z;
74};
75
76/// Convert a 3D vector for cube map coordinates to 2D texture coordinates along with the face name
77static std::tuple<float24, float24, PAddr> ConvertCubeCoord(float24 u, float24 v, float24 w,
78 const TexturingRegs& regs) {
79 const float abs_u = std::abs(u.ToFloat32());
80 const float abs_v = std::abs(v.ToFloat32());
81 const float abs_w = std::abs(w.ToFloat32());
82 float24 x, y, z;
83 PAddr addr;
84 if (abs_u > abs_v && abs_u > abs_w) {
85 if (u > float24::FromFloat32(0)) {
86 addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::PositiveX);
87 y = -v;
88 } else {
89 addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::NegativeX);
90 y = v;
91 }
92 x = -w;
93 z = u;
94 } else if (abs_v > abs_w) {
95 if (v > float24::FromFloat32(0)) {
96 addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::PositiveY);
97 x = u;
98 } else {
99 addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::NegativeY);
100 x = -u;
101 }
102 y = w;
103 z = v;
104 } else {
105 if (w > float24::FromFloat32(0)) {
106 addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::PositiveZ);
107 y = -v;
108 } else {
109 addr = regs.GetCubePhysicalAddress(TexturingRegs::CubeFace::NegativeZ);
110 y = v;
111 }
112 x = u;
113 z = w;
114 }
115 const float24 half = float24::FromFloat32(0.5f);
116 return std::make_tuple(x / z * half + half, y / z * half + half, addr);
117}
118
119MICROPROFILE_DEFINE(GPU_Rasterization, "GPU", "Rasterization", MP_RGB(50, 50, 240));
120
121/**
122 * Helper function for ProcessTriangle with the "reversed" flag to allow for implementing
123 * culling via recursion.
124 */
125static void ProcessTriangleInternal(const Vertex& v0, const Vertex& v1, const Vertex& v2,
126 bool reversed = false) {
127 const auto& regs = g_state.regs;
128 MICROPROFILE_SCOPE(GPU_Rasterization);
129
130 // vertex positions in rasterizer coordinates
131 static auto FloatToFix = [](float24 flt) {
132 // TODO: Rounding here is necessary to prevent garbage pixels at
133 // triangle borders. Is it that the correct solution, though?
134 return Fix12P4(static_cast<unsigned short>(round(flt.ToFloat32() * 16.0f)));
135 };
136 static auto ScreenToRasterizerCoordinates = [](const Math::Vec3<float24>& vec) {
137 return Math::Vec3<Fix12P4>{FloatToFix(vec.x), FloatToFix(vec.y), FloatToFix(vec.z)};
138 };
139
140 Math::Vec3<Fix12P4> vtxpos[3]{ScreenToRasterizerCoordinates(v0.screenpos),
141 ScreenToRasterizerCoordinates(v1.screenpos),
142 ScreenToRasterizerCoordinates(v2.screenpos)};
143
144 if (regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepAll) {
145 // Make sure we always end up with a triangle wound counter-clockwise
146 if (!reversed && SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0) {
147 ProcessTriangleInternal(v0, v2, v1, true);
148 return;
149 }
150 } else {
151 if (!reversed && regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepClockWise) {
152 // Reverse vertex order and use the CCW code path.
153 ProcessTriangleInternal(v0, v2, v1, true);
154 return;
155 }
156
157 // Cull away triangles which are wound clockwise.
158 if (SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0)
159 return;
160 }
161
162 u16 min_x = std::min({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
163 u16 min_y = std::min({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
164 u16 max_x = std::max({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
165 u16 max_y = std::max({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
166
167 // Convert the scissor box coordinates to 12.4 fixed point
168 u16 scissor_x1 = (u16)(regs.rasterizer.scissor_test.x1 << 4);
169 u16 scissor_y1 = (u16)(regs.rasterizer.scissor_test.y1 << 4);
170 // x2,y2 have +1 added to cover the entire sub-pixel area
171 u16 scissor_x2 = (u16)((regs.rasterizer.scissor_test.x2 + 1) << 4);
172 u16 scissor_y2 = (u16)((regs.rasterizer.scissor_test.y2 + 1) << 4);
173
174 if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Include) {
175 // Calculate the new bounds
176 min_x = std::max(min_x, scissor_x1);
177 min_y = std::max(min_y, scissor_y1);
178 max_x = std::min(max_x, scissor_x2);
179 max_y = std::min(max_y, scissor_y2);
180 }
181
182 min_x &= Fix12P4::IntMask();
183 min_y &= Fix12P4::IntMask();
184 max_x = ((max_x + Fix12P4::FracMask()) & Fix12P4::IntMask());
185 max_y = ((max_y + Fix12P4::FracMask()) & Fix12P4::IntMask());
186
187 // Triangle filling rules: Pixels on the right-sided edge or on flat bottom edges are not
188 // drawn. Pixels on any other triangle border are drawn. This is implemented with three bias
189 // values which are added to the barycentric coordinates w0, w1 and w2, respectively.
190 // NOTE: These are the PSP filling rules. Not sure if the 3DS uses the same ones...
191 auto IsRightSideOrFlatBottomEdge = [](const Math::Vec2<Fix12P4>& vtx,
192 const Math::Vec2<Fix12P4>& line1,
193 const Math::Vec2<Fix12P4>& line2) {
194 if (line1.y == line2.y) {
195 // just check if vertex is above us => bottom line parallel to x-axis
196 return vtx.y < line1.y;
197 } else {
198 // check if vertex is on our left => right side
199 // TODO: Not sure how likely this is to overflow
200 return (int)vtx.x < (int)line1.x +
201 ((int)line2.x - (int)line1.x) * ((int)vtx.y - (int)line1.y) /
202 ((int)line2.y - (int)line1.y);
203 }
204 };
205 int bias0 =
206 IsRightSideOrFlatBottomEdge(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) ? -1 : 0;
207 int bias1 =
208 IsRightSideOrFlatBottomEdge(vtxpos[1].xy(), vtxpos[2].xy(), vtxpos[0].xy()) ? -1 : 0;
209 int bias2 =
210 IsRightSideOrFlatBottomEdge(vtxpos[2].xy(), vtxpos[0].xy(), vtxpos[1].xy()) ? -1 : 0;
211
212 auto w_inverse = Math::MakeVec(v0.pos.w, v1.pos.w, v2.pos.w);
213
214 auto textures = regs.texturing.GetTextures();
215 auto tev_stages = regs.texturing.GetTevStages();
216
217 bool stencil_action_enable =
218 g_state.regs.framebuffer.output_merger.stencil_test.enable &&
219 g_state.regs.framebuffer.framebuffer.depth_format == FramebufferRegs::DepthFormat::D24S8;
220 const auto stencil_test = g_state.regs.framebuffer.output_merger.stencil_test;
221
222 // Enter rasterization loop, starting at the center of the topleft bounding box corner.
223 // TODO: Not sure if looping through x first might be faster
224 for (u16 y = min_y + 8; y < max_y; y += 0x10) {
225 for (u16 x = min_x + 8; x < max_x; x += 0x10) {
226
227 // Do not process the pixel if it's inside the scissor box and the scissor mode is set
228 // to Exclude
229 if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Exclude) {
230 if (x >= scissor_x1 && x < scissor_x2 && y >= scissor_y1 && y < scissor_y2)
231 continue;
232 }
233
234 // Calculate the barycentric coordinates w0, w1 and w2
235 int w0 = bias0 + SignedArea(vtxpos[1].xy(), vtxpos[2].xy(), {x, y});
236 int w1 = bias1 + SignedArea(vtxpos[2].xy(), vtxpos[0].xy(), {x, y});
237 int w2 = bias2 + SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), {x, y});
238 int wsum = w0 + w1 + w2;
239
240 // If current pixel is not covered by the current primitive
241 if (w0 < 0 || w1 < 0 || w2 < 0)
242 continue;
243
244 auto baricentric_coordinates =
245 Math::MakeVec(float24::FromFloat32(static_cast<float>(w0)),
246 float24::FromFloat32(static_cast<float>(w1)),
247 float24::FromFloat32(static_cast<float>(w2)));
248 float24 interpolated_w_inverse =
249 float24::FromFloat32(1.0f) / Math::Dot(w_inverse, baricentric_coordinates);
250
251 // interpolated_z = z / w
252 float interpolated_z_over_w =
253 (v0.screenpos[2].ToFloat32() * w0 + v1.screenpos[2].ToFloat32() * w1 +
254 v2.screenpos[2].ToFloat32() * w2) /
255 wsum;
256
257 // Not fully accurate. About 3 bits in precision are missing.
258 // Z-Buffer (z / w * scale + offset)
259 float depth_scale = float24::FromRaw(regs.rasterizer.viewport_depth_range).ToFloat32();
260 float depth_offset =
261 float24::FromRaw(regs.rasterizer.viewport_depth_near_plane).ToFloat32();
262 float depth = interpolated_z_over_w * depth_scale + depth_offset;
263
264 // Potentially switch to W-Buffer
265 if (regs.rasterizer.depthmap_enable ==
266 Pica::RasterizerRegs::DepthBuffering::WBuffering) {
267 // W-Buffer (z * scale + w * offset = (z / w * scale + offset) * w)
268 depth *= interpolated_w_inverse.ToFloat32() * wsum;
269 }
270
271 // Clamp the result
272 depth = MathUtil::Clamp(depth, 0.0f, 1.0f);
273
274 // Perspective correct attribute interpolation:
275 // Attribute values cannot be calculated by simple linear interpolation since
276 // they are not linear in screen space. For example, when interpolating a
277 // texture coordinate across two vertices, something simple like
278 // u = (u0*w0 + u1*w1)/(w0+w1)
279 // will not work. However, the attribute value divided by the
280 // clipspace w-coordinate (u/w) and and the inverse w-coordinate (1/w) are linear
281 // in screenspace. Hence, we can linearly interpolate these two independently and
282 // calculate the interpolated attribute by dividing the results.
283 // I.e.
284 // u_over_w = ((u0/v0.pos.w)*w0 + (u1/v1.pos.w)*w1)/(w0+w1)
285 // one_over_w = (( 1/v0.pos.w)*w0 + ( 1/v1.pos.w)*w1)/(w0+w1)
286 // u = u_over_w / one_over_w
287 //
288 // The generalization to three vertices is straightforward in baricentric coordinates.
289 auto GetInterpolatedAttribute = [&](float24 attr0, float24 attr1, float24 attr2) {
290 auto attr_over_w = Math::MakeVec(attr0, attr1, attr2);
291 float24 interpolated_attr_over_w = Math::Dot(attr_over_w, baricentric_coordinates);
292 return interpolated_attr_over_w * interpolated_w_inverse;
293 };
294
295 Math::Vec4<u8> primary_color{
296 (u8)(
297 GetInterpolatedAttribute(v0.color.r(), v1.color.r(), v2.color.r()).ToFloat32() *
298 255),
299 (u8)(
300 GetInterpolatedAttribute(v0.color.g(), v1.color.g(), v2.color.g()).ToFloat32() *
301 255),
302 (u8)(
303 GetInterpolatedAttribute(v0.color.b(), v1.color.b(), v2.color.b()).ToFloat32() *
304 255),
305 (u8)(
306 GetInterpolatedAttribute(v0.color.a(), v1.color.a(), v2.color.a()).ToFloat32() *
307 255),
308 };
309
310 Math::Vec2<float24> uv[3];
311 uv[0].u() = GetInterpolatedAttribute(v0.tc0.u(), v1.tc0.u(), v2.tc0.u());
312 uv[0].v() = GetInterpolatedAttribute(v0.tc0.v(), v1.tc0.v(), v2.tc0.v());
313 uv[1].u() = GetInterpolatedAttribute(v0.tc1.u(), v1.tc1.u(), v2.tc1.u());
314 uv[1].v() = GetInterpolatedAttribute(v0.tc1.v(), v1.tc1.v(), v2.tc1.v());
315 uv[2].u() = GetInterpolatedAttribute(v0.tc2.u(), v1.tc2.u(), v2.tc2.u());
316 uv[2].v() = GetInterpolatedAttribute(v0.tc2.v(), v1.tc2.v(), v2.tc2.v());
317
318 Math::Vec4<u8> texture_color[4]{};
319 for (int i = 0; i < 3; ++i) {
320 const auto& texture = textures[i];
321 if (!texture.enabled)
322 continue;
323
324 DEBUG_ASSERT(0 != texture.config.address);
325
326 int coordinate_i =
327 (i == 2 && regs.texturing.main_config.texture2_use_coord1) ? 1 : i;
328 float24 u = uv[coordinate_i].u();
329 float24 v = uv[coordinate_i].v();
330
331 // Only unit 0 respects the texturing type (according to 3DBrew)
332 // TODO: Refactor so cubemaps and shadowmaps can be handled
333 PAddr texture_address = texture.config.GetPhysicalAddress();
334 if (i == 0) {
335 switch (texture.config.type) {
336 case TexturingRegs::TextureConfig::Texture2D:
337 break;
338 case TexturingRegs::TextureConfig::TextureCube: {
339 auto w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
340 std::tie(u, v, texture_address) = ConvertCubeCoord(u, v, w, regs.texturing);
341 break;
342 }
343 case TexturingRegs::TextureConfig::Projection2D: {
344 auto tc0_w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
345 u /= tc0_w;
346 v /= tc0_w;
347 break;
348 }
349 default:
350 // TODO: Change to LOG_ERROR when more types are handled.
351 LOG_DEBUG(HW_GPU, "Unhandled texture type %x", (int)texture.config.type);
352 UNIMPLEMENTED();
353 break;
354 }
355 }
356
357 int s = (int)(u * float24::FromFloat32(static_cast<float>(texture.config.width)))
358 .ToFloat32();
359 int t = (int)(v * float24::FromFloat32(static_cast<float>(texture.config.height)))
360 .ToFloat32();
361
362 bool use_border_s = false;
363 bool use_border_t = false;
364
365 if (texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder) {
366 use_border_s = s < 0 || s >= static_cast<int>(texture.config.width);
367 } else if (texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder2) {
368 use_border_s = s >= static_cast<int>(texture.config.width);
369 }
370
371 if (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder) {
372 use_border_t = t < 0 || t >= static_cast<int>(texture.config.height);
373 } else if (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder2) {
374 use_border_t = t >= static_cast<int>(texture.config.height);
375 }
376
377 if (use_border_s || use_border_t) {
378 auto border_color = texture.config.border_color;
379 texture_color[i] = {border_color.r, border_color.g, border_color.b,
380 border_color.a};
381 } else {
382 // Textures are laid out from bottom to top, hence we invert the t coordinate.
383 // NOTE: This may not be the right place for the inversion.
384 // TODO: Check if this applies to ETC textures, too.
385 s = GetWrappedTexCoord(texture.config.wrap_s, s, texture.config.width);
386 t = texture.config.height - 1 -
387 GetWrappedTexCoord(texture.config.wrap_t, t, texture.config.height);
388
389 const u8* texture_data = Memory::GetPhysicalPointer(texture_address);
390 auto info =
391 Texture::TextureInfo::FromPicaRegister(texture.config, texture.format);
392
393 // TODO: Apply the min and mag filters to the texture
394 texture_color[i] = Texture::LookupTexture(texture_data, s, t, info);
395#if PICA_DUMP_TEXTURES
396 DebugUtils::DumpTexture(texture.config, texture_data);
397#endif
398 }
399 }
400
401 // sample procedural texture
402 if (regs.texturing.main_config.texture3_enable) {
403 const auto& proctex_uv = uv[regs.texturing.main_config.texture3_coordinates];
404 texture_color[3] = ProcTex(proctex_uv.u().ToFloat32(), proctex_uv.v().ToFloat32(),
405 g_state.regs.texturing, g_state.proctex);
406 }
407
408 // Texture environment - consists of 6 stages of color and alpha combining.
409 //
410 // Color combiners take three input color values from some source (e.g. interpolated
411 // vertex color, texture color, previous stage, etc), perform some very simple
412 // operations on each of them (e.g. inversion) and then calculate the output color
413 // with some basic arithmetic. Alpha combiners can be configured separately but work
414 // analogously.
415 Math::Vec4<u8> combiner_output;
416 Math::Vec4<u8> combiner_buffer = {0, 0, 0, 0};
417 Math::Vec4<u8> next_combiner_buffer = {
418 regs.texturing.tev_combiner_buffer_color.r,
419 regs.texturing.tev_combiner_buffer_color.g,
420 regs.texturing.tev_combiner_buffer_color.b,
421 regs.texturing.tev_combiner_buffer_color.a,
422 };
423
424 Math::Vec4<u8> primary_fragment_color = {0, 0, 0, 0};
425 Math::Vec4<u8> secondary_fragment_color = {0, 0, 0, 0};
426
427 if (!g_state.regs.lighting.disable) {
428 Math::Quaternion<float> normquat = Math::Quaternion<float>{
429 {GetInterpolatedAttribute(v0.quat.x, v1.quat.x, v2.quat.x).ToFloat32(),
430 GetInterpolatedAttribute(v0.quat.y, v1.quat.y, v2.quat.y).ToFloat32(),
431 GetInterpolatedAttribute(v0.quat.z, v1.quat.z, v2.quat.z).ToFloat32()},
432 GetInterpolatedAttribute(v0.quat.w, v1.quat.w, v2.quat.w).ToFloat32(),
433 }.Normalized();
434
435 Math::Vec3<float> view{
436 GetInterpolatedAttribute(v0.view.x, v1.view.x, v2.view.x).ToFloat32(),
437 GetInterpolatedAttribute(v0.view.y, v1.view.y, v2.view.y).ToFloat32(),
438 GetInterpolatedAttribute(v0.view.z, v1.view.z, v2.view.z).ToFloat32(),
439 };
440 std::tie(primary_fragment_color, secondary_fragment_color) = ComputeFragmentsColors(
441 g_state.regs.lighting, g_state.lighting, normquat, view, texture_color);
442 }
443
444 for (unsigned tev_stage_index = 0; tev_stage_index < tev_stages.size();
445 ++tev_stage_index) {
446 const auto& tev_stage = tev_stages[tev_stage_index];
447 using Source = TexturingRegs::TevStageConfig::Source;
448
449 auto GetSource = [&](Source source) -> Math::Vec4<u8> {
450 switch (source) {
451 case Source::PrimaryColor:
452 return primary_color;
453
454 case Source::PrimaryFragmentColor:
455 return primary_fragment_color;
456
457 case Source::SecondaryFragmentColor:
458 return secondary_fragment_color;
459
460 case Source::Texture0:
461 return texture_color[0];
462
463 case Source::Texture1:
464 return texture_color[1];
465
466 case Source::Texture2:
467 return texture_color[2];
468
469 case Source::Texture3:
470 return texture_color[3];
471
472 case Source::PreviousBuffer:
473 return combiner_buffer;
474
475 case Source::Constant:
476 return {tev_stage.const_r, tev_stage.const_g, tev_stage.const_b,
477 tev_stage.const_a};
478
479 case Source::Previous:
480 return combiner_output;
481
482 default:
483 LOG_ERROR(HW_GPU, "Unknown color combiner source %d", (int)source);
484 UNIMPLEMENTED();
485 return {0, 0, 0, 0};
486 }
487 };
488
489 // color combiner
490 // NOTE: Not sure if the alpha combiner might use the color output of the previous
491 // stage as input. Hence, we currently don't directly write the result to
492 // combiner_output.rgb(), but instead store it in a temporary variable until
493 // alpha combining has been done.
494 Math::Vec3<u8> color_result[3] = {
495 GetColorModifier(tev_stage.color_modifier1, GetSource(tev_stage.color_source1)),
496 GetColorModifier(tev_stage.color_modifier2, GetSource(tev_stage.color_source2)),
497 GetColorModifier(tev_stage.color_modifier3, GetSource(tev_stage.color_source3)),
498 };
499 auto color_output = ColorCombine(tev_stage.color_op, color_result);
500
501 u8 alpha_output;
502 if (tev_stage.color_op == TexturingRegs::TevStageConfig::Operation::Dot3_RGBA) {
503 // result of Dot3_RGBA operation is also placed to the alpha component
504 alpha_output = color_output.x;
505 } else {
506 // alpha combiner
507 std::array<u8, 3> alpha_result = {{
508 GetAlphaModifier(tev_stage.alpha_modifier1,
509 GetSource(tev_stage.alpha_source1)),
510 GetAlphaModifier(tev_stage.alpha_modifier2,
511 GetSource(tev_stage.alpha_source2)),
512 GetAlphaModifier(tev_stage.alpha_modifier3,
513 GetSource(tev_stage.alpha_source3)),
514 }};
515 alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result);
516 }
517
518 combiner_output[0] =
519 std::min((unsigned)255, color_output.r() * tev_stage.GetColorMultiplier());
520 combiner_output[1] =
521 std::min((unsigned)255, color_output.g() * tev_stage.GetColorMultiplier());
522 combiner_output[2] =
523 std::min((unsigned)255, color_output.b() * tev_stage.GetColorMultiplier());
524 combiner_output[3] =
525 std::min((unsigned)255, alpha_output * tev_stage.GetAlphaMultiplier());
526
527 combiner_buffer = next_combiner_buffer;
528
529 if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferColor(
530 tev_stage_index)) {
531 next_combiner_buffer.r() = combiner_output.r();
532 next_combiner_buffer.g() = combiner_output.g();
533 next_combiner_buffer.b() = combiner_output.b();
534 }
535
536 if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferAlpha(
537 tev_stage_index)) {
538 next_combiner_buffer.a() = combiner_output.a();
539 }
540 }
541
542 const auto& output_merger = regs.framebuffer.output_merger;
543 // TODO: Does alpha testing happen before or after stencil?
544 if (output_merger.alpha_test.enable) {
545 bool pass = false;
546
547 switch (output_merger.alpha_test.func) {
548 case FramebufferRegs::CompareFunc::Never:
549 pass = false;
550 break;
551
552 case FramebufferRegs::CompareFunc::Always:
553 pass = true;
554 break;
555
556 case FramebufferRegs::CompareFunc::Equal:
557 pass = combiner_output.a() == output_merger.alpha_test.ref;
558 break;
559
560 case FramebufferRegs::CompareFunc::NotEqual:
561 pass = combiner_output.a() != output_merger.alpha_test.ref;
562 break;
563
564 case FramebufferRegs::CompareFunc::LessThan:
565 pass = combiner_output.a() < output_merger.alpha_test.ref;
566 break;
567
568 case FramebufferRegs::CompareFunc::LessThanOrEqual:
569 pass = combiner_output.a() <= output_merger.alpha_test.ref;
570 break;
571
572 case FramebufferRegs::CompareFunc::GreaterThan:
573 pass = combiner_output.a() > output_merger.alpha_test.ref;
574 break;
575
576 case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
577 pass = combiner_output.a() >= output_merger.alpha_test.ref;
578 break;
579 }
580
581 if (!pass)
582 continue;
583 }
584
585 // Apply fog combiner
586 // Not fully accurate. We'd have to know what data type is used to
587 // store the depth etc. Using float for now until we know more
588 // about Pica datatypes
589 if (regs.texturing.fog_mode == TexturingRegs::FogMode::Fog) {
590 const Math::Vec3<u8> fog_color = {
591 static_cast<u8>(regs.texturing.fog_color.r.Value()),
592 static_cast<u8>(regs.texturing.fog_color.g.Value()),
593 static_cast<u8>(regs.texturing.fog_color.b.Value()),
594 };
595
596 // Get index into fog LUT
597 float fog_index;
598 if (g_state.regs.texturing.fog_flip) {
599 fog_index = (1.0f - depth) * 128.0f;
600 } else {
601 fog_index = depth * 128.0f;
602 }
603
604 // Generate clamped fog factor from LUT for given fog index
605 float fog_i = MathUtil::Clamp(floorf(fog_index), 0.0f, 127.0f);
606 float fog_f = fog_index - fog_i;
607 const auto& fog_lut_entry = g_state.fog.lut[static_cast<unsigned int>(fog_i)];
608 float fog_factor = fog_lut_entry.ToFloat() + fog_lut_entry.DiffToFloat() * fog_f;
609 fog_factor = MathUtil::Clamp(fog_factor, 0.0f, 1.0f);
610
611 // Blend the fog
612 for (unsigned i = 0; i < 3; i++) {
613 combiner_output[i] = static_cast<u8>(fog_factor * combiner_output[i] +
614 (1.0f - fog_factor) * fog_color[i]);
615 }
616 }
617
618 u8 old_stencil = 0;
619
620 auto UpdateStencil = [stencil_test, x, y,
621 &old_stencil](Pica::FramebufferRegs::StencilAction action) {
622 u8 new_stencil =
623 PerformStencilAction(action, old_stencil, stencil_test.reference_value);
624 if (g_state.regs.framebuffer.framebuffer.allow_depth_stencil_write != 0)
625 SetStencil(x >> 4, y >> 4, (new_stencil & stencil_test.write_mask) |
626 (old_stencil & ~stencil_test.write_mask));
627 };
628
629 if (stencil_action_enable) {
630 old_stencil = GetStencil(x >> 4, y >> 4);
631 u8 dest = old_stencil & stencil_test.input_mask;
632 u8 ref = stencil_test.reference_value & stencil_test.input_mask;
633
634 bool pass = false;
635 switch (stencil_test.func) {
636 case FramebufferRegs::CompareFunc::Never:
637 pass = false;
638 break;
639
640 case FramebufferRegs::CompareFunc::Always:
641 pass = true;
642 break;
643
644 case FramebufferRegs::CompareFunc::Equal:
645 pass = (ref == dest);
646 break;
647
648 case FramebufferRegs::CompareFunc::NotEqual:
649 pass = (ref != dest);
650 break;
651
652 case FramebufferRegs::CompareFunc::LessThan:
653 pass = (ref < dest);
654 break;
655
656 case FramebufferRegs::CompareFunc::LessThanOrEqual:
657 pass = (ref <= dest);
658 break;
659
660 case FramebufferRegs::CompareFunc::GreaterThan:
661 pass = (ref > dest);
662 break;
663
664 case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
665 pass = (ref >= dest);
666 break;
667 }
668
669 if (!pass) {
670 UpdateStencil(stencil_test.action_stencil_fail);
671 continue;
672 }
673 }
674
675 // Convert float to integer
676 unsigned num_bits =
677 FramebufferRegs::DepthBitsPerPixel(regs.framebuffer.framebuffer.depth_format);
678 u32 z = (u32)(depth * ((1 << num_bits) - 1));
679
680 if (output_merger.depth_test_enable) {
681 u32 ref_z = GetDepth(x >> 4, y >> 4);
682
683 bool pass = false;
684
685 switch (output_merger.depth_test_func) {
686 case FramebufferRegs::CompareFunc::Never:
687 pass = false;
688 break;
689
690 case FramebufferRegs::CompareFunc::Always:
691 pass = true;
692 break;
693
694 case FramebufferRegs::CompareFunc::Equal:
695 pass = z == ref_z;
696 break;
697
698 case FramebufferRegs::CompareFunc::NotEqual:
699 pass = z != ref_z;
700 break;
701
702 case FramebufferRegs::CompareFunc::LessThan:
703 pass = z < ref_z;
704 break;
705
706 case FramebufferRegs::CompareFunc::LessThanOrEqual:
707 pass = z <= ref_z;
708 break;
709
710 case FramebufferRegs::CompareFunc::GreaterThan:
711 pass = z > ref_z;
712 break;
713
714 case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
715 pass = z >= ref_z;
716 break;
717 }
718
719 if (!pass) {
720 if (stencil_action_enable)
721 UpdateStencil(stencil_test.action_depth_fail);
722 continue;
723 }
724 }
725
726 if (regs.framebuffer.framebuffer.allow_depth_stencil_write != 0 &&
727 output_merger.depth_write_enable) {
728
729 SetDepth(x >> 4, y >> 4, z);
730 }
731
732 // The stencil depth_pass action is executed even if depth testing is disabled
733 if (stencil_action_enable)
734 UpdateStencil(stencil_test.action_depth_pass);
735
736 auto dest = GetPixel(x >> 4, y >> 4);
737 Math::Vec4<u8> blend_output = combiner_output;
738
739 if (output_merger.alphablend_enable) {
740 auto params = output_merger.alpha_blending;
741
742 auto LookupFactor = [&](unsigned channel,
743 FramebufferRegs::BlendFactor factor) -> u8 {
744 DEBUG_ASSERT(channel < 4);
745
746 const Math::Vec4<u8> blend_const = {
747 static_cast<u8>(output_merger.blend_const.r),
748 static_cast<u8>(output_merger.blend_const.g),
749 static_cast<u8>(output_merger.blend_const.b),
750 static_cast<u8>(output_merger.blend_const.a),
751 };
752
753 switch (factor) {
754 case FramebufferRegs::BlendFactor::Zero:
755 return 0;
756
757 case FramebufferRegs::BlendFactor::One:
758 return 255;
759
760 case FramebufferRegs::BlendFactor::SourceColor:
761 return combiner_output[channel];
762
763 case FramebufferRegs::BlendFactor::OneMinusSourceColor:
764 return 255 - combiner_output[channel];
765
766 case FramebufferRegs::BlendFactor::DestColor:
767 return dest[channel];
768
769 case FramebufferRegs::BlendFactor::OneMinusDestColor:
770 return 255 - dest[channel];
771
772 case FramebufferRegs::BlendFactor::SourceAlpha:
773 return combiner_output.a();
774
775 case FramebufferRegs::BlendFactor::OneMinusSourceAlpha:
776 return 255 - combiner_output.a();
777
778 case FramebufferRegs::BlendFactor::DestAlpha:
779 return dest.a();
780
781 case FramebufferRegs::BlendFactor::OneMinusDestAlpha:
782 return 255 - dest.a();
783
784 case FramebufferRegs::BlendFactor::ConstantColor:
785 return blend_const[channel];
786
787 case FramebufferRegs::BlendFactor::OneMinusConstantColor:
788 return 255 - blend_const[channel];
789
790 case FramebufferRegs::BlendFactor::ConstantAlpha:
791 return blend_const.a();
792
793 case FramebufferRegs::BlendFactor::OneMinusConstantAlpha:
794 return 255 - blend_const.a();
795
796 case FramebufferRegs::BlendFactor::SourceAlphaSaturate:
797 // Returns 1.0 for the alpha channel
798 if (channel == 3)
799 return 255;
800 return std::min(combiner_output.a(), static_cast<u8>(255 - dest.a()));
801
802 default:
803 LOG_CRITICAL(HW_GPU, "Unknown blend factor %x", factor);
804 UNIMPLEMENTED();
805 break;
806 }
807
808 return combiner_output[channel];
809 };
810
811 auto srcfactor = Math::MakeVec(LookupFactor(0, params.factor_source_rgb),
812 LookupFactor(1, params.factor_source_rgb),
813 LookupFactor(2, params.factor_source_rgb),
814 LookupFactor(3, params.factor_source_a));
815
816 auto dstfactor = Math::MakeVec(LookupFactor(0, params.factor_dest_rgb),
817 LookupFactor(1, params.factor_dest_rgb),
818 LookupFactor(2, params.factor_dest_rgb),
819 LookupFactor(3, params.factor_dest_a));
820
821 blend_output = EvaluateBlendEquation(combiner_output, srcfactor, dest, dstfactor,
822 params.blend_equation_rgb);
823 blend_output.a() = EvaluateBlendEquation(combiner_output, srcfactor, dest,
824 dstfactor, params.blend_equation_a)
825 .a();
826 } else {
827 blend_output =
828 Math::MakeVec(LogicOp(combiner_output.r(), dest.r(), output_merger.logic_op),
829 LogicOp(combiner_output.g(), dest.g(), output_merger.logic_op),
830 LogicOp(combiner_output.b(), dest.b(), output_merger.logic_op),
831 LogicOp(combiner_output.a(), dest.a(), output_merger.logic_op));
832 }
833
834 const Math::Vec4<u8> result = {
835 output_merger.red_enable ? blend_output.r() : dest.r(),
836 output_merger.green_enable ? blend_output.g() : dest.g(),
837 output_merger.blue_enable ? blend_output.b() : dest.b(),
838 output_merger.alpha_enable ? blend_output.a() : dest.a(),
839 };
840
841 if (regs.framebuffer.framebuffer.allow_color_write != 0)
842 DrawPixel(x >> 4, y >> 4, result);
843 }
844 }
845}
846
847void ProcessTriangle(const Vertex& v0, const Vertex& v1, const Vertex& v2) {
848 ProcessTriangleInternal(v0, v1, v2);
849}
850
851} // namespace Rasterizer
852
853} // namespace Pica