/
thin3d_d3d9.cpp
845 lines (752 loc) · 25 KB
/
thin3d_d3d9.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
#include <vector>
#include <cstdio>
#include <cstdint>
#ifdef _DEBUG
#define D3D_DEBUG_INFO
#endif
#include <d3d9.h>
#ifdef USE_CRT_DBG
#undef new
#endif
#include <d3dx9.h>
#ifdef USE_CRT_DBG
#define new DBG_NEW
#endif
#include "base/logging.h"
#include "math/lin/matrix4x4.h"
#include "thin3d/thin3d.h"
#include "thin3d/d3dx9_loader.h"
namespace Draw {
// Could be declared as u8
static const D3DCMPFUNC compareToD3D9[] = {
D3DCMP_NEVER,
D3DCMP_LESS,
D3DCMP_EQUAL,
D3DCMP_LESSEQUAL,
D3DCMP_GREATER,
D3DCMP_NOTEQUAL,
D3DCMP_GREATEREQUAL,
D3DCMP_ALWAYS
};
// Could be declared as u8
static const D3DBLENDOP blendEqToD3D9[] = {
D3DBLENDOP_ADD,
D3DBLENDOP_SUBTRACT,
D3DBLENDOP_REVSUBTRACT,
D3DBLENDOP_MIN,
D3DBLENDOP_MAX,
};
// Could be declared as u8
static const D3DBLEND blendFactorToD3D9[] = {
D3DBLEND_ZERO,
D3DBLEND_ONE,
D3DBLEND_SRCCOLOR,
D3DBLEND_SRCALPHA,
D3DBLEND_INVSRCCOLOR,
D3DBLEND_INVSRCALPHA,
D3DBLEND_DESTCOLOR,
D3DBLEND_DESTALPHA,
D3DBLEND_INVDESTCOLOR,
D3DBLEND_INVDESTALPHA,
D3DBLEND_BLENDFACTOR,
};
static const D3DTEXTUREADDRESS texWrapToD3D9[] = {
D3DTADDRESS_WRAP,
D3DTADDRESS_CLAMP,
};
static const D3DTEXTUREFILTERTYPE texFilterToD3D9[] = {
D3DTEXF_POINT,
D3DTEXF_LINEAR,
};
static const D3DPRIMITIVETYPE primToD3D9[] = {
D3DPT_POINTLIST,
D3DPT_LINELIST,
D3DPT_LINESTRIP,
D3DPT_TRIANGLELIST,
D3DPT_TRIANGLESTRIP,
D3DPT_TRIANGLEFAN,
// These aren't available.
D3DPT_POINTLIST, // tess
D3DPT_POINTLIST, // geom ...
D3DPT_POINTLIST,
D3DPT_POINTLIST,
D3DPT_POINTLIST,
};
static const int primCountDivisor[] = {
1,
2,
3,
3,
3,
1,
1,
1,
1,
1,
};
class Thin3DDX9DepthStencilState : public DepthStencilState {
public:
BOOL depthTestEnabled;
BOOL depthWriteEnabled;
D3DCMPFUNC depthCompare;
void Apply(LPDIRECT3DDEVICE9 device) {
device->SetRenderState(D3DRS_ZENABLE, depthTestEnabled);
device->SetRenderState(D3DRS_ZWRITEENABLE, depthWriteEnabled);
device->SetRenderState(D3DRS_ZFUNC, depthCompare);
}
};
class D3D9RasterState : public RasterState {
public:
DWORD cullMode;
void Apply(LPDIRECT3DDEVICE9 device) {
device->SetRenderState(D3DRS_CULLMODE, cullMode);
device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
}
};
class D3D9BlendState : public BlendState {
public:
bool enabled;
D3DBLENDOP eqCol, eqAlpha;
D3DBLEND srcCol, srcAlpha, dstCol, dstAlpha;
uint32_t fixedColor;
void Apply(LPDIRECT3DDEVICE9 device) {
device->SetRenderState(D3DRS_ALPHABLENDENABLE, (DWORD)enabled);
device->SetRenderState(D3DRS_BLENDOP, eqCol);
device->SetRenderState(D3DRS_BLENDOPALPHA, eqAlpha);
device->SetRenderState(D3DRS_SRCBLEND, srcCol);
device->SetRenderState(D3DRS_DESTBLEND, dstCol);
device->SetRenderState(D3DRS_SRCBLENDALPHA, srcAlpha);
device->SetRenderState(D3DRS_DESTBLENDALPHA, dstAlpha);
// device->SetRenderState(, fixedColor);
}
};
class D3D9SamplerState : public SamplerState {
public:
D3DTEXTUREADDRESS wrapS, wrapT;
D3DTEXTUREFILTERTYPE magFilt, minFilt, mipFilt;
void Apply(LPDIRECT3DDEVICE9 device, int index) {
device->SetSamplerState(index, D3DSAMP_ADDRESSU, wrapS);
device->SetSamplerState(index, D3DSAMP_ADDRESSV, wrapT);
device->SetSamplerState(index, D3DSAMP_MAGFILTER, magFilt);
device->SetSamplerState(index, D3DSAMP_MINFILTER, minFilt);
device->SetSamplerState(index, D3DSAMP_MIPFILTER, mipFilt);
}
};
class Thin3DDX9Buffer : public Buffer {
public:
Thin3DDX9Buffer(LPDIRECT3DDEVICE9 device, size_t size, uint32_t flags) : vbuffer_(nullptr), ibuffer_(nullptr), maxSize_(size) {
if (flags & BufferUsageFlag::INDEXDATA) {
DWORD usage = D3DUSAGE_DYNAMIC;
device->CreateIndexBuffer((UINT)size, usage, D3DFMT_INDEX32, D3DPOOL_DEFAULT, &ibuffer_, NULL);
} else {
DWORD usage = D3DUSAGE_DYNAMIC;
device->CreateVertexBuffer((UINT)size, usage, 0, D3DPOOL_DEFAULT, &vbuffer_, NULL);
}
}
virtual ~Thin3DDX9Buffer() override {
if (ibuffer_) {
ibuffer_->Release();
}
if (vbuffer_) {
vbuffer_->Release();
}
}
void SetData(const uint8_t *data, size_t size) override {
if (!size)
return;
if (size > maxSize_) {
ELOG("Can't SetData with bigger size than buffer was created with on D3D");
return;
}
if (vbuffer_) {
void *ptr;
vbuffer_->Lock(0, (UINT)size, &ptr, D3DLOCK_DISCARD);
memcpy(ptr, data, size);
vbuffer_->Unlock();
} else if (ibuffer_) {
void *ptr;
ibuffer_->Lock(0, (UINT)size, &ptr, D3DLOCK_DISCARD);
memcpy(ptr, data, size);
ibuffer_->Unlock();
}
}
void SubData(const uint8_t *data, size_t offset, size_t size) override {
if (!size)
return;
if (offset + size > maxSize_) {
ELOG("Can't SubData with bigger size than buffer was created with on D3D");
return;
}
if (vbuffer_) {
void *ptr;
HRESULT res = vbuffer_->Lock((UINT)offset, (UINT)size, &ptr, D3DLOCK_DISCARD);
if (!FAILED(res)) {
memcpy(ptr, data, size);
vbuffer_->Unlock();
}
} else if (ibuffer_) {
void *ptr;
HRESULT res = ibuffer_->Lock((UINT)offset, (UINT)size, &ptr, D3DLOCK_DISCARD);
if (!FAILED(res)) {
memcpy(ptr, data, size);
ibuffer_->Unlock();
}
}
}
void BindAsVertexBuf(LPDIRECT3DDEVICE9 device, int vertexSize, int offset = 0) {
if (vbuffer_)
device->SetStreamSource(0, vbuffer_, offset, vertexSize);
}
void BindAsIndexBuf(LPDIRECT3DDEVICE9 device) {
if (ibuffer_)
device->SetIndices(ibuffer_);
}
private:
LPDIRECT3DVERTEXBUFFER9 vbuffer_;
LPDIRECT3DINDEXBUFFER9 ibuffer_;
size_t maxSize_;
};
class Thin3DDX9VertexFormat : public InputLayout {
public:
Thin3DDX9VertexFormat(LPDIRECT3DDEVICE9 device, const std::vector<VertexComponent> &components, int stride);
~Thin3DDX9VertexFormat() {
if (decl_) {
decl_->Release();
}
}
int GetStride() const { return stride_; }
void Apply(LPDIRECT3DDEVICE9 device) {
device->SetVertexDeclaration(decl_);
}
bool RequiresBuffer() override {
return false;
}
private:
LPDIRECT3DVERTEXDECLARATION9 decl_;
int stride_;
};
class D3D9ShaderModule : public ShaderModule {
public:
D3D9ShaderModule(ShaderStage stage) : stage_(stage), vshader_(NULL), pshader_(NULL), constantTable_(NULL) {}
~D3D9ShaderModule() {
if (vshader_)
vshader_->Release();
if (pshader_)
pshader_->Release();
if (constantTable_)
constantTable_->Release();
}
bool Compile(LPDIRECT3DDEVICE9 device, const char *source);
void Apply(LPDIRECT3DDEVICE9 device) {
if (stage_ == ShaderStage::FRAGMENT) {
device->SetPixelShader(pshader_);
} else {
device->SetVertexShader(vshader_);
}
}
void SetVector(LPDIRECT3DDEVICE9 device, const char *name, float *value, int n);
void SetMatrix4x4(LPDIRECT3DDEVICE9 device, const char *name, const float value[16]);
ShaderStage GetStage() const override { return stage_; }
private:
ShaderStage stage_;
LPDIRECT3DVERTEXSHADER9 vshader_;
LPDIRECT3DPIXELSHADER9 pshader_;
LPD3DXCONSTANTTABLE constantTable_;
};
class D3D9Pipeline : public Pipeline {
public:
D3D9Pipeline(LPDIRECT3DDEVICE9 device) : device_(device) {}
D3D9ShaderModule *vshader;
D3D9ShaderModule *pshader;
void Apply(LPDIRECT3DDEVICE9 device);
void SetVector(const char *name, float *value, int n) { vshader->SetVector(device_, name, value, n); pshader->SetVector(device_, name, value, n); }
void SetMatrix4x4(const char *name, const float value[16]) { vshader->SetMatrix4x4(device_, name, value); } // pshaders don't usually have matrices
private:
LPDIRECT3DDEVICE9 device_;
};
class D3D9Texture : public Texture {
public:
D3D9Texture(LPDIRECT3DDEVICE9 device, LPDIRECT3DDEVICE9EX deviceEx) : device_(device), deviceEx_(deviceEx), type_(TextureType::UNKNOWN), fmt_(D3DFMT_UNKNOWN), tex_(NULL), volTex_(NULL), cubeTex_(NULL) {
}
D3D9Texture(LPDIRECT3DDEVICE9 device, LPDIRECT3DDEVICE9EX deviceEx, TextureType type, DataFormat format, int width, int height, int depth, int mipLevels);
~D3D9Texture();
bool Create(TextureType type, DataFormat format, int width, int height, int depth, int mipLevels) override;
void SetImageData(int x, int y, int z, int width, int height, int depth, int level, int stride, const uint8_t *data) override;
void AutoGenMipmaps() override {}
void SetToSampler(LPDIRECT3DDEVICE9 device, int sampler);
void Finalize(int zim_flags) override {}
private:
LPDIRECT3DDEVICE9 device_;
LPDIRECT3DDEVICE9EX deviceEx_;
TextureType type_;
D3DFORMAT fmt_;
LPDIRECT3DTEXTURE9 tex_;
LPDIRECT3DVOLUMETEXTURE9 volTex_;
LPDIRECT3DCUBETEXTURE9 cubeTex_;
};
D3DFORMAT FormatToD3D(DataFormat fmt) {
switch (fmt) {
case DataFormat::R8G8B8A8_UNORM: return D3DFMT_A8R8G8B8;
case DataFormat::R4G4B4A4_UNORM: return D3DFMT_A4R4G4B4;
case DataFormat::D24_S8: return D3DFMT_D24S8;
case DataFormat::D16: return D3DFMT_D16;
default: return D3DFMT_UNKNOWN;
}
}
D3D9Texture::D3D9Texture(LPDIRECT3DDEVICE9 device, LPDIRECT3DDEVICE9EX deviceEx, TextureType type, DataFormat format, int width, int height, int depth, int mipLevels)
: device_(device), deviceEx_(deviceEx), type_(type), tex_(NULL), volTex_(NULL), cubeTex_(NULL) {
Create(type, format, width, height, depth, mipLevels);
}
D3D9Texture::~D3D9Texture() {
if (tex_) {
tex_->Release();
}
if (volTex_) {
volTex_->Release();
}
if (cubeTex_) {
cubeTex_->Release();
}
}
bool D3D9Texture::Create(TextureType type, DataFormat format, int width, int height, int depth, int mipLevels) {
width_ = width;
height_ = height;
depth_ = depth;
type_ = type;
tex_ = NULL;
fmt_ = FormatToD3D(format);
HRESULT hr = E_FAIL;
D3DPOOL pool = D3DPOOL_MANAGED;
int usage = 0;
if (deviceEx_ != nullptr) {
pool = D3DPOOL_DEFAULT;
usage = D3DUSAGE_DYNAMIC;
}
switch (type) {
case LINEAR1D:
case LINEAR2D:
hr = device_->CreateTexture(width, height, mipLevels, usage, fmt_, pool, &tex_, NULL);
break;
case LINEAR3D:
hr = device_->CreateVolumeTexture(width, height, depth, mipLevels, usage, fmt_, pool, &volTex_, NULL);
break;
case CUBE:
hr = device_->CreateCubeTexture(width, mipLevels, usage, fmt_, pool, &cubeTex_, NULL);
break;
}
if (FAILED(hr)) {
ELOG("Texture creation failed");
return false;
}
return true;
}
inline uint16_t Shuffle4444(uint16_t x) {
return (x << 12) | (x >> 4);
}
// Just switches R and G.
inline uint32_t Shuffle8888(uint32_t x) {
return (x & 0xFF00FF00) | ((x >> 16) & 0xFF) | ((x << 16) & 0xFF0000);
}
void D3D9Texture::SetImageData(int x, int y, int z, int width, int height, int depth, int level, int stride, const uint8_t *data) {
if (!tex_) {
return;
}
if (level == 0) {
width_ = width;
height_ = height;
depth_ = depth;
}
switch (type_) {
case LINEAR2D:
{
D3DLOCKED_RECT rect;
if (x == 0 && y == 0) {
tex_->LockRect(level, &rect, NULL, 0);
for (int i = 0; i < height; i++) {
uint8_t *dest = (uint8_t *)rect.pBits + rect.Pitch * i;
const uint8_t *source = data + stride * i;
int j;
switch (fmt_) {
case D3DFMT_A4R4G4B4:
// This is backwards from OpenGL so we need to shuffle around a bit.
for (j = 0; j < width; j++) {
((uint16_t *)dest)[j] = Shuffle4444(((uint16_t *)source)[j]);
}
break;
case D3DFMT_A8R8G8B8:
for (j = 0; j < width; j++) {
((uint32_t *)dest)[j] = Shuffle8888(((uint32_t *)source)[j]);
}
break;
}
}
tex_->UnlockRect(level);
}
break;
}
default:
ELOG("Non-LINEAR2D textures not yet supported");
break;
}
}
void D3D9Texture::SetToSampler(LPDIRECT3DDEVICE9 device, int sampler) {
switch (type_) {
case LINEAR1D:
case LINEAR2D:
device->SetTexture(sampler, tex_);
break;
case LINEAR3D:
device->SetTexture(sampler, volTex_);
break;
case CUBE:
device->SetTexture(sampler, cubeTex_);
break;
}
}
class D3D9Context : public DrawContext {
public:
D3D9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, IDirect3DDevice9 *device, IDirect3DDevice9Ex *deviceEx);
~D3D9Context();
DepthStencilState *CreateDepthStencilState(const DepthStencilStateDesc &desc) override;
BlendState *CreateBlendState(const BlendStateDesc &desc) override;
SamplerState *CreateSamplerState(const SamplerStateDesc &desc) override;
RasterState *CreateRasterState(const RasterStateDesc &desc) override;
Buffer *CreateBuffer(size_t size, uint32_t usageFlags) override;
Pipeline *CreatePipeline(const PipelineDesc &desc) override;
InputLayout *CreateVertexFormat(const std::vector<VertexComponent> &components, int stride, ShaderModule *vshader) override;
Texture *CreateTexture() override;
Texture *CreateTexture(TextureType type, DataFormat format, int width, int height, int depth, int mipLevels) override;
ShaderModule *CreateShaderModule(ShaderStage stage, const char *glsl_source, const char *hlsl_source, const char *vulkan_source) override;
// Bound state objects. Too cumbersome to add them all as parameters to Draw.
void SetBlendState(BlendState *state) override {
D3D9BlendState *bs = static_cast<D3D9BlendState *>(state);
bs->Apply(device_);
}
void SetDepthStencilState(DepthStencilState *state) override {
Thin3DDX9DepthStencilState *bs = static_cast<Thin3DDX9DepthStencilState *>(state);
bs->Apply(device_);
}
void SetRasterState(RasterState *state) override {
D3D9RasterState *bs = static_cast<D3D9RasterState *>(state);
bs->Apply(device_);
}
void BindTextures(int start, int count, Texture **textures) override;
void BindSamplerStates(int start, int count, SamplerState **states) override {
for (int i = 0; i < count; ++i) {
D3D9SamplerState *s = static_cast<D3D9SamplerState *>(states[start + i]);
s->Apply(device_, start + i);
}
}
void BindPipeline(Pipeline *pipeline) {
curPipeline_ = (D3D9Pipeline *)pipeline;
}
// Raster state
void SetScissorRect(int left, int top, int width, int height) override;
void SetViewports(int count, Viewport *viewports) override;
void Draw(Primitive prim, InputLayout *format, Buffer *vdata, int vertexCount, int offset) override;
void DrawIndexed(Primitive prim, InputLayout *format, Buffer *vdata, Buffer *idata, int vertexCount, int offset) override;
void DrawUP(Primitive prim, InputLayout *format, const void *vdata, int vertexCount) override;
void Clear(int mask, uint32_t colorval, float depthVal, int stencilVal);
std::string GetInfoString(InfoField info) const override {
switch (info) {
case APIVERSION: return "DirectX 9.0";
case VENDORSTRING: return identifier_.Description;
case VENDOR: return "-";
case RENDERER: return identifier_.Driver; // eh, sort of
case SHADELANGVERSION: return shadeLangVersion_;
case APINAME: return "Direct3D 9";
default: return "?";
}
}
private:
LPDIRECT3D9 d3d_;
LPDIRECT3D9EX d3dEx_;
LPDIRECT3DDEVICE9 device_;
LPDIRECT3DDEVICE9EX deviceEx_;
int adapterId_;
D3DADAPTER_IDENTIFIER9 identifier_;
D3DCAPS9 caps_;
char shadeLangVersion_[64];
D3D9Pipeline *curPipeline_;
};
D3D9Context::D3D9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, IDirect3DDevice9 *device, IDirect3DDevice9Ex *deviceEx)
: d3d_(d3d), d3dEx_(d3dEx), adapterId_(adapterId), device_(device), deviceEx_(deviceEx) {
CreatePresets();
d3d->GetAdapterIdentifier(adapterId, 0, &identifier_);
if (!FAILED(device->GetDeviceCaps(&caps_))) {
sprintf(shadeLangVersion_, "PS: %04x VS: %04x", caps_.PixelShaderVersion & 0xFFFF, caps_.VertexShaderVersion & 0xFFFF);
} else {
strcpy(shadeLangVersion_, "N/A");
}
}
D3D9Context::~D3D9Context() {
}
ShaderModule *D3D9Context::CreateShaderModule(ShaderStage stage, const char *glsl_source, const char *hlsl_source, const char *vulkan_source) {
D3D9ShaderModule *shader = new D3D9ShaderModule(stage);
if (shader->Compile(device_, hlsl_source)) {
return shader;
} else {
delete shader;
return NULL;
}
}
Pipeline *D3D9Context::CreatePipeline(const PipelineDesc &desc) {
if (!desc.shaders.size()) {
ELOG("ShaderSet requires at least one shader");
return NULL;
}
D3D9Pipeline *shaderSet = new D3D9Pipeline(device_);
for (auto iter : desc.shaders) {
if (iter->GetStage() == ShaderStage::FRAGMENT) {
shaderSet->pshader = static_cast<D3D9ShaderModule *>(iter);
}
else if (iter->GetStage() == ShaderStage::VERTEX) {
shaderSet->vshader = static_cast<D3D9ShaderModule *>(iter);
}
}
return shaderSet;
}
DepthStencilState *D3D9Context::CreateDepthStencilState(const DepthStencilStateDesc &desc) {
Thin3DDX9DepthStencilState *ds = new Thin3DDX9DepthStencilState();
ds->depthTestEnabled = desc.depthTestEnabled;
ds->depthWriteEnabled = desc.depthWriteEnabled;
ds->depthCompare = compareToD3D9[(int)desc.depthCompare];
return ds;
}
InputLayout *D3D9Context::CreateVertexFormat(const std::vector<VertexComponent> &components, int stride, ShaderModule *vshader) {
Thin3DDX9VertexFormat *fmt = new Thin3DDX9VertexFormat(device_, components, stride);
return fmt;
}
BlendState *D3D9Context::CreateBlendState(const BlendStateDesc &desc) {
D3D9BlendState *bs = new D3D9BlendState();
bs->enabled = desc.enabled;
bs->eqCol = blendEqToD3D9[(int)desc.eqCol];
bs->srcCol = blendFactorToD3D9[(int)desc.srcCol];
bs->dstCol = blendFactorToD3D9[(int)desc.dstCol];
bs->eqAlpha = blendEqToD3D9[(int)desc.eqAlpha];
bs->srcAlpha = blendFactorToD3D9[(int)desc.srcAlpha];
bs->dstAlpha = blendFactorToD3D9[(int)desc.dstAlpha];
// Ignore logic ops, we don't support them in D3D9
return bs;
}
SamplerState *D3D9Context::CreateSamplerState(const SamplerStateDesc &desc) {
D3D9SamplerState *samps = new D3D9SamplerState();
samps->wrapS = texWrapToD3D9[(int)desc.wrapU];
samps->wrapT = texWrapToD3D9[(int)desc.wrapV];
samps->magFilt = texFilterToD3D9[(int)desc.magFilter];
samps->minFilt = texFilterToD3D9[(int)desc.minFilter];
samps->mipFilt = texFilterToD3D9[(int)desc.mipFilter];
return samps;
}
RasterState *D3D9Context::CreateRasterState(const RasterStateDesc &desc) {
D3D9RasterState *rs = new D3D9RasterState();
rs->cullMode = D3DCULL_NONE;
if (desc.cull == CullMode::NONE) {
return rs;
}
switch (desc.facing) {
case Facing::CW:
switch (desc.cull) {
case CullMode::FRONT: rs->cullMode = D3DCULL_CCW; break;
case CullMode::BACK: rs->cullMode = D3DCULL_CW; break;
}
case Facing::CCW:
switch (desc.cull) {
case CullMode::FRONT: rs->cullMode = D3DCULL_CW; break;
case CullMode::BACK: rs->cullMode = D3DCULL_CCW; break;
}
}
return rs;
}
Texture *D3D9Context::CreateTexture() {
D3D9Texture *tex = new D3D9Texture(device_, deviceEx_);
return tex;
}
Texture *D3D9Context::CreateTexture(TextureType type, DataFormat format, int width, int height, int depth, int mipLevels) {
D3D9Texture *tex = new D3D9Texture(device_, deviceEx_, type, format, width, height, depth, mipLevels);
return tex;
}
void D3D9Context::BindTextures(int start, int count, Texture **textures) {
for (int i = start; i < start + count; i++) {
D3D9Texture *tex = static_cast<D3D9Texture *>(textures[i - start]);
tex->SetToSampler(device_, i);
}
}
static void SemanticToD3D9UsageAndIndex(int semantic, BYTE *usage, BYTE *index) {
*index = 0;
switch (semantic) {
case SEM_POSITION:
*usage = D3DDECLUSAGE_POSITION;
break;
case SEM_NORMAL:
*usage = D3DDECLUSAGE_NORMAL;
break;
case SEM_TANGENT:
*usage = D3DDECLUSAGE_TANGENT;
break;
case SEM_BINORMAL:
*usage = D3DDECLUSAGE_BINORMAL;
break;
case SEM_COLOR0:
*usage = D3DDECLUSAGE_COLOR;
break;
case SEM_TEXCOORD0:
*usage = D3DDECLUSAGE_TEXCOORD;
break;
case SEM_TEXCOORD1:
*usage = D3DDECLUSAGE_TEXCOORD;
*index = 1;
break;
}
}
static int VertexDataTypeToD3DType(DataFormat type) {
switch (type) {
case DataFormat::R32G32_FLOAT: return D3DDECLTYPE_FLOAT2;
case DataFormat::R32G32B32_FLOAT: return D3DDECLTYPE_FLOAT3;
case DataFormat::R32G32B32A32_FLOAT: return D3DDECLTYPE_FLOAT4;
case DataFormat::R8G8B8A8_UNORM: return D3DDECLTYPE_UBYTE4N; // D3DCOLOR?
default: return D3DDECLTYPE_UNUSED;
}
}
Thin3DDX9VertexFormat::Thin3DDX9VertexFormat(LPDIRECT3DDEVICE9 device, const std::vector<VertexComponent> &components, int stride) : decl_(NULL) {
D3DVERTEXELEMENT9 *elements = new D3DVERTEXELEMENT9[components.size() + 1];
size_t i;
for (i = 0; i < components.size(); i++) {
elements[i].Stream = 0;
elements[i].Offset = components[i].offset;
elements[i].Method = D3DDECLMETHOD_DEFAULT;
SemanticToD3D9UsageAndIndex(components[i].semantic, &elements[i].Usage, &elements[i].UsageIndex);
elements[i].Type = VertexDataTypeToD3DType(components[i].type);
}
D3DVERTEXELEMENT9 end = D3DDECL_END();
// Zero the last one.
memcpy(&elements[i], &end, sizeof(elements[i]));
HRESULT hr = device->CreateVertexDeclaration(elements, &decl_);
if (FAILED(hr)) {
ELOG("Error creating vertex decl");
}
delete[] elements;
stride_ = stride;
}
Buffer *D3D9Context::CreateBuffer(size_t size, uint32_t usageFlags) {
return new Thin3DDX9Buffer(device_, size, usageFlags);
}
void D3D9Pipeline::Apply(LPDIRECT3DDEVICE9 device) {
vshader->Apply(device);
pshader->Apply(device);
}
void D3D9Context::Draw(Primitive prim, InputLayout *format, Buffer *vdata, int vertexCount, int offset) {
Thin3DDX9Buffer *vbuf = static_cast<Thin3DDX9Buffer *>(vdata);
Thin3DDX9VertexFormat *fmt = static_cast<Thin3DDX9VertexFormat *>(format);
vbuf->BindAsVertexBuf(device_, fmt->GetStride(), offset);
curPipeline_->Apply(device_);
fmt->Apply(device_);
device_->DrawPrimitive(primToD3D9[(int)prim], offset, vertexCount / 3);
}
void D3D9Context::DrawIndexed(Primitive prim, InputLayout *format, Buffer *vdata, Buffer *idata, int vertexCount, int offset) {
Thin3DDX9Buffer *vbuf = static_cast<Thin3DDX9Buffer *>(vdata);
Thin3DDX9Buffer *ibuf = static_cast<Thin3DDX9Buffer *>(idata);
Thin3DDX9VertexFormat *fmt = static_cast<Thin3DDX9VertexFormat *>(format);
curPipeline_->Apply(device_);
fmt->Apply(device_);
vbuf->BindAsVertexBuf(device_, fmt->GetStride(), offset);
ibuf->BindAsIndexBuf(device_);
device_->DrawIndexedPrimitive(primToD3D9[(int)prim], 0, 0, vertexCount, 0, vertexCount / primCountDivisor[(int)prim]);
}
void D3D9Context::DrawUP(Primitive prim, InputLayout *format, const void *vdata, int vertexCount) {
Thin3DDX9VertexFormat *fmt = static_cast<Thin3DDX9VertexFormat *>(format);
curPipeline_->Apply(device_);
fmt->Apply(device_);
device_->DrawPrimitiveUP(primToD3D9[(int)prim], vertexCount / 3, vdata, fmt->GetStride());
}
static uint32_t SwapRB(uint32_t c) {
return (c & 0xFF00FF00) | ((c >> 16) & 0xFF) | ((c << 16) & 0xFF0000);
}
void D3D9Context::Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) {
UINT d3dMask = 0;
if (mask & ClearFlag::COLOR) d3dMask |= D3DCLEAR_TARGET;
if (mask & ClearFlag::DEPTH) d3dMask |= D3DCLEAR_ZBUFFER;
if (mask & ClearFlag::STENCIL) d3dMask |= D3DCLEAR_STENCIL;
device_->Clear(0, NULL, d3dMask, (D3DCOLOR)SwapRB(colorval), depthVal, stencilVal);
}
void D3D9Context::SetScissorRect(int left, int top, int width, int height) {
RECT rc;
rc.left = left;
rc.top = top;
rc.right = left + width;
rc.bottom = top + height;
device_->SetScissorRect(&rc);
}
void D3D9Context::SetViewports(int count, Viewport *viewports) {
D3DVIEWPORT9 vp;
vp.X = (DWORD)viewports[0].TopLeftX;
vp.Y = (DWORD)viewports[0].TopLeftY;
vp.Width = (DWORD)viewports[0].Width;
vp.Height = (DWORD)viewports[0].Height;
vp.MinZ = viewports[0].MinDepth;
vp.MaxZ = viewports[0].MaxDepth;
device_->SetViewport(&vp);
}
bool D3D9ShaderModule::Compile(LPDIRECT3DDEVICE9 device, const char *source) {
LPD3DXMACRO defines = NULL;
LPD3DXINCLUDE includes = NULL;
DWORD flags = 0;
LPD3DXBUFFER codeBuffer;
LPD3DXBUFFER errorBuffer;
const char *profile = stage_ == ShaderStage::FRAGMENT ? "ps_2_0" : "vs_2_0";
HRESULT hr = dyn_D3DXCompileShader(source, (UINT)strlen(source), defines, includes, "main", profile, flags, &codeBuffer, &errorBuffer, &constantTable_);
if (FAILED(hr)) {
const char *error = (const char *)errorBuffer->GetBufferPointer();
OutputDebugStringA(source);
OutputDebugStringA(error);
errorBuffer->Release();
if (codeBuffer)
codeBuffer->Release();
if (constantTable_)
constantTable_->Release();
return false;
}
bool success = false;
if (stage_ == ShaderStage::FRAGMENT) {
HRESULT result = device->CreatePixelShader((DWORD *)codeBuffer->GetBufferPointer(), &pshader_);
success = SUCCEEDED(result);
} else {
HRESULT result = device->CreateVertexShader((DWORD *)codeBuffer->GetBufferPointer(), &vshader_);
success = SUCCEEDED(result);
}
#if 0
// Just for testing. Will later use to pre populate uniform tables.
D3DXCONSTANTTABLE_DESC desc;
constantTable_->GetDesc(&desc);
for (UINT i = 0; i < desc.Constants; i++) {
D3DXHANDLE c = constantTable_->GetConstant(NULL, i);
D3DXCONSTANT_DESC cdesc;
UINT count = 1;
constantTable_->GetConstantDesc(c, &cdesc, &count);
ILOG("%s", cdesc.Name);
}
#endif
codeBuffer->Release();
return true;
}
void D3D9ShaderModule::SetVector(LPDIRECT3DDEVICE9 device, const char *name, float *value, int n) {
D3DXHANDLE handle = constantTable_->GetConstantByName(NULL, name);
if (handle) {
constantTable_->SetFloatArray(device, handle, value, n);
}
}
void D3D9ShaderModule::SetMatrix4x4(LPDIRECT3DDEVICE9 device, const char *name, const float value[16]) {
D3DXHANDLE handle = constantTable_->GetConstantByName(NULL, name);
if (handle) {
constantTable_->SetFloatArray(device, handle, value, 16);
}
}
DrawContext *T3DCreateDX9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, IDirect3DDevice9 *device, IDirect3DDevice9Ex *deviceEx) {
int d3dx_ver = LoadD3DX9Dynamic();
if (!d3dx_ver) {
ELOG("Failed to load D3DX9!");
return NULL;
}
return new D3D9Context(d3d, d3dEx, adapterId, device, deviceEx);
}
} // namespace Draw