CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/GPU/Software/TransformUnit.cpp
Views: 1401
// Copyright (c) 2013- PPSSPP Project.12// This program is free software: you can redistribute it and/or modify3// it under the terms of the GNU General Public License as published by4// the Free Software Foundation, version 2.0 or later versions.56// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License 2.0 for more details.1011// A copy of the GPL 2.0 should have been included with the program.12// If not, see http://www.gnu.org/licenses/1314// Official git repository and contact information can be found at15// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.1617#include <cmath>18#include <algorithm>1920#include "Common/Common.h"21#include "Common/CPUDetect.h"22#include "Common/Math/math_util.h"23#include "Common/MemoryUtil.h"24#include "Common/Profiler/Profiler.h"25#include "Core/Config.h"26#include "GPU/GPUState.h"27#include "GPU/Common/DrawEngineCommon.h"28#include "GPU/Common/VertexDecoderCommon.h"29#include "GPU/Common/SplineCommon.h"30#include "GPU/Common/TextureDecoder.h"31#include "GPU/Debugger/Debugger.h"32#include "GPU/Software/BinManager.h"33#include "GPU/Software/Clipper.h"34#include "GPU/Software/FuncId.h"35#include "GPU/Software/Lighting.h"36#include "GPU/Software/Rasterizer.h"37#include "GPU/Software/RasterizerRectangle.h"38#include "GPU/Software/TransformUnit.h"3940#define TRANSFORM_BUF_SIZE (65536 * 48)4142TransformUnit::TransformUnit() {43decoded_ = (u8 *)AllocateAlignedMemory(TRANSFORM_BUF_SIZE, 16);44if (!decoded_)45return;46binner_ = new BinManager();47}4849TransformUnit::~TransformUnit() {50FreeAlignedMemory(decoded_);51delete binner_;52}5354bool TransformUnit::IsStarted() {55return binner_ && decoded_;56}5758SoftwareDrawEngine::SoftwareDrawEngine() {59flushOnParams_ = false;60}6162SoftwareDrawEngine::~SoftwareDrawEngine() {}6364void SoftwareDrawEngine::NotifyConfigChanged() {65DrawEngineCommon::NotifyConfigChanged();66decOptions_.applySkinInDecode = true;67}6869void SoftwareDrawEngine::DispatchFlush() {70transformUnit.Flush("debug");71}7273void SoftwareDrawEngine::DispatchSubmitPrim(const void *verts, const void *inds, GEPrimitiveType prim, int vertexCount, u32 vertTypeID, bool clockwise, int *bytesRead) {74_assert_msg_(clockwise, "Mixed cull mode not supported.");75transformUnit.SubmitPrimitive(verts, inds, prim, vertexCount, vertTypeID, bytesRead, this);76}7778void SoftwareDrawEngine::DispatchSubmitImm(GEPrimitiveType prim, TransformedVertex *buffer, int vertexCount, int cullMode, bool continuation) {79uint32_t vertTypeID = GetVertTypeID(gstate.vertType | GE_VTYPE_POS_FLOAT, gstate.getUVGenMode(), true);8081int flipCull = cullMode != gstate.getCullMode() ? 1 : 0;82// TODO: For now, just setting all dirty.83transformUnit.SetDirty(SoftDirty(-1));84gstate.cullmode ^= flipCull;8586// TODO: This is a bit ugly. Should bypass when clipping...87uint32_t xScale = gstate.viewportxscale;88uint32_t xCenter = gstate.viewportxcenter;89uint32_t yScale = gstate.viewportyscale;90uint32_t yCenter = gstate.viewportycenter;91uint32_t zScale = gstate.viewportzscale;92uint32_t zCenter = gstate.viewportzcenter;9394// Force scale to 1 and center to zero.95gstate.viewportxscale = (GE_CMD_VIEWPORTXSCALE << 24) | 0x3F8000;96gstate.viewportxcenter = (GE_CMD_VIEWPORTXCENTER << 24) | 0x000000;97gstate.viewportyscale = (GE_CMD_VIEWPORTYSCALE << 24) | 0x3F8000;98gstate.viewportycenter = (GE_CMD_VIEWPORTYCENTER << 24) | 0x000000;99// Z we scale to 65535 for neg z clipping.100gstate.viewportzscale = (GE_CMD_VIEWPORTZSCALE << 24) | 0x477FFF;101gstate.viewportzcenter = (GE_CMD_VIEWPORTZCENTER << 24) | 0x000000;102103// Before we start, submit 0 prims to reset the prev prim type.104// Following submits will always be KEEP_PREVIOUS.105if (!continuation)106transformUnit.SubmitPrimitive(nullptr, nullptr, prim, 0, vertTypeID, nullptr, this);107108for (int i = 0; i < vertexCount; i++) {109ClipVertexData vert;110vert.clippos = ClipCoords(buffer[i].pos);111vert.v.texturecoords.x = buffer[i].u;112vert.v.texturecoords.y = buffer[i].v;113vert.v.texturecoords.z = buffer[i].uv_w;114if (gstate.isModeThrough()) {115vert.v.texturecoords.x *= gstate.getTextureWidth(0);116vert.v.texturecoords.y *= gstate.getTextureHeight(0);117} else {118vert.clippos.z *= 1.0f / 65535.0f;119}120vert.v.clipw = buffer[i].pos_w;121vert.v.color0 = buffer[i].color0_32;122vert.v.color1 = gstate.isUsingSecondaryColor() && !gstate.isModeThrough() ? buffer[i].color1_32 : 0;123vert.v.fogdepth = buffer[i].fog;124vert.v.screenpos.x = (int)(buffer[i].x * 16.0f);125vert.v.screenpos.y = (int)(buffer[i].y * 16.0f);126vert.v.screenpos.z = (u16)(u32)buffer[i].z;127128transformUnit.SubmitImmVertex(vert, this);129}130131gstate.viewportxscale = xScale;132gstate.viewportxcenter = xCenter;133gstate.viewportyscale = yScale;134gstate.viewportycenter = yCenter;135gstate.viewportzscale = zScale;136gstate.viewportzcenter = zCenter;137138gstate.cullmode ^= flipCull;139// TODO: Should really clear, but a bunch of values are forced so we this is safest.140transformUnit.SetDirty(SoftDirty(-1));141}142143VertexDecoder *SoftwareDrawEngine::FindVertexDecoder(u32 vtype) {144const u32 vertTypeID = GetVertTypeID(vtype, gstate.getUVGenMode(), true);145return DrawEngineCommon::GetVertexDecoder(vertTypeID);146}147148WorldCoords TransformUnit::ModelToWorld(const ModelCoords &coords) {149return Vec3ByMatrix43(coords, gstate.worldMatrix);150}151152WorldCoords TransformUnit::ModelToWorldNormal(const ModelCoords &coords) {153return Norm3ByMatrix43(coords, gstate.worldMatrix);154}155156ViewCoords TransformUnit::WorldToView(const WorldCoords &coords) {157return Vec3ByMatrix43(coords, gstate.viewMatrix);158}159160ClipCoords TransformUnit::ViewToClip(const ViewCoords &coords) {161return Vec3ByMatrix44(coords, gstate.projMatrix);162}163164template <bool depthClamp, bool alwaysCheckRange>165static ScreenCoords ClipToScreenInternal(Vec3f scaled, const ClipCoords &coords, bool *outside_range_flag) {166ScreenCoords ret;167168// Account for rounding for X and Y.169// TODO: Validate actual rounding range.170const float SCREEN_BOUND = 4095.0f + (15.5f / 16.0f);171172// This matches hardware tests - depth is clamped when this flag is on.173if constexpr (depthClamp) {174// Note: if the depth is clipped (z/w <= -1.0), the outside_range_flag should NOT be set, even for x and y.175if ((alwaysCheckRange || coords.z > -coords.w) && (scaled.x >= SCREEN_BOUND || scaled.y >= SCREEN_BOUND || scaled.x < 0 || scaled.y < 0)) {176*outside_range_flag = true;177}178179if (scaled.z < 0.f)180scaled.z = 0.f;181else if (scaled.z > 65535.0f)182scaled.z = 65535.0f;183} else if (scaled.x > SCREEN_BOUND || scaled.y >= SCREEN_BOUND || scaled.x < 0 || scaled.y < 0 || scaled.z < 0.0f || scaled.z >= 65536.0f) {184*outside_range_flag = true;185}186187// 16 = 0xFFFF / 4095.9375188// Round up at 0.625 to the nearest subpixel.189static_assert(SCREEN_SCALE_FACTOR == 16, "Currently only supports scale 16");190int x = (int)(scaled.x * 16.0f + 0.375f - gstate.getOffsetX16());191int y = (int)(scaled.y * 16.0f + 0.375f - gstate.getOffsetY16());192return ScreenCoords(x, y, scaled.z);193}194195static inline ScreenCoords ClipToScreenInternal(const ClipCoords &coords, bool *outside_range_flag) {196// Parameters here can seem invalid, but the PSP is fine with negative viewport widths etc.197// The checking that OpenGL and D3D do is actually quite superflous as the calculations still "work"198// with some pretty crazy inputs, which PSP games are happy to do at times.199float xScale = gstate.getViewportXScale();200float xCenter = gstate.getViewportXCenter();201float yScale = gstate.getViewportYScale();202float yCenter = gstate.getViewportYCenter();203float zScale = gstate.getViewportZScale();204float zCenter = gstate.getViewportZCenter();205206float x = coords.x * xScale / coords.w + xCenter;207float y = coords.y * yScale / coords.w + yCenter;208float z = coords.z * zScale / coords.w + zCenter;209210if (gstate.isDepthClampEnabled()) {211return ClipToScreenInternal<true, true>(Vec3f(x, y, z), coords, outside_range_flag);212}213return ClipToScreenInternal<false, true>(Vec3f(x, y, z), coords, outside_range_flag);214}215216ScreenCoords TransformUnit::ClipToScreen(const ClipCoords &coords, bool *outsideRangeFlag) {217return ClipToScreenInternal(coords, outsideRangeFlag);218}219220ScreenCoords TransformUnit::DrawingToScreen(const DrawingCoords &coords, u16 z) {221ScreenCoords ret;222ret.x = (u32)coords.x * SCREEN_SCALE_FACTOR;223ret.y = (u32)coords.y * SCREEN_SCALE_FACTOR;224ret.z = z;225return ret;226}227228enum class MatrixMode {229POS_TO_CLIP = 1,230WORLD_TO_CLIP = 2,231};232233struct TransformState {234Lighting::State lightingState;235236float matrix[16];237Vec4f posToFog;238Vec3f screenScale;239Vec3f screenAdd;240241ScreenCoords(*roundToScreen)(Vec3f scaled, const ClipCoords &coords, bool *outside_range_flag);242243struct {244bool enableTransform : 1;245bool enableLighting : 1;246bool enableFog : 1;247bool readUV : 1;248bool negateNormals : 1;249uint8_t uvGenMode : 2;250uint8_t matrixMode : 2;251};252};253254void ComputeTransformState(TransformState *state, const VertexReader &vreader) {255state->enableTransform = !vreader.isThrough();256state->enableLighting = gstate.isLightingEnabled();257state->enableFog = gstate.isFogEnabled();258state->readUV = !gstate.isModeClear() && gstate.isTextureMapEnabled() && vreader.hasUV();259state->negateNormals = gstate.areNormalsReversed();260261state->uvGenMode = gstate.getUVGenMode();262if (state->uvGenMode == GE_TEXMAP_UNKNOWN)263state->uvGenMode = GE_TEXMAP_TEXTURE_COORDS;264265if (state->enableTransform) {266bool canSkipWorldPos = true;267if (state->enableLighting) {268Lighting::ComputeState(&state->lightingState, vreader.hasColor0());269canSkipWorldPos = !state->lightingState.usesWorldPos;270} else {271state->lightingState.usesWorldNormal = state->uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP;272}273274float world[16];275float view[16];276float worldview[16];277ConvertMatrix4x3To4x4(view, gstate.viewMatrix);278if (state->enableFog || canSkipWorldPos) {279ConvertMatrix4x3To4x4(world, gstate.worldMatrix);280Matrix4ByMatrix4(worldview, world, view);281}282283if (canSkipWorldPos) {284state->matrixMode = (uint8_t)MatrixMode::POS_TO_CLIP;285Matrix4ByMatrix4(state->matrix, worldview, gstate.projMatrix);286} else {287state->matrixMode = (uint8_t)MatrixMode::WORLD_TO_CLIP;288Matrix4ByMatrix4(state->matrix, view, gstate.projMatrix);289}290291if (state->enableFog) {292float fogEnd = getFloat24(gstate.fog1);293float fogSlope = getFloat24(gstate.fog2);294295// We bake fog end and slope into the dot product.296state->posToFog = Vec4f(worldview[2], worldview[6], worldview[10], worldview[14] + fogEnd);297298// If either are NAN/INF, we simplify so there's no inf + -inf muddying things.299// This is required for Outrun to render proper skies, for example.300// The PSP treats these exponents as if they were valid.301if (my_isnanorinf(fogEnd)) {302bool sign = std::signbit(fogEnd);303// The multiply would reverse it if it wasn't infinity (doesn't matter if it's infnan.)304if (std::signbit(fogSlope))305sign = !sign;306// Also allow a multiply by zero (slope) to result in zero, regardless of sign.307// Act like it was negative and clamped to zero.308if (fogSlope == 0.0f)309sign = true;310311// Since this is constant for the entire draw, we don't even use infinity.312float forced = sign ? 0.0f : 1.0f;313state->posToFog = Vec4f(0.0f, 0.0f, 0.0f, forced);314} else if (my_isnanorinf(fogSlope)) {315// We can't have signs differ with infinities, so we use a large value.316// Anything outside [0, 1] will clamp, so this essentially forces extremes.317fogSlope = std::signbit(fogSlope) ? -262144.0f : 262144.0f;318state->posToFog *= fogSlope;319} else {320state->posToFog *= fogSlope;321}322}323324state->screenScale = Vec3f(gstate.getViewportXScale(), gstate.getViewportYScale(), gstate.getViewportZScale());325state->screenAdd = Vec3f(gstate.getViewportXCenter(), gstate.getViewportYCenter(), gstate.getViewportZCenter());326}327328if (gstate.isDepthClampEnabled())329state->roundToScreen = &ClipToScreenInternal<true, false>;330else331state->roundToScreen = &ClipToScreenInternal<false, false>;332}333334#if defined(_M_SSE)335#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)336[[gnu::target("sse4.1")]]337#endif338static inline __m128 Dot43SSE4(__m128 a, __m128 b) {339__m128 multiplied = _mm_mul_ps(a, _mm_insert_ps(b, _mm_set1_ps(1.0f), 0x30));340__m128 lanes3311 = _mm_movehdup_ps(multiplied);341__m128 partial = _mm_add_ps(multiplied, lanes3311);342return _mm_add_ss(partial, _mm_movehl_ps(lanes3311, partial));343}344#endif345346static inline float Dot43(const Vec4f &a, const Vec3f &b) {347#if defined(_M_SSE) && !PPSSPP_ARCH(X86)348if (cpu_info.bSSE4_1)349return _mm_cvtss_f32(Dot43SSE4(a.vec, b.vec));350#elif PPSSPP_ARCH(ARM64_NEON)351float32x4_t multipled = vmulq_f32(a.vec, vsetq_lane_f32(1.0f, b.vec, 3));352float32x2_t add1 = vget_low_f32(vpaddq_f32(multipled, multipled));353float32x2_t add2 = vpadd_f32(add1, add1);354return vget_lane_f32(add2, 0);355#endif356return Dot(a, Vec4f(b, 1.0f));357}358359ClipVertexData TransformUnit::ReadVertex(const VertexReader &vreader, const TransformState &state) {360PROFILE_THIS_SCOPE("read_vert");361// If we ever thread this, we'll have to change this.362ClipVertexData vertex;363364ModelCoords pos;365// VertexDecoder normally scales z, but we want it unscaled.366vreader.ReadPosThroughZ16(pos.AsArray());367368static Vec3Packedf lastTC;369if (state.readUV) {370vreader.ReadUV(vertex.v.texturecoords.AsArray());371vertex.v.texturecoords.q() = 0.0f;372lastTC = vertex.v.texturecoords;373} else {374vertex.v.texturecoords = lastTC;375}376377static Vec3f lastnormal;378if (vreader.hasNormal())379vreader.ReadNrm(lastnormal.AsArray());380Vec3f normal = lastnormal;381if (state.negateNormals)382normal = -normal;383384if (vreader.hasColor0()) {385vertex.v.color0 = vreader.ReadColor0_8888();386} else {387vertex.v.color0 = gstate.getMaterialAmbientRGBA();388}389390vertex.v.color1 = 0;391392if (state.enableTransform) {393WorldCoords worldpos;394395switch (MatrixMode(state.matrixMode)) {396case MatrixMode::POS_TO_CLIP:397vertex.clippos = Vec3ByMatrix44(pos, state.matrix);398break;399400case MatrixMode::WORLD_TO_CLIP:401worldpos = TransformUnit::ModelToWorld(pos);402vertex.clippos = Vec3ByMatrix44(worldpos, state.matrix);403break;404}405406Vec3f screenScaled;407#ifdef _M_SSE408screenScaled.vec = _mm_mul_ps(vertex.clippos.vec, state.screenScale.vec);409screenScaled.vec = _mm_div_ps(screenScaled.vec, _mm_shuffle_ps(vertex.clippos.vec, vertex.clippos.vec, _MM_SHUFFLE(3, 3, 3, 3)));410screenScaled.vec = _mm_add_ps(screenScaled.vec, state.screenAdd.vec);411#else412screenScaled = vertex.clippos.xyz() * state.screenScale / vertex.clippos.w + state.screenAdd;413#endif414bool outside_range_flag = false;415vertex.v.screenpos = state.roundToScreen(screenScaled, vertex.clippos, &outside_range_flag);416if (outside_range_flag) {417// We use this, essentially, as the flag.418vertex.v.screenpos.x = 0x7FFFFFFF;419return vertex;420}421422if (state.enableFog) {423vertex.v.fogdepth = Dot43(state.posToFog, pos);424} else {425vertex.v.fogdepth = 1.0f;426}427vertex.v.clipw = vertex.clippos.w;428429Vec3<float> worldnormal;430if (state.lightingState.usesWorldNormal) {431worldnormal = TransformUnit::ModelToWorldNormal(normal);432worldnormal.NormalizeOr001();433}434435// Time to generate some texture coords. Lighting will handle shade mapping.436if (state.uvGenMode == GE_TEXMAP_TEXTURE_MATRIX) {437Vec3f source;438switch (gstate.getUVProjMode()) {439case GE_PROJMAP_POSITION:440source = pos;441break;442443case GE_PROJMAP_UV:444source = Vec3f(vertex.v.texturecoords.uv(), 0.0f);445break;446447case GE_PROJMAP_NORMALIZED_NORMAL:448// This does not use 0, 0, 1 if length is zero.449source = normal.Normalized(cpu_info.bSSE4_1);450break;451452case GE_PROJMAP_NORMAL:453source = normal;454break;455}456457// Note that UV scale/offset are not used in this mode.458Vec3<float> stq = Vec3ByMatrix43(source, gstate.tgenMatrix);459vertex.v.texturecoords = Vec3Packedf(stq.x, stq.y, stq.z);460} else if (state.uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP) {461Lighting::GenerateLightST(vertex.v, worldnormal);462}463464PROFILE_THIS_SCOPE("light");465if (state.enableLighting)466Lighting::Process(vertex.v, worldpos, worldnormal, state.lightingState);467} else {468vertex.v.screenpos.x = (int)(pos[0] * SCREEN_SCALE_FACTOR);469vertex.v.screenpos.y = (int)(pos[1] * SCREEN_SCALE_FACTOR);470vertex.v.screenpos.z = pos[2];471vertex.v.clipw = 1.0f;472vertex.v.fogdepth = 1.0f;473}474475return vertex;476}477478void TransformUnit::SetDirty(SoftDirty flags) {479binner_->SetDirty(flags);480}481SoftDirty TransformUnit::GetDirty() {482return binner_->GetDirty();483}484485class SoftwareVertexReader {486public:487SoftwareVertexReader(u8 *base, VertexDecoder &vdecoder, u32 vertex_type, int vertex_count, const void *vertices, const void *indices, const TransformState &transformState, TransformUnit &transform)488: vreader_(base, vdecoder.GetDecVtxFmt(), vertex_type), conv_(vertex_type, indices), transformState_(transformState), transform_(transform) {489useIndices_ = indices != nullptr;490lowerBound_ = 0;491upperBound_ = vertex_count == 0 ? 0 : vertex_count - 1;492493if (useIndices_)494GetIndexBounds(indices, vertex_count, vertex_type, &lowerBound_, &upperBound_);495if (vertex_count != 0)496vdecoder.DecodeVerts(base, vertices, &gstate_c.uv, lowerBound_, upperBound_);497498// If we're only using a subset of verts, it's better to decode with random access (usually.)499// However, if we're reusing a lot of verts, we should read and cache them.500useCache_ = useIndices_ && vertex_count > (upperBound_ - lowerBound_ + 1);501if (useCache_ && (int)cached_.size() < upperBound_ - lowerBound_ + 1)502cached_.resize(std::max(128, upperBound_ - lowerBound_ + 1));503}504505const VertexReader &GetVertexReader() const {506return vreader_;507}508509bool IsThrough() const {510return vreader_.isThrough();511}512513void UpdateCache() {514if (!useCache_)515return;516517for (int i = 0; i < upperBound_ - lowerBound_ + 1; ++i) {518vreader_.Goto(i);519cached_[i] = transform_.ReadVertex(vreader_, transformState_);520}521}522523inline ClipVertexData Read(int vtx) {524if (useIndices_) {525if (useCache_) {526return cached_[conv_(vtx) - lowerBound_];527}528vreader_.Goto(conv_(vtx) - lowerBound_);529} else {530vreader_.Goto(vtx);531}532533return transform_.ReadVertex(vreader_, transformState_);534};535536protected:537VertexReader vreader_;538const IndexConverter conv_;539const TransformState &transformState_;540TransformUnit &transform_;541uint16_t lowerBound_;542uint16_t upperBound_;543static std::vector<ClipVertexData> cached_;544bool useIndices_ = false;545bool useCache_ = false;546};547548// Static to reduce allocations mid-frame.549std::vector<ClipVertexData> SoftwareVertexReader::cached_;550551void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, GEPrimitiveType prim_type, int vertex_count, u32 vertex_type, int *bytesRead, SoftwareDrawEngine *drawEngine)552{553VertexDecoder &vdecoder = *drawEngine->FindVertexDecoder(vertex_type);554555if (bytesRead)556*bytesRead = vertex_count * vdecoder.VertexSize();557558// Frame skipping.559if (gstate_c.skipDrawReason & SKIPDRAW_SKIPFRAME) {560return;561}562// Vertices without position are just entirely culled.563// Note: Throughmode does draw 8-bit primitives, but positions are always zero - handled in decode.564if ((vertex_type & GE_VTYPE_POS_MASK) == 0)565return;566567static TransformState transformState;568SoftwareVertexReader vreader(decoded_, vdecoder, vertex_type, vertex_count, vertices, indices, transformState, *this);569570if (prim_type != GE_PRIM_KEEP_PREVIOUS) {571data_index_ = 0;572prev_prim_ = prim_type;573} else {574prim_type = prev_prim_;575}576577binner_->UpdateState();578hasDraws_ = true;579580if (binner_->HasDirty(SoftDirty::LIGHT_ALL | SoftDirty::TRANSFORM_ALL)) {581ComputeTransformState(&transformState, vreader.GetVertexReader());582binner_->ClearDirty(SoftDirty::LIGHT_ALL | SoftDirty::TRANSFORM_ALL);583}584vreader.UpdateCache();585586bool skipCull = !gstate.isCullEnabled() || gstate.isModeClear();587const CullType cullType = skipCull ? CullType::OFF : (gstate.getCullMode() ? CullType::CCW : CullType::CW);588589if (vreader.IsThrough() && cullType == CullType::OFF && prim_type == GE_PRIM_TRIANGLES && data_index_ == 0 && vertex_count >= 6 && ((vertex_count) % 6) == 0) {590// Some games send rectangles as a series of regular triangles.591// We look for this, but only in throughmode.592ClipVertexData buf[6];593// Could start at data_index_ and copy to buf, but there's little reason.594int buf_index = 0;595_assert_(data_index_ == 0);596597for (int vtx = 0; vtx < vertex_count; ++vtx) {598buf[buf_index++] = vreader.Read(vtx);599if (buf_index < 6)600continue;601602int tl = -1, br = -1;603if (Rasterizer::DetectRectangleFromPair(binner_->State(), buf, &tl, &br)) {604Clipper::ProcessRect(buf[tl], buf[br], *binner_);605} else {606SendTriangle(cullType, &buf[0]);607SendTriangle(cullType, &buf[3]);608}609610buf_index = 0;611}612613if (buf_index >= 3) {614SendTriangle(cullType, &buf[0]);615data_index_ = 0;616for (int i = 3; i < buf_index; ++i) {617data_[data_index_++] = buf[i];618}619} else if (buf_index > 0) {620for (int i = 0; i < buf_index; ++i) {621data_[i] = buf[i];622}623data_index_ = buf_index;624} else {625data_index_ = 0;626}627628return;629}630631// Note: intentionally, these allow for the case of vertex_count == 0, but data_index_ > 0.632// This is used for immediate-mode primitives.633switch (prim_type) {634case GE_PRIM_POINTS:635for (int i = 0; i < data_index_; ++i)636Clipper::ProcessPoint(data_[i], *binner_);637data_index_ = 0;638for (int vtx = 0; vtx < vertex_count; ++vtx) {639data_[0] = vreader.Read(vtx);640Clipper::ProcessPoint(data_[0], *binner_);641}642break;643644case GE_PRIM_LINES:645for (int i = 0; i < data_index_ - 1; i += 2)646Clipper::ProcessLine(data_[i + 0], data_[i + 1], *binner_);647data_index_ &= 1;648for (int vtx = 0; vtx < vertex_count; ++vtx) {649data_[data_index_++] = vreader.Read(vtx);650if (data_index_ == 2) {651Clipper::ProcessLine(data_[0], data_[1], *binner_);652data_index_ = 0;653}654}655break;656657case GE_PRIM_TRIANGLES:658for (int vtx = 0; vtx < vertex_count; ++vtx) {659data_[data_index_++] = vreader.Read(vtx);660if (data_index_ < 3) {661// Keep reading. Note: an incomplete prim will stay read for GE_PRIM_KEEP_PREVIOUS.662continue;663}664// Okay, we've got enough verts. Reset the index for next time.665data_index_ = 0;666667SendTriangle(cullType, &data_[0]);668}669// In case vertex_count was 0.670if (data_index_ >= 3) {671SendTriangle(cullType, &data_[0]);672data_index_ = 0;673}674break;675676case GE_PRIM_RECTANGLES:677for (int vtx = 0; vtx < vertex_count; ++vtx) {678data_[data_index_++] = vreader.Read(vtx);679680if (data_index_ == 4 && vreader.IsThrough() && cullType == CullType::OFF) {681if (Rasterizer::DetectRectangleThroughModeSlices(binner_->State(), data_)) {682data_[1] = data_[3];683data_index_ = 2;684}685}686687if (data_index_ == 4) {688Clipper::ProcessRect(data_[0], data_[1], *binner_);689Clipper::ProcessRect(data_[2], data_[3], *binner_);690data_index_ = 0;691}692}693694if (data_index_ >= 2) {695Clipper::ProcessRect(data_[0], data_[1], *binner_);696data_index_ -= 2;697}698break;699700case GE_PRIM_LINE_STRIP:701{702// Don't draw a line when loading the first vertex.703// If data_index_ is 1 or 2, etc., it means we're continuing a line strip.704int skip_count = data_index_ == 0 ? 1 : 0;705for (int vtx = 0; vtx < vertex_count; ++vtx) {706data_[(data_index_++) & 1] = vreader.Read(vtx);707708if (skip_count) {709--skip_count;710} else {711// We already incremented data_index_, so data_index_ & 1 is previous one.712Clipper::ProcessLine(data_[data_index_ & 1], data_[(data_index_ & 1) ^ 1], *binner_);713}714}715// If this is from immediate-mode drawing, we always had one new vert (already in data_.)716if (isImmDraw_ && data_index_ >= 2)717Clipper::ProcessLine(data_[data_index_ & 1], data_[(data_index_ & 1) ^ 1], *binner_);718break;719}720721case GE_PRIM_TRIANGLE_STRIP:722{723// Don't draw a triangle when loading the first two vertices.724int skip_count = data_index_ >= 2 ? 0 : 2 - data_index_;725int start_vtx = 0;726727// If index count == 4, check if we can convert to a rectangle.728// This is for Darkstalkers (and should speed up many 2D games).729if (data_index_ == 0 && vertex_count >= 4 && (vertex_count & 1) == 0 && cullType == CullType::OFF) {730for (int base = 0; base < vertex_count - 2; base += 2) {731for (int vtx = base == 0 ? 0 : 2; vtx < 4; ++vtx) {732data_[vtx] = vreader.Read(base + vtx);733}734735// If a strip is effectively a rectangle, draw it as such!736int tl = -1, br = -1;737if (Rasterizer::DetectRectangleFromStrip(binner_->State(), data_, &tl, &br)) {738Clipper::ProcessRect(data_[tl], data_[br], *binner_);739start_vtx += 2;740skip_count = 2;741if (base + 4 >= vertex_count) {742start_vtx = vertex_count;743break;744}745746// Just copy the first two so we can detect easier.747// TODO: Maybe should give detection two halves?748data_[0] = data_[2];749data_[1] = data_[3];750data_index_ = 2;751} else {752// Go into triangle mode. Unfortunately, we re-read the verts.753break;754}755}756}757758for (int vtx = start_vtx; vtx < vertex_count && skip_count > 0; ++vtx) {759int provoking_index = (data_index_++) % 3;760data_[provoking_index] = vreader.Read(vtx);761--skip_count;762++start_vtx;763}764765for (int vtx = start_vtx; vtx < vertex_count; ++vtx) {766int provoking_index = (data_index_++) % 3;767data_[provoking_index] = vreader.Read(vtx);768769int wind = (data_index_ - 1) % 2;770CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);771SendTriangle(altCullType, &data_[0], provoking_index);772}773774// If this is from immediate-mode drawing, we always had one new vert (already in data_.)775if (isImmDraw_ && data_index_ >= 3) {776int provoking_index = (data_index_ - 1) % 3;777int wind = (data_index_ - 1) % 2;778CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);779SendTriangle(altCullType, &data_[0], provoking_index);780}781break;782}783784case GE_PRIM_TRIANGLE_FAN:785{786// Don't draw a triangle when loading the first two vertices.787// (this doesn't count the central one.)788int skip_count = data_index_ <= 1 ? 1 : 0;789int start_vtx = 0;790791// Only read the central vertex if we're not continuing.792if (data_index_ == 0 && vertex_count > 0) {793data_[0] = vreader.Read(0);794data_index_++;795start_vtx = 1;796}797798if (data_index_ == 1 && vertex_count == 4 && cullType == CullType::OFF) {799for (int vtx = start_vtx; vtx < vertex_count; ++vtx) {800data_[vtx] = vreader.Read(vtx);801}802803int tl = -1, br = -1;804if (Rasterizer::DetectRectangleFromFan(binner_->State(), data_, &tl, &br)) {805Clipper::ProcessRect(data_[tl], data_[br], *binner_);806break;807}808}809810for (int vtx = start_vtx; vtx < vertex_count && skip_count > 0; ++vtx) {811int provoking_index = 2 - ((data_index_++) % 2);812data_[provoking_index] = vreader.Read(vtx);813--skip_count;814++start_vtx;815}816817for (int vtx = start_vtx; vtx < vertex_count; ++vtx) {818int provoking_index = 2 - ((data_index_++) % 2);819data_[provoking_index] = vreader.Read(vtx);820821int wind = (data_index_ - 1) % 2;822CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);823SendTriangle(altCullType, &data_[0], provoking_index);824}825826// If this is from immediate-mode drawing, we always had one new vert (already in data_.)827if (isImmDraw_ && data_index_ >= 3) {828int wind = (data_index_ - 1) % 2;829int provoking_index = 2 - wind;830CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);831SendTriangle(altCullType, &data_[0], provoking_index);832}833break;834}835836default:837ERROR_LOG(Log::G3D, "Unexpected prim type: %d", prim_type);838break;839}840}841842void TransformUnit::SubmitImmVertex(const ClipVertexData &vert, SoftwareDrawEngine *drawEngine) {843// Where we put it is different for STRIP/FAN types.844switch (prev_prim_) {845case GE_PRIM_POINTS:846case GE_PRIM_LINES:847case GE_PRIM_TRIANGLES:848case GE_PRIM_RECTANGLES:849// This is the easy one. SubmitPrimitive resets data_index_.850data_[data_index_++] = vert;851break;852853case GE_PRIM_LINE_STRIP:854// This one alternates, and data_index_ > 0 means it draws a segment.855data_[(data_index_++) & 1] = vert;856break;857858case GE_PRIM_TRIANGLE_STRIP:859data_[(data_index_++) % 3] = vert;860break;861862case GE_PRIM_TRIANGLE_FAN:863if (data_index_ == 0) {864data_[data_index_++] = vert;865} else {866int provoking_index = 2 - ((data_index_++) % 2);867data_[provoking_index] = vert;868}869break;870871default:872_assert_msg_(false, "Invalid prim type: %d", (int)prev_prim_);873break;874}875876uint32_t vertTypeID = GetVertTypeID(gstate.vertType | GE_VTYPE_POS_FLOAT, gstate.getUVGenMode(), true);877// This now processes the step with shared logic, given the existing data_.878isImmDraw_ = true;879SubmitPrimitive(nullptr, nullptr, GE_PRIM_KEEP_PREVIOUS, 0, vertTypeID, nullptr, drawEngine);880isImmDraw_ = false;881}882883void TransformUnit::SendTriangle(CullType cullType, const ClipVertexData *verts, int provoking) {884if (cullType == CullType::OFF) {885Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_);886Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_);887} else if (cullType == CullType::CW) {888Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_);889} else {890Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_);891}892}893894void TransformUnit::Flush(const char *reason) {895if (!hasDraws_)896return;897898binner_->Flush(reason);899GPUDebug::NotifyDraw();900hasDraws_ = false;901}902903void TransformUnit::GetStats(char *buffer, size_t bufsize) {904// TODO: More stats?905binner_->GetStats(buffer, bufsize);906}907908void TransformUnit::FlushIfOverlap(const char *reason, bool modifying, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h) {909if (!hasDraws_)910return;911912if (binner_->HasPendingWrite(addr, stride, w, h))913Flush(reason);914if (modifying && binner_->HasPendingRead(addr, stride, w, h))915Flush(reason);916}917918void TransformUnit::NotifyClutUpdate(const void *src) {919binner_->UpdateClut(src);920}921922// TODO: This probably is not the best interface.923// Also, we should try to merge this into the similar function in DrawEngineCommon.924bool TransformUnit::GetCurrentSimpleVertices(int count, std::vector<GPUDebugVertex> &vertices, std::vector<u16> &indices) {925// This is always for the current vertices.926u16 indexLowerBound = 0;927u16 indexUpperBound = count - 1;928929if (!Memory::IsValidAddress(gstate_c.vertexAddr) || count == 0)930return false;931932if (count > 0 && (gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) {933const u8 *inds = Memory::GetPointer(gstate_c.indexAddr);934const u16_le *inds16 = (const u16_le *)inds;935const u32_le *inds32 = (const u32_le *)inds;936937if (inds) {938GetIndexBounds(inds, count, gstate.vertType, &indexLowerBound, &indexUpperBound);939indices.resize(count);940switch (gstate.vertType & GE_VTYPE_IDX_MASK) {941case GE_VTYPE_IDX_8BIT:942for (int i = 0; i < count; ++i) {943indices[i] = inds[i];944}945break;946case GE_VTYPE_IDX_16BIT:947for (int i = 0; i < count; ++i) {948indices[i] = inds16[i];949}950break;951case GE_VTYPE_IDX_32BIT:952WARN_LOG_REPORT_ONCE(simpleIndexes32, Log::G3D, "SimpleVertices: Decoding 32-bit indexes");953for (int i = 0; i < count; ++i) {954// These aren't documented and should be rare. Let's bounds check each one.955if (inds32[i] != (u16)inds32[i]) {956ERROR_LOG_REPORT_ONCE(simpleIndexes32Bounds, Log::G3D, "SimpleVertices: Index outside 16-bit range");957}958indices[i] = (u16)inds32[i];959}960break;961}962} else {963indices.clear();964}965} else {966indices.clear();967}968969static std::vector<u32> temp_buffer;970static std::vector<SimpleVertex> simpleVertices;971temp_buffer.resize(std::max((int)indexUpperBound, 8192) * 128 / sizeof(u32));972simpleVertices.resize(indexUpperBound + 1);973974VertexDecoder vdecoder;975VertexDecoderOptions options{};976options.applySkinInDecode = true;977vdecoder.SetVertexType(gstate.vertType, options);978979if (!Memory::IsValidRange(gstate_c.vertexAddr, (indexUpperBound + 1) * vdecoder.VertexSize()))980return false;981982DrawEngineCommon::NormalizeVertices((u8 *)(&simpleVertices[0]), (u8 *)(&temp_buffer[0]), Memory::GetPointer(gstate_c.vertexAddr), &vdecoder, indexLowerBound, indexUpperBound, gstate.vertType);983984float world[16];985float view[16];986float worldview[16];987float worldviewproj[16];988ConvertMatrix4x3To4x4(world, gstate.worldMatrix);989ConvertMatrix4x3To4x4(view, gstate.viewMatrix);990Matrix4ByMatrix4(worldview, world, view);991Matrix4ByMatrix4(worldviewproj, worldview, gstate.projMatrix);992993const float zScale = gstate.getViewportZScale();994const float zCenter = gstate.getViewportZCenter();995996vertices.resize(indexUpperBound + 1);997for (int i = indexLowerBound; i <= indexUpperBound; ++i) {998const SimpleVertex &vert = simpleVertices[i];9991000if (gstate.isModeThrough()) {1001if (gstate.vertType & GE_VTYPE_TC_MASK) {1002vertices[i].u = vert.uv[0];1003vertices[i].v = vert.uv[1];1004} else {1005vertices[i].u = 0.0f;1006vertices[i].v = 0.0f;1007}1008vertices[i].x = vert.pos.x;1009vertices[i].y = vert.pos.y;1010vertices[i].z = vert.pos.z;1011} else {1012Vec4f clipPos = Vec3ByMatrix44(vert.pos, worldviewproj);1013bool outsideRangeFlag;1014ScreenCoords screenPos = ClipToScreen(clipPos, &outsideRangeFlag);1015float z = clipPos.z * zScale / clipPos.w + zCenter;10161017if (gstate.vertType & GE_VTYPE_TC_MASK) {1018vertices[i].u = vert.uv[0] * (float)gstate.getTextureWidth(0);1019vertices[i].v = vert.uv[1] * (float)gstate.getTextureHeight(0);1020} else {1021vertices[i].u = 0.0f;1022vertices[i].v = 0.0f;1023}1024vertices[i].x = (float)screenPos.x / SCREEN_SCALE_FACTOR;1025vertices[i].y = (float)screenPos.y / SCREEN_SCALE_FACTOR;1026vertices[i].z = screenPos.z <= 0 || screenPos.z >= 0xFFFF ? z : (float)screenPos.z;1027}10281029if (gstate.vertType & GE_VTYPE_COL_MASK) {1030memcpy(vertices[i].c, vert.color, sizeof(vertices[i].c));1031} else {1032memset(vertices[i].c, 0, sizeof(vertices[i].c));1033}1034vertices[i].nx = vert.nrm.x;1035vertices[i].ny = vert.nrm.y;1036vertices[i].nz = vert.nrm.z;1037}10381039// The GE debugger expects these to be set.1040gstate_c.curTextureWidth = gstate.getTextureWidth(0);1041gstate_c.curTextureHeight = gstate.getTextureHeight(0);10421043return true;1044}104510461047