1 // Copyright (c) 2013- PPSSPP Project.
2
3 // This program is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, version 2.0 or later versions.
6
7 // This program is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 // GNU General Public License 2.0 for more details.
11
12 // A copy of the GPL 2.0 should have been included with the program.
13 // If not, see http://www.gnu.org/licenses/
14
15 // Official git repository and contact information can be found at
16 // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18 #include <algorithm>
19 #include <cmath>
20 #include "Common/CPUDetect.h"
21 #include "Common/Math/math_util.h"
22 #include "Common/GPU/OpenGL/GLFeatures.h"
23
24 #include "Core/Config.h"
25 #include "GPU/GPUState.h"
26 #include "GPU/Math3D.h"
27 #include "GPU/Common/FramebufferManagerCommon.h"
28 #include "GPU/Common/GPUStateUtils.h"
29 #include "GPU/Common/SoftwareTransformCommon.h"
30 #include "GPU/Common/TransformCommon.h"
31 #include "GPU/Common/TextureCacheCommon.h"
32 #include "GPU/Common/VertexDecoderCommon.h"
33
34 // This is the software transform pipeline, which is necessary for supporting RECT
35 // primitives correctly without geometry shaders, and may be easier to use for
36 // debugging than the hardware transform pipeline.
37
38 // There's code here that simply expands transformed RECTANGLES into plain triangles.
39
40 // We're gonna have to keep software transforming RECTANGLES, unless we use a geom shader which we can't on OpenGL ES 2.0 or DX9.
41 // Usually, though, these primitives don't use lighting etc so it's no biggie performance wise, but it would be nice to get rid of
42 // this code.
43
44 // Actually, if we find the camera-relative right and down vectors, it might even be possible to add the extra points in pre-transformed
45 // space and thus make decent use of hardware transform.
46
47 // Actually again, single quads could be drawn more efficiently using GL_TRIANGLE_STRIP, no need to duplicate verts as for
48 // GL_TRIANGLES. Still need to sw transform to compute the extra two corners though.
49 //
50
51 // The verts are in the order: BR BL TL TR
SwapUVs(TransformedVertex & a,TransformedVertex & b)52 static void SwapUVs(TransformedVertex &a, TransformedVertex &b) {
53 float tempu = a.u;
54 float tempv = a.v;
55 a.u = b.u;
56 a.v = b.v;
57 b.u = tempu;
58 b.v = tempv;
59 }
60
61 // 2 3 3 2 0 3 2 1
62 // to to or
63 // 1 0 0 1 1 2 3 0
64
65 // Note: 0 is BR and 2 is TL.
66
RotateUV(TransformedVertex v[4],float flippedMatrix[16],bool flippedY)67 static void RotateUV(TransformedVertex v[4], float flippedMatrix[16], bool flippedY) {
68 // Transform these two coordinates to figure out whether they're flipped or not.
69 Vec4f tl;
70 Vec3ByMatrix44(tl.AsArray(), v[2].pos, flippedMatrix);
71
72 Vec4f br;
73 Vec3ByMatrix44(br.AsArray(), v[0].pos, flippedMatrix);
74
75 float ySign = flippedY ? -1.0 : 1.0;
76
77 const float invtlw = 1.0f / tl.w;
78 const float invbrw = 1.0f / br.w;
79 const float x1 = tl.x * invtlw;
80 const float x2 = br.x * invbrw;
81 const float y1 = tl.y * invtlw * ySign;
82 const float y2 = br.y * invbrw * ySign;
83
84 if ((x1 < x2 && y1 < y2) || (x1 > x2 && y1 > y2))
85 SwapUVs(v[1], v[3]);
86 }
87
RotateUVThrough(TransformedVertex v[4])88 static void RotateUVThrough(TransformedVertex v[4]) {
89 float x1 = v[2].x;
90 float x2 = v[0].x;
91 float y1 = v[2].y;
92 float y2 = v[0].y;
93
94 if ((x1 < x2 && y1 > y2) || (x1 > x2 && y1 < y2))
95 SwapUVs(v[1], v[3]);
96 }
97
98 // Clears on the PSP are best done by drawing a series of vertical strips
99 // in clear mode. This tries to detect that.
IsReallyAClear(const TransformedVertex * transformed,int numVerts,float x2,float y2)100 static bool IsReallyAClear(const TransformedVertex *transformed, int numVerts, float x2, float y2) {
101 if (transformed[0].x != 0.0f || transformed[0].y != 0.0f)
102 return false;
103
104 // Color and Z are decided by the second vertex, so only need to check those for matching color.
105 u32 matchcolor = transformed[1].color0_32;
106 float matchz = transformed[1].z;
107
108 for (int i = 1; i < numVerts; i++) {
109 if ((i & 1) == 0) {
110 // Top left of a rectangle
111 if (transformed[i].y != 0.0f)
112 return false;
113 if (i > 0 && transformed[i].x != transformed[i - 1].x)
114 return false;
115 } else {
116 if (transformed[i].color0_32 != matchcolor || transformed[i].z != matchz)
117 return false;
118 // Bottom right
119 if (transformed[i].y < y2)
120 return false;
121 if (transformed[i].x <= transformed[i - 1].x)
122 return false;
123 }
124 }
125
126 // The last vertical strip often extends outside the drawing area.
127 if (transformed[numVerts - 1].x < x2)
128 return false;
129
130 return true;
131 }
132
ColorIndexOffset(int prim,GEShadeMode shadeMode,bool clearMode)133 static int ColorIndexOffset(int prim, GEShadeMode shadeMode, bool clearMode) {
134 if (shadeMode != GE_SHADE_FLAT || clearMode) {
135 return 0;
136 }
137
138 switch (prim) {
139 case GE_PRIM_LINES:
140 case GE_PRIM_LINE_STRIP:
141 return 1;
142
143 case GE_PRIM_TRIANGLES:
144 case GE_PRIM_TRIANGLE_STRIP:
145 return 2;
146
147 case GE_PRIM_TRIANGLE_FAN:
148 return 1;
149
150 case GE_PRIM_RECTANGLES:
151 // We already use BR color when expanding, so no need to offset.
152 return 0;
153
154 default:
155 break;
156 }
157 return 0;
158 }
159
Decode(int prim,u32 vertType,const DecVtxFormat & decVtxFormat,int maxIndex,SoftwareTransformResult * result)160 void SoftwareTransform::Decode(int prim, u32 vertType, const DecVtxFormat &decVtxFormat, int maxIndex, SoftwareTransformResult *result) {
161 u8 *decoded = params_.decoded;
162 TransformedVertex *transformed = params_.transformed;
163 bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0;
164 bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled();
165
166 float uscale = 1.0f;
167 float vscale = 1.0f;
168 if (throughmode) {
169 uscale /= gstate_c.curTextureWidth;
170 vscale /= gstate_c.curTextureHeight;
171 }
172
173 bool skinningEnabled = vertTypeIsSkinningEnabled(vertType);
174
175 const int w = gstate.getTextureWidth(0);
176 const int h = gstate.getTextureHeight(0);
177 float widthFactor = (float) w / (float) gstate_c.curTextureWidth;
178 float heightFactor = (float) h / (float) gstate_c.curTextureHeight;
179
180 Lighter lighter(vertType);
181 float fog_end = getFloat24(gstate.fog1);
182 float fog_slope = getFloat24(gstate.fog2);
183 // Same fixup as in ShaderManagerGLES.cpp
184 if (my_isnanorinf(fog_end)) {
185 // Not really sure what a sensible value might be, but let's try 64k.
186 fog_end = std::signbit(fog_end) ? -65535.0f : 65535.0f;
187 }
188 if (my_isnanorinf(fog_slope)) {
189 fog_slope = std::signbit(fog_slope) ? -65535.0f : 65535.0f;
190 }
191
192 int provokeIndOffset = 0;
193 if (params_.provokeFlatFirst) {
194 provokeIndOffset = ColorIndexOffset(prim, gstate.getShadeMode(), gstate.isModeClear());
195 }
196
197 VertexReader reader(decoded, decVtxFormat, vertType);
198 if (throughmode) {
199 for (int index = 0; index < maxIndex; index++) {
200 // Do not touch the coordinates or the colors. No lighting.
201 reader.Goto(index);
202 // TODO: Write to a flexible buffer, we don't always need all four components.
203 TransformedVertex &vert = transformed[index];
204 reader.ReadPos(vert.pos);
205
206 if (reader.hasColor0()) {
207 if (provokeIndOffset != 0 && index + provokeIndOffset < maxIndex) {
208 reader.Goto(index + provokeIndOffset);
209 reader.ReadColor0_8888(vert.color0);
210 reader.Goto(index);
211 } else {
212 reader.ReadColor0_8888(vert.color0);
213 }
214 } else {
215 vert.color0_32 = gstate.getMaterialAmbientRGBA();
216 }
217
218 if (reader.hasUV()) {
219 reader.ReadUV(vert.uv);
220
221 vert.u *= uscale;
222 vert.v *= vscale;
223 } else {
224 vert.u = 0.0f;
225 vert.v = 0.0f;
226 }
227
228 // Ignore color1 and fog, never used in throughmode anyway.
229 // The w of uv is also never used (hardcoded to 1.0.)
230 }
231 } else {
232 // Okay, need to actually perform the full transform.
233 for (int index = 0; index < maxIndex; index++) {
234 reader.Goto(index);
235
236 float v[3] = {0, 0, 0};
237 Vec4f c0 = Vec4f(1, 1, 1, 1);
238 Vec4f c1 = Vec4f(0, 0, 0, 0);
239 float uv[3] = {0, 0, 1};
240 float fogCoef = 1.0f;
241
242 float out[3];
243 float pos[3];
244 Vec3f normal(0, 0, 1);
245 Vec3f worldnormal(0, 0, 1);
246 reader.ReadPos(pos);
247
248 float ruv[2] = { 0.0f, 0.0f };
249 if (reader.hasUV())
250 reader.ReadUV(ruv);
251
252 // Read all the provoking vertex values here.
253 Vec4f unlitColor;
254 if (provokeIndOffset != 0 && index + provokeIndOffset < maxIndex)
255 reader.Goto(index + provokeIndOffset);
256 if (reader.hasColor0())
257 reader.ReadColor0(unlitColor.AsArray());
258 else
259 unlitColor = Vec4f::FromRGBA(gstate.getMaterialAmbientRGBA());
260 if (reader.hasNormal())
261 reader.ReadNrm(normal.AsArray());
262
263 if (!skinningEnabled) {
264 Vec3ByMatrix43(out, pos, gstate.worldMatrix);
265 if (reader.hasNormal()) {
266 if (gstate.areNormalsReversed()) {
267 normal = -normal;
268 }
269 Norm3ByMatrix43(worldnormal.AsArray(), normal.AsArray(), gstate.worldMatrix);
270 worldnormal = worldnormal.NormalizedOr001(cpu_info.bSSE4_1);
271 }
272 } else {
273 float weights[8];
274 // TODO: For flat, are weights from the provoking used for color/normal?
275 reader.Goto(index);
276 reader.ReadWeights(weights);
277
278 // Skinning
279 Vec3f psum(0, 0, 0);
280 Vec3f nsum(0, 0, 0);
281 for (int i = 0; i < vertTypeGetNumBoneWeights(vertType); i++) {
282 if (weights[i] != 0.0f) {
283 Vec3ByMatrix43(out, pos, gstate.boneMatrix+i*12);
284 Vec3f tpos(out);
285 psum += tpos * weights[i];
286 if (reader.hasNormal()) {
287 Vec3f norm;
288 Norm3ByMatrix43(norm.AsArray(), normal.AsArray(), gstate.boneMatrix+i*12);
289 nsum += norm * weights[i];
290 }
291 }
292 }
293
294 // Yes, we really must multiply by the world matrix too.
295 Vec3ByMatrix43(out, psum.AsArray(), gstate.worldMatrix);
296 if (reader.hasNormal()) {
297 normal = nsum;
298 if (gstate.areNormalsReversed()) {
299 normal = -normal;
300 }
301 Norm3ByMatrix43(worldnormal.AsArray(), normal.AsArray(), gstate.worldMatrix);
302 worldnormal = worldnormal.NormalizedOr001(cpu_info.bSSE4_1);
303 }
304 }
305
306 // Perform lighting here if enabled.
307 if (gstate.isLightingEnabled()) {
308 float litColor0[4];
309 float litColor1[4];
310 lighter.Light(litColor0, litColor1, unlitColor.AsArray(), out, worldnormal);
311
312 // Don't ignore gstate.lmode - we should send two colors in that case
313 for (int j = 0; j < 4; j++) {
314 c0[j] = litColor0[j];
315 }
316 if (lmode) {
317 // Separate colors
318 for (int j = 0; j < 4; j++) {
319 c1[j] = litColor1[j];
320 }
321 } else {
322 // Summed color into c0 (will clamp in ToRGBA().)
323 for (int j = 0; j < 4; j++) {
324 c0[j] += litColor1[j];
325 }
326 }
327 } else {
328 for (int j = 0; j < 4; j++) {
329 c0[j] = unlitColor[j];
330 }
331 if (lmode) {
332 // c1 is already 0.
333 }
334 }
335
336 // Perform texture coordinate generation after the transform and lighting - one style of UV depends on lights.
337 switch (gstate.getUVGenMode()) {
338 case GE_TEXMAP_TEXTURE_COORDS: // UV mapping
339 case GE_TEXMAP_UNKNOWN: // Seen in Riviera. Unsure of meaning, but this works.
340 // We always prescale in the vertex decoder now.
341 uv[0] = ruv[0];
342 uv[1] = ruv[1];
343 uv[2] = 1.0f;
344 break;
345
346 case GE_TEXMAP_TEXTURE_MATRIX:
347 {
348 // TODO: What's the correct behavior with flat shading? Provoked normal or real normal?
349
350 // Projection mapping
351 Vec3f source;
352 switch (gstate.getUVProjMode()) {
353 case GE_PROJMAP_POSITION: // Use model space XYZ as source
354 source = pos;
355 break;
356
357 case GE_PROJMAP_UV: // Use unscaled UV as source
358 source = Vec3f(ruv[0], ruv[1], 0.0f);
359 break;
360
361 case GE_PROJMAP_NORMALIZED_NORMAL: // Use normalized normal as source
362 source = normal.NormalizedOr001(cpu_info.bSSE4_1);
363 if (!reader.hasNormal()) {
364 ERROR_LOG_REPORT(G3D, "Normal projection mapping without normal?");
365 }
366 break;
367
368 case GE_PROJMAP_NORMAL: // Use non-normalized normal as source!
369 source = normal;
370 if (!reader.hasNormal()) {
371 ERROR_LOG_REPORT(G3D, "Normal projection mapping without normal?");
372 }
373 break;
374 }
375
376 float uvw[3];
377 Vec3ByMatrix43(uvw, &source.x, gstate.tgenMatrix);
378 uv[0] = uvw[0];
379 uv[1] = uvw[1];
380 uv[2] = uvw[2];
381 }
382 break;
383
384 case GE_TEXMAP_ENVIRONMENT_MAP:
385 // Shade mapping - use two light sources to generate U and V.
386 {
387 auto getLPosFloat = [&](int l, int i) {
388 return getFloat24(gstate.lpos[l * 3 + i]);
389 };
390 auto getLPos = [&](int l) {
391 return Vec3f(getLPosFloat(l, 0), getLPosFloat(l, 1), getLPosFloat(l, 2));
392 };
393 auto calcShadingLPos = [&](int l) {
394 Vec3f pos = getLPos(l);
395 return pos.NormalizedOr001(cpu_info.bSSE4_1);
396 };
397 // Might not have lighting enabled, so don't use lighter.
398 Vec3f lightpos0 = calcShadingLPos(gstate.getUVLS0());
399 Vec3f lightpos1 = calcShadingLPos(gstate.getUVLS1());
400
401 uv[0] = (1.0f + Dot(lightpos0, worldnormal))/2.0f;
402 uv[1] = (1.0f + Dot(lightpos1, worldnormal))/2.0f;
403 uv[2] = 1.0f;
404 }
405 break;
406
407 default:
408 // Illegal
409 ERROR_LOG_REPORT(G3D, "Impossible UV gen mode? %d", gstate.getUVGenMode());
410 break;
411 }
412
413 uv[0] = uv[0] * widthFactor;
414 uv[1] = uv[1] * heightFactor;
415
416 // Transform the coord by the view matrix.
417 Vec3ByMatrix43(v, out, gstate.viewMatrix);
418 fogCoef = (v[2] + fog_end) * fog_slope;
419
420 // TODO: Write to a flexible buffer, we don't always need all four components.
421 memcpy(&transformed[index].x, v, 3 * sizeof(float));
422 transformed[index].fog = fogCoef;
423 memcpy(&transformed[index].u, uv, 3 * sizeof(float));
424 transformed[index].color0_32 = c0.ToRGBA();
425 transformed[index].color1_32 = c1.ToRGBA();
426
427 // The multiplication by the projection matrix is still performed in the vertex shader.
428 // So is vertex depth rounding, to simulate the 16-bit depth buffer.
429 }
430 }
431
432 // Here's the best opportunity to try to detect rectangles used to clear the screen, and
433 // replace them with real clears. This can provide a speedup on certain mobile chips.
434 //
435 // An alternative option is to simply ditch all the verts except the first and last to create a single
436 // rectangle out of many. Quite a small optimization though.
437 // Experiment: Disable on PowerVR (see issue #6290)
438 // TODO: This bleeds outside the play area in non-buffered mode. Big deal? Probably not.
439 // TODO: Allow creating a depth clear and a color draw.
440 bool reallyAClear = false;
441 if (maxIndex > 1 && prim == GE_PRIM_RECTANGLES && gstate.isModeClear()) {
442 int scissorX2 = gstate.getScissorX2() + 1;
443 int scissorY2 = gstate.getScissorY2() + 1;
444 reallyAClear = IsReallyAClear(transformed, maxIndex, scissorX2, scissorY2);
445 if (reallyAClear && gstate.getColorMask() != 0xFFFFFFFF && (gstate.isClearModeColorMask() || gstate.isClearModeAlphaMask())) {
446 result->setSafeSize = true;
447 result->safeWidth = scissorX2;
448 result->safeHeight = scissorY2;
449 }
450 }
451 if (params_.allowClear && reallyAClear && gl_extensions.gpuVendor != GPU_VENDOR_IMGTEC) {
452 // If alpha is not allowed to be separate, it must match for both depth/stencil and color. Vulkan requires this.
453 bool alphaMatchesColor = gstate.isClearModeColorMask() == gstate.isClearModeAlphaMask();
454 bool depthMatchesStencil = gstate.isClearModeAlphaMask() == gstate.isClearModeDepthMask();
455 bool matchingComponents = params_.allowSeparateAlphaClear || (alphaMatchesColor && depthMatchesStencil);
456 bool stencilNotMasked = !gstate.isClearModeAlphaMask() || gstate.getStencilWriteMask() == 0x00;
457 if (matchingComponents && stencilNotMasked) {
458 result->color = transformed[1].color0_32;
459 // Need to rescale from a [0, 1] float. This is the final transformed value.
460 result->depth = ToScaledDepthFromIntegerScale((int)(transformed[1].z * 65535.0f));
461 result->action = SW_CLEAR;
462 gpuStats.numClears++;
463 return;
464 }
465 }
466
467 // Detect full screen "clears" that might not be so obvious, to set the safe size if possible.
468 if (!result->setSafeSize && prim == GE_PRIM_RECTANGLES && maxIndex == 2) {
469 bool clearingColor = gstate.isModeClear() && (gstate.isClearModeColorMask() || gstate.isClearModeAlphaMask());
470 bool writingColor = gstate.getColorMask() != 0xFFFFFFFF;
471 bool startsZeroX = transformed[0].x <= 0.0f && transformed[1].x > 0.0f && transformed[1].x > transformed[0].x;
472 bool startsZeroY = transformed[0].y <= 0.0f && transformed[1].y > 0.0f && transformed[1].y > transformed[0].y;
473
474 if (startsZeroX && startsZeroY && (clearingColor || writingColor)) {
475 int scissorX2 = gstate.getScissorX2() + 1;
476 int scissorY2 = gstate.getScissorY2() + 1;
477 result->setSafeSize = true;
478 result->safeWidth = std::min(scissorX2, (int)transformed[1].x);
479 result->safeHeight = std::min(scissorY2, (int)transformed[1].y);
480 }
481 }
482 }
483
484 // Also, this assumes SetTexture() has already figured out the actual texture height.
DetectOffsetTexture(int maxIndex)485 void SoftwareTransform::DetectOffsetTexture(int maxIndex) {
486 TransformedVertex *transformed = params_.transformed;
487
488 const int w = gstate.getTextureWidth(0);
489 const int h = gstate.getTextureHeight(0);
490 float widthFactor = (float)w / (float)gstate_c.curTextureWidth;
491 float heightFactor = (float)h / (float)gstate_c.curTextureHeight;
492
493 // Breath of Fire 3 does some interesting rendering here, probably from being a port.
494 // It draws at 384x240 to two buffers in VRAM, one right after the other.
495 // We end up creating separate framebuffers, and rendering to each.
496 // But the game then stretches this to the screen - and reads from a single 512 tall texture.
497 // We initially use the first framebuffer. This code detects the read from the second.
498 //
499 // First Vs: 12, 228 - second Vs: 252, 468 - estimated fb height: 272
500
501 // If curTextureHeight is < h, it must be a framebuffer that wasn't full height.
502 if (gstate_c.curTextureHeight < (u32)h && maxIndex >= 2) {
503 // This is the max V that will still land within the framebuffer (since it's shorter.)
504 // We already adjusted V to the framebuffer above.
505 const float maxAvailableV = 1.0f;
506 // This is the max V that would've been inside the original texture size.
507 const float maxValidV = heightFactor;
508
509 // Apparently, Assassin's Creed: Bloodlines accesses just outside.
510 const float invTexH = 1.0f / gstate_c.curTextureHeight; // size of one texel.
511
512 // Are either TL or BR inside the texture but outside the framebuffer?
513 const bool tlOutside = transformed[0].v > maxAvailableV + invTexH && transformed[0].v <= maxValidV;
514 const bool brOutside = transformed[1].v > maxAvailableV + invTexH && transformed[1].v <= maxValidV;
515
516 // If TL isn't outside, is it at least near the end?
517 // We check this because some games do 0-512 from a 272 tall framebuf.
518 const bool tlAlmostOutside = transformed[0].v > maxAvailableV * 0.5f && transformed[0].v <= maxValidV;
519
520 if (tlOutside || (brOutside && tlAlmostOutside)) {
521 const u32 prevXOffset = gstate_c.curTextureXOffset;
522 const u32 prevYOffset = gstate_c.curTextureYOffset;
523
524 // This is how far the nearest coord is, so that's where we'll look for the next framebuf.
525 const u32 yOffset = (int)(gstate_c.curTextureHeight * std::min(transformed[0].v, transformed[1].v));
526 if (params_.texCache->SetOffsetTexture(yOffset)) {
527 const float oldWidthFactor = widthFactor;
528 const float oldHeightFactor = heightFactor;
529 widthFactor = (float)w / (float)gstate_c.curTextureWidth;
530 heightFactor = (float)h / (float)gstate_c.curTextureHeight;
531
532 // We need to subtract this offset from the UVs to address the new framebuf.
533 const float adjustedYOffset = yOffset + prevYOffset - gstate_c.curTextureYOffset;
534 const float yDiff = (float)adjustedYOffset / (float)h;
535 const float adjustedXOffset = prevXOffset - gstate_c.curTextureXOffset;
536 const float xDiff = (float)adjustedXOffset / (float)w;
537
538 for (int index = 0; index < maxIndex; ++index) {
539 transformed[index].u = (transformed[index].u / oldWidthFactor - xDiff) * widthFactor;
540 transformed[index].v = (transformed[index].v / oldHeightFactor - yDiff) * heightFactor;
541 }
542
543 // We undid the offset, so reset. This avoids a different shader.
544 gstate_c.curTextureXOffset = prevXOffset;
545 gstate_c.curTextureYOffset = prevYOffset;
546 }
547 }
548 }
549 }
550
551 // NOTE: The viewport must be up to date!
BuildDrawingParams(int prim,int vertexCount,u32 vertType,u16 * & inds,int & maxIndex,SoftwareTransformResult * result)552 void SoftwareTransform::BuildDrawingParams(int prim, int vertexCount, u32 vertType, u16 *&inds, int &maxIndex, SoftwareTransformResult *result) {
553 TransformedVertex *transformed = params_.transformed;
554 TransformedVertex *transformedExpanded = params_.transformedExpanded;
555 bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0;
556
557 // Step 2: expand rectangles.
558 result->drawBuffer = transformed;
559 int numTrans = 0;
560
561 FramebufferManagerCommon *fbman = params_.fbman;
562 bool useBufferedRendering = fbman->UseBufferedRendering();
563
564 bool flippedY = g_Config.iGPUBackend == (int)GPUBackend::OPENGL && !useBufferedRendering;
565
566 if (prim != GE_PRIM_RECTANGLES) {
567 // We can simply draw the unexpanded buffer.
568 numTrans = vertexCount;
569 result->drawIndexed = true;
570 } else {
571 // Pretty bad hackery where we re-do the transform (in RotateUV) to see if the vertices are flipped in screen space.
572 // Since we've already got API-specific assumptions (Y direction, etc) baked into the projMatrix (which we arguably shouldn't),
573 // this gets nasty and very hard to understand.
574
575 float flippedMatrix[16];
576 if (!throughmode) {
577 memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float));
578
579 const bool invertedY = flippedY ? (gstate_c.vpHeight < 0) : (gstate_c.vpHeight > 0);
580 if (invertedY) {
581 flippedMatrix[1] = -flippedMatrix[1];
582 flippedMatrix[5] = -flippedMatrix[5];
583 flippedMatrix[9] = -flippedMatrix[9];
584 flippedMatrix[13] = -flippedMatrix[13];
585 }
586 const bool invertedX = gstate_c.vpWidth < 0;
587 if (invertedX) {
588 flippedMatrix[0] = -flippedMatrix[0];
589 flippedMatrix[4] = -flippedMatrix[4];
590 flippedMatrix[8] = -flippedMatrix[8];
591 flippedMatrix[12] = -flippedMatrix[12];
592 }
593 }
594
595 //rectangles always need 2 vertices, disregard the last one if there's an odd number
596 vertexCount = vertexCount & ~1;
597 numTrans = 0;
598 result->drawBuffer = transformedExpanded;
599 TransformedVertex *trans = &transformedExpanded[0];
600 const u16 *indsIn = (const u16 *)inds;
601 u16 *newInds = inds + vertexCount;
602 u16 *indsOut = newInds;
603 maxIndex = 4 * (vertexCount / 2);
604 for (int i = 0; i < vertexCount; i += 2) {
605 const TransformedVertex &transVtxTL = transformed[indsIn[i + 0]];
606 const TransformedVertex &transVtxBR = transformed[indsIn[i + 1]];
607
608 // We have to turn the rectangle into two triangles, so 6 points.
609 // This is 4 verts + 6 indices.
610
611 // bottom right
612 trans[0] = transVtxBR;
613
614 // top right
615 trans[1] = transVtxBR;
616 trans[1].y = transVtxTL.y;
617 trans[1].v = transVtxTL.v;
618
619 // top left
620 trans[2] = transVtxBR;
621 trans[2].x = transVtxTL.x;
622 trans[2].y = transVtxTL.y;
623 trans[2].u = transVtxTL.u;
624 trans[2].v = transVtxTL.v;
625
626 // bottom left
627 trans[3] = transVtxBR;
628 trans[3].x = transVtxTL.x;
629 trans[3].u = transVtxTL.u;
630
631 // That's the four corners. Now process UV rotation.
632 if (throughmode)
633 RotateUVThrough(trans);
634 else
635 RotateUV(trans, flippedMatrix, flippedY);
636
637 // Triangle: BR-TR-TL
638 indsOut[0] = i * 2 + 0;
639 indsOut[1] = i * 2 + 1;
640 indsOut[2] = i * 2 + 2;
641 // Triangle: BL-BR-TL
642 indsOut[3] = i * 2 + 3;
643 indsOut[4] = i * 2 + 0;
644 indsOut[5] = i * 2 + 2;
645 trans += 4;
646 indsOut += 6;
647
648 numTrans += 6;
649 }
650 inds = newInds;
651 result->drawIndexed = true;
652
653 // We don't know the color until here, so we have to do it now, instead of in StateMapping.
654 // Might want to reconsider the order of things later...
655 if (gstate.isModeClear() && gstate.isClearModeAlphaMask()) {
656 result->setStencil = true;
657 if (vertexCount > 1) {
658 // Take the bottom right alpha value of the first rect as the stencil value.
659 // Technically, each rect could individually fill its stencil, but most of the
660 // time they use the same one.
661 result->stencilValue = transformed[indsIn[1]].color0[3];
662 } else {
663 result->stencilValue = 0;
664 }
665 }
666 }
667
668 if (gstate.isModeClear()) {
669 gpuStats.numClears++;
670 }
671
672 result->action = SW_DRAW_PRIMITIVES;
673 result->drawNumTrans = numTrans;
674 }
675