CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/GPU/Directx9/DrawEngineDX9.cpp
Views: 1401
1
// Copyright (c) 2012- 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 <wrl/client.h>
20
21
#include "Common/Log.h"
22
#include "Common/MemoryUtil.h"
23
#include "Common/TimeUtil.h"
24
#include "Core/MemMap.h"
25
#include "Core/System.h"
26
#include "Core/Config.h"
27
#include "Core/CoreTiming.h"
28
29
#include "Common/GPU/D3D9/D3D9StateCache.h"
30
31
#include "GPU/Math3D.h"
32
#include "GPU/GPUState.h"
33
#include "GPU/ge_constants.h"
34
35
#include "GPU/Common/SplineCommon.h"
36
#include "GPU/Common/TransformCommon.h"
37
#include "GPU/Common/VertexDecoderCommon.h"
38
#include "GPU/Common/SoftwareTransformCommon.h"
39
#include "GPU/Debugger/Debugger.h"
40
#include "GPU/Directx9/TextureCacheDX9.h"
41
#include "GPU/Directx9/DrawEngineDX9.h"
42
#include "GPU/Directx9/ShaderManagerDX9.h"
43
#include "GPU/Directx9/GPU_DX9.h"
44
45
using Microsoft::WRL::ComPtr;
46
47
static const D3DPRIMITIVETYPE d3d_prim[8] = {
48
// Points, which are expanded to triangles.
49
D3DPT_TRIANGLELIST,
50
// Lines and line strips, which are also expanded to triangles.
51
D3DPT_TRIANGLELIST,
52
D3DPT_TRIANGLELIST,
53
D3DPT_TRIANGLELIST,
54
D3DPT_TRIANGLESTRIP,
55
D3DPT_TRIANGLEFAN,
56
// Rectangles, which are expanded to triangles.
57
D3DPT_TRIANGLELIST,
58
};
59
60
static const int D3DPRIMITIVEVERTEXCOUNT[8][2] = {
61
{0, 0}, // invalid
62
{1, 0}, // 1 = D3DPT_POINTLIST,
63
{2, 0}, // 2 = D3DPT_LINELIST,
64
{2, 1}, // 3 = D3DPT_LINESTRIP,
65
{3, 0}, // 4 = D3DPT_TRIANGLELIST,
66
{1, 2}, // 5 = D3DPT_TRIANGLESTRIP,
67
{1, 2}, // 6 = D3DPT_TRIANGLEFAN,
68
};
69
70
inline int D3DPrimCount(D3DPRIMITIVETYPE prim, int size) {
71
return (size / D3DPRIMITIVEVERTEXCOUNT[prim][0]) - D3DPRIMITIVEVERTEXCOUNT[prim][1];
72
}
73
74
enum {
75
TRANSFORMED_VERTEX_BUFFER_SIZE = VERTEX_BUFFER_MAX * sizeof(TransformedVertex)
76
};
77
78
static const D3DVERTEXELEMENT9 TransformedVertexElements[] = {
79
{ 0, offsetof(TransformedVertex, pos), D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
80
{ 0, offsetof(TransformedVertex, uv), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
81
{ 0, offsetof(TransformedVertex, color0), D3DDECLTYPE_UBYTE4N, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
82
{ 0, offsetof(TransformedVertex, color1), D3DDECLTYPE_UBYTE4N, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 1 },
83
{ 0, offsetof(TransformedVertex, fog), D3DDECLTYPE_FLOAT1, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
84
D3DDECL_END()
85
};
86
87
DrawEngineDX9::DrawEngineDX9(Draw::DrawContext *draw) : draw_(draw), vertexDeclMap_(64) {
88
device_ = (LPDIRECT3DDEVICE9)draw->GetNativeObject(Draw::NativeObject::DEVICE);
89
decOptions_.expandAllWeightsToFloat = true;
90
decOptions_.expand8BitNormalsToFloat = true;
91
92
indexGen.Setup(decIndex_);
93
94
InitDeviceObjects();
95
96
tessDataTransferDX9 = new TessellationDataTransferDX9();
97
tessDataTransfer = tessDataTransferDX9;
98
99
device_->CreateVertexDeclaration(TransformedVertexElements, &transformedVertexDecl_);
100
}
101
102
DrawEngineDX9::~DrawEngineDX9() {
103
DestroyDeviceObjects();
104
vertexDeclMap_.Clear();
105
delete tessDataTransferDX9;
106
}
107
108
void DrawEngineDX9::InitDeviceObjects() {
109
draw_->SetInvalidationCallback(std::bind(&DrawEngineDX9::Invalidate, this, std::placeholders::_1));
110
}
111
112
void DrawEngineDX9::DestroyDeviceObjects() {
113
if (draw_) {
114
draw_->SetInvalidationCallback(InvalidationCallback());
115
}
116
ClearTrackedVertexArrays();
117
}
118
119
struct DeclTypeInfo {
120
u32 type;
121
const char * name;
122
};
123
124
static const DeclTypeInfo VComp[] = {
125
{ 0, "NULL" }, // DEC_NONE,
126
{ D3DDECLTYPE_FLOAT1, "D3DDECLTYPE_FLOAT1 " }, // DEC_FLOAT_1,
127
{ D3DDECLTYPE_FLOAT2, "D3DDECLTYPE_FLOAT2 " }, // DEC_FLOAT_2,
128
{ D3DDECLTYPE_FLOAT3, "D3DDECLTYPE_FLOAT3 " }, // DEC_FLOAT_3,
129
{ D3DDECLTYPE_FLOAT4, "D3DDECLTYPE_FLOAT4 " }, // DEC_FLOAT_4,
130
131
{ 0, "UNUSED" }, // DEC_S8_3,
132
133
{ D3DDECLTYPE_SHORT4N, "D3DDECLTYPE_SHORT4N " }, // DEC_S16_3,
134
{ D3DDECLTYPE_UBYTE4N, "D3DDECLTYPE_UBYTE4N " }, // DEC_U8_1,
135
{ D3DDECLTYPE_UBYTE4N, "D3DDECLTYPE_UBYTE4N " }, // DEC_U8_2,
136
{ D3DDECLTYPE_UBYTE4N, "D3DDECLTYPE_UBYTE4N " }, // DEC_U8_3,
137
{ D3DDECLTYPE_UBYTE4N, "D3DDECLTYPE_UBYTE4N " }, // DEC_U8_4,
138
{0, "UNUSED_DEC_U16_1" }, // DEC_U16_1,
139
{0, "UNUSED_DEC_U16_2" }, // DEC_U16_2,
140
{D3DDECLTYPE_USHORT4N ,"D3DDECLTYPE_USHORT4N "}, // DEC_U16_3,
141
{D3DDECLTYPE_USHORT4N ,"D3DDECLTYPE_USHORT4N "}, // DEC_U16_4,
142
};
143
144
static void VertexAttribSetup(D3DVERTEXELEMENT9 * VertexElement, u8 fmt, u8 offset, u8 usage, u8 usage_index = 0) {
145
memset(VertexElement, 0, sizeof(D3DVERTEXELEMENT9));
146
VertexElement->Offset = offset;
147
VertexElement->Type = VComp[fmt].type;
148
VertexElement->Usage = usage;
149
VertexElement->UsageIndex = usage_index;
150
}
151
152
HRESULT DrawEngineDX9::SetupDecFmtForDraw(const DecVtxFormat &decFmt, u32 pspFmt, IDirect3DVertexDeclaration9 **ppVertextDeclaration) {
153
ComPtr<IDirect3DVertexDeclaration9> vertexDeclCached;
154
if (vertexDeclMap_.Get(pspFmt, &vertexDeclCached)) {
155
*ppVertextDeclaration = vertexDeclCached.Detach();
156
return S_OK;
157
} else {
158
D3DVERTEXELEMENT9 VertexElements[8];
159
D3DVERTEXELEMENT9 *VertexElement = &VertexElements[0];
160
161
// Vertices Elements orders
162
// WEIGHT
163
if (decFmt.w0fmt != 0) {
164
VertexAttribSetup(VertexElement, decFmt.w0fmt, decFmt.w0off, D3DDECLUSAGE_TEXCOORD, 1);
165
VertexElement++;
166
}
167
168
if (decFmt.w1fmt != 0) {
169
VertexAttribSetup(VertexElement, decFmt.w1fmt, decFmt.w1off, D3DDECLUSAGE_TEXCOORD, 2);
170
VertexElement++;
171
}
172
173
// TC
174
if (decFmt.uvfmt != 0) {
175
VertexAttribSetup(VertexElement, decFmt.uvfmt, decFmt.uvoff, D3DDECLUSAGE_TEXCOORD, 0);
176
VertexElement++;
177
}
178
179
// COLOR
180
if (decFmt.c0fmt != 0) {
181
VertexAttribSetup(VertexElement, decFmt.c0fmt, decFmt.c0off, D3DDECLUSAGE_COLOR, 0);
182
VertexElement++;
183
}
184
// Never used ?
185
if (decFmt.c1fmt != 0) {
186
VertexAttribSetup(VertexElement, decFmt.c1fmt, decFmt.c1off, D3DDECLUSAGE_COLOR, 1);
187
VertexElement++;
188
}
189
190
// NORMAL
191
if (decFmt.nrmfmt != 0) {
192
VertexAttribSetup(VertexElement, decFmt.nrmfmt, decFmt.nrmoff, D3DDECLUSAGE_NORMAL, 0);
193
VertexElement++;
194
}
195
196
// POSITION
197
// Always
198
VertexAttribSetup(VertexElement, DecVtxFormat::PosFmt(), decFmt.posoff, D3DDECLUSAGE_POSITION, 0);
199
VertexElement++;
200
201
// End
202
D3DVERTEXELEMENT9 end = D3DDECL_END();
203
memcpy(VertexElement, &end, sizeof(D3DVERTEXELEMENT9));
204
205
// Create declaration
206
ComPtr<IDirect3DVertexDeclaration9> pHardwareVertexDecl;
207
HRESULT hr = device_->CreateVertexDeclaration( VertexElements, &pHardwareVertexDecl );
208
if (FAILED(hr)) {
209
ERROR_LOG(Log::G3D, "Failed to create vertex declaration!");
210
}
211
212
// Add it to map
213
vertexDeclMap_.Insert(pspFmt, pHardwareVertexDecl);
214
*ppVertextDeclaration = pHardwareVertexDecl.Detach();
215
return hr;
216
}
217
}
218
219
static uint32_t SwapRB(uint32_t c) {
220
return (c & 0xFF00FF00) | ((c >> 16) & 0xFF) | ((c << 16) & 0xFF0000);
221
}
222
223
void DrawEngineDX9::BeginFrame() {
224
lastRenderStepId_ = -1;
225
}
226
227
// In D3D, we're synchronous and state carries over so all we reset here on a new step is the viewport/scissor.
228
void DrawEngineDX9::Invalidate(InvalidationCallbackFlags flags) {
229
if (flags & InvalidationCallbackFlags::RENDER_PASS_STATE) {
230
gstate_c.Dirty(DIRTY_VIEWPORTSCISSOR_STATE | DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);
231
}
232
}
233
234
// The inline wrapper in the header checks for numDrawCalls_ == 0
235
void DrawEngineDX9::DoFlush() {
236
bool textureNeedsApply = false;
237
if (gstate_c.IsDirty(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS) && !gstate.isModeClear() && gstate.isTextureMapEnabled()) {
238
textureCache_->SetTexture();
239
gstate_c.Clean(DIRTY_TEXTURE_IMAGE | DIRTY_TEXTURE_PARAMS);
240
textureNeedsApply = true;
241
} else if (gstate.getTextureAddress(0) == (gstate.getFrameBufRawAddress() | 0x04000000)) {
242
// This catches the case of clearing a texture. (#10957)
243
gstate_c.Dirty(DIRTY_TEXTURE_IMAGE);
244
}
245
246
GEPrimitiveType prim = prevPrim_;
247
248
// Always use software for flat shading to fix the provoking index.
249
bool tess = gstate_c.submitType == SubmitType::HW_BEZIER || gstate_c.submitType == SubmitType::HW_SPLINE;
250
bool useHWTransform = CanUseHardwareTransform(prim) && (tess || gstate.getShadeMode() != GE_SHADE_FLAT);
251
252
if (useHWTransform) {
253
LPDIRECT3DVERTEXBUFFER9 vb_ = nullptr;
254
LPDIRECT3DINDEXBUFFER9 ib_ = nullptr;
255
256
int vertexCount;
257
int maxIndex;
258
bool useElements;
259
DecodeVerts(decoded_);
260
DecodeIndsAndGetData(&prim, &vertexCount, &maxIndex, &useElements, false);
261
gpuStats.numUncachedVertsDrawn += vertexCount;
262
263
_dbg_assert_((int)prim > 0);
264
265
bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE;
266
if (gstate.isModeThrough()) {
267
gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255);
268
} else {
269
gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255);
270
}
271
272
if (textureNeedsApply) {
273
textureCache_->ApplyTexture();
274
}
275
276
ApplyDrawState(prim);
277
ApplyDrawStateLate();
278
279
VSShader *vshader = shaderManager_->ApplyShader(true, useHWTessellation_, dec_, decOptions_.expandAllWeightsToFloat, decOptions_.applySkinInDecode, pipelineState_);
280
ComPtr<IDirect3DVertexDeclaration9> pHardwareVertexDecl;
281
SetupDecFmtForDraw(dec_->GetDecVtxFmt(), dec_->VertexType(), &pHardwareVertexDecl);
282
283
if (pHardwareVertexDecl) {
284
device_->SetVertexDeclaration(pHardwareVertexDecl.Get());
285
if (vb_ == NULL) {
286
if (useElements) {
287
device_->DrawIndexedPrimitiveUP(d3d_prim[prim], 0, numDecodedVerts_, D3DPrimCount(d3d_prim[prim], vertexCount), decIndex_, D3DFMT_INDEX16, decoded_, dec_->GetDecVtxFmt().stride);
288
} else {
289
device_->DrawPrimitiveUP(d3d_prim[prim], D3DPrimCount(d3d_prim[prim], vertexCount), decoded_, dec_->GetDecVtxFmt().stride);
290
}
291
} else {
292
device_->SetStreamSource(0, vb_, 0, dec_->GetDecVtxFmt().stride);
293
294
if (useElements) {
295
device_->SetIndices(ib_);
296
297
device_->DrawIndexedPrimitive(d3d_prim[prim], 0, 0, numDecodedVerts_, 0, D3DPrimCount(d3d_prim[prim], vertexCount));
298
} else {
299
device_->DrawPrimitive(d3d_prim[prim], 0, D3DPrimCount(d3d_prim[prim], vertexCount));
300
}
301
}
302
}
303
} else {
304
if (!decOptions_.applySkinInDecode) {
305
decOptions_.applySkinInDecode = true;
306
lastVType_ |= (1 << 26);
307
dec_ = GetVertexDecoder(lastVType_);
308
}
309
DecodeVerts(decoded_);
310
int vertexCount = DecodeInds();
311
312
bool hasColor = (lastVType_ & GE_VTYPE_COL_MASK) != GE_VTYPE_COL_NONE;
313
if (gstate.isModeThrough()) {
314
gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && (hasColor || gstate.getMaterialAmbientA() == 255);
315
} else {
316
gstate_c.vertexFullAlpha = gstate_c.vertexFullAlpha && ((hasColor && (gstate.materialupdate & 1)) || gstate.getMaterialAmbientA() == 255) && (!gstate.isLightingEnabled() || gstate.getAmbientA() == 255);
317
}
318
319
gpuStats.numUncachedVertsDrawn += vertexCount;
320
prim = IndexGenerator::GeneralPrim((GEPrimitiveType)drawInds_[0].prim);
321
VERBOSE_LOG(Log::G3D, "Flush prim %i SW! %i verts in one go", prim, vertexCount);
322
323
u16 *inds = decIndex_;
324
SoftwareTransformResult result{};
325
SoftwareTransformParams params{};
326
params.decoded = decoded_;
327
params.transformed = transformed_;
328
params.transformedExpanded = transformedExpanded_;
329
params.fbman = framebufferManager_;
330
params.texCache = textureCache_;
331
params.allowClear = true;
332
params.allowSeparateAlphaClear = false;
333
params.flippedY = false;
334
params.usesHalfZ = true;
335
336
if (gstate.getShadeMode() == GE_SHADE_FLAT) {
337
// We need to rotate the index buffer to simulate a different provoking vertex.
338
// We do this before line expansion etc.
339
int indexCount = RemainingIndices(inds);
340
IndexBufferProvokingLastToFirst(prim, inds, vertexCount);
341
}
342
343
// We need correct viewport values in gstate_c already.
344
if (gstate_c.IsDirty(DIRTY_VIEWPORTSCISSOR_STATE)) {
345
ViewportAndScissor vpAndScissor;
346
ConvertViewportAndScissor(framebufferManager_->UseBufferedRendering(),
347
framebufferManager_->GetRenderWidth(), framebufferManager_->GetRenderHeight(),
348
framebufferManager_->GetTargetBufferWidth(), framebufferManager_->GetTargetBufferHeight(),
349
vpAndScissor);
350
UpdateCachedViewportState(vpAndScissor);
351
}
352
353
int maxIndex = numDecodedVerts_;
354
SoftwareTransform swTransform(params);
355
356
// Half pixel offset hack.
357
float xOffset = -1.0f / gstate_c.curRTRenderWidth;
358
float yOffset = 1.0f / gstate_c.curRTRenderHeight;
359
360
const Lin::Vec3 trans(gstate_c.vpXOffset + xOffset, -gstate_c.vpYOffset + yOffset, gstate_c.vpZOffset * 0.5f + 0.5f);
361
const Lin::Vec3 scale(gstate_c.vpWidthScale, gstate_c.vpHeightScale, gstate_c.vpDepthScale * 0.5f);
362
swTransform.SetProjMatrix(gstate.projMatrix, gstate_c.vpWidth < 0, gstate_c.vpHeight > 0, trans, scale);
363
364
swTransform.Transform(prim, dec_->VertexType(), dec_->GetDecVtxFmt(), numDecodedVerts_, &result);
365
// Non-zero depth clears are unusual, but some drivers don't match drawn depth values to cleared values.
366
// Games sometimes expect exact matches (see #12626, for example) for equal comparisons.
367
if (result.action == SW_CLEAR && everUsedEqualDepth_ && gstate.isClearModeDepthMask() && result.depth > 0.0f && result.depth < 1.0f)
368
result.action = SW_NOT_READY;
369
370
if (textureNeedsApply) {
371
gstate_c.pixelMapped = result.pixelMapped;
372
textureCache_->ApplyTexture();
373
gstate_c.pixelMapped = false;
374
}
375
376
ApplyDrawState(prim);
377
378
if (result.action == SW_NOT_READY)
379
swTransform.BuildDrawingParams(prim, vertexCount, dec_->VertexType(), inds, RemainingIndices(inds), numDecodedVerts_, VERTEX_BUFFER_MAX, &result);
380
if (result.setSafeSize)
381
framebufferManager_->SetSafeSize(result.safeWidth, result.safeHeight);
382
383
ApplyDrawStateLate();
384
385
VSShader *vshader = shaderManager_->ApplyShader(false, false, dec_, decOptions_.expandAllWeightsToFloat, true, pipelineState_);
386
387
if (result.action == SW_DRAW_INDEXED) {
388
if (result.setStencil) {
389
dxstate.stencilFunc.set(D3DCMP_ALWAYS);
390
dxstate.stencilRef.set(result.stencilValue);
391
dxstate.stencilCompareMask.set(255);
392
}
393
394
// TODO: Add a post-transform cache here for multi-RECTANGLES only.
395
// Might help for text drawing.
396
397
device_->SetVertexDeclaration(transformedVertexDecl_.Get());
398
device_->DrawIndexedPrimitiveUP(d3d_prim[prim], 0, numDecodedVerts_, D3DPrimCount(d3d_prim[prim], result.drawNumTrans), inds, D3DFMT_INDEX16, result.drawBuffer, sizeof(TransformedVertex));
399
} else if (result.action == SW_CLEAR) {
400
u32 clearColor = result.color;
401
float clearDepth = result.depth;
402
403
int mask = gstate.isClearModeColorMask() ? D3DCLEAR_TARGET : 0;
404
if (gstate.isClearModeAlphaMask()) mask |= D3DCLEAR_STENCIL;
405
if (gstate.isClearModeDepthMask()) mask |= D3DCLEAR_ZBUFFER;
406
407
if (mask & D3DCLEAR_TARGET) {
408
framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason);
409
}
410
411
device_->Clear(0, NULL, mask, SwapRB(clearColor), clearDepth, clearColor >> 24);
412
413
if (gstate_c.Use(GPU_USE_CLEAR_RAM_HACK) && gstate.isClearModeColorMask() && (gstate.isClearModeAlphaMask() || gstate_c.framebufFormat == GE_FORMAT_565)) {
414
int scissorX1 = gstate.getScissorX1();
415
int scissorY1 = gstate.getScissorY1();
416
int scissorX2 = gstate.getScissorX2() + 1;
417
int scissorY2 = gstate.getScissorY2() + 1;
418
framebufferManager_->ApplyClearToMemory(scissorX1, scissorY1, scissorX2, scissorY2, clearColor);
419
}
420
}
421
decOptions_.applySkinInDecode = g_Config.bSoftwareSkinning;
422
}
423
424
ResetAfterDrawInline();
425
framebufferManager_->SetColorUpdated(gstate_c.skipDrawReason);
426
GPUDebug::NotifyDraw();
427
}
428
429
void TessellationDataTransferDX9::SendDataToShader(const SimpleVertex *const *points, int size_u, int size_v, u32 vertType, const Spline::Weight2D &weights) {
430
// TODO
431
}
432
433