Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/GPU/Software/TransformUnit.cpp
3186 views
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 "ppsspp_config.h"
19
20
#include <cmath>
21
22
#include "Common/Common.h"
23
#include "Common/CPUDetect.h"
24
#include "Common/Math/math_util.h"
25
#include "Common/MemoryUtil.h"
26
#include "Common/Profiler/Profiler.h"
27
#include "GPU/GPUState.h"
28
#include "GPU/Common/DrawEngineCommon.h"
29
#include "GPU/Common/VertexDecoderCommon.h"
30
#include "GPU/Common/SoftwareTransformCommon.h"
31
#include "Common/Math/SIMDHeaders.h"
32
#include "GPU/Software/BinManager.h"
33
#include "GPU/Software/Clipper.h"
34
#include "GPU/Software/Lighting.h"
35
#include "GPU/Software/RasterizerRectangle.h"
36
#include "GPU/Software/TransformUnit.h"
37
38
// For the SSE4 stuff
39
#if PPSSPP_ARCH(SSE2)
40
#include <smmintrin.h>
41
#endif
42
43
#define TRANSFORM_BUF_SIZE (65536 * 48)
44
45
TransformUnit::TransformUnit() {
46
decoded_ = (u8 *)AllocateAlignedMemory(TRANSFORM_BUF_SIZE, 16);
47
_assert_(decoded_);
48
binner_ = new BinManager();
49
}
50
51
TransformUnit::~TransformUnit() {
52
FreeAlignedMemory(decoded_);
53
delete binner_;
54
}
55
56
bool TransformUnit::IsStarted() {
57
return binner_ && decoded_;
58
}
59
60
SoftwareDrawEngine::SoftwareDrawEngine() {
61
flushOnParams_ = false;
62
}
63
64
SoftwareDrawEngine::~SoftwareDrawEngine() {}
65
66
void SoftwareDrawEngine::NotifyConfigChanged() {
67
DrawEngineCommon::NotifyConfigChanged();
68
applySkinInDecode_ = true;
69
}
70
71
void SoftwareDrawEngine::Flush() {
72
transformUnit.Flush(gpuCommon_, "debug");
73
}
74
75
void SoftwareDrawEngine::DispatchSubmitPrim(const void *verts, const void *inds, GEPrimitiveType prim, int vertexCount, u32 vertTypeID, bool clockwise, int *bytesRead) {
76
_assert_msg_(clockwise, "Mixed cull mode not supported.");
77
transformUnit.SubmitPrimitive(verts, inds, prim, vertexCount, vertTypeID, bytesRead, this);
78
}
79
80
void SoftwareDrawEngine::DispatchSubmitImm(GEPrimitiveType prim, TransformedVertex *buffer, int vertexCount, int cullMode, bool continuation) {
81
uint32_t vertTypeID = GetVertTypeID(gstate.vertType | GE_VTYPE_POS_FLOAT, gstate.getUVGenMode(), true);
82
83
int flipCull = cullMode != gstate.getCullMode() ? 1 : 0;
84
// TODO: For now, just setting all dirty.
85
transformUnit.SetDirty(SoftDirty(-1));
86
gstate.cullmode ^= flipCull;
87
88
// TODO: This is a bit ugly. Should bypass when clipping...
89
uint32_t xScale = gstate.viewportxscale;
90
uint32_t xCenter = gstate.viewportxcenter;
91
uint32_t yScale = gstate.viewportyscale;
92
uint32_t yCenter = gstate.viewportycenter;
93
uint32_t zScale = gstate.viewportzscale;
94
uint32_t zCenter = gstate.viewportzcenter;
95
96
// Force scale to 1 and center to zero.
97
gstate.viewportxscale = (GE_CMD_VIEWPORTXSCALE << 24) | 0x3F8000;
98
gstate.viewportxcenter = (GE_CMD_VIEWPORTXCENTER << 24) | 0x000000;
99
gstate.viewportyscale = (GE_CMD_VIEWPORTYSCALE << 24) | 0x3F8000;
100
gstate.viewportycenter = (GE_CMD_VIEWPORTYCENTER << 24) | 0x000000;
101
// Z we scale to 65535 for neg z clipping.
102
gstate.viewportzscale = (GE_CMD_VIEWPORTZSCALE << 24) | 0x477FFF;
103
gstate.viewportzcenter = (GE_CMD_VIEWPORTZCENTER << 24) | 0x000000;
104
105
// Before we start, submit 0 prims to reset the prev prim type.
106
// Following submits will always be KEEP_PREVIOUS.
107
if (!continuation)
108
transformUnit.SubmitPrimitive(nullptr, nullptr, prim, 0, vertTypeID, nullptr, this);
109
110
for (int i = 0; i < vertexCount; i++) {
111
ClipVertexData vert;
112
vert.clippos = ClipCoords(buffer[i].pos);
113
vert.v.texturecoords.x = buffer[i].u;
114
vert.v.texturecoords.y = buffer[i].v;
115
vert.v.texturecoords.z = buffer[i].uv_w;
116
if (gstate.isModeThrough()) {
117
vert.v.texturecoords.x *= gstate.getTextureWidth(0);
118
vert.v.texturecoords.y *= gstate.getTextureHeight(0);
119
} else {
120
vert.clippos.z *= 1.0f / 65535.0f;
121
}
122
vert.v.clipw = buffer[i].pos_w;
123
vert.v.color0 = buffer[i].color0_32;
124
vert.v.color1 = gstate.isUsingSecondaryColor() && !gstate.isModeThrough() ? buffer[i].color1_32 : 0;
125
vert.v.fogdepth = buffer[i].fog;
126
vert.v.screenpos.x = (int)(buffer[i].x * 16.0f);
127
vert.v.screenpos.y = (int)(buffer[i].y * 16.0f);
128
vert.v.screenpos.z = (u16)(u32)buffer[i].z;
129
130
transformUnit.SubmitImmVertex(vert, this);
131
}
132
133
gstate.viewportxscale = xScale;
134
gstate.viewportxcenter = xCenter;
135
gstate.viewportyscale = yScale;
136
gstate.viewportycenter = yCenter;
137
gstate.viewportzscale = zScale;
138
gstate.viewportzcenter = zCenter;
139
140
gstate.cullmode ^= flipCull;
141
// TODO: Should really clear, but a bunch of values are forced so we this is safest.
142
transformUnit.SetDirty(SoftDirty(-1));
143
}
144
145
VertexDecoder *SoftwareDrawEngine::FindVertexDecoder(u32 vtype) {
146
const u32 vertTypeID = GetVertTypeID(vtype, gstate.getUVGenMode(), true);
147
return DrawEngineCommon::GetVertexDecoder(vertTypeID);
148
}
149
150
WorldCoords TransformUnit::ModelToWorld(const ModelCoords &coords) {
151
return Vec3ByMatrix43(coords, gstate.worldMatrix);
152
}
153
154
WorldCoords TransformUnit::ModelToWorldNormal(const ModelCoords &coords) {
155
return Norm3ByMatrix43(coords, gstate.worldMatrix);
156
}
157
158
template <bool depthClamp, bool alwaysCheckRange>
159
static ScreenCoords ClipToScreenInternal(Vec3f scaled, const ClipCoords &coords, bool *outside_range_flag) {
160
ScreenCoords ret;
161
162
// Account for rounding for X and Y.
163
// TODO: Validate actual rounding range.
164
const float SCREEN_BOUND = 4095.0f + (15.5f / 16.0f);
165
166
// This matches hardware tests - depth is clamped when this flag is on.
167
if constexpr (depthClamp) {
168
// Note: if the depth is clipped (z/w <= -1.0), the outside_range_flag should NOT be set, even for x and y.
169
if ((alwaysCheckRange || coords.z > -coords.w) && (scaled.x >= SCREEN_BOUND || scaled.y >= SCREEN_BOUND || scaled.x < 0 || scaled.y < 0)) {
170
*outside_range_flag = true;
171
}
172
173
if (scaled.z < 0.f)
174
scaled.z = 0.f;
175
else if (scaled.z > 65535.0f)
176
scaled.z = 65535.0f;
177
} else if (scaled.x > SCREEN_BOUND || scaled.y >= SCREEN_BOUND || scaled.x < 0 || scaled.y < 0 || scaled.z < 0.0f || scaled.z >= 65536.0f) {
178
*outside_range_flag = true;
179
}
180
181
// 16 = 0xFFFF / 4095.9375
182
// Round up at 0.625 to the nearest subpixel.
183
static_assert(SCREEN_SCALE_FACTOR == 16, "Currently only supports scale 16");
184
int x = (int)(scaled.x * 16.0f + 0.375f - gstate.getOffsetX16());
185
int y = (int)(scaled.y * 16.0f + 0.375f - gstate.getOffsetY16());
186
return ScreenCoords(x, y, scaled.z);
187
}
188
189
static inline ScreenCoords ClipToScreenInternal(const ClipCoords &coords, bool *outside_range_flag) {
190
// Parameters here can seem invalid, but the PSP is fine with negative viewport widths etc.
191
// The checking that OpenGL and D3D do is actually quite superflous as the calculations still "work"
192
// with some pretty crazy inputs, which PSP games are happy to do at times.
193
float xScale = gstate.getViewportXScale();
194
float xCenter = gstate.getViewportXCenter();
195
float yScale = gstate.getViewportYScale();
196
float yCenter = gstate.getViewportYCenter();
197
float zScale = gstate.getViewportZScale();
198
float zCenter = gstate.getViewportZCenter();
199
200
float x = coords.x * xScale / coords.w + xCenter;
201
float y = coords.y * yScale / coords.w + yCenter;
202
float z = coords.z * zScale / coords.w + zCenter;
203
204
if (gstate.isDepthClampEnabled()) {
205
return ClipToScreenInternal<true, true>(Vec3f(x, y, z), coords, outside_range_flag);
206
}
207
return ClipToScreenInternal<false, true>(Vec3f(x, y, z), coords, outside_range_flag);
208
}
209
210
ScreenCoords TransformUnit::ClipToScreen(const ClipCoords &coords, bool *outsideRangeFlag) {
211
return ClipToScreenInternal(coords, outsideRangeFlag);
212
}
213
214
ScreenCoords TransformUnit::DrawingToScreen(const DrawingCoords &coords, u16 z) {
215
ScreenCoords ret;
216
ret.x = (u32)coords.x * SCREEN_SCALE_FACTOR;
217
ret.y = (u32)coords.y * SCREEN_SCALE_FACTOR;
218
ret.z = z;
219
return ret;
220
}
221
222
enum class MatrixMode {
223
POS_TO_CLIP = 1,
224
WORLD_TO_CLIP = 2,
225
};
226
227
struct TransformState {
228
Lighting::State lightingState;
229
230
float matrix[16];
231
Vec4f posToFog;
232
Vec3f screenScale;
233
Vec3f screenAdd;
234
235
ScreenCoords(*roundToScreen)(Vec3f scaled, const ClipCoords &coords, bool *outside_range_flag);
236
237
struct {
238
bool enableTransform : 1;
239
bool enableLighting : 1;
240
bool enableFog : 1;
241
bool readUV : 1;
242
bool negateNormals : 1;
243
uint8_t uvGenMode : 2;
244
uint8_t matrixMode : 2;
245
};
246
};
247
248
void ComputeTransformState(TransformState *state, const VertexReader &vreader) {
249
state->enableTransform = !vreader.isThrough();
250
state->enableLighting = gstate.isLightingEnabled();
251
state->enableFog = gstate.isFogEnabled();
252
state->readUV = !gstate.isModeClear() && gstate.isTextureMapEnabled() && vreader.hasUV();
253
state->negateNormals = gstate.areNormalsReversed();
254
255
state->uvGenMode = gstate.getUVGenMode();
256
if (state->uvGenMode == GE_TEXMAP_UNKNOWN)
257
state->uvGenMode = GE_TEXMAP_TEXTURE_COORDS;
258
259
if (state->enableTransform) {
260
bool canSkipWorldPos = true;
261
if (state->enableLighting) {
262
Lighting::ComputeState(&state->lightingState, vreader.hasColor0());
263
canSkipWorldPos = !state->lightingState.usesWorldPos;
264
} else {
265
state->lightingState.usesWorldNormal = state->uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP;
266
}
267
268
float world[16];
269
float view[16];
270
float worldview[16];
271
ConvertMatrix4x3To4x4(view, gstate.viewMatrix);
272
if (state->enableFog || canSkipWorldPos) {
273
ConvertMatrix4x3To4x4(world, gstate.worldMatrix);
274
Matrix4ByMatrix4(worldview, world, view);
275
}
276
277
if (canSkipWorldPos) {
278
state->matrixMode = (uint8_t)MatrixMode::POS_TO_CLIP;
279
Matrix4ByMatrix4(state->matrix, worldview, gstate.projMatrix);
280
} else {
281
state->matrixMode = (uint8_t)MatrixMode::WORLD_TO_CLIP;
282
Matrix4ByMatrix4(state->matrix, view, gstate.projMatrix);
283
}
284
285
if (state->enableFog) {
286
float fogEnd = getFloat24(gstate.fog1);
287
float fogSlope = getFloat24(gstate.fog2);
288
289
// We bake fog end and slope into the dot product.
290
state->posToFog = Vec4f(worldview[2], worldview[6], worldview[10], worldview[14] + fogEnd);
291
292
// If either are NAN/INF, we simplify so there's no inf + -inf muddying things.
293
// This is required for Outrun to render proper skies, for example.
294
// The PSP treats these exponents as if they were valid.
295
if (my_isnanorinf(fogEnd)) {
296
bool sign = std::signbit(fogEnd);
297
// The multiply would reverse it if it wasn't infinity (doesn't matter if it's infnan.)
298
if (std::signbit(fogSlope))
299
sign = !sign;
300
// Also allow a multiply by zero (slope) to result in zero, regardless of sign.
301
// Act like it was negative and clamped to zero.
302
if (fogSlope == 0.0f)
303
sign = true;
304
305
// Since this is constant for the entire draw, we don't even use infinity.
306
float forced = sign ? 0.0f : 1.0f;
307
state->posToFog = Vec4f(0.0f, 0.0f, 0.0f, forced);
308
} else if (my_isnanorinf(fogSlope)) {
309
// We can't have signs differ with infinities, so we use a large value.
310
// Anything outside [0, 1] will clamp, so this essentially forces extremes.
311
fogSlope = std::signbit(fogSlope) ? -262144.0f : 262144.0f;
312
state->posToFog *= fogSlope;
313
} else {
314
state->posToFog *= fogSlope;
315
}
316
}
317
318
state->screenScale = Vec3f(gstate.getViewportXScale(), gstate.getViewportYScale(), gstate.getViewportZScale());
319
state->screenAdd = Vec3f(gstate.getViewportXCenter(), gstate.getViewportYCenter(), gstate.getViewportZCenter());
320
}
321
322
if (gstate.isDepthClampEnabled())
323
state->roundToScreen = &ClipToScreenInternal<true, false>;
324
else
325
state->roundToScreen = &ClipToScreenInternal<false, false>;
326
}
327
328
#if defined(_M_SSE)
329
#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)
330
[[gnu::target("sse4.1")]]
331
#endif
332
static inline __m128 Dot43SSE4(__m128 a, __m128 b) {
333
__m128 multiplied = _mm_mul_ps(a, _mm_insert_ps(b, _mm_set1_ps(1.0f), 0x30));
334
__m128 lanes3311 = _mm_movehdup_ps(multiplied);
335
__m128 partial = _mm_add_ps(multiplied, lanes3311);
336
return _mm_add_ss(partial, _mm_movehl_ps(lanes3311, partial));
337
}
338
#endif
339
340
static inline float Dot43(const Vec4f &a, const Vec3f &b) {
341
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
342
if (cpu_info.bSSE4_1)
343
return _mm_cvtss_f32(Dot43SSE4(a.vec, b.vec));
344
#elif PPSSPP_ARCH(ARM64_NEON)
345
float32x4_t multipled = vmulq_f32(a.vec, vsetq_lane_f32(1.0f, b.vec, 3));
346
float32x2_t add1 = vget_low_f32(vpaddq_f32(multipled, multipled));
347
float32x2_t add2 = vpadd_f32(add1, add1);
348
return vget_lane_f32(add2, 0);
349
#endif
350
return Dot(a, Vec4f(b, 1.0f));
351
}
352
353
ClipVertexData TransformUnit::ReadVertex(const VertexReader &vreader, const TransformState &state) {
354
PROFILE_THIS_SCOPE("read_vert");
355
// If we ever thread this, we'll have to change this.
356
ClipVertexData vertex;
357
358
ModelCoords pos;
359
// VertexDecoder normally scales z, but we want it unscaled.
360
vreader.ReadPosThroughZ16(pos.AsArray());
361
362
static Vec3Packedf lastTC;
363
if (state.readUV) {
364
vreader.ReadUV(vertex.v.texturecoords.AsArray());
365
vertex.v.texturecoords.q() = 0.0f;
366
lastTC = vertex.v.texturecoords;
367
} else {
368
vertex.v.texturecoords = lastTC;
369
}
370
371
static Vec3f lastnormal;
372
if (vreader.hasNormal())
373
vreader.ReadNrm(lastnormal.AsArray());
374
Vec3f normal = lastnormal;
375
if (state.negateNormals)
376
normal = -normal;
377
378
if (vreader.hasColor0()) {
379
vertex.v.color0 = vreader.ReadColor0_8888();
380
} else {
381
vertex.v.color0 = gstate.getMaterialAmbientRGBA();
382
}
383
384
vertex.v.color1 = 0;
385
386
if (state.enableTransform) {
387
WorldCoords worldpos;
388
389
switch (MatrixMode(state.matrixMode)) {
390
case MatrixMode::POS_TO_CLIP:
391
vertex.clippos = Vec3ByMatrix44(pos, state.matrix);
392
break;
393
394
case MatrixMode::WORLD_TO_CLIP:
395
worldpos = TransformUnit::ModelToWorld(pos);
396
vertex.clippos = Vec3ByMatrix44(worldpos, state.matrix);
397
break;
398
}
399
400
Vec3f screenScaled;
401
#ifdef _M_SSE
402
screenScaled.vec = _mm_mul_ps(vertex.clippos.vec, state.screenScale.vec);
403
screenScaled.vec = _mm_div_ps(screenScaled.vec, _mm_shuffle_ps(vertex.clippos.vec, vertex.clippos.vec, _MM_SHUFFLE(3, 3, 3, 3)));
404
screenScaled.vec = _mm_add_ps(screenScaled.vec, state.screenAdd.vec);
405
#else
406
screenScaled = vertex.clippos.xyz() * state.screenScale / vertex.clippos.w + state.screenAdd;
407
#endif
408
bool outside_range_flag = false;
409
vertex.v.screenpos = state.roundToScreen(screenScaled, vertex.clippos, &outside_range_flag);
410
if (outside_range_flag) {
411
// We use this, essentially, as the flag.
412
vertex.v.screenpos.x = 0x7FFFFFFF;
413
return vertex;
414
}
415
416
if (state.enableFog) {
417
vertex.v.fogdepth = Dot43(state.posToFog, pos);
418
} else {
419
vertex.v.fogdepth = 1.0f;
420
}
421
vertex.v.clipw = vertex.clippos.w;
422
423
Vec3<float> worldnormal;
424
if (state.lightingState.usesWorldNormal) {
425
worldnormal = TransformUnit::ModelToWorldNormal(normal);
426
worldnormal.NormalizeOr001();
427
}
428
429
// Time to generate some texture coords. Lighting will handle shade mapping.
430
if (state.uvGenMode == GE_TEXMAP_TEXTURE_MATRIX) {
431
Vec3f source;
432
switch (gstate.getUVProjMode()) {
433
case GE_PROJMAP_POSITION:
434
source = pos;
435
break;
436
437
case GE_PROJMAP_UV:
438
source = Vec3f(vertex.v.texturecoords.uv(), 0.0f);
439
break;
440
441
case GE_PROJMAP_NORMALIZED_NORMAL:
442
// This does not use 0, 0, 1 if length is zero.
443
source = normal.Normalized(cpu_info.bSSE4_1);
444
break;
445
446
case GE_PROJMAP_NORMAL:
447
source = normal;
448
break;
449
}
450
451
// Note that UV scale/offset are not used in this mode.
452
Vec3<float> stq = Vec3ByMatrix43(source, gstate.tgenMatrix);
453
vertex.v.texturecoords = Vec3Packedf(stq.x, stq.y, stq.z);
454
} else if (state.uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP) {
455
Lighting::GenerateLightST(vertex.v, worldnormal);
456
}
457
458
PROFILE_THIS_SCOPE("light");
459
if (state.enableLighting)
460
Lighting::Process(vertex.v, worldpos, worldnormal, state.lightingState);
461
} else {
462
vertex.v.screenpos.x = (int)(pos[0] * SCREEN_SCALE_FACTOR);
463
vertex.v.screenpos.y = (int)(pos[1] * SCREEN_SCALE_FACTOR);
464
vertex.v.screenpos.z = pos[2];
465
vertex.v.clipw = 1.0f;
466
vertex.v.fogdepth = 1.0f;
467
}
468
469
return vertex;
470
}
471
472
void TransformUnit::SetDirty(SoftDirty flags) {
473
binner_->SetDirty(flags);
474
}
475
SoftDirty TransformUnit::GetDirty() {
476
return binner_->GetDirty();
477
}
478
479
class SoftwareVertexReader {
480
public:
481
SoftwareVertexReader(u8 *base, VertexDecoder &vdecoder, u32 vertex_type, int vertex_count, const void *vertices, const void *indices, const TransformState &transformState, TransformUnit &transform)
482
: vreader_(base, vdecoder.GetDecVtxFmt(), vertex_type), conv_(vertex_type, indices), transformState_(transformState), transform_(transform) {
483
useIndices_ = indices != nullptr;
484
lowerBound_ = 0;
485
upperBound_ = vertex_count == 0 ? 0 : vertex_count - 1;
486
487
if (useIndices_)
488
GetIndexBounds(indices, vertex_count, vertex_type, &lowerBound_, &upperBound_);
489
if (vertex_count != 0)
490
vdecoder.DecodeVerts(base, vertices, &gstate_c.uv, lowerBound_, upperBound_);
491
492
// If we're only using a subset of verts, it's better to decode with random access (usually.)
493
// However, if we're reusing a lot of verts, we should read and cache them.
494
useCache_ = useIndices_ && vertex_count > (upperBound_ - lowerBound_ + 1);
495
if (useCache_ && (int)cached_.size() < upperBound_ - lowerBound_ + 1)
496
cached_.resize(std::max(128, upperBound_ - lowerBound_ + 1));
497
}
498
499
const VertexReader &GetVertexReader() const {
500
return vreader_;
501
}
502
503
bool IsThrough() const {
504
return vreader_.isThrough();
505
}
506
507
void UpdateCache() {
508
if (!useCache_)
509
return;
510
511
for (int i = 0; i < upperBound_ - lowerBound_ + 1; ++i) {
512
vreader_.Goto(i);
513
cached_[i] = transform_.ReadVertex(vreader_, transformState_);
514
}
515
}
516
517
inline ClipVertexData Read(int vtx) {
518
if (useIndices_) {
519
if (useCache_) {
520
return cached_[conv_(vtx) - lowerBound_];
521
}
522
vreader_.Goto(conv_(vtx) - lowerBound_);
523
} else {
524
vreader_.Goto(vtx);
525
}
526
527
return transform_.ReadVertex(vreader_, transformState_);
528
};
529
530
protected:
531
VertexReader vreader_;
532
const IndexConverter conv_;
533
const TransformState &transformState_;
534
TransformUnit &transform_;
535
uint16_t lowerBound_;
536
uint16_t upperBound_;
537
static std::vector<ClipVertexData> cached_;
538
bool useIndices_ = false;
539
bool useCache_ = false;
540
};
541
542
// Static to reduce allocations mid-frame.
543
std::vector<ClipVertexData> SoftwareVertexReader::cached_;
544
545
void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, GEPrimitiveType prim_type, int vertex_count, u32 vertex_type, int *bytesRead, SoftwareDrawEngine *drawEngine)
546
{
547
VertexDecoder &vdecoder = *drawEngine->FindVertexDecoder(vertex_type);
548
549
if (bytesRead)
550
*bytesRead = vertex_count * vdecoder.VertexSize();
551
552
// Frame skipping.
553
if (gstate_c.skipDrawReason & SKIPDRAW_SKIPFRAME) {
554
return;
555
}
556
// Vertices without position are just entirely culled.
557
// Note: Throughmode does draw 8-bit primitives, but positions are always zero - handled in decode.
558
if ((vertex_type & GE_VTYPE_POS_MASK) == 0)
559
return;
560
561
static TransformState transformState;
562
SoftwareVertexReader vreader(decoded_, vdecoder, vertex_type, vertex_count, vertices, indices, transformState, *this);
563
564
if (prim_type != GE_PRIM_KEEP_PREVIOUS) {
565
data_index_ = 0;
566
prev_prim_ = prim_type;
567
} else {
568
prim_type = prev_prim_;
569
}
570
571
binner_->UpdateState();
572
hasDraws_ = true;
573
574
if (binner_->HasDirty(SoftDirty::LIGHT_ALL | SoftDirty::TRANSFORM_ALL)) {
575
ComputeTransformState(&transformState, vreader.GetVertexReader());
576
binner_->ClearDirty(SoftDirty::LIGHT_ALL | SoftDirty::TRANSFORM_ALL);
577
}
578
vreader.UpdateCache();
579
580
bool skipCull = !gstate.isCullEnabled() || gstate.isModeClear();
581
const CullType cullType = skipCull ? CullType::OFF : (gstate.getCullMode() ? CullType::CCW : CullType::CW);
582
583
if (vreader.IsThrough() && cullType == CullType::OFF && prim_type == GE_PRIM_TRIANGLES && data_index_ == 0 && vertex_count >= 6 && ((vertex_count) % 6) == 0) {
584
// Some games send rectangles as a series of regular triangles.
585
// We look for this, but only in throughmode.
586
ClipVertexData buf[6];
587
// Could start at data_index_ and copy to buf, but there's little reason.
588
int buf_index = 0;
589
_assert_(data_index_ == 0);
590
591
for (int vtx = 0; vtx < vertex_count; ++vtx) {
592
buf[buf_index++] = vreader.Read(vtx);
593
if (buf_index < 6)
594
continue;
595
596
int tl = -1, br = -1;
597
if (Rasterizer::DetectRectangleFromPair(binner_->State(), buf, &tl, &br)) {
598
Clipper::ProcessRect(buf[tl], buf[br], *binner_);
599
} else {
600
SendTriangle(cullType, &buf[0]);
601
SendTriangle(cullType, &buf[3]);
602
}
603
604
buf_index = 0;
605
}
606
607
if (buf_index >= 3) {
608
SendTriangle(cullType, &buf[0]);
609
data_index_ = 0;
610
for (int i = 3; i < buf_index; ++i) {
611
data_[data_index_++] = buf[i];
612
}
613
} else if (buf_index > 0) {
614
for (int i = 0; i < buf_index; ++i) {
615
data_[i] = buf[i];
616
}
617
data_index_ = buf_index;
618
} else {
619
data_index_ = 0;
620
}
621
622
return;
623
}
624
625
// Note: intentionally, these allow for the case of vertex_count == 0, but data_index_ > 0.
626
// This is used for immediate-mode primitives.
627
switch (prim_type) {
628
case GE_PRIM_POINTS:
629
for (int i = 0; i < data_index_; ++i)
630
Clipper::ProcessPoint(data_[i], *binner_);
631
data_index_ = 0;
632
for (int vtx = 0; vtx < vertex_count; ++vtx) {
633
data_[0] = vreader.Read(vtx);
634
Clipper::ProcessPoint(data_[0], *binner_);
635
}
636
break;
637
638
case GE_PRIM_LINES:
639
for (int i = 0; i < data_index_ - 1; i += 2)
640
Clipper::ProcessLine(data_[i + 0], data_[i + 1], *binner_);
641
data_index_ &= 1;
642
for (int vtx = 0; vtx < vertex_count; ++vtx) {
643
data_[data_index_++] = vreader.Read(vtx);
644
if (data_index_ == 2) {
645
Clipper::ProcessLine(data_[0], data_[1], *binner_);
646
data_index_ = 0;
647
}
648
}
649
break;
650
651
case GE_PRIM_TRIANGLES:
652
for (int vtx = 0; vtx < vertex_count; ++vtx) {
653
data_[data_index_++] = vreader.Read(vtx);
654
if (data_index_ < 3) {
655
// Keep reading. Note: an incomplete prim will stay read for GE_PRIM_KEEP_PREVIOUS.
656
continue;
657
}
658
// Okay, we've got enough verts. Reset the index for next time.
659
data_index_ = 0;
660
661
SendTriangle(cullType, &data_[0]);
662
}
663
// In case vertex_count was 0.
664
if (data_index_ >= 3) {
665
SendTriangle(cullType, &data_[0]);
666
data_index_ = 0;
667
}
668
break;
669
670
case GE_PRIM_RECTANGLES:
671
for (int vtx = 0; vtx < vertex_count; ++vtx) {
672
data_[data_index_++] = vreader.Read(vtx);
673
674
if (data_index_ == 4 && vreader.IsThrough() && cullType == CullType::OFF) {
675
if (Rasterizer::DetectRectangleThroughModeSlices(binner_->State(), data_)) {
676
data_[1] = data_[3];
677
data_index_ = 2;
678
}
679
}
680
681
if (data_index_ == 4) {
682
Clipper::ProcessRect(data_[0], data_[1], *binner_);
683
Clipper::ProcessRect(data_[2], data_[3], *binner_);
684
data_index_ = 0;
685
}
686
}
687
688
if (data_index_ >= 2) {
689
Clipper::ProcessRect(data_[0], data_[1], *binner_);
690
data_index_ -= 2;
691
}
692
break;
693
694
case GE_PRIM_LINE_STRIP:
695
{
696
// Don't draw a line when loading the first vertex.
697
// If data_index_ is 1 or 2, etc., it means we're continuing a line strip.
698
int skip_count = data_index_ == 0 ? 1 : 0;
699
for (int vtx = 0; vtx < vertex_count; ++vtx) {
700
data_[(data_index_++) & 1] = vreader.Read(vtx);
701
702
if (skip_count) {
703
--skip_count;
704
} else {
705
// We already incremented data_index_, so data_index_ & 1 is previous one.
706
Clipper::ProcessLine(data_[data_index_ & 1], data_[(data_index_ & 1) ^ 1], *binner_);
707
}
708
}
709
// If this is from immediate-mode drawing, we always had one new vert (already in data_.)
710
if (isImmDraw_ && data_index_ >= 2)
711
Clipper::ProcessLine(data_[data_index_ & 1], data_[(data_index_ & 1) ^ 1], *binner_);
712
break;
713
}
714
715
case GE_PRIM_TRIANGLE_STRIP:
716
{
717
// Don't draw a triangle when loading the first two vertices.
718
int skip_count = data_index_ >= 2 ? 0 : 2 - data_index_;
719
int start_vtx = 0;
720
721
// If index count == 4, check if we can convert to a rectangle.
722
// This is for Darkstalkers (and should speed up many 2D games).
723
if (data_index_ == 0 && vertex_count >= 4 && (vertex_count & 1) == 0 && cullType == CullType::OFF) {
724
for (int base = 0; base < vertex_count - 2; base += 2) {
725
for (int vtx = base == 0 ? 0 : 2; vtx < 4; ++vtx) {
726
data_[vtx] = vreader.Read(base + vtx);
727
}
728
729
// If a strip is effectively a rectangle, draw it as such!
730
int tl = -1, br = -1;
731
if (Rasterizer::DetectRectangleFromStrip(binner_->State(), data_, &tl, &br)) {
732
Clipper::ProcessRect(data_[tl], data_[br], *binner_);
733
start_vtx += 2;
734
skip_count = 2;
735
if (base + 4 >= vertex_count) {
736
start_vtx = vertex_count;
737
break;
738
}
739
740
// Just copy the first two so we can detect easier.
741
// TODO: Maybe should give detection two halves?
742
data_[0] = data_[2];
743
data_[1] = data_[3];
744
data_index_ = 2;
745
} else {
746
// Go into triangle mode. Unfortunately, we re-read the verts.
747
break;
748
}
749
}
750
}
751
752
for (int vtx = start_vtx; vtx < vertex_count && skip_count > 0; ++vtx) {
753
int provoking_index = (data_index_++) % 3;
754
data_[provoking_index] = vreader.Read(vtx);
755
--skip_count;
756
++start_vtx;
757
}
758
759
for (int vtx = start_vtx; vtx < vertex_count; ++vtx) {
760
int provoking_index = (data_index_++) % 3;
761
data_[provoking_index] = vreader.Read(vtx);
762
763
int wind = (data_index_ - 1) % 2;
764
CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);
765
SendTriangle(altCullType, &data_[0], provoking_index);
766
}
767
768
// If this is from immediate-mode drawing, we always had one new vert (already in data_.)
769
if (isImmDraw_ && data_index_ >= 3) {
770
int provoking_index = (data_index_ - 1) % 3;
771
int wind = (data_index_ - 1) % 2;
772
CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);
773
SendTriangle(altCullType, &data_[0], provoking_index);
774
}
775
break;
776
}
777
778
case GE_PRIM_TRIANGLE_FAN:
779
{
780
// Don't draw a triangle when loading the first two vertices.
781
// (this doesn't count the central one.)
782
int skip_count = data_index_ <= 1 ? 1 : 0;
783
int start_vtx = 0;
784
785
// Only read the central vertex if we're not continuing.
786
if (data_index_ == 0 && vertex_count > 0) {
787
data_[0] = vreader.Read(0);
788
data_index_++;
789
start_vtx = 1;
790
}
791
792
if (data_index_ == 1 && vertex_count == 4 && cullType == CullType::OFF) {
793
for (int vtx = start_vtx; vtx < vertex_count; ++vtx) {
794
data_[vtx] = vreader.Read(vtx);
795
}
796
797
int tl = -1, br = -1;
798
if (Rasterizer::DetectRectangleFromFan(binner_->State(), data_, &tl, &br)) {
799
Clipper::ProcessRect(data_[tl], data_[br], *binner_);
800
break;
801
}
802
}
803
804
for (int vtx = start_vtx; vtx < vertex_count && skip_count > 0; ++vtx) {
805
int provoking_index = 2 - ((data_index_++) % 2);
806
data_[provoking_index] = vreader.Read(vtx);
807
--skip_count;
808
++start_vtx;
809
}
810
811
for (int vtx = start_vtx; vtx < vertex_count; ++vtx) {
812
int provoking_index = 2 - ((data_index_++) % 2);
813
data_[provoking_index] = vreader.Read(vtx);
814
815
int wind = (data_index_ - 1) % 2;
816
CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);
817
SendTriangle(altCullType, &data_[0], provoking_index);
818
}
819
820
// If this is from immediate-mode drawing, we always had one new vert (already in data_.)
821
if (isImmDraw_ && data_index_ >= 3) {
822
int wind = (data_index_ - 1) % 2;
823
int provoking_index = 2 - wind;
824
CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);
825
SendTriangle(altCullType, &data_[0], provoking_index);
826
}
827
break;
828
}
829
830
default:
831
ERROR_LOG(Log::G3D, "Unexpected prim type: %d", prim_type);
832
break;
833
}
834
}
835
836
void TransformUnit::SubmitImmVertex(const ClipVertexData &vert, SoftwareDrawEngine *drawEngine) {
837
// Where we put it is different for STRIP/FAN types.
838
switch (prev_prim_) {
839
case GE_PRIM_POINTS:
840
case GE_PRIM_LINES:
841
case GE_PRIM_TRIANGLES:
842
case GE_PRIM_RECTANGLES:
843
// This is the easy one. SubmitPrimitive resets data_index_.
844
data_[data_index_++] = vert;
845
break;
846
847
case GE_PRIM_LINE_STRIP:
848
// This one alternates, and data_index_ > 0 means it draws a segment.
849
data_[(data_index_++) & 1] = vert;
850
break;
851
852
case GE_PRIM_TRIANGLE_STRIP:
853
data_[(data_index_++) % 3] = vert;
854
break;
855
856
case GE_PRIM_TRIANGLE_FAN:
857
if (data_index_ == 0) {
858
data_[data_index_++] = vert;
859
} else {
860
int provoking_index = 2 - ((data_index_++) % 2);
861
data_[provoking_index] = vert;
862
}
863
break;
864
865
default:
866
_assert_msg_(false, "Invalid prim type: %d", (int)prev_prim_);
867
break;
868
}
869
870
uint32_t vertTypeID = GetVertTypeID(gstate.vertType | GE_VTYPE_POS_FLOAT, gstate.getUVGenMode(), true);
871
// This now processes the step with shared logic, given the existing data_.
872
isImmDraw_ = true;
873
SubmitPrimitive(nullptr, nullptr, GE_PRIM_KEEP_PREVIOUS, 0, vertTypeID, nullptr, drawEngine);
874
isImmDraw_ = false;
875
}
876
877
void TransformUnit::SendTriangle(CullType cullType, const ClipVertexData *verts, int provoking) {
878
if (cullType == CullType::OFF) {
879
Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_);
880
Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_);
881
} else if (cullType == CullType::CW) {
882
Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_);
883
} else {
884
Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_);
885
}
886
}
887
888
void TransformUnit::Flush(GPUCommon *common, const char *reason) {
889
if (!hasDraws_)
890
return;
891
892
binner_->Flush(reason);
893
common->NotifyFlush();
894
hasDraws_ = false;
895
}
896
897
void TransformUnit::GetStats(char *buffer, size_t bufsize) {
898
// TODO: More stats?
899
binner_->GetStats(buffer, bufsize);
900
}
901
902
void TransformUnit::FlushIfOverlap(GPUCommon *common, const char *reason, bool modifying, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h) {
903
if (!hasDraws_)
904
return;
905
906
if (binner_->HasPendingWrite(addr, stride, w, h))
907
Flush(common, reason);
908
if (modifying && binner_->HasPendingRead(addr, stride, w, h))
909
Flush(common, reason);
910
}
911
912
void TransformUnit::NotifyClutUpdate(const void *src) {
913
binner_->UpdateClut(src);
914
}
915
916
// TODO: This probably is not the best interface.
917
// Also, we should try to merge this into the similar function in DrawEngineCommon.
918
bool TransformUnit::GetCurrentDrawAsDebugVertices(int count, std::vector<GPUDebugVertex> &vertices, std::vector<u16> &indices) {
919
// This is always for the current vertices.
920
u16 indexLowerBound = 0;
921
u16 indexUpperBound = count - 1;
922
923
if (!Memory::IsValidAddress(gstate_c.vertexAddr) || count == 0)
924
return false;
925
926
if (count > 0 && (gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) {
927
const u8 *inds = Memory::GetPointer(gstate_c.indexAddr);
928
const u16_le *inds16 = (const u16_le *)inds;
929
const u32_le *inds32 = (const u32_le *)inds;
930
931
if (inds) {
932
GetIndexBounds(inds, count, gstate.vertType, &indexLowerBound, &indexUpperBound);
933
indices.resize(count);
934
switch (gstate.vertType & GE_VTYPE_IDX_MASK) {
935
case GE_VTYPE_IDX_8BIT:
936
for (int i = 0; i < count; ++i) {
937
indices[i] = inds[i];
938
}
939
break;
940
case GE_VTYPE_IDX_16BIT:
941
for (int i = 0; i < count; ++i) {
942
indices[i] = inds16[i];
943
}
944
break;
945
case GE_VTYPE_IDX_32BIT:
946
WARN_LOG_REPORT_ONCE(simpleIndexes32, Log::G3D, "SimpleVertices: Decoding 32-bit indexes");
947
for (int i = 0; i < count; ++i) {
948
// These aren't documented and should be rare. Let's bounds check each one.
949
if (inds32[i] != (u16)inds32[i]) {
950
ERROR_LOG_REPORT_ONCE(simpleIndexes32Bounds, Log::G3D, "SimpleVertices: Index outside 16-bit range");
951
}
952
indices[i] = (u16)inds32[i];
953
}
954
break;
955
}
956
} else {
957
indices.clear();
958
}
959
} else {
960
indices.clear();
961
}
962
963
static std::vector<u32> temp_buffer;
964
static std::vector<SimpleVertex> simpleVertices;
965
temp_buffer.resize(std::max((int)indexUpperBound, 8192) * 128 / sizeof(u32));
966
simpleVertices.resize(indexUpperBound + 1);
967
968
VertexDecoder vdecoder;
969
VertexDecoderOptions options{};
970
u32 vertTypeID = GetVertTypeID(gstate.vertType, gstate.getUVGenMode(), true);
971
vdecoder.SetVertexType(vertTypeID, options);
972
973
if (!Memory::IsValidRange(gstate_c.vertexAddr, (indexUpperBound + 1) * vdecoder.VertexSize()))
974
return false;
975
976
::NormalizeVertices(&simpleVertices[0], (u8 *)(&temp_buffer[0]), Memory::GetPointer(gstate_c.vertexAddr), indexLowerBound, indexUpperBound, &vdecoder, gstate.vertType);
977
978
float world[16];
979
float view[16];
980
float worldview[16];
981
float worldviewproj[16];
982
ConvertMatrix4x3To4x4(world, gstate.worldMatrix);
983
ConvertMatrix4x3To4x4(view, gstate.viewMatrix);
984
Matrix4ByMatrix4(worldview, world, view);
985
Matrix4ByMatrix4(worldviewproj, worldview, gstate.projMatrix);
986
987
const float zScale = gstate.getViewportZScale();
988
const float zCenter = gstate.getViewportZCenter();
989
990
vertices.resize(indexUpperBound + 1);
991
for (int i = indexLowerBound; i <= indexUpperBound; ++i) {
992
const SimpleVertex &vert = simpleVertices[i];
993
994
if (gstate.isModeThrough()) {
995
if (gstate.vertType & GE_VTYPE_TC_MASK) {
996
vertices[i].u = vert.uv[0];
997
vertices[i].v = vert.uv[1];
998
} else {
999
vertices[i].u = 0.0f;
1000
vertices[i].v = 0.0f;
1001
}
1002
vertices[i].x = vert.pos.x;
1003
vertices[i].y = vert.pos.y;
1004
vertices[i].z = vert.pos.z;
1005
} else {
1006
Vec4f clipPos = Vec3ByMatrix44(vert.pos, worldviewproj);
1007
bool outsideRangeFlag;
1008
ScreenCoords screenPos = ClipToScreen(clipPos, &outsideRangeFlag);
1009
float z = clipPos.z * zScale / clipPos.w + zCenter;
1010
1011
if (gstate.vertType & GE_VTYPE_TC_MASK) {
1012
vertices[i].u = vert.uv[0] * (float)gstate.getTextureWidth(0);
1013
vertices[i].v = vert.uv[1] * (float)gstate.getTextureHeight(0);
1014
} else {
1015
vertices[i].u = 0.0f;
1016
vertices[i].v = 0.0f;
1017
}
1018
vertices[i].x = (float)screenPos.x / SCREEN_SCALE_FACTOR;
1019
vertices[i].y = (float)screenPos.y / SCREEN_SCALE_FACTOR;
1020
vertices[i].z = screenPos.z <= 0 || screenPos.z >= 0xFFFF ? z : (float)screenPos.z;
1021
}
1022
1023
if (gstate.vertType & GE_VTYPE_COL_MASK) {
1024
memcpy(vertices[i].c, vert.color, sizeof(vertices[i].c));
1025
} else {
1026
memset(vertices[i].c, 0, sizeof(vertices[i].c));
1027
}
1028
vertices[i].nx = vert.nrm.x;
1029
vertices[i].ny = vert.nrm.y;
1030
vertices[i].nz = vert.nrm.z;
1031
}
1032
1033
// The GE debugger expects these to be set.
1034
gstate_c.curTextureWidth = gstate.getTextureWidth(0);
1035
gstate_c.curTextureHeight = gstate.getTextureHeight(0);
1036
1037
return true;
1038
}
1039
1040