-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathali3dd3d.cpp
2099 lines (1849 loc) · 67.7 KB
/
ali3dd3d.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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-2025 various contributors
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// https://opensource.org/license/artistic-2-0/
//
//=============================================================================
#include "core/platform.h"
#if AGS_HAS_DIRECT3D
#include "platform/windows/gfx/ali3dd3d.h"
#include <algorithm>
#include <stack>
#include <SDL.h>
#include <glm/ext.hpp>
#include "ac/sys_events.h"
#include "ac/timer.h"
#include "debug/out.h"
#include "gfx/ali3dexception.h"
#include "gfx/gfx_def.h"
#include "gfx/gfxfilter_d3d.h"
#include "gfx/gfxfilter_aad3d.h"
#include "platform/base/agsplatformdriver.h"
#include "platform/base/sys_main.h"
#include "util/matrix.h"
using namespace AGS::Common;
// Necessary to update textures from 8-bit bitmaps
extern RGB palette[256];
namespace AGS
{
namespace Engine
{
namespace D3D
{
using namespace Common;
void RectToRECT(const Rect &in_rc, RECT &out_rc)
{
out_rc.left = in_rc.Left;
out_rc.top = in_rc.Top;
out_rc.right = in_rc.Right + 1;
out_rc.bottom = in_rc.Bottom + 1;
}
void RectToRECT(const Rect &in_rc, D3DRECT &out_rc)
{
out_rc.x1 = in_rc.Left;
out_rc.y1 = in_rc.Top;
out_rc.x2 = in_rc.Right + 1;
out_rc.y2 = in_rc.Bottom + 1;
}
size_t D3DTexture::GetMemSize() const
{
// FIXME: a proper size in video memory, check Direct3D docs
size_t sz = 0u;
for (const auto &tile : _tiles)
sz += tile.allocWidth * tile.allocHeight * 4;
return sz;
}
void D3DBitmap::ReleaseTextureData()
{
_renderSurface = nullptr;
_data.reset();
}
static D3DFORMAT color_depth_to_d3d_format(int color_depth, bool wantAlpha);
static int d3d_format_to_color_depth(D3DFORMAT format, bool secondary);
D3DGfxModeList::D3DGfxModeList(const D3DPtr &direct3d, int display_index, D3DFORMAT d3dformat)
: _direct3d(direct3d)
, _displayIndex(display_index)
, _pixelFormat(d3dformat)
{
_adapterIndex = SDL_Direct3D9GetAdapterIndex(display_index);
_modeCount = _direct3d->GetAdapterModeCount(_adapterIndex, _pixelFormat);
}
bool D3DGfxModeList::GetMode(int index, DisplayMode &mode) const
{
if (_direct3d && index >= 0 && index < _modeCount)
{
D3DDISPLAYMODE d3d_mode;
if (SUCCEEDED(_direct3d->EnumAdapterModes(_adapterIndex, _pixelFormat, index, &d3d_mode)))
{
mode.DisplayIndex = _displayIndex;
mode.Width = d3d_mode.Width;
mode.Height = d3d_mode.Height;
mode.ColorDepth = d3d_format_to_color_depth(d3d_mode.Format, false);
mode.RefreshRate = d3d_mode.RefreshRate;
return true;
}
}
return false;
}
// The custom FVF, which describes the custom vertex structure.
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1)
D3DGraphicsDriver::D3DGraphicsDriver(const D3DPtr &d3d)
{
direct3d = d3d;
_legacyPixelShader = false;
set_up_default_vertices();
_smoothScaling = false;
_pixelRenderXOffset = 0;
_pixelRenderYOffset = 0;
_renderAtScreenRes = false;
// Shifts comply to D3DFMT_A8R8G8B8
_vmem_a_shift_32 = 24;
_vmem_r_shift_32 = 16;
_vmem_g_shift_32 = 8;
_vmem_b_shift_32 = 0;
}
D3DGraphicsDriver::BackbufferState::BackbufferState(const D3DSurfacePtr &surface,
const Size &surf_size, const Size &rend_sz,
const Rect &view, const glm::mat4 &proj, const PlaneScaling &scale, int filter)
: Surface(surface), SurfSize(surf_size), RendSize(rend_sz)
, Viewport(view), Projection(proj), Scaling(scale), Filter(filter)
{
assert(Surface != nullptr);
}
D3DGraphicsDriver::BackbufferState::BackbufferState(D3DSurfacePtr &&surface,
const Size &surf_size, const Size &rend_sz,
const Rect &view, const glm::mat4 &proj, const PlaneScaling &scale, int filter)
: Surface(std::move(surface)), SurfSize(surf_size), RendSize(rend_sz)
, Viewport(view), Projection(proj), Scaling(scale), Filter(filter)
{
assert(Surface != nullptr);
}
void D3DGraphicsDriver::set_up_default_vertices()
{
defaultVertices[0].position.x = 0.0f;
defaultVertices[0].position.y = 0.0f;
defaultVertices[0].position.z = 0.0f;
defaultVertices[0].normal.x = 0.0f;
defaultVertices[0].normal.y = 0.0f;
defaultVertices[0].normal.z = -1.0f;
//defaultVertices[0].color=0xffffffff;
defaultVertices[0].tu=0.0;
defaultVertices[0].tv=0.0;
defaultVertices[1].position.x = 1.0f;
defaultVertices[1].position.y = 0.0f;
defaultVertices[1].position.z = 0.0f;
defaultVertices[1].normal.x = 0.0f;
defaultVertices[1].normal.y = 0.0f;
defaultVertices[1].normal.z = -1.0f;
//defaultVertices[1].color=0xffffffff;
defaultVertices[1].tu=1.0;
defaultVertices[1].tv=0.0;
defaultVertices[2].position.x = 0.0f;
defaultVertices[2].position.y = -1.0f;
defaultVertices[2].position.z = 0.0f;
defaultVertices[2].normal.x = 0.0f;
defaultVertices[2].normal.y = 0.0f;
defaultVertices[2].normal.z = -1.0f;
//defaultVertices[2].color=0xffffffff;
defaultVertices[2].tu=0.0;
defaultVertices[2].tv=1.0;
defaultVertices[3].position.x = 1.0f;
defaultVertices[3].position.y = -1.0f;
defaultVertices[3].position.z = 0.0f;
defaultVertices[3].normal.x = 0.0f;
defaultVertices[3].normal.y = 0.0f;
defaultVertices[3].normal.z = -1.0f;
//defaultVertices[3].color=0xffffffff;
defaultVertices[3].tu=1.0;
defaultVertices[3].tv=1.0;
}
void D3DGraphicsDriver::OnModeSet(const DisplayMode &mode)
{
GraphicsDriverBase::OnModeSet(mode);
// The display mode has been set up successfully, save the
// final refresh rate that we are using
D3DDISPLAYMODE final_display_mode;
if (direct3ddevice->GetDisplayMode(0, &final_display_mode) == D3D_OK) {
_mode.RefreshRate = final_display_mode.RefreshRate;
}
else {
_mode.RefreshRate = 0;
}
}
void D3DGraphicsDriver::ReleaseDisplayMode()
{
if (!IsModeSet())
return;
_screenBackbuffer = BackbufferState();
OnModeReleased();
ClearDrawLists();
ClearDrawBackups();
DestroyFxPool();
DestroyAllStageScreens();
sys_window_set_style(kWnd_Windowed);
}
bool D3DGraphicsDriver::FirstTimeInit()
{
HRESULT hr;
direct3ddevice->GetCreationParameters(&direct3dcreateparams);
direct3ddevice->GetDeviceCaps(&direct3ddevicecaps);
// the PixelShader.fx uses ps_1_4
// the PixelShaderLegacy.fx needs ps_2_0
int requiredPSMajorVersion = 1;
int requiredPSMinorVersion = 4;
if (_legacyPixelShader) {
requiredPSMajorVersion = 2;
requiredPSMinorVersion = 0;
}
if (direct3ddevicecaps.PixelShaderVersion < D3DPS_VERSION(requiredPSMajorVersion, requiredPSMinorVersion))
{
direct3ddevice = nullptr;
SDL_SetError("Graphics card does not support Pixel Shader %d.%d", requiredPSMajorVersion, requiredPSMinorVersion);
previousError = SDL_GetError();
return false;
}
_capsVsync = (direct3ddevicecaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE) != 0;
if (!_capsVsync)
Debug::Printf(kDbgMsg_Warn, "WARNING: Vertical sync is not supported. Setting will be kept at driver default.");
// Load the pixel shader!!
HMODULE exeHandle = GetModuleHandle(NULL);
HRSRC hRes = FindResource(exeHandle, (_legacyPixelShader) ? "PIXEL_SHADER_LEGACY" : "PIXEL_SHADER", "DATA");
if (hRes)
{
HGLOBAL hGlobal = LoadResource(exeHandle, hRes);
if (hGlobal)
{
DWORD *dataPtr = (DWORD*)LockResource(hGlobal);
hr = direct3ddevice->CreatePixelShader(dataPtr, pixelShader.Acquire());
if (hr != D3D_OK)
{
direct3ddevice = nullptr;
SDL_SetError("Failed to create pixel shader: 0x%08X", hr);
previousError = SDL_GetError();
return false;
}
UnlockResource(hGlobal);
}
}
if (pixelShader == nullptr)
{
direct3ddevice = nullptr;
SDL_SetError("Failed to load pixel shader resource");
previousError = SDL_GetError();
return false;
}
if (direct3ddevice->CreateVertexBuffer(4*sizeof(CUSTOMVERTEX), D3DUSAGE_WRITEONLY,
D3DFVF_CUSTOMVERTEX, D3DPOOL_MANAGED, vertexbuffer.Acquire(), NULL) != D3D_OK)
{
direct3ddevice = nullptr;
SDL_SetError("Failed to create vertex buffer");
previousError = SDL_GetError();
return false;
}
CUSTOMVERTEX *vertices;
vertexbuffer->Lock(0, 0, (void**)&vertices, D3DLOCK_DISCARD);
for (int i = 0; i < 4; i++)
{
vertices[i] = defaultVertices[i];
}
vertexbuffer->Unlock();
direct3ddevice->GetGammaRamp(0, &defaultgammaramp);
if (defaultgammaramp.red[255] < 256)
{
// correct bug in some gfx drivers that returns gamma ramp
// values from 0-255 instead of 0-65535
for (int i = 0; i < 256; i++)
{
defaultgammaramp.red[i] *= 256;
defaultgammaramp.green[i] *= 256;
defaultgammaramp.blue[i] *= 256;
}
}
currentgammaramp = defaultgammaramp;
return true;
}
/* color_depth_to_d3d_format:
* Convert a colour depth into the appropriate D3D tag
*/
static D3DFORMAT color_depth_to_d3d_format(int color_depth, bool wantAlpha)
{
if (wantAlpha)
{
switch (color_depth)
{
case 8:
return D3DFMT_P8;
case 15:
case 16:
return D3DFMT_A1R5G5B5;
case 24:
case 32:
return D3DFMT_A8R8G8B8;
}
}
else
{
switch (color_depth)
{
case 8:
return D3DFMT_P8;
case 15: // don't use X1R5G5B5 because some cards don't support it
return D3DFMT_A1R5G5B5;
case 16:
return D3DFMT_R5G6B5;
case 24:
return D3DFMT_R8G8B8;
case 32:
return D3DFMT_X8R8G8B8;
}
}
return D3DFMT_UNKNOWN;
}
/* d3d_format_to_color_depth:
* Convert a D3D tag to colour depth
*
* TODO: this is currently an inversion of color_depth_to_d3d_format;
* check later if more formats should be handled
*/
static int d3d_format_to_color_depth(D3DFORMAT format, bool secondary)
{
switch (format)
{
case D3DFMT_P8:
return 8;
case D3DFMT_A1R5G5B5:
return secondary ? 15 : 16;
case D3DFMT_X1R5G5B5:
return secondary ? 15 : 16;
case D3DFMT_R5G6B5:
return 16;
case D3DFMT_R8G8B8:
return secondary ? 24 : 32;
case D3DFMT_A8R8G8B8:
case D3DFMT_X8R8G8B8:
return 32;
}
return 0;
}
bool D3DGraphicsDriver::IsModeSupported(const DisplayMode &mode)
{
if (mode.Width <= 0 || mode.Height <= 0 || mode.ColorDepth <= 0)
{
SDL_SetError("Invalid resolution parameters: %d x %d x %d", mode.Width, mode.Height, mode.ColorDepth);
return false;
}
if (!mode.IsRealFullscreen())
{
return true;
}
D3DFORMAT pixelFormat = color_depth_to_d3d_format(mode.ColorDepth, false);
D3DDISPLAYMODE d3d_mode;
const UINT use_adapter = SDL_Direct3D9GetAdapterIndex(mode.DisplayIndex);
int mode_count = direct3d->GetAdapterModeCount(use_adapter, pixelFormat);
for (int i = 0; i < mode_count; i++)
{
if (FAILED(direct3d->EnumAdapterModes(use_adapter, pixelFormat, i, &d3d_mode)))
{
SDL_SetError("IDirect3D9::EnumAdapterModes failed");
return false;
}
if ((d3d_mode.Width == static_cast<uint32_t>(mode.Width)) &&
(d3d_mode.Height == static_cast<uint32_t>(mode.Height)))
{
return true;
}
}
SDL_SetError("The requested adapter mode is not supported");
return false;
}
bool D3DGraphicsDriver::SupportsGammaControl()
{
if ((direct3ddevicecaps.Caps2 & D3DCAPS2_FULLSCREENGAMMA) == 0)
return false;
if (!_mode.IsRealFullscreen())
return false;
return true;
}
void D3DGraphicsDriver::SetGamma(int newGamma)
{
for (int i = 0; i < 256; i++)
{
int newValue = ((int)defaultgammaramp.red[i] * newGamma) / 100;
if (newValue >= 65535)
newValue = 65535;
currentgammaramp.red[i] = newValue;
currentgammaramp.green[i] = newValue;
currentgammaramp.blue[i] = newValue;
}
direct3ddevice->SetGammaRamp(0, D3DSGR_NO_CALIBRATION, ¤tgammaramp);
}
void D3DGraphicsDriver::ResetDeviceIfNecessary()
{
HRESULT hr = direct3ddevice->TestCooperativeLevel();
if (hr == D3DERR_DEVICELOST)
{
throw Ali3DFullscreenLostException();
}
if (hr == D3DERR_DEVICENOTRESET)
{
hr = ResetDeviceAndRestore();
if (hr != D3D_OK)
{
throw Ali3DException(String::FromFormat("IDirect3DDevice9::Reset: failed: error code: 0x%08X", hr));
}
}
else if (hr != D3D_OK)
{
throw Ali3DException(String::FromFormat("IDirect3DDevice9::TestCooperativeLevel: failed: error code: 0x%08X", hr));
}
}
HRESULT D3DGraphicsDriver::ResetDeviceAndRestore()
{
HRESULT hr = ResetD3DDevice();
if (hr != D3D_OK)
return hr;
// Reinitialize D3D settings, backbuffer surface, etc
InitializeD3DState();
CreateVirtualScreen();
return D3D_OK;
}
bool D3DGraphicsDriver::CreateDisplayMode(const DisplayMode &mode)
{
if (!IsModeSupported(mode))
return false;
SDL_Window *window = sys_get_window();
int use_display = mode.DisplayIndex;
if (!window)
{
sys_window_create("", mode.DisplayIndex, mode.Width, mode.Height, mode.Mode);
}
else
{
#if (AGS_SUPPORT_MULTIDISPLAY)
// If user requested an exclusive fullscreen, move window to where we created it first,
// because DirectX does not normally support switching displays in exclusive mode.
// NOTE: we may in theory support this, but we'd have to release and recreate
// ALL the resources, including all textures currently in memory.
if (mode.IsRealFullscreen() &&
(_fullscreenDisplay > 0) && (sys_get_window_display_index() != _fullscreenDisplay))
{
use_display = _fullscreenDisplay;
sys_window_fit_in_display(_fullscreenDisplay);
}
#endif
}
HWND hwnd = (HWND)sys_win_get_window();
memset( &d3dpp, 0, sizeof(d3dpp) );
d3dpp.BackBufferWidth = mode.Width;
d3dpp.BackBufferHeight = mode.Height;
d3dpp.BackBufferFormat = color_depth_to_d3d_format(mode.ColorDepth, false);
d3dpp.BackBufferCount = 1;
d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
// THIS MUST BE SWAPEFFECT_COPY FOR PlayVideo TO WORK
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY; //D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hwnd;
d3dpp.Windowed = mode.IsRealFullscreen() ? FALSE : TRUE;
d3dpp.EnableAutoDepthStencil = FALSE;
d3dpp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; // we need this flag to access the backbuffer with lockrect
d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
if (mode.Vsync)
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
else
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
/* If full screen, specify the refresh rate */
// TODO find a way to avoid the wrong refreshrate to be set on mode.RefreshRate
// for now it's best to let it set automatically, so we prevent alt tab delays due to mismatching refreshrates
//if ((d3dpp.Windowed == FALSE) && (mode.RefreshRate > 0))
// d3dpp.FullScreen_RefreshRateInHz = mode.RefreshRate;
if (_initGfxCallback != nullptr)
_initGfxCallback(&d3dpp);
bool first_time_init = direct3ddevice == nullptr;
HRESULT hr = 0;
if (direct3ddevice)
{
hr = ResetD3DDevice();
}
else
{
const UINT use_adapter = SDL_Direct3D9GetAdapterIndex(use_display);
hr = direct3d->CreateDevice(use_adapter, D3DDEVTYPE_HAL, hwnd,
D3DCREATE_MIXED_VERTEXPROCESSING | D3DCREATE_MULTITHREADED, // multithreaded required for AVI player
&d3dpp, direct3ddevice.Acquire());
}
if (hr != D3D_OK)
{
if (!previousError.IsEmpty())
SDL_SetError(previousError.GetCStr());
else
SDL_SetError("Failed to create Direct3D Device: 0x%08X", hr);
return false;
}
if (first_time_init)
{
if (!FirstTimeInit())
return false;
}
else
{
// Only adjust window styles in non-fullscreen modes:
// for real fullscreen Direct3D will adjust the window and display.
if (!mode.IsRealFullscreen())
{
sys_window_set_style(mode.Mode, Size(mode.Width, mode.Height));
sys_window_bring_to_front();
}
}
return true;
}
void D3DGraphicsDriver::SetBlendOp(D3DBLENDOP blend_op, D3DBLEND src_factor, D3DBLEND dst_factor)
{
direct3ddevice->SetRenderState(D3DRS_BLENDOP, blend_op);
direct3ddevice->SetRenderState(D3DRS_SRCBLEND, src_factor);
direct3ddevice->SetRenderState(D3DRS_DESTBLEND, dst_factor);
}
void D3DGraphicsDriver::SetBlendOpAlpha(D3DBLENDOP blend_op, D3DBLEND src_factor, D3DBLEND dst_factor)
{
direct3ddevice->SetRenderState(D3DRS_BLENDOPALPHA, blend_op);
direct3ddevice->SetRenderState(D3DRS_SRCBLENDALPHA, src_factor);
direct3ddevice->SetRenderState(D3DRS_DESTBLENDALPHA, dst_factor);
}
void D3DGraphicsDriver::InitializeD3DState()
{
direct3ddevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_RGBA(0, 0, 0, 255), 0.5f, 0);
// set the render flags.
direct3ddevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
direct3ddevice->SetRenderState(D3DRS_LIGHTING, true);
direct3ddevice->SetRenderState(D3DRS_ZENABLE, FALSE);
direct3ddevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
SetBlendOp(D3DBLENDOP_ADD, D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA);
direct3ddevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
direct3ddevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
direct3ddevice->SetRenderState(D3DRS_ALPHAREF, (DWORD)0);
direct3ddevice->SetFVF(D3DFVF_CUSTOMVERTEX);
D3DMATERIAL9 material;
ZeroMemory(&material, sizeof(material)); //zero memory ( NEW )
material.Diffuse.r = 1.0f; //diffuse color ( NEW )
material.Diffuse.g = 1.0f;
material.Diffuse.b = 1.0f;
direct3ddevice->SetMaterial(&material);
D3DLIGHT9 d3dLight;
ZeroMemory(&d3dLight, sizeof(D3DLIGHT9));
// Set up a white point light.
d3dLight.Type = D3DLIGHT_DIRECTIONAL;
d3dLight.Diffuse.r = 1.0f;
d3dLight.Diffuse.g = 1.0f;
d3dLight.Diffuse.b = 1.0f;
d3dLight.Diffuse.a = 1.0f;
d3dLight.Ambient.r = 1.0f;
d3dLight.Ambient.g = 1.0f;
d3dLight.Ambient.b = 1.0f;
d3dLight.Specular.r = 1.0f;
d3dLight.Specular.g = 1.0f;
d3dLight.Specular.b = 1.0f;
// Position it high in the scene and behind the user.
// Remember, these coordinates are in world space, so
// the user could be anywhere in world space, too.
// For the purposes of this example, assume the user
// is at the origin of world space.
d3dLight.Direction.x = 0.0f;
d3dLight.Direction.y = 0.0f;
d3dLight.Direction.z = 1.0f;
// Don't attenuate.
d3dLight.Attenuation0 = 1.0f;
d3dLight.Range = 1000.0f;
// Set the property information for the first light.
direct3ddevice->SetLight(0, &d3dLight);
direct3ddevice->LightEnable(0, TRUE);
// Set gamma
direct3ddevice->SetGammaRamp(0, D3DSGR_NO_CALIBRATION, ¤tgammaramp);
// If we already have a render frame configured, then setup viewport immediately
SetupViewport();
}
void D3DGraphicsDriver::SetupViewport()
{
if (!IsModeSet() || !IsRenderFrameValid() || !IsNativeSizeValid())
return;
const float src_width = _srcRect.GetWidth();
const float src_height = _srcRect.GetHeight();
const float disp_width = _mode.Width;
const float disp_height = _mode.Height;
// Setup orthographic projection matrix
glm::mat4 identity(1.f);
glm::mat4 mat_ortho = glmex::ortho_d3d(src_width, src_height);
direct3ddevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)glm::value_ptr(identity));
direct3ddevice->SetTransform(D3DTS_VIEW, (D3DMATRIX*)glm::value_ptr(identity));
direct3ddevice->SetTransform(D3DTS_PROJECTION, (D3DMATRIX*)glm::value_ptr(mat_ortho));
// See "Directly Mapping Texels to Pixels" MSDN article for why this is necessary
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb219690.aspx
_pixelRenderXOffset = (src_width / disp_width) / 2.0f;
_pixelRenderYOffset = (src_height / disp_height) / 2.0f;
// Clear the screen before setting a viewport.
ClearScreenRect(RectWH(0, 0, _mode.Width, _mode.Height), nullptr);
// Set Viewport.
SetD3DViewport(_dstRect);
D3DSurfacePtr backbuffer;
HRESULT hr = direct3ddevice->GetRenderTarget(0, backbuffer.Acquire());
assert(hr == D3D_OK);
_screenBackbuffer = BackbufferState(std::move(backbuffer), Size(_mode.Width, _mode.Height), _srcRect.GetSize(),
_dstRect, mat_ortho, _scaling, _filter ? _filter->GetSamplerStateForStandardSprite() : D3DTEXF_POINT);
// View and Projection matrixes are currently fixed in Direct3D renderer
_stageMatrixes.View = identity;
_stageMatrixes.Projection = mat_ortho;
}
void D3DGraphicsDriver::SetGraphicsFilter(PD3DFilter filter)
{
_filter = filter;
_screenBackbuffer.Filter = _filter->GetSamplerStateForStandardSprite();
OnSetFilter();
}
void D3DGraphicsDriver::SetTintMethod(TintMethod method)
{
_legacyPixelShader = (method == TintReColourise);
}
bool D3DGraphicsDriver::SetDisplayMode(const DisplayMode &mode)
{
ReleaseDisplayMode();
if (mode.ColorDepth < 15)
{
SDL_SetError("Direct3D driver does not support 256-color display mode");
return false;
}
if (!CreateDisplayMode(mode))
return false;
OnInit();
DisplayMode set_mode = mode;
set_mode.DisplayIndex = sys_get_window_display_index();
OnModeSet(set_mode);
if ((_fullscreenDisplay < 0) || set_mode.IsRealFullscreen())
_fullscreenDisplay = set_mode.DisplayIndex;
InitializeD3DState();
CreateVirtualScreen();
return true;
}
void D3DGraphicsDriver::UpdateDeviceScreen(const Size &screen_sz)
{
if (_mode.IsRealFullscreen())
return; // ignore in exclusive fs mode
_mode.Width = screen_sz.Width;
_mode.Height = screen_sz.Height;
// TODO: following resets D3D9 device, which may be sub-optimal;
// there seem to be an option to not do this if new window size is smaller
// and SWAPEFFECT_COPY flag is set, in which case (supposedly) we could
// draw using same device parameters, but adjusting viewport accordingly.
d3dpp.BackBufferWidth = _mode.Width;
d3dpp.BackBufferHeight = _mode.Height;
HRESULT hr = ResetDeviceAndRestore();
if (hr != D3D_OK)
{
Debug::Printf("D3DGraphicsDriver: Failed to reset D3D device");
return;
}
// Display mode could've changed, so re-setup viewport, matrixes, etc
SetupViewport();
}
void D3DGraphicsDriver::CreateVirtualScreen()
{
if (!IsModeSet() || !IsNativeSizeValid())
return;
// Set up native surface
// TODO: maybe not do this always, but only allocate if necessary
// when render option is set, or temporarily for making a screenshot.
if (_nativeSurface)
{
DestroyDDB(_nativeSurface);
_nativeSurface = nullptr;
}
_nativeSurface = (D3DBitmap*)CreateRenderTargetDDB(
_srcRect.GetWidth(), _srcRect.GetHeight(), _mode.ColorDepth, true);
glm::mat4 mat_ortho = glmex::ortho_d3d(_srcRect.GetWidth(), _srcRect.GetHeight());
_nativeBackbuffer = BackbufferState(_nativeSurface->_renderSurface,
_srcRect.GetSize(), _srcRect.GetSize(), _srcRect, mat_ortho, PlaneScaling(), D3DTEXF_POINT);
// Preset initial stage screen for plugin raw drawing
SetStageScreen(0, _srcRect.GetSize());
}
HRESULT D3DGraphicsDriver::ResetD3DDevice()
{
// Direct3D documentation:
// Before calling the IDirect3DDevice9::Reset method for a device,
// an application should release any explicit render targets, depth stencil
// surfaces, additional swap chains, state blocks, and D3DPOOL_DEFAULT
// resources associated with the device.
_screenBackbuffer = BackbufferState();
_nativeBackbuffer = BackbufferState();
if (_nativeSurface)
{
DestroyDDB(_nativeSurface);
_nativeSurface = nullptr;
}
ReleaseRenderTargetData();
HRESULT hr = direct3ddevice->Reset(&d3dpp);
if (hr != D3D_OK)
return hr;
RecreateRenderTargets();
return D3D_OK;
}
void D3DGraphicsDriver::ReleaseRenderTargetData()
{
// Remove RT surface ref from all the existing batches
for (auto &batch : _spriteBatches)
{
batch.RenderSurface = nullptr;
}
for (auto &batch : _backupBatches)
{
batch.RenderSurface = nullptr;
}
// Release the RTs internal data
for (auto &ddb : _renderTargets)
{
ddb->ReleaseTextureData();
}
}
void D3DGraphicsDriver::RecreateRenderTargets()
{
for (auto &ddb : _renderTargets)
{
ddb->ReleaseTextureData();
// FIXME: this ugly accessing internal texture members
ddb->_data.reset(reinterpret_cast<D3DTexture*>(CreateTexture(ddb->_width, ddb->_height, ddb->_colDepth, ddb->_opaque, true)));
auto &tex = ddb->_data->_tiles[0].texture;
HRESULT hr = tex->GetSurfaceLevel(0, ddb->_renderSurface.Acquire());
assert(hr == D3D_OK);
}
// Reappoint RT surfaces in existing batches
for (auto &batch : _spriteBatches)
{
if (batch.RenderTarget)
{
assert(!batch.RenderSurface);
batch.RenderSurface = ((D3DBitmap*)batch.RenderTarget)->_renderSurface;
}
}
for (auto &batch : _backupBatches)
{
if (batch.RenderTarget)
{
assert(!batch.RenderSurface);
batch.RenderSurface = ((D3DBitmap*)batch.RenderTarget)->_renderSurface;
}
}
}
bool D3DGraphicsDriver::SetNativeResolution(const GraphicResolution &native_res)
{
OnSetNativeRes(native_res);
// Also make sure viewport is updated using new native & destination rectangles
SetupViewport();
CreateVirtualScreen();
return !_srcRect.IsEmpty();
}
bool D3DGraphicsDriver::SetRenderFrame(const Rect &dst_rect)
{
OnSetRenderFrame(dst_rect);
// Also make sure viewport is updated using new native & destination rectangles
SetupViewport();
return !_dstRect.IsEmpty();
}
int D3DGraphicsDriver::GetDisplayDepthForNativeDepth(int /*native_color_depth*/) const
{
// TODO: check for device caps to know which depth is supported?
return 32;
}
IGfxModeList *D3DGraphicsDriver::GetSupportedModeList(int display_index, int color_depth)
{
return new D3DGfxModeList(direct3d, display_index, color_depth_to_d3d_format(color_depth, false));
}
PGfxFilter D3DGraphicsDriver::GetGraphicsFilter() const
{
return _filter;
}
void D3DGraphicsDriver::UnInit()
{
OnUnInit();
ReleaseDisplayMode();
if (_nativeSurface)
{
DestroyDDB(_nativeSurface);
_nativeSurface = nullptr;
}
_nativeBackbuffer = BackbufferState();
vertexbuffer = nullptr;
pixelShader = nullptr;
direct3ddevice = nullptr;
sys_window_destroy();
}
D3DGraphicsDriver::~D3DGraphicsDriver()
{
D3DGraphicsDriver::UnInit();
}
void D3DGraphicsDriver::ClearRectangle(int x1, int y1, int x2, int y2, RGB *colorToUse)
{
// NOTE: this function is practically useless at the moment, because D3D redraws whole game frame each time
if (!direct3ddevice) return;
Rect r(x1, y1, x2, y2);
r = _scaling.ScaleRange(r);
ClearScreenRect(r, colorToUse);
}
void D3DGraphicsDriver::ClearScreenRect(const Rect &r, RGB *colorToUse)
{
D3DRECT rectToClear;
RectToRECT(r, rectToClear);
DWORD colorDword = 0;
if (colorToUse != nullptr)
colorDword = D3DCOLOR_XRGB(colorToUse->r, colorToUse->g, colorToUse->b);
direct3ddevice->Clear(1, &rectToClear, D3DCLEAR_TARGET, colorDword, 0.5f, 0);
}
void D3DGraphicsDriver::GetCopyOfScreenIntoDDB(IDriverDependantBitmap *target, uint32_t batch_skip_filter)
{
// If we normally render in screen res, restore last frame's lists and
// render in native res on the given target;
// Also force re-render last frame if we require batch filtering
if (_renderAtScreenRes || (batch_skip_filter != 0))
{
bool old_render_res = _renderAtScreenRes;
_renderAtScreenRes = false;
RedrawLastFrame(batch_skip_filter);
Render(target);
_renderAtScreenRes = old_render_res;
}
else
{
// If we normally render in native res, then simply render backbuffer contents
D3DBitmap *bitmap = (D3DBitmap*)target;
Size surf_sz(bitmap->_width, bitmap->_height);
BackbufferState backbuffer = BackbufferState(bitmap->_renderSurface, surf_sz, surf_sz,
RectWH(0, 0, surf_sz.Width, surf_sz.Height), glmex::ortho_d3d(surf_sz.Width, surf_sz.Height),
PlaneScaling(), D3DTEXF_POINT);
SetBackbufferState(&backbuffer, true);
if (direct3ddevice->BeginScene() != D3D_OK)
{
throw Ali3DException("IDirect3DDevice9::BeginScene failed");
}
RenderTexture(_nativeSurface, 0, 0, glmex::identity(), SpriteColorTransform(), _srcRect.GetSize());
direct3ddevice->EndScene();
}
}
bool D3DGraphicsDriver::GetCopyOfScreenIntoBitmap(Bitmap *destination,
const Rect *src_rect, bool at_native_res,
GraphicResolution *want_fmt, uint32_t batch_skip_filter)
{
// Currently don't support copying in screen resolution when we are rendering in native
if (!_renderAtScreenRes)
at_native_res = true;
Rect copy_from = src_rect ? *src_rect : _srcRect;
if (!at_native_res)
copy_from = _scaling.ScaleRange(copy_from);
if (destination->GetColorDepth() != _mode.ColorDepth || destination->GetSize() != copy_from.GetSize())
{
if (want_fmt)
*want_fmt = GraphicResolution(copy_from.GetWidth(), copy_from.GetHeight(), _mode.ColorDepth);
return false;
}
// If we are rendering sprites at the screen resolution, and requested native res,
// re-render last frame to the native surface;
// Also force re-render last frame if we require batch filtering
if ((at_native_res && _renderAtScreenRes) || (batch_skip_filter != 0))
{
bool old_render_res = _renderAtScreenRes;
_renderAtScreenRes = !at_native_res;
RedrawLastFrame(batch_skip_filter);
RenderImpl(true);
_renderAtScreenRes = old_render_res;
}
D3DSurfacePtr surface;
{
Rect viewport;
if (at_native_res)
{
// with render to texture the texture mipmap surface can't be locked directly
// we have to create a surface with D3DPOOL_SYSTEMMEM for GetRenderTargetData
if (direct3ddevice->CreateOffscreenPlainSurface(
_srcRect.GetWidth(),
_srcRect.GetHeight(),
color_depth_to_d3d_format(_mode.ColorDepth, false),
D3DPOOL_SYSTEMMEM,
surface.Acquire(),
NULL) != D3D_OK)
{
throw Ali3DException("CreateOffscreenPlainSurface failed");
}