summaryrefslogtreecommitdiff
path: root/src/video_core/swrasterizer
diff options
context:
space:
mode:
authorGravatar James Rowe2018-01-11 20:07:44 -0700
committerGravatar James Rowe2018-01-12 19:11:03 -0700
commit1d28b2e142f845773e2b90e267d9632e196a99b9 (patch)
tree027a3586a0fc927731afb3711c328c6dafc8551f /src/video_core/swrasterizer
parentMassive removal of unused modules (diff)
downloadyuzu-1d28b2e142f845773e2b90e267d9632e196a99b9.tar.gz
yuzu-1d28b2e142f845773e2b90e267d9632e196a99b9.tar.xz
yuzu-1d28b2e142f845773e2b90e267d9632e196a99b9.zip
Remove references to PICA and rasterizers in video_core
Diffstat (limited to 'src/video_core/swrasterizer')
-rw-r--r--src/video_core/swrasterizer/clipper.cpp197
-rw-r--r--src/video_core/swrasterizer/clipper.h21
-rw-r--r--src/video_core/swrasterizer/framebuffer.cpp360
-rw-r--r--src/video_core/swrasterizer/framebuffer.h29
-rw-r--r--src/video_core/swrasterizer/lighting.cpp308
-rw-r--r--src/video_core/swrasterizer/lighting.h19
-rw-r--r--src/video_core/swrasterizer/proctex.cpp223
-rw-r--r--src/video_core/swrasterizer/proctex.h16
-rw-r--r--src/video_core/swrasterizer/rasterizer.cpp853
-rw-r--r--src/video_core/swrasterizer/rasterizer.h48
-rw-r--r--src/video_core/swrasterizer/swrasterizer.cpp15
-rw-r--r--src/video_core/swrasterizer/swrasterizer.h27
-rw-r--r--src/video_core/swrasterizer/texturing.cpp244
-rw-r--r--src/video_core/swrasterizer/texturing.h28
14 files changed, 0 insertions, 2388 deletions
diff --git a/src/video_core/swrasterizer/clipper.cpp b/src/video_core/swrasterizer/clipper.cpp
deleted file mode 100644
index c1ed48398..000000000
--- a/src/video_core/swrasterizer/clipper.cpp
+++ /dev/null
@@ -1,197 +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 <cstddef>
8#include <boost/container/static_vector.hpp>
9#include <boost/container/vector.hpp>
10#include "common/bit_field.h"
11#include "common/common_types.h"
12#include "common/logging/log.h"
13#include "common/vector_math.h"
14#include "video_core/pica_state.h"
15#include "video_core/pica_types.h"
16#include "video_core/shader/shader.h"
17#include "video_core/swrasterizer/clipper.h"
18#include "video_core/swrasterizer/rasterizer.h"
19
20using Pica::Rasterizer::Vertex;
21
22namespace Pica {
23
24namespace Clipper {
25
26struct ClippingEdge {
27public:
28 ClippingEdge(Math::Vec4<float24> coeffs, Math::Vec4<float24> bias = Math::Vec4<float24>(
29 float24::FromFloat32(0), float24::FromFloat32(0),
30 float24::FromFloat32(0), float24::FromFloat32(0)))
31 : coeffs(coeffs), bias(bias) {}
32
33 bool IsInside(const Vertex& vertex) const {
34 return Math::Dot(vertex.pos + bias, coeffs) >= float24::FromFloat32(0);
35 }
36
37 bool IsOutSide(const Vertex& vertex) const {
38 return !IsInside(vertex);
39 }
40
41 Vertex GetIntersection(const Vertex& v0, const Vertex& v1) const {
42 float24 dp = Math::Dot(v0.pos + bias, coeffs);
43 float24 dp_prev = Math::Dot(v1.pos + bias, coeffs);
44 float24 factor = dp_prev / (dp_prev - dp);
45
46 return Vertex::Lerp(factor, v0, v1);
47 }
48
49private:
50 float24 pos;
51 Math::Vec4<float24> coeffs;
52 Math::Vec4<float24> bias;
53};
54
55static void InitScreenCoordinates(Vertex& vtx) {
56 struct {
57 float24 halfsize_x;
58 float24 offset_x;
59 float24 halfsize_y;
60 float24 offset_y;
61 float24 zscale;
62 float24 offset_z;
63 } viewport;
64
65 const auto& regs = g_state.regs;
66 viewport.halfsize_x = float24::FromRaw(regs.rasterizer.viewport_size_x);
67 viewport.halfsize_y = float24::FromRaw(regs.rasterizer.viewport_size_y);
68 viewport.offset_x = float24::FromFloat32(static_cast<float>(regs.rasterizer.viewport_corner.x));
69 viewport.offset_y = float24::FromFloat32(static_cast<float>(regs.rasterizer.viewport_corner.y));
70
71 float24 inv_w = float24::FromFloat32(1.f) / vtx.pos.w;
72 vtx.pos.w = inv_w;
73 vtx.quat *= inv_w;
74 vtx.color *= inv_w;
75 vtx.tc0 *= inv_w;
76 vtx.tc1 *= inv_w;
77 vtx.tc0_w *= inv_w;
78 vtx.view *= inv_w;
79 vtx.tc2 *= inv_w;
80
81 vtx.screenpos[0] =
82 (vtx.pos.x * inv_w + float24::FromFloat32(1.0)) * viewport.halfsize_x + viewport.offset_x;
83 vtx.screenpos[1] =
84 (vtx.pos.y * inv_w + float24::FromFloat32(1.0)) * viewport.halfsize_y + viewport.offset_y;
85 vtx.screenpos[2] = vtx.pos.z * inv_w;
86}
87
88void ProcessTriangle(const OutputVertex& v0, const OutputVertex& v1, const OutputVertex& v2) {
89 using boost::container::static_vector;
90
91 // Clipping a planar n-gon against a plane will remove at least 1 vertex and introduces 2 at
92 // the new edge (or less in degenerate cases). As such, we can say that each clipping plane
93 // introduces at most 1 new vertex to the polygon. Since we start with a triangle and have a
94 // fixed 6 clipping planes, the maximum number of vertices of the clipped polygon is 3 + 6 = 9.
95 static const size_t MAX_VERTICES = 9;
96 static_vector<Vertex, MAX_VERTICES> buffer_a = {v0, v1, v2};
97 static_vector<Vertex, MAX_VERTICES> buffer_b;
98
99 auto FlipQuaternionIfOpposite = [](auto& a, const auto& b) {
100 if (Math::Dot(a, b) < float24::Zero())
101 a = a * float24::FromFloat32(-1.0f);
102 };
103
104 // Flip the quaternions if they are opposite to prevent interpolating them over the wrong
105 // direction.
106 FlipQuaternionIfOpposite(buffer_a[1].quat, buffer_a[0].quat);
107 FlipQuaternionIfOpposite(buffer_a[2].quat, buffer_a[0].quat);
108
109 auto* output_list = &buffer_a;
110 auto* input_list = &buffer_b;
111
112 // NOTE: We clip against a w=epsilon plane to guarantee that the output has a positive w value.
113 // TODO: Not sure if this is a valid approach. Also should probably instead use the smallest
114 // epsilon possible within float24 accuracy.
115 static const float24 EPSILON = float24::FromFloat32(0.00001f);
116 static const float24 f0 = float24::FromFloat32(0.0);
117 static const float24 f1 = float24::FromFloat32(1.0);
118 static const std::array<ClippingEdge, 7> clipping_edges = {{
119 {Math::MakeVec(-f1, f0, f0, f1)}, // x = +w
120 {Math::MakeVec(f1, f0, f0, f1)}, // x = -w
121 {Math::MakeVec(f0, -f1, f0, f1)}, // y = +w
122 {Math::MakeVec(f0, f1, f0, f1)}, // y = -w
123 {Math::MakeVec(f0, f0, -f1, f0)}, // z = 0
124 {Math::MakeVec(f0, f0, f1, f1)}, // z = -w
125 {Math::MakeVec(f0, f0, f0, f1), Math::Vec4<float24>(f0, f0, f0, EPSILON)}, // w = EPSILON
126 }};
127
128 // Simple implementation of the Sutherland-Hodgman clipping algorithm.
129 // TODO: Make this less inefficient (currently lots of useless buffering overhead happens here)
130 auto Clip = [&](const ClippingEdge& edge) {
131 std::swap(input_list, output_list);
132 output_list->clear();
133
134 const Vertex* reference_vertex = &input_list->back();
135
136 for (const auto& vertex : *input_list) {
137 // NOTE: This algorithm changes vertex order in some cases!
138 if (edge.IsInside(vertex)) {
139 if (edge.IsOutSide(*reference_vertex)) {
140 output_list->push_back(edge.GetIntersection(vertex, *reference_vertex));
141 }
142
143 output_list->push_back(vertex);
144 } else if (edge.IsInside(*reference_vertex)) {
145 output_list->push_back(edge.GetIntersection(vertex, *reference_vertex));
146 }
147 reference_vertex = &vertex;
148 }
149 };
150
151 for (auto edge : clipping_edges) {
152 Clip(edge);
153
154 // Need to have at least a full triangle to continue...
155 if (output_list->size() < 3)
156 return;
157 }
158
159 if (g_state.regs.rasterizer.clip_enable) {
160 ClippingEdge custom_edge{g_state.regs.rasterizer.GetClipCoef()};
161 Clip(custom_edge);
162
163 if (output_list->size() < 3)
164 return;
165 }
166
167 InitScreenCoordinates((*output_list)[0]);
168 InitScreenCoordinates((*output_list)[1]);
169
170 for (size_t i = 0; i < output_list->size() - 2; i++) {
171 Vertex& vtx0 = (*output_list)[0];
172 Vertex& vtx1 = (*output_list)[i + 1];
173 Vertex& vtx2 = (*output_list)[i + 2];
174
175 InitScreenCoordinates(vtx2);
176
177 LOG_TRACE(Render_Software,
178 "Triangle %lu/%lu at position (%.3f, %.3f, %.3f, %.3f), "
179 "(%.3f, %.3f, %.3f, %.3f), (%.3f, %.3f, %.3f, %.3f) and "
180 "screen position (%.2f, %.2f, %.2f), (%.2f, %.2f, %.2f), (%.2f, %.2f, %.2f)",
181 i + 1, output_list->size() - 2, vtx0.pos.x.ToFloat32(), vtx0.pos.y.ToFloat32(),
182 vtx0.pos.z.ToFloat32(), vtx0.pos.w.ToFloat32(), vtx1.pos.x.ToFloat32(),
183 vtx1.pos.y.ToFloat32(), vtx1.pos.z.ToFloat32(), vtx1.pos.w.ToFloat32(),
184 vtx2.pos.x.ToFloat32(), vtx2.pos.y.ToFloat32(), vtx2.pos.z.ToFloat32(),
185 vtx2.pos.w.ToFloat32(), vtx0.screenpos.x.ToFloat32(),
186 vtx0.screenpos.y.ToFloat32(), vtx0.screenpos.z.ToFloat32(),
187 vtx1.screenpos.x.ToFloat32(), vtx1.screenpos.y.ToFloat32(),
188 vtx1.screenpos.z.ToFloat32(), vtx2.screenpos.x.ToFloat32(),
189 vtx2.screenpos.y.ToFloat32(), vtx2.screenpos.z.ToFloat32());
190
191 Rasterizer::ProcessTriangle(vtx0, vtx1, vtx2);
192 }
193}
194
195} // namespace
196
197} // namespace
diff --git a/src/video_core/swrasterizer/clipper.h b/src/video_core/swrasterizer/clipper.h
deleted file mode 100644
index b51af0af9..000000000
--- a/src/video_core/swrasterizer/clipper.h
+++ /dev/null
@@ -1,21 +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#pragma once
6
7namespace Pica {
8
9namespace Shader {
10struct OutputVertex;
11}
12
13namespace Clipper {
14
15using Shader::OutputVertex;
16
17void ProcessTriangle(const OutputVertex& v0, const OutputVertex& v1, const OutputVertex& v2);
18
19} // namespace
20
21} // namespace
diff --git a/src/video_core/swrasterizer/framebuffer.cpp b/src/video_core/swrasterizer/framebuffer.cpp
deleted file mode 100644
index f34eab6cf..000000000
--- a/src/video_core/swrasterizer/framebuffer.cpp
+++ /dev/null
@@ -1,360 +0,0 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6
7#include "common/assert.h"
8#include "common/color.h"
9#include "common/common_types.h"
10#include "common/logging/log.h"
11#include "common/math_util.h"
12#include "common/vector_math.h"
13#include "core/hw/gpu.h"
14#include "core/memory.h"
15#include "video_core/pica_state.h"
16#include "video_core/regs_framebuffer.h"
17#include "video_core/swrasterizer/framebuffer.h"
18#include "video_core/utils.h"
19
20namespace Pica {
21namespace Rasterizer {
22
23void DrawPixel(int x, int y, const Math::Vec4<u8>& color) {
24 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
25 const PAddr addr = framebuffer.GetColorBufferPhysicalAddress();
26
27 // Similarly to textures, the render framebuffer is laid out from bottom to top, too.
28 // NOTE: The framebuffer height register contains the actual FB height minus one.
29 y = framebuffer.height - y;
30
31 const u32 coarse_y = y & ~7;
32 u32 bytes_per_pixel =
33 GPU::Regs::BytesPerPixel(GPU::Regs::PixelFormat(framebuffer.color_format.Value()));
34 u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) +
35 coarse_y * framebuffer.width * bytes_per_pixel;
36 u8* dst_pixel = Memory::GetPhysicalPointer(addr) + dst_offset;
37
38 switch (framebuffer.color_format) {
39 case FramebufferRegs::ColorFormat::RGBA8:
40 Color::EncodeRGBA8(color, dst_pixel);
41 break;
42
43 case FramebufferRegs::ColorFormat::RGB8:
44 Color::EncodeRGB8(color, dst_pixel);
45 break;
46
47 case FramebufferRegs::ColorFormat::RGB5A1:
48 Color::EncodeRGB5A1(color, dst_pixel);
49 break;
50
51 case FramebufferRegs::ColorFormat::RGB565:
52 Color::EncodeRGB565(color, dst_pixel);
53 break;
54
55 case FramebufferRegs::ColorFormat::RGBA4:
56 Color::EncodeRGBA4(color, dst_pixel);
57 break;
58
59 default:
60 LOG_CRITICAL(Render_Software, "Unknown framebuffer color format %x",
61 framebuffer.color_format.Value());
62 UNIMPLEMENTED();
63 }
64}
65
66const Math::Vec4<u8> GetPixel(int x, int y) {
67 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
68 const PAddr addr = framebuffer.GetColorBufferPhysicalAddress();
69
70 y = framebuffer.height - y;
71
72 const u32 coarse_y = y & ~7;
73 u32 bytes_per_pixel =
74 GPU::Regs::BytesPerPixel(GPU::Regs::PixelFormat(framebuffer.color_format.Value()));
75 u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) +
76 coarse_y * framebuffer.width * bytes_per_pixel;
77 u8* src_pixel = Memory::GetPhysicalPointer(addr) + src_offset;
78
79 switch (framebuffer.color_format) {
80 case FramebufferRegs::ColorFormat::RGBA8:
81 return Color::DecodeRGBA8(src_pixel);
82
83 case FramebufferRegs::ColorFormat::RGB8:
84 return Color::DecodeRGB8(src_pixel);
85
86 case FramebufferRegs::ColorFormat::RGB5A1:
87 return Color::DecodeRGB5A1(src_pixel);
88
89 case FramebufferRegs::ColorFormat::RGB565:
90 return Color::DecodeRGB565(src_pixel);
91
92 case FramebufferRegs::ColorFormat::RGBA4:
93 return Color::DecodeRGBA4(src_pixel);
94
95 default:
96 LOG_CRITICAL(Render_Software, "Unknown framebuffer color format %x",
97 framebuffer.color_format.Value());
98 UNIMPLEMENTED();
99 }
100
101 return {0, 0, 0, 0};
102}
103
104u32 GetDepth(int x, int y) {
105 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
106 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
107 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
108
109 y = framebuffer.height - y;
110
111 const u32 coarse_y = y & ~7;
112 u32 bytes_per_pixel = FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
113 u32 stride = framebuffer.width * bytes_per_pixel;
114
115 u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
116 u8* src_pixel = depth_buffer + src_offset;
117
118 switch (framebuffer.depth_format) {
119 case FramebufferRegs::DepthFormat::D16:
120 return Color::DecodeD16(src_pixel);
121 case FramebufferRegs::DepthFormat::D24:
122 return Color::DecodeD24(src_pixel);
123 case FramebufferRegs::DepthFormat::D24S8:
124 return Color::DecodeD24S8(src_pixel).x;
125 default:
126 LOG_CRITICAL(HW_GPU, "Unimplemented depth format %u", framebuffer.depth_format);
127 UNIMPLEMENTED();
128 return 0;
129 }
130}
131
132u8 GetStencil(int x, int y) {
133 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
134 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
135 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
136
137 y = framebuffer.height - y;
138
139 const u32 coarse_y = y & ~7;
140 u32 bytes_per_pixel = Pica::FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
141 u32 stride = framebuffer.width * bytes_per_pixel;
142
143 u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
144 u8* src_pixel = depth_buffer + src_offset;
145
146 switch (framebuffer.depth_format) {
147 case FramebufferRegs::DepthFormat::D24S8:
148 return Color::DecodeD24S8(src_pixel).y;
149
150 default:
151 LOG_WARNING(
152 HW_GPU,
153 "GetStencil called for function which doesn't have a stencil component (format %u)",
154 framebuffer.depth_format);
155 return 0;
156 }
157}
158
159void SetDepth(int x, int y, u32 value) {
160 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
161 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
162 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
163
164 y = framebuffer.height - y;
165
166 const u32 coarse_y = y & ~7;
167 u32 bytes_per_pixel = FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
168 u32 stride = framebuffer.width * bytes_per_pixel;
169
170 u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
171 u8* dst_pixel = depth_buffer + dst_offset;
172
173 switch (framebuffer.depth_format) {
174 case FramebufferRegs::DepthFormat::D16:
175 Color::EncodeD16(value, dst_pixel);
176 break;
177
178 case FramebufferRegs::DepthFormat::D24:
179 Color::EncodeD24(value, dst_pixel);
180 break;
181
182 case FramebufferRegs::DepthFormat::D24S8:
183 Color::EncodeD24X8(value, dst_pixel);
184 break;
185
186 default:
187 LOG_CRITICAL(HW_GPU, "Unimplemented depth format %u", framebuffer.depth_format);
188 UNIMPLEMENTED();
189 break;
190 }
191}
192
193void SetStencil(int x, int y, u8 value) {
194 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
195 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
196 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
197
198 y = framebuffer.height - y;
199
200 const u32 coarse_y = y & ~7;
201 u32 bytes_per_pixel = Pica::FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
202 u32 stride = framebuffer.width * bytes_per_pixel;
203
204 u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
205 u8* dst_pixel = depth_buffer + dst_offset;
206
207 switch (framebuffer.depth_format) {
208 case Pica::FramebufferRegs::DepthFormat::D16:
209 case Pica::FramebufferRegs::DepthFormat::D24:
210 // Nothing to do
211 break;
212
213 case Pica::FramebufferRegs::DepthFormat::D24S8:
214 Color::EncodeX24S8(value, dst_pixel);
215 break;
216
217 default:
218 LOG_CRITICAL(HW_GPU, "Unimplemented depth format %u", framebuffer.depth_format);
219 UNIMPLEMENTED();
220 break;
221 }
222}
223
224u8 PerformStencilAction(FramebufferRegs::StencilAction action, u8 old_stencil, u8 ref) {
225 switch (action) {
226 case FramebufferRegs::StencilAction::Keep:
227 return old_stencil;
228
229 case FramebufferRegs::StencilAction::Zero:
230 return 0;
231
232 case FramebufferRegs::StencilAction::Replace:
233 return ref;
234
235 case FramebufferRegs::StencilAction::Increment:
236 // Saturated increment
237 return std::min<u8>(old_stencil, 254) + 1;
238
239 case FramebufferRegs::StencilAction::Decrement:
240 // Saturated decrement
241 return std::max<u8>(old_stencil, 1) - 1;
242
243 case FramebufferRegs::StencilAction::Invert:
244 return ~old_stencil;
245
246 case FramebufferRegs::StencilAction::IncrementWrap:
247 return old_stencil + 1;
248
249 case FramebufferRegs::StencilAction::DecrementWrap:
250 return old_stencil - 1;
251
252 default:
253 LOG_CRITICAL(HW_GPU, "Unknown stencil action %x", (int)action);
254 UNIMPLEMENTED();
255 return 0;
256 }
257}
258
259Math::Vec4<u8> EvaluateBlendEquation(const Math::Vec4<u8>& src, const Math::Vec4<u8>& srcfactor,
260 const Math::Vec4<u8>& dest, const Math::Vec4<u8>& destfactor,
261 FramebufferRegs::BlendEquation equation) {
262 Math::Vec4<int> result;
263
264 auto src_result = (src * srcfactor).Cast<int>();
265 auto dst_result = (dest * destfactor).Cast<int>();
266
267 switch (equation) {
268 case FramebufferRegs::BlendEquation::Add:
269 result = (src_result + dst_result) / 255;
270 break;
271
272 case FramebufferRegs::BlendEquation::Subtract:
273 result = (src_result - dst_result) / 255;
274 break;
275
276 case FramebufferRegs::BlendEquation::ReverseSubtract:
277 result = (dst_result - src_result) / 255;
278 break;
279
280 // TODO: How do these two actually work? OpenGL doesn't include the blend factors in the
281 // min/max computations, but is this what the 3DS actually does?
282 case FramebufferRegs::BlendEquation::Min:
283 result.r() = std::min(src.r(), dest.r());
284 result.g() = std::min(src.g(), dest.g());
285 result.b() = std::min(src.b(), dest.b());
286 result.a() = std::min(src.a(), dest.a());
287 break;
288
289 case FramebufferRegs::BlendEquation::Max:
290 result.r() = std::max(src.r(), dest.r());
291 result.g() = std::max(src.g(), dest.g());
292 result.b() = std::max(src.b(), dest.b());
293 result.a() = std::max(src.a(), dest.a());
294 break;
295
296 default:
297 LOG_CRITICAL(HW_GPU, "Unknown RGB blend equation %x", equation);
298 UNIMPLEMENTED();
299 }
300
301 return Math::Vec4<u8>(MathUtil::Clamp(result.r(), 0, 255), MathUtil::Clamp(result.g(), 0, 255),
302 MathUtil::Clamp(result.b(), 0, 255), MathUtil::Clamp(result.a(), 0, 255));
303};
304
305u8 LogicOp(u8 src, u8 dest, FramebufferRegs::LogicOp op) {
306 switch (op) {
307 case FramebufferRegs::LogicOp::Clear:
308 return 0;
309
310 case FramebufferRegs::LogicOp::And:
311 return src & dest;
312
313 case FramebufferRegs::LogicOp::AndReverse:
314 return src & ~dest;
315
316 case FramebufferRegs::LogicOp::Copy:
317 return src;
318
319 case FramebufferRegs::LogicOp::Set:
320 return 255;
321
322 case FramebufferRegs::LogicOp::CopyInverted:
323 return ~src;
324
325 case FramebufferRegs::LogicOp::NoOp:
326 return dest;
327
328 case FramebufferRegs::LogicOp::Invert:
329 return ~dest;
330
331 case FramebufferRegs::LogicOp::Nand:
332 return ~(src & dest);
333
334 case FramebufferRegs::LogicOp::Or:
335 return src | dest;
336
337 case FramebufferRegs::LogicOp::Nor:
338 return ~(src | dest);
339
340 case FramebufferRegs::LogicOp::Xor:
341 return src ^ dest;
342
343 case FramebufferRegs::LogicOp::Equiv:
344 return ~(src ^ dest);
345
346 case FramebufferRegs::LogicOp::AndInverted:
347 return ~src & dest;
348
349 case FramebufferRegs::LogicOp::OrReverse:
350 return src | ~dest;
351
352 case FramebufferRegs::LogicOp::OrInverted:
353 return ~src | dest;
354 }
355
356 UNREACHABLE();
357};
358
359} // namespace Rasterizer
360} // namespace Pica
diff --git a/src/video_core/swrasterizer/framebuffer.h b/src/video_core/swrasterizer/framebuffer.h
deleted file mode 100644
index 4a32a4979..000000000
--- a/src/video_core/swrasterizer/framebuffer.h
+++ /dev/null
@@ -1,29 +0,0 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "common/common_types.h"
8#include "common/vector_math.h"
9#include "video_core/regs_framebuffer.h"
10
11namespace Pica {
12namespace Rasterizer {
13
14void DrawPixel(int x, int y, const Math::Vec4<u8>& color);
15const Math::Vec4<u8> GetPixel(int x, int y);
16u32 GetDepth(int x, int y);
17u8 GetStencil(int x, int y);
18void SetDepth(int x, int y, u32 value);
19void SetStencil(int x, int y, u8 value);
20u8 PerformStencilAction(FramebufferRegs::StencilAction action, u8 old_stencil, u8 ref);
21
22Math::Vec4<u8> EvaluateBlendEquation(const Math::Vec4<u8>& src, const Math::Vec4<u8>& srcfactor,
23 const Math::Vec4<u8>& dest, const Math::Vec4<u8>& destfactor,
24 FramebufferRegs::BlendEquation equation);
25
26u8 LogicOp(u8 src, u8 dest, FramebufferRegs::LogicOp op);
27
28} // namespace Rasterizer
29} // namespace Pica
diff --git a/src/video_core/swrasterizer/lighting.cpp b/src/video_core/swrasterizer/lighting.cpp
deleted file mode 100644
index 5fa748611..000000000
--- a/src/video_core/swrasterizer/lighting.cpp
+++ /dev/null
@@ -1,308 +0,0 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "common/math_util.h"
6#include "video_core/swrasterizer/lighting.h"
7
8namespace Pica {
9
10static float LookupLightingLut(const Pica::State::Lighting& lighting, size_t lut_index, u8 index,
11 float delta) {
12 ASSERT_MSG(lut_index < lighting.luts.size(), "Out of range lut");
13 ASSERT_MSG(index < lighting.luts[lut_index].size(), "Out of range index");
14
15 const auto& lut = lighting.luts[lut_index][index];
16
17 float lut_value = lut.ToFloat();
18 float lut_diff = lut.DiffToFloat();
19
20 return lut_value + lut_diff * delta;
21}
22
23std::tuple<Math::Vec4<u8>, Math::Vec4<u8>> ComputeFragmentsColors(
24 const Pica::LightingRegs& lighting, const Pica::State::Lighting& lighting_state,
25 const Math::Quaternion<float>& normquat, const Math::Vec3<float>& view,
26 const Math::Vec4<u8> (&texture_color)[4]) {
27
28 Math::Vec3<float> surface_normal;
29 Math::Vec3<float> surface_tangent;
30
31 if (lighting.config0.bump_mode != LightingRegs::LightingBumpMode::None) {
32 Math::Vec3<float> perturbation =
33 texture_color[lighting.config0.bump_selector].xyz().Cast<float>() / 127.5f -
34 Math::MakeVec(1.0f, 1.0f, 1.0f);
35 if (lighting.config0.bump_mode == LightingRegs::LightingBumpMode::NormalMap) {
36 if (!lighting.config0.disable_bump_renorm) {
37 const float z_square = 1 - perturbation.xy().Length2();
38 perturbation.z = std::sqrt(std::max(z_square, 0.0f));
39 }
40 surface_normal = perturbation;
41 surface_tangent = Math::MakeVec(1.0f, 0.0f, 0.0f);
42 } else if (lighting.config0.bump_mode == LightingRegs::LightingBumpMode::TangentMap) {
43 surface_normal = Math::MakeVec(0.0f, 0.0f, 1.0f);
44 surface_tangent = perturbation;
45 } else {
46 LOG_ERROR(HW_GPU, "Unknown bump mode %u", lighting.config0.bump_mode.Value());
47 }
48 } else {
49 surface_normal = Math::MakeVec(0.0f, 0.0f, 1.0f);
50 surface_tangent = Math::MakeVec(1.0f, 0.0f, 0.0f);
51 }
52
53 // Use the normalized the quaternion when performing the rotation
54 auto normal = Math::QuaternionRotate(normquat, surface_normal);
55 auto tangent = Math::QuaternionRotate(normquat, surface_tangent);
56
57 Math::Vec4<float> diffuse_sum = {0.0f, 0.0f, 0.0f, 1.0f};
58 Math::Vec4<float> specular_sum = {0.0f, 0.0f, 0.0f, 1.0f};
59
60 for (unsigned light_index = 0; light_index <= lighting.max_light_index; ++light_index) {
61 unsigned num = lighting.light_enable.GetNum(light_index);
62 const auto& light_config = lighting.light[num];
63
64 Math::Vec3<float> refl_value = {};
65 Math::Vec3<float> position = {float16::FromRaw(light_config.x).ToFloat32(),
66 float16::FromRaw(light_config.y).ToFloat32(),
67 float16::FromRaw(light_config.z).ToFloat32()};
68 Math::Vec3<float> light_vector;
69
70 if (light_config.config.directional)
71 light_vector = position;
72 else
73 light_vector = position + view;
74
75 light_vector.Normalize();
76
77 Math::Vec3<float> norm_view = view.Normalized();
78 Math::Vec3<float> half_vector = norm_view + light_vector;
79
80 float dist_atten = 1.0f;
81 if (!lighting.IsDistAttenDisabled(num)) {
82 auto distance = (-view - position).Length();
83 float scale = Pica::float20::FromRaw(light_config.dist_atten_scale).ToFloat32();
84 float bias = Pica::float20::FromRaw(light_config.dist_atten_bias).ToFloat32();
85 size_t lut =
86 static_cast<size_t>(LightingRegs::LightingSampler::DistanceAttenuation) + num;
87
88 float sample_loc = MathUtil::Clamp(scale * distance + bias, 0.0f, 1.0f);
89
90 u8 lutindex =
91 static_cast<u8>(MathUtil::Clamp(std::floor(sample_loc * 256.0f), 0.0f, 255.0f));
92 float delta = sample_loc * 256 - lutindex;
93 dist_atten = LookupLightingLut(lighting_state, lut, lutindex, delta);
94 }
95
96 auto GetLutValue = [&](LightingRegs::LightingLutInput input, bool abs,
97 LightingRegs::LightingScale scale_enum,
98 LightingRegs::LightingSampler sampler) {
99 float result = 0.0f;
100
101 switch (input) {
102 case LightingRegs::LightingLutInput::NH:
103 result = Math::Dot(normal, half_vector.Normalized());
104 break;
105
106 case LightingRegs::LightingLutInput::VH:
107 result = Math::Dot(norm_view, half_vector.Normalized());
108 break;
109
110 case LightingRegs::LightingLutInput::NV:
111 result = Math::Dot(normal, norm_view);
112 break;
113
114 case LightingRegs::LightingLutInput::LN:
115 result = Math::Dot(light_vector, normal);
116 break;
117
118 case LightingRegs::LightingLutInput::SP: {
119 Math::Vec3<s32> spot_dir{light_config.spot_x.Value(), light_config.spot_y.Value(),
120 light_config.spot_z.Value()};
121 result = Math::Dot(light_vector, spot_dir.Cast<float>() / 2047.0f);
122 break;
123 }
124 case LightingRegs::LightingLutInput::CP:
125 if (lighting.config0.config == LightingRegs::LightingConfig::Config7) {
126 const Math::Vec3<float> norm_half_vector = half_vector.Normalized();
127 const Math::Vec3<float> half_vector_proj =
128 norm_half_vector - normal * Math::Dot(normal, norm_half_vector);
129 result = Math::Dot(half_vector_proj, tangent);
130 } else {
131 result = 0.0f;
132 }
133 break;
134 default:
135 LOG_CRITICAL(HW_GPU, "Unknown lighting LUT input %u\n", static_cast<u32>(input));
136 UNIMPLEMENTED();
137 result = 0.0f;
138 }
139
140 u8 index;
141 float delta;
142
143 if (abs) {
144 if (light_config.config.two_sided_diffuse)
145 result = std::abs(result);
146 else
147 result = std::max(result, 0.0f);
148
149 float flr = std::floor(result * 256.0f);
150 index = static_cast<u8>(MathUtil::Clamp(flr, 0.0f, 255.0f));
151 delta = result * 256 - index;
152 } else {
153 float flr = std::floor(result * 128.0f);
154 s8 signed_index = static_cast<s8>(MathUtil::Clamp(flr, -128.0f, 127.0f));
155 delta = result * 128.0f - signed_index;
156 index = static_cast<u8>(signed_index);
157 }
158
159 float scale = lighting.lut_scale.GetScale(scale_enum);
160 return scale *
161 LookupLightingLut(lighting_state, static_cast<size_t>(sampler), index, delta);
162 };
163
164 // If enabled, compute spot light attenuation value
165 float spot_atten = 1.0f;
166 if (!lighting.IsSpotAttenDisabled(num) &&
167 LightingRegs::IsLightingSamplerSupported(
168 lighting.config0.config, LightingRegs::LightingSampler::SpotlightAttenuation)) {
169 auto lut = LightingRegs::SpotlightAttenuationSampler(num);
170 spot_atten = GetLutValue(lighting.lut_input.sp, lighting.abs_lut_input.disable_sp == 0,
171 lighting.lut_scale.sp, lut);
172 }
173
174 // Specular 0 component
175 float d0_lut_value = 1.0f;
176 if (lighting.config1.disable_lut_d0 == 0 &&
177 LightingRegs::IsLightingSamplerSupported(
178 lighting.config0.config, LightingRegs::LightingSampler::Distribution0)) {
179 d0_lut_value =
180 GetLutValue(lighting.lut_input.d0, lighting.abs_lut_input.disable_d0 == 0,
181 lighting.lut_scale.d0, LightingRegs::LightingSampler::Distribution0);
182 }
183
184 Math::Vec3<float> specular_0 = d0_lut_value * light_config.specular_0.ToVec3f();
185
186 // If enabled, lookup ReflectRed value, otherwise, 1.0 is used
187 if (lighting.config1.disable_lut_rr == 0 &&
188 LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
189 LightingRegs::LightingSampler::ReflectRed)) {
190 refl_value.x =
191 GetLutValue(lighting.lut_input.rr, lighting.abs_lut_input.disable_rr == 0,
192 lighting.lut_scale.rr, LightingRegs::LightingSampler::ReflectRed);
193 } else {
194 refl_value.x = 1.0f;
195 }
196
197 // If enabled, lookup ReflectGreen value, otherwise, ReflectRed value is used
198 if (lighting.config1.disable_lut_rg == 0 &&
199 LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
200 LightingRegs::LightingSampler::ReflectGreen)) {
201 refl_value.y =
202 GetLutValue(lighting.lut_input.rg, lighting.abs_lut_input.disable_rg == 0,
203 lighting.lut_scale.rg, LightingRegs::LightingSampler::ReflectGreen);
204 } else {
205 refl_value.y = refl_value.x;
206 }
207
208 // If enabled, lookup ReflectBlue value, otherwise, ReflectRed value is used
209 if (lighting.config1.disable_lut_rb == 0 &&
210 LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
211 LightingRegs::LightingSampler::ReflectBlue)) {
212 refl_value.z =
213 GetLutValue(lighting.lut_input.rb, lighting.abs_lut_input.disable_rb == 0,
214 lighting.lut_scale.rb, LightingRegs::LightingSampler::ReflectBlue);
215 } else {
216 refl_value.z = refl_value.x;
217 }
218
219 // Specular 1 component
220 float d1_lut_value = 1.0f;
221 if (lighting.config1.disable_lut_d1 == 0 &&
222 LightingRegs::IsLightingSamplerSupported(
223 lighting.config0.config, LightingRegs::LightingSampler::Distribution1)) {
224 d1_lut_value =
225 GetLutValue(lighting.lut_input.d1, lighting.abs_lut_input.disable_d1 == 0,
226 lighting.lut_scale.d1, LightingRegs::LightingSampler::Distribution1);
227 }
228
229 Math::Vec3<float> specular_1 =
230 d1_lut_value * refl_value * light_config.specular_1.ToVec3f();
231
232 // Fresnel
233 // Note: only the last entry in the light slots applies the Fresnel factor
234 if (light_index == lighting.max_light_index && lighting.config1.disable_lut_fr == 0 &&
235 LightingRegs::IsLightingSamplerSupported(lighting.config0.config,
236 LightingRegs::LightingSampler::Fresnel)) {
237
238 float lut_value =
239 GetLutValue(lighting.lut_input.fr, lighting.abs_lut_input.disable_fr == 0,
240 lighting.lut_scale.fr, LightingRegs::LightingSampler::Fresnel);
241
242 // Enabled for diffuse lighting alpha component
243 if (lighting.config0.fresnel_selector ==
244 LightingRegs::LightingFresnelSelector::PrimaryAlpha ||
245 lighting.config0.fresnel_selector == LightingRegs::LightingFresnelSelector::Both) {
246 diffuse_sum.a() = lut_value;
247 }
248
249 // Enabled for the specular lighting alpha component
250 if (lighting.config0.fresnel_selector ==
251 LightingRegs::LightingFresnelSelector::SecondaryAlpha ||
252 lighting.config0.fresnel_selector == LightingRegs::LightingFresnelSelector::Both) {
253 specular_sum.a() = lut_value;
254 }
255 }
256
257 auto dot_product = Math::Dot(light_vector, normal);
258
259 // Calculate clamp highlights before applying the two-sided diffuse configuration to the dot
260 // product.
261 float clamp_highlights = 1.0f;
262 if (lighting.config0.clamp_highlights) {
263 if (dot_product <= 0.0f)
264 clamp_highlights = 0.0f;
265 else
266 clamp_highlights = 1.0f;
267 }
268
269 if (light_config.config.two_sided_diffuse)
270 dot_product = std::abs(dot_product);
271 else
272 dot_product = std::max(dot_product, 0.0f);
273
274 if (light_config.config.geometric_factor_0 || light_config.config.geometric_factor_1) {
275 float geo_factor = half_vector.Length2();
276 geo_factor = geo_factor == 0.0f ? 0.0f : std::min(dot_product / geo_factor, 1.0f);
277 if (light_config.config.geometric_factor_0) {
278 specular_0 *= geo_factor;
279 }
280 if (light_config.config.geometric_factor_1) {
281 specular_1 *= geo_factor;
282 }
283 }
284
285 auto diffuse =
286 light_config.diffuse.ToVec3f() * dot_product + light_config.ambient.ToVec3f();
287 diffuse_sum += Math::MakeVec(diffuse * dist_atten * spot_atten, 0.0f);
288
289 specular_sum += Math::MakeVec(
290 (specular_0 + specular_1) * clamp_highlights * dist_atten * spot_atten, 0.0f);
291 }
292
293 diffuse_sum += Math::MakeVec(lighting.global_ambient.ToVec3f(), 0.0f);
294
295 auto diffuse = Math::MakeVec<float>(MathUtil::Clamp(diffuse_sum.x, 0.0f, 1.0f) * 255,
296 MathUtil::Clamp(diffuse_sum.y, 0.0f, 1.0f) * 255,
297 MathUtil::Clamp(diffuse_sum.z, 0.0f, 1.0f) * 255,
298 MathUtil::Clamp(diffuse_sum.w, 0.0f, 1.0f) * 255)
299 .Cast<u8>();
300 auto specular = Math::MakeVec<float>(MathUtil::Clamp(specular_sum.x, 0.0f, 1.0f) * 255,
301 MathUtil::Clamp(specular_sum.y, 0.0f, 1.0f) * 255,
302 MathUtil::Clamp(specular_sum.z, 0.0f, 1.0f) * 255,
303 MathUtil::Clamp(specular_sum.w, 0.0f, 1.0f) * 255)
304 .Cast<u8>();
305 return std::make_tuple(diffuse, specular);
306}
307
308} // namespace Pica
diff --git a/src/video_core/swrasterizer/lighting.h b/src/video_core/swrasterizer/lighting.h
deleted file mode 100644
index d807a3d94..000000000
--- a/src/video_core/swrasterizer/lighting.h
+++ /dev/null
@@ -1,19 +0,0 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <tuple>
8#include "common/quaternion.h"
9#include "common/vector_math.h"
10#include "video_core/pica_state.h"
11
12namespace Pica {
13
14std::tuple<Math::Vec4<u8>, Math::Vec4<u8>> ComputeFragmentsColors(
15 const Pica::LightingRegs& lighting, const Pica::State::Lighting& lighting_state,
16 const Math::Quaternion<float>& normquat, const Math::Vec3<float>& view,
17 const Math::Vec4<u8> (&texture_color)[4]);
18
19} // namespace Pica
diff --git a/src/video_core/swrasterizer/proctex.cpp b/src/video_core/swrasterizer/proctex.cpp
deleted file mode 100644
index b69892778..000000000
--- a/src/video_core/swrasterizer/proctex.cpp
+++ /dev/null
@@ -1,223 +0,0 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <array>
6#include <cmath>
7#include "common/math_util.h"
8#include "video_core/swrasterizer/proctex.h"
9
10namespace Pica {
11namespace Rasterizer {
12
13using ProcTexClamp = TexturingRegs::ProcTexClamp;
14using ProcTexShift = TexturingRegs::ProcTexShift;
15using ProcTexCombiner = TexturingRegs::ProcTexCombiner;
16using ProcTexFilter = TexturingRegs::ProcTexFilter;
17
18static float LookupLUT(const std::array<State::ProcTex::ValueEntry, 128>& lut, float coord) {
19 // For NoiseLUT/ColorMap/AlphaMap, coord=0.0 is lut[0], coord=127.0/128.0 is lut[127] and
20 // coord=1.0 is lut[127]+lut_diff[127]. For other indices, the result is interpolated using
21 // value entries and difference entries.
22 coord *= 128;
23 const int index_int = std::min(static_cast<int>(coord), 127);
24 const float frac = coord - index_int;
25 return lut[index_int].ToFloat() + frac * lut[index_int].DiffToFloat();
26}
27
28// These function are used to generate random noise for procedural texture. Their results are
29// verified against real hardware, but it's not known if the algorithm is the same as hardware.
30static unsigned int NoiseRand1D(unsigned int v) {
31 static constexpr std::array<unsigned int, 16> table{
32 {0, 4, 10, 8, 4, 9, 7, 12, 5, 15, 13, 14, 11, 15, 2, 11}};
33 return ((v % 9 + 2) * 3 & 0xF) ^ table[(v / 9) & 0xF];
34}
35
36static float NoiseRand2D(unsigned int x, unsigned int y) {
37 static constexpr std::array<unsigned int, 16> table{
38 {10, 2, 15, 8, 0, 7, 4, 5, 5, 13, 2, 6, 13, 9, 3, 14}};
39 unsigned int u2 = NoiseRand1D(x);
40 unsigned int v2 = NoiseRand1D(y);
41 v2 += ((u2 & 3) == 1) ? 4 : 0;
42 v2 ^= (u2 & 1) * 6;
43 v2 += 10 + u2;
44 v2 &= 0xF;
45 v2 ^= table[u2];
46 return -1.0f + v2 * 2.0f / 15.0f;
47}
48
49static float NoiseCoef(float u, float v, TexturingRegs regs, State::ProcTex state) {
50 const float freq_u = float16::FromRaw(regs.proctex_noise_frequency.u).ToFloat32();
51 const float freq_v = float16::FromRaw(regs.proctex_noise_frequency.v).ToFloat32();
52 const float phase_u = float16::FromRaw(regs.proctex_noise_u.phase).ToFloat32();
53 const float phase_v = float16::FromRaw(regs.proctex_noise_v.phase).ToFloat32();
54 const float x = 9 * freq_u * std::abs(u + phase_u);
55 const float y = 9 * freq_v * std::abs(v + phase_v);
56 const int x_int = static_cast<int>(x);
57 const int y_int = static_cast<int>(y);
58 const float x_frac = x - x_int;
59 const float y_frac = y - y_int;
60
61 const float g0 = NoiseRand2D(x_int, y_int) * (x_frac + y_frac);
62 const float g1 = NoiseRand2D(x_int + 1, y_int) * (x_frac + y_frac - 1);
63 const float g2 = NoiseRand2D(x_int, y_int + 1) * (x_frac + y_frac - 1);
64 const float g3 = NoiseRand2D(x_int + 1, y_int + 1) * (x_frac + y_frac - 2);
65 const float x_noise = LookupLUT(state.noise_table, x_frac);
66 const float y_noise = LookupLUT(state.noise_table, y_frac);
67 return Math::BilinearInterp(g0, g1, g2, g3, x_noise, y_noise);
68}
69
70static float GetShiftOffset(float v, ProcTexShift mode, ProcTexClamp clamp_mode) {
71 const float offset = (clamp_mode == ProcTexClamp::MirroredRepeat) ? 1 : 0.5f;
72 switch (mode) {
73 case ProcTexShift::None:
74 return 0;
75 case ProcTexShift::Odd:
76 return offset * (((int)v / 2) % 2);
77 case ProcTexShift::Even:
78 return offset * ((((int)v + 1) / 2) % 2);
79 default:
80 LOG_CRITICAL(HW_GPU, "Unknown shift mode %u", static_cast<u32>(mode));
81 return 0;
82 }
83};
84
85static void ClampCoord(float& coord, ProcTexClamp mode) {
86 switch (mode) {
87 case ProcTexClamp::ToZero:
88 if (coord > 1.0f)
89 coord = 0.0f;
90 break;
91 case ProcTexClamp::ToEdge:
92 coord = std::min(coord, 1.0f);
93 break;
94 case ProcTexClamp::SymmetricalRepeat:
95 coord = coord - std::floor(coord);
96 break;
97 case ProcTexClamp::MirroredRepeat: {
98 int integer = static_cast<int>(coord);
99 float frac = coord - integer;
100 coord = (integer % 2) == 0 ? frac : (1.0f - frac);
101 break;
102 }
103 case ProcTexClamp::Pulse:
104 if (coord <= 0.5f)
105 coord = 0.0f;
106 else
107 coord = 1.0f;
108 break;
109 default:
110 LOG_CRITICAL(HW_GPU, "Unknown clamp mode %u", static_cast<u32>(mode));
111 coord = std::min(coord, 1.0f);
112 break;
113 }
114}
115
116float CombineAndMap(float u, float v, ProcTexCombiner combiner,
117 const std::array<State::ProcTex::ValueEntry, 128>& map_table) {
118 float f;
119 switch (combiner) {
120 case ProcTexCombiner::U:
121 f = u;
122 break;
123 case ProcTexCombiner::U2:
124 f = u * u;
125 break;
126 case TexturingRegs::ProcTexCombiner::V:
127 f = v;
128 break;
129 case TexturingRegs::ProcTexCombiner::V2:
130 f = v * v;
131 break;
132 case TexturingRegs::ProcTexCombiner::Add:
133 f = (u + v) * 0.5f;
134 break;
135 case TexturingRegs::ProcTexCombiner::Add2:
136 f = (u * u + v * v) * 0.5f;
137 break;
138 case TexturingRegs::ProcTexCombiner::SqrtAdd2:
139 f = std::min(std::sqrt(u * u + v * v), 1.0f);
140 break;
141 case TexturingRegs::ProcTexCombiner::Min:
142 f = std::min(u, v);
143 break;
144 case TexturingRegs::ProcTexCombiner::Max:
145 f = std::max(u, v);
146 break;
147 case TexturingRegs::ProcTexCombiner::RMax:
148 f = std::min(((u + v) * 0.5f + std::sqrt(u * u + v * v)) * 0.5f, 1.0f);
149 break;
150 default:
151 LOG_CRITICAL(HW_GPU, "Unknown combiner %u", static_cast<u32>(combiner));
152 f = 0.0f;
153 break;
154 }
155 return LookupLUT(map_table, f);
156}
157
158Math::Vec4<u8> ProcTex(float u, float v, TexturingRegs regs, State::ProcTex state) {
159 u = std::abs(u);
160 v = std::abs(v);
161
162 // Get shift offset before noise generation
163 const float u_shift = GetShiftOffset(v, regs.proctex.u_shift, regs.proctex.u_clamp);
164 const float v_shift = GetShiftOffset(u, regs.proctex.v_shift, regs.proctex.v_clamp);
165
166 // Generate noise
167 if (regs.proctex.noise_enable) {
168 float noise = NoiseCoef(u, v, regs, state);
169 u += noise * regs.proctex_noise_u.amplitude / 4095.0f;
170 v += noise * regs.proctex_noise_v.amplitude / 4095.0f;
171 u = std::abs(u);
172 v = std::abs(v);
173 }
174
175 // Shift
176 u += u_shift;
177 v += v_shift;
178
179 // Clamp
180 ClampCoord(u, regs.proctex.u_clamp);
181 ClampCoord(v, regs.proctex.v_clamp);
182
183 // Combine and map
184 const float lut_coord = CombineAndMap(u, v, regs.proctex.color_combiner, state.color_map_table);
185
186 // Look up the color
187 // For the color lut, coord=0.0 is lut[offset] and coord=1.0 is lut[offset+width-1]
188 const u32 offset = regs.proctex_lut_offset;
189 const u32 width = regs.proctex_lut.width;
190 const float index = offset + (lut_coord * (width - 1));
191 Math::Vec4<u8> final_color;
192 // TODO(wwylele): implement mipmap
193 switch (regs.proctex_lut.filter) {
194 case ProcTexFilter::Linear:
195 case ProcTexFilter::LinearMipmapLinear:
196 case ProcTexFilter::LinearMipmapNearest: {
197 const int index_int = static_cast<int>(index);
198 const float frac = index - index_int;
199 const auto color_value = state.color_table[index_int].ToVector().Cast<float>();
200 const auto color_diff = state.color_diff_table[index_int].ToVector().Cast<float>();
201 final_color = (color_value + frac * color_diff).Cast<u8>();
202 break;
203 }
204 case ProcTexFilter::Nearest:
205 case ProcTexFilter::NearestMipmapLinear:
206 case ProcTexFilter::NearestMipmapNearest:
207 final_color = state.color_table[static_cast<int>(std::round(index))].ToVector();
208 break;
209 }
210
211 if (regs.proctex.separate_alpha) {
212 // Note: in separate alpha mode, the alpha channel skips the color LUT look up stage. It
213 // uses the output of CombineAndMap directly instead.
214 const float final_alpha =
215 CombineAndMap(u, v, regs.proctex.alpha_combiner, state.alpha_map_table);
216 return Math::MakeVec<u8>(final_color.rgb(), static_cast<u8>(final_alpha * 255));
217 } else {
218 return final_color;
219 }
220}
221
222} // namespace Rasterizer
223} // namespace Pica
diff --git a/src/video_core/swrasterizer/proctex.h b/src/video_core/swrasterizer/proctex.h
deleted file mode 100644
index 036e4620e..000000000
--- a/src/video_core/swrasterizer/proctex.h
+++ /dev/null
@@ -1,16 +0,0 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "common/common_types.h"
6#include "common/vector_math.h"
7#include "video_core/pica_state.h"
8
9namespace Pica {
10namespace Rasterizer {
11
12/// Generates procedural texture color for the given coordinates
13Math::Vec4<u8> ProcTex(float u, float v, TexturingRegs regs, State::ProcTex state);
14
15} // namespace Rasterizer
16} // namespace Pica
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
diff --git a/src/video_core/swrasterizer/rasterizer.h b/src/video_core/swrasterizer/rasterizer.h
deleted file mode 100644
index 66cd6cfd4..000000000
--- a/src/video_core/swrasterizer/rasterizer.h
+++ /dev/null
@@ -1,48 +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#pragma once
6
7#include "video_core/shader/shader.h"
8
9namespace Pica {
10
11namespace Rasterizer {
12
13struct Vertex : Shader::OutputVertex {
14 Vertex(const OutputVertex& v) : OutputVertex(v) {}
15
16 // Attributes used to store intermediate results
17 // position after perspective divide
18 Math::Vec3<float24> screenpos;
19
20 // Linear interpolation
21 // factor: 0=this, 1=vtx
22 // Note: This function cannot be called after perspective divide
23 void Lerp(float24 factor, const Vertex& vtx) {
24 pos = pos * factor + vtx.pos * (float24::FromFloat32(1) - factor);
25 quat = quat * factor + vtx.quat * (float24::FromFloat32(1) - factor);
26 color = color * factor + vtx.color * (float24::FromFloat32(1) - factor);
27 tc0 = tc0 * factor + vtx.tc0 * (float24::FromFloat32(1) - factor);
28 tc1 = tc1 * factor + vtx.tc1 * (float24::FromFloat32(1) - factor);
29 tc0_w = tc0_w * factor + vtx.tc0_w * (float24::FromFloat32(1) - factor);
30 view = view * factor + vtx.view * (float24::FromFloat32(1) - factor);
31 tc2 = tc2 * factor + vtx.tc2 * (float24::FromFloat32(1) - factor);
32 }
33
34 // Linear interpolation
35 // factor: 0=v0, 1=v1
36 // Note: This function cannot be called after perspective divide
37 static Vertex Lerp(float24 factor, const Vertex& v0, const Vertex& v1) {
38 Vertex ret = v0;
39 ret.Lerp(factor, v1);
40 return ret;
41 }
42};
43
44void ProcessTriangle(const Vertex& v0, const Vertex& v1, const Vertex& v2);
45
46} // namespace Rasterizer
47
48} // namespace Pica
diff --git a/src/video_core/swrasterizer/swrasterizer.cpp b/src/video_core/swrasterizer/swrasterizer.cpp
deleted file mode 100644
index 402b705dd..000000000
--- a/src/video_core/swrasterizer/swrasterizer.cpp
+++ /dev/null
@@ -1,15 +0,0 @@
1// Copyright 2015 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "video_core/swrasterizer/clipper.h"
6#include "video_core/swrasterizer/swrasterizer.h"
7
8namespace VideoCore {
9
10void SWRasterizer::AddTriangle(const Pica::Shader::OutputVertex& v0,
11 const Pica::Shader::OutputVertex& v1,
12 const Pica::Shader::OutputVertex& v2) {
13 Pica::Clipper::ProcessTriangle(v0, v1, v2);
14}
15}
diff --git a/src/video_core/swrasterizer/swrasterizer.h b/src/video_core/swrasterizer/swrasterizer.h
deleted file mode 100644
index 04ebd5312..000000000
--- a/src/video_core/swrasterizer/swrasterizer.h
+++ /dev/null
@@ -1,27 +0,0 @@
1// Copyright 2015 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "common/common_types.h"
8#include "video_core/rasterizer_interface.h"
9
10namespace Pica {
11namespace Shader {
12struct OutputVertex;
13}
14}
15
16namespace VideoCore {
17
18class SWRasterizer : public RasterizerInterface {
19 void AddTriangle(const Pica::Shader::OutputVertex& v0, const Pica::Shader::OutputVertex& v1,
20 const Pica::Shader::OutputVertex& v2) override;
21 void DrawTriangles() override {}
22 void NotifyPicaRegisterChanged(u32 id) override {}
23 void FlushAll() override {}
24 void FlushRegion(PAddr addr, u64 size) override {}
25 void FlushAndInvalidateRegion(PAddr addr, u64 size) override {}
26};
27}
diff --git a/src/video_core/swrasterizer/texturing.cpp b/src/video_core/swrasterizer/texturing.cpp
deleted file mode 100644
index 79b1ce841..000000000
--- a/src/video_core/swrasterizer/texturing.cpp
+++ /dev/null
@@ -1,244 +0,0 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6
7#include "common/assert.h"
8#include "common/common_types.h"
9#include "common/math_util.h"
10#include "common/vector_math.h"
11#include "video_core/regs_texturing.h"
12#include "video_core/swrasterizer/texturing.h"
13
14namespace Pica {
15namespace Rasterizer {
16
17using TevStageConfig = TexturingRegs::TevStageConfig;
18
19int GetWrappedTexCoord(TexturingRegs::TextureConfig::WrapMode mode, int val, unsigned size) {
20 switch (mode) {
21 case TexturingRegs::TextureConfig::ClampToEdge2:
22 // For negative coordinate, ClampToEdge2 behaves the same as Repeat
23 if (val < 0) {
24 return static_cast<int>(static_cast<unsigned>(val) % size);
25 }
26 // [[fallthrough]]
27 case TexturingRegs::TextureConfig::ClampToEdge:
28 val = std::max(val, 0);
29 val = std::min(val, static_cast<int>(size) - 1);
30 return val;
31
32 case TexturingRegs::TextureConfig::ClampToBorder:
33 return val;
34
35 case TexturingRegs::TextureConfig::ClampToBorder2:
36 // For ClampToBorder2, the case of positive coordinate beyond the texture size is already
37 // handled outside. Here we only handle the negative coordinate in the same way as Repeat.
38 case TexturingRegs::TextureConfig::Repeat2:
39 case TexturingRegs::TextureConfig::Repeat3:
40 case TexturingRegs::TextureConfig::Repeat:
41 return static_cast<int>(static_cast<unsigned>(val) % size);
42
43 case TexturingRegs::TextureConfig::MirroredRepeat: {
44 unsigned int coord = (static_cast<unsigned>(val) % (2 * size));
45 if (coord >= size)
46 coord = 2 * size - 1 - coord;
47 return static_cast<int>(coord);
48 }
49
50 default:
51 LOG_ERROR(HW_GPU, "Unknown texture coordinate wrapping mode %x", (int)mode);
52 UNIMPLEMENTED();
53 return 0;
54 }
55};
56
57Math::Vec3<u8> GetColorModifier(TevStageConfig::ColorModifier factor,
58 const Math::Vec4<u8>& values) {
59 using ColorModifier = TevStageConfig::ColorModifier;
60
61 switch (factor) {
62 case ColorModifier::SourceColor:
63 return values.rgb();
64
65 case ColorModifier::OneMinusSourceColor:
66 return (Math::Vec3<u8>(255, 255, 255) - values.rgb()).Cast<u8>();
67
68 case ColorModifier::SourceAlpha:
69 return values.aaa();
70
71 case ColorModifier::OneMinusSourceAlpha:
72 return (Math::Vec3<u8>(255, 255, 255) - values.aaa()).Cast<u8>();
73
74 case ColorModifier::SourceRed:
75 return values.rrr();
76
77 case ColorModifier::OneMinusSourceRed:
78 return (Math::Vec3<u8>(255, 255, 255) - values.rrr()).Cast<u8>();
79
80 case ColorModifier::SourceGreen:
81 return values.ggg();
82
83 case ColorModifier::OneMinusSourceGreen:
84 return (Math::Vec3<u8>(255, 255, 255) - values.ggg()).Cast<u8>();
85
86 case ColorModifier::SourceBlue:
87 return values.bbb();
88
89 case ColorModifier::OneMinusSourceBlue:
90 return (Math::Vec3<u8>(255, 255, 255) - values.bbb()).Cast<u8>();
91 }
92
93 UNREACHABLE();
94};
95
96u8 GetAlphaModifier(TevStageConfig::AlphaModifier factor, const Math::Vec4<u8>& values) {
97 using AlphaModifier = TevStageConfig::AlphaModifier;
98
99 switch (factor) {
100 case AlphaModifier::SourceAlpha:
101 return values.a();
102
103 case AlphaModifier::OneMinusSourceAlpha:
104 return 255 - values.a();
105
106 case AlphaModifier::SourceRed:
107 return values.r();
108
109 case AlphaModifier::OneMinusSourceRed:
110 return 255 - values.r();
111
112 case AlphaModifier::SourceGreen:
113 return values.g();
114
115 case AlphaModifier::OneMinusSourceGreen:
116 return 255 - values.g();
117
118 case AlphaModifier::SourceBlue:
119 return values.b();
120
121 case AlphaModifier::OneMinusSourceBlue:
122 return 255 - values.b();
123 }
124
125 UNREACHABLE();
126};
127
128Math::Vec3<u8> ColorCombine(TevStageConfig::Operation op, const Math::Vec3<u8> input[3]) {
129 using Operation = TevStageConfig::Operation;
130
131 switch (op) {
132 case Operation::Replace:
133 return input[0];
134
135 case Operation::Modulate:
136 return ((input[0] * input[1]) / 255).Cast<u8>();
137
138 case Operation::Add: {
139 auto result = input[0] + input[1];
140 result.r() = std::min(255, result.r());
141 result.g() = std::min(255, result.g());
142 result.b() = std::min(255, result.b());
143 return result.Cast<u8>();
144 }
145
146 case Operation::AddSigned: {
147 // TODO(bunnei): Verify that the color conversion from (float) 0.5f to
148 // (byte) 128 is correct
149 auto result =
150 input[0].Cast<int>() + input[1].Cast<int>() - Math::MakeVec<int>(128, 128, 128);
151 result.r() = MathUtil::Clamp<int>(result.r(), 0, 255);
152 result.g() = MathUtil::Clamp<int>(result.g(), 0, 255);
153 result.b() = MathUtil::Clamp<int>(result.b(), 0, 255);
154 return result.Cast<u8>();
155 }
156
157 case Operation::Lerp:
158 return ((input[0] * input[2] +
159 input[1] * (Math::MakeVec<u8>(255, 255, 255) - input[2]).Cast<u8>()) /
160 255)
161 .Cast<u8>();
162
163 case Operation::Subtract: {
164 auto result = input[0].Cast<int>() - input[1].Cast<int>();
165 result.r() = std::max(0, result.r());
166 result.g() = std::max(0, result.g());
167 result.b() = std::max(0, result.b());
168 return result.Cast<u8>();
169 }
170
171 case Operation::MultiplyThenAdd: {
172 auto result = (input[0] * input[1] + 255 * input[2].Cast<int>()) / 255;
173 result.r() = std::min(255, result.r());
174 result.g() = std::min(255, result.g());
175 result.b() = std::min(255, result.b());
176 return result.Cast<u8>();
177 }
178
179 case Operation::AddThenMultiply: {
180 auto result = input[0] + input[1];
181 result.r() = std::min(255, result.r());
182 result.g() = std::min(255, result.g());
183 result.b() = std::min(255, result.b());
184 result = (result * input[2].Cast<int>()) / 255;
185 return result.Cast<u8>();
186 }
187 case Operation::Dot3_RGB:
188 case Operation::Dot3_RGBA: {
189 // Not fully accurate. Worst case scenario seems to yield a +/-3 error. Some HW results
190 // indicate that the per-component computation can't have a higher precision than 1/256,
191 // while dot3_rgb((0x80,g0,b0), (0x7F,g1,b1)) and dot3_rgb((0x80,g0,b0), (0x80,g1,b1)) give
192 // different results.
193 int result = ((input[0].r() * 2 - 255) * (input[1].r() * 2 - 255) + 128) / 256 +
194 ((input[0].g() * 2 - 255) * (input[1].g() * 2 - 255) + 128) / 256 +
195 ((input[0].b() * 2 - 255) * (input[1].b() * 2 - 255) + 128) / 256;
196 result = std::max(0, std::min(255, result));
197 return {(u8)result, (u8)result, (u8)result};
198 }
199 default:
200 LOG_ERROR(HW_GPU, "Unknown color combiner operation %d", (int)op);
201 UNIMPLEMENTED();
202 return {0, 0, 0};
203 }
204};
205
206u8 AlphaCombine(TevStageConfig::Operation op, const std::array<u8, 3>& input) {
207 switch (op) {
208 using Operation = TevStageConfig::Operation;
209 case Operation::Replace:
210 return input[0];
211
212 case Operation::Modulate:
213 return input[0] * input[1] / 255;
214
215 case Operation::Add:
216 return std::min(255, input[0] + input[1]);
217
218 case Operation::AddSigned: {
219 // TODO(bunnei): Verify that the color conversion from (float) 0.5f to (byte) 128 is correct
220 auto result = static_cast<int>(input[0]) + static_cast<int>(input[1]) - 128;
221 return static_cast<u8>(MathUtil::Clamp<int>(result, 0, 255));
222 }
223
224 case Operation::Lerp:
225 return (input[0] * input[2] + input[1] * (255 - input[2])) / 255;
226
227 case Operation::Subtract:
228 return std::max(0, (int)input[0] - (int)input[1]);
229
230 case Operation::MultiplyThenAdd:
231 return std::min(255, (input[0] * input[1] + 255 * input[2]) / 255);
232
233 case Operation::AddThenMultiply:
234 return (std::min(255, (input[0] + input[1])) * input[2]) / 255;
235
236 default:
237 LOG_ERROR(HW_GPU, "Unknown alpha combiner operation %d", (int)op);
238 UNIMPLEMENTED();
239 return 0;
240 }
241};
242
243} // namespace Rasterizer
244} // namespace Pica
diff --git a/src/video_core/swrasterizer/texturing.h b/src/video_core/swrasterizer/texturing.h
deleted file mode 100644
index 24f74a5a3..000000000
--- a/src/video_core/swrasterizer/texturing.h
+++ /dev/null
@@ -1,28 +0,0 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "common/common_types.h"
8#include "common/vector_math.h"
9#include "video_core/regs_texturing.h"
10
11namespace Pica {
12namespace Rasterizer {
13
14int GetWrappedTexCoord(TexturingRegs::TextureConfig::WrapMode mode, int val, unsigned size);
15
16Math::Vec3<u8> GetColorModifier(TexturingRegs::TevStageConfig::ColorModifier factor,
17 const Math::Vec4<u8>& values);
18
19u8 GetAlphaModifier(TexturingRegs::TevStageConfig::AlphaModifier factor,
20 const Math::Vec4<u8>& values);
21
22Math::Vec3<u8> ColorCombine(TexturingRegs::TevStageConfig::Operation op,
23 const Math::Vec3<u8> input[3]);
24
25u8 AlphaCombine(TexturingRegs::TevStageConfig::Operation op, const std::array<u8, 3>& input);
26
27} // namespace Rasterizer
28} // namespace Pica