Repository navigation
Expand file tree
/
Copy pathd3d8_device.c
More file actions
4481 lines (4176 loc) · 198 KB
/
Copy pathd3d8_device.c
File metadata and controls
4481 lines (4176 loc) · 198 KB
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
/**
* D3D8→D3D11 Compatibility Device Implementation
*
* Implements the Xbox D3D8 IDirect3DDevice8 interface using D3D11.
* The game's translated RenderWare code calls D3D8 methods through
* COM vtables; this layer translates those calls to D3D11 equivalents.
*
* Architecture:
* - D3D11 device and swap chain created during initialization
* - Render state tracking: D3D8 states mapped to D3D11 state objects
* - Texture/buffer management: D3D8 resource handles wrap D3D11 resources
* - Fixed-function pipeline: emulated via D3D11 shaders (the Xbox D3D8
* pipeline is configurable but not fully programmable)
*
* Build: Requires Windows SDK with d3d11.h and dxgi.h
*/
#include "d3d8_internal.h"
#include <dxgi1_6.h>
#include "kernel/preview_log.h"
#include "d3d8_scaled_lines.h"
#include "d3d8_triangle_depth.h"
#include "d3d8_compiler.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Device diagnostics are launch options, not live renderer state. Only literal
* keys are used here; retain absent values as well as present/empty strings so
* a disabled capture does not rescan the CRT environment on every draw. Live
* screenshot requests still use g_debug_armed/forced_capture_path below. Like
* the D3D11 immediate context, this cache is owned by the rendering thread. */
static const char *d3d8_cached_getenv(const char *name)
{
typedef struct D3D8EnvCacheEntry {
const char *name;
const char *value;
} D3D8EnvCacheEntry;
static D3D8EnvCacheEntry cache[64];
uintptr_t key = (uintptr_t)name;
size_t index = (size_t)((key >> 4u) ^ (key >> 12u)) & 63u;
size_t probe;
for (probe = 0u; probe < 64u; ++probe) {
D3D8EnvCacheEntry *entry = &cache[(index + probe) & 63u];
if (entry->name == name)
return entry->value;
if (entry->name == NULL) {
entry->name = name;
entry->value = getenv(name);
return entry->value;
}
}
return getenv(name);
}
/* ================================================================
* Internal device state
* ================================================================ */
/* Maximum tracked render states, texture stages, and transforms */
#define MAX_RENDER_STATES 256
#define MAX_TEXTURE_STAGES 4
#define MAX_TSS_STATES 32
#define MAX_TRANSFORMS 512
#define MAX_LIGHTS 8
typedef struct D3D8DeviceState {
/* D3D11 objects */
ID3D11Device *d3d11_device;
ID3D11DeviceContext *d3d11_context;
IDXGISwapChain *swap_chain;
BOOL flip_model;
UINT swap_chain_flags;
/* Default render targets */
ID3D11RenderTargetView *default_rtv;
ID3D11DepthStencilView *default_dsv;
ID3D11Texture2D *default_depth;
ID3D11Texture2D *cpu_frame_texture;
ID3D11ShaderResourceView *cpu_frame_srv;
ID3D11RenderTargetView *current_rtv;
ID3D11DepthStencilView *current_dsv;
UINT current_target_width;
UINT current_target_height;
UINT current_target_physical_width;
UINT current_target_physical_height;
ID3D11VertexShader *resolve_vs;
ID3D11PixelShader *resolve_ps;
ID3D11SamplerState *resolve_sampler;
ID3D11PixelShader *packed_color_depth_ps;
ID3D11DepthStencilState *packed_color_depth_state;
BOOL packed_color_depth_checked;
ID3D11PixelShader *packed_color_depth_fallback_ps;
ID3D11DepthStencilState *packed_color_depth_fallback_state;
ID3D11PixelShader *packed_color_stencil_bit_ps[8];
ID3D11DepthStencilState *packed_color_stencil_bit_state[8];
BOOL packed_color_depth_fallback_checked;
ID3D11PixelShader *depth_alias_ps;
ID3D11PixelShader *depth_alias_uniform_ps;
ID3D11DepthStencilState *depth_alias_uniform_state;
ID3D11PixelShader *depth_alias_stencil_bit_ps[8];
ID3D11DepthStencilState *depth_alias_stencil_bit_state[8];
ID3D11Buffer *depth_alias_cb;
ID3D11Texture2D *depth_alias_source_texture;
ID3D11ShaderResourceView *depth_alias_source_depth_srv;
ID3D11ShaderResourceView *depth_alias_source_stencil_srv;
UINT depth_alias_source_width;
UINT depth_alias_source_height;
ID3D11BlendState *host_overlay_blend;
ID3D11PixelShader *pvideo_ps;
ID3D11Buffer *pvideo_cb;
ID3D11Texture2D *pvideo_texture;
ID3D11ShaderResourceView *pvideo_srv;
UINT pvideo_width;
UINT pvideo_height;
ID3D11PixelShader *masked_clear_ps;
ID3D11Buffer *masked_clear_cb;
ID3D11BlendState *masked_clear_blend[16];
/* Window */
HWND hwnd;
UINT width;
UINT height;
D3DFORMAT backbuffer_format;
/* State tracking */
DWORD render_states[MAX_RENDER_STATES];
DWORD tss[MAX_TEXTURE_STAGES][MAX_TSS_STATES];
D3DMATRIX transforms[MAX_TRANSFORMS];
D3DVIEWPORT8 viewport;
D3DMATERIAL8 material;
D3DLIGHT8 lights[MAX_LIGHTS];
BOOL light_enable[MAX_LIGHTS];
D3DGAMMARAMP gamma_ramp;
BOOL gamma_ramp_valid;
/* Current shader/FVF */
DWORD vertex_shader;
DWORD pixel_shader;
/* Scene state */
BOOL in_scene;
/* Reference count */
LONG ref_count;
} D3D8DeviceState;
/* Global device instance (Xbox has a single D3D device) */
static D3D8DeviceState g_device_state;
#include "d3d8_frame_timing.h"
static BOOL g_pending_scanout_present;
static BOOL g_vsync_enabled = FALSE;
static uint64_t g_frame_submissions, g_frame_interval_serial;
static uint32_t g_frame_intervals_us[512], g_frame_interval_count, g_frame_interval_next;
static LARGE_INTEGER g_frame_frequency, g_frame_previous;
static uint32_t g_debug_submission_source;
void d3d8_DebugSetSubmissionSource(uint32_t source) { g_debug_submission_source = source; }
uint32_t d3d8_DebugGetSubmissionSource(void) { return g_debug_submission_source; }
static void (*g_debug_submission_callback)(uint64_t, int64_t, int64_t);
void d3d8_DebugSetSubmissionCallback(void (*callback)(uint64_t, int64_t, int64_t))
{
g_debug_submission_callback = callback;
}
static void record_frame_submission(void)
{
LARGE_INTEGER now;
++g_frame_submissions;
if (!g_frame_frequency.QuadPart) QueryPerformanceFrequency(&g_frame_frequency);
if (g_frame_frequency.QuadPart <= 0 || !QueryPerformanceCounter(&now)) return;
if (g_frame_previous.QuadPart && now.QuadPart >= g_frame_previous.QuadPart) {
double us = (double)(now.QuadPart - g_frame_previous.QuadPart) *
1000000.0 / (double)g_frame_frequency.QuadPart;
g_frame_intervals_us[g_frame_interval_next] =
us > 4294967295.0 ? UINT32_MAX : (uint32_t)us;
++g_frame_interval_serial;
g_frame_interval_next = (g_frame_interval_next + 1u) & 511u;
if (g_frame_interval_count < 512u) ++g_frame_interval_count;
}
g_frame_previous = now;
if (g_debug_submission_callback)
g_debug_submission_callback(g_frame_submissions, now.QuadPart, g_frame_frequency.QuadPart);
}
static int compare_frame_intervals(const void *a, const void *b)
{
uint32_t x = *(const uint32_t *)a, y = *(const uint32_t *)b;
return (x > y) - (x < y);
}
void d3d8_GetFrameTimingSnapshot(D3D8FrameTimingSnapshot *out)
{
uint32_t values[512], count = g_frame_interval_count;
uint64_t sum = 0;
if (!out) return;
memset(out, 0, sizeof(*out));
out->submitted_frames = g_frame_submissions; out->samples = count;
if (!count) return;
memcpy(values, g_frame_intervals_us, count * sizeof(values[0]));
qsort(values, count, sizeof(values[0]), compare_frame_intervals);
for (uint32_t i = 0; i < count; ++i) sum += values[i];
out->mean_ms = (double)sum / (double)count / 1000.0;
out->p50_ms = values[(count * 50u + 99u) / 100u - 1u] / 1000.0;
out->p95_ms = values[(count * 95u + 99u) / 100u - 1u] / 1000.0;
out->p99_ms = values[(count * 99u + 99u) / 100u - 1u] / 1000.0;
out->max_ms = values[count - 1u] / 1000.0;
}
uint32_t d3d8_GetFrameIntervalHistory(uint64_t after_serial, uint32_t *out,
uint32_t capacity, uint64_t *serial)
{
uint64_t available = after_serial <= g_frame_interval_serial ?
g_frame_interval_serial - after_serial : 0;
uint32_t count, first;
if (serial) *serial = g_frame_interval_serial;
if (!out || !capacity) return 0;
if (available > g_frame_interval_count) available = g_frame_interval_count;
if (available > capacity) available = capacity;
count = (uint32_t)available;
first = (g_frame_interval_next + 512u - count) & 511u;
for (uint32_t i = 0; i < count; ++i)
out[i] = g_frame_intervals_us[(first + i) & 511u];
return count;
}
static void (*g_host_overlay_callback)(void);
void d3d8_SetHostOverlayCallback(void (*callback)(void)){g_host_overlay_callback=callback;}
/* Preserve Present's result; querying removal reason is failure-only. */
static HRESULT preview_present(IDXGISwapChain *chain, UINT flags)
{
const UINT sync = g_vsync_enabled ? 1u : 0u;
flags &= ~DXGI_PRESENT_ALLOW_TEARING;
if (g_device_state.flip_model && sync == 0u &&
(g_device_state.swap_chain_flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING)) {
BOOL fullscreen = FALSE;
if (SUCCEEDED(IDXGISwapChain_GetFullscreenState(chain, &fullscreen, NULL)) && !fullscreen)
flags |= DXGI_PRESENT_ALLOW_TEARING;
}
if(g_host_overlay_callback && !(flags & DXGI_PRESENT_TEST))g_host_overlay_callback();
HRESULT result = IDXGISwapChain_Present(chain, sync, flags);
/* Flip presentation unbinds back buffer zero. Restore the tracked guest
* output target as well: guest rendering can still be on an offscreen RT. */
if (g_device_state.flip_model && SUCCEEDED(result) && g_device_state.current_rtv)
ID3D11DeviceContext_OMSetRenderTargets(g_device_state.d3d11_context, 1u,
&g_device_state.current_rtv, g_device_state.current_dsv);
/* Direct FLIP_STALL presentation consumes any deferred host submission too.
* Leaving the flag armed would later Present a discarded/stale backbuffer. */
g_pending_scanout_present = FALSE;
if (result == S_OK) record_frame_submission();
if (FAILED(result))
xbox_preview_log_event("graphics-error", "Present HRESULT=%08lX removal_reason=%08lX",
result, g_device_state.d3d11_device ?
ID3D11Device_GetDeviceRemovedReason(g_device_state.d3d11_device) : S_OK);
return result;
}
static IDirect3DDevice8 g_device;
static BOOL g_device_initialized = FALSE;
static UINT g_presentation_aspect_width = 4u;
static UINT g_presentation_aspect_height = 3u;
static UINT g_frame_cap_fps = 30u;
static LONGLONG g_next_frame_slot;
void d3d8_SetPresentationAspect(UINT width, UINT height)
{
if (width != 0u && height != 0u) {
g_presentation_aspect_width = width;
g_presentation_aspect_height = height;
}
}
void d3d8_SetFrameCap(UINT fps)
{
if (fps != 0u && fps != 30u && fps != 60u && fps != 90u && fps != 120u)
fps = 30u;
if (g_frame_cap_fps != fps) {
g_frame_cap_fps = fps;
g_next_frame_slot = 0; /* Do not inherit a deadline from the old cap. */
}
}
void d3d8_SetVSync(BOOL enabled)
{
enabled = !!enabled;
if (g_vsync_enabled != enabled) {
g_vsync_enabled = enabled;
g_next_frame_slot = 0; /* Presentation can now block for a different interval. */
}
}
/* Current resource bindings */
static IDirect3DVertexBuffer8 *g_cur_vb = NULL;
static UINT g_cur_vb_stride = 0;
static IDirect3DIndexBuffer8 *g_cur_ib = NULL;
static UINT g_cur_ib_base_vertex = 0;
static IDirect3DBaseTexture8 *g_cur_textures[4] = { NULL };
/* Forward declarations */
static const IDirect3DDevice8Vtbl g_device_vtbl;
static void up_ring_shutdown(void);
/* ================================================================
* Public frame pump (called from recompiled game code)
* ================================================================ */
static void d3d8_pump_host_messages(void)
{
MSG msg;
while (PeekMessageA(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT) {
fprintf(stderr, "[HOST-WINDOW] WM_QUIT site=frame-pump code=%llu\n",
(unsigned long long)msg.wParam);
fflush(stderr);
/* Run registered plugin/log cleanup on a normal exit. */
exit(0);
}
TranslateMessage(&msg);
DispatchMessageA(&msg);
}
}
static BOOL g_debug_capture_at_flip;
static BOOL g_debug_force_capture;
static unsigned int g_present_frame_count;
static char g_debug_armed_capture_path[MAX_PATH];
static char g_debug_forced_capture_path[MAX_PATH];
static void (*g_debug_present_callback)(void);
static void d3d8_debug_backbuffer_stats(void);
static void d3d8_debug_capture_display_refresh(ULONGLONG now_ms);
static void d3d8_debug_detect_present_flash(ULONGLONG now_ms);
void d3d8_DebugSetPresentCallback(void (*callback)(void))
{
g_debug_present_callback = callback;
}
void d3d8_DebugArmFlipCapture(const char *path)
{
if (!path || !path[0] || g_debug_armed_capture_path[0])
return;
strncpy_s(g_debug_armed_capture_path,
sizeof(g_debug_armed_capture_path), path, _TRUNCATE);
fprintf(stderr, "D3D8: armed event-relative flip capture: %s\n",
g_debug_armed_capture_path);
}
/* Last pacing wait overshoot; uses the existing QPC samples, never another wait. */
static LONGLONG g_frame_pacing_late_ticks;
void d3d8_WaitForGuestFrameSlot(void)
{
static LARGE_INTEGER frequency;
static int initialized;
LARGE_INTEGER now;
LONGLONG interval;
g_frame_pacing_late_ticks = 0;
if (g_frame_cap_fps == 0u ||
d3d8_cached_getenv("MERCENARIES_DISABLE_FLIP_PACING") != NULL) {
g_next_frame_slot = 0;
return;
}
if (!initialized) {
QueryPerformanceFrequency(&frequency);
initialized = 1;
}
if (frequency.QuadPart <= 0)
return;
QueryPerformanceCounter(&now);
/* Pace each completed guest frame, whether it reaches scanout directly at
* FLIP_STALL or after a deferred AA resolve. This controls distinct
* simulated/rendered frames rather than host repeats. The independent Xbox
* vblank service stays at 60 Hz; it does not define this user-selected cap. */
interval = frequency.QuadPart / g_frame_cap_fps;
if (interval < 1) interval = 1;
if (g_next_frame_slot == 0) {
g_next_frame_slot = now.QuadPart + interval;
} else if (now.QuadPart >= g_next_frame_slot) {
/* A slow frame has already missed its slot. Rebase the next deadline
* and return immediately: sleeping another complete interval here
* turns a GPU-limited 16 fps workload into roughly 12 fps and causes
* a recurring hitch. This does not uncap fast frames; their deadline
* remains in the future and they still wait below. */
g_next_frame_slot = now.QuadPart + interval;
return;
}
while (now.QuadPart < g_next_frame_slot) {
const LONGLONG remaining = g_next_frame_slot - now.QuadPart;
const DWORD remaining_ms =
(DWORD)((remaining * 1000) / frequency.QuadPart);
if (remaining_ms > 1)
Sleep(remaining_ms - 1);
else
SwitchToThread();
QueryPerformanceCounter(&now);
}
g_frame_pacing_late_ticks = now.QuadPart - g_next_frame_slot;
g_next_frame_slot += interval;
}
void d3d8_PresentFrame(void)
{
static int trace_timing = -1;
static LONGLONG trace_period_ticks, previous_start_ticks, previous_end_ticks;
static double trace_ticks_per_ms;
static UINT trace_calls;
static uint64_t trace_previous_submissions, trace_other_submissions;
static double trace_max_duration_ms, trace_max_gap_ms;
static double trace_max_prepare_ms, trace_max_wait_ms, trace_max_present_ms;
ULONGLONG start_ms;
LARGE_INTEGER trace_start = {0}, trace_prepared = {0};
LARGE_INTEGER trace_waited = {0}, trace_end = {0};
double trace_gap_ms = 0.0, trace_outside_ms = 0.0;
uint64_t trace_submissions_before = 0u, trace_submissions_between = 0u;
if (trace_timing < 0) {
LARGE_INTEGER frequency;
trace_timing = d3d8_cached_getenv("MERCENARIES_TRACE_PRESENT_TIMING") != NULL;
if (trace_timing) {
trace_timing = QueryPerformanceFrequency(&frequency) && frequency.QuadPart > 0;
if (trace_timing)
trace_ticks_per_ms = (double)frequency.QuadPart / 1000.0;
}
}
start_ms = GetTickCount64();
if (trace_timing) {
/* TickCount quantization can turn a ~33 ms gap into 47 ms. Use QPC
* for attribution; keep the existing millisecond capture clock. */
QueryPerformanceCounter(&trace_start);
trace_submissions_before = g_frame_submissions;
trace_submissions_between = trace_submissions_before - trace_previous_submissions;
if (previous_start_ticks != 0)
trace_gap_ms = (trace_start.QuadPart - previous_start_ticks) / trace_ticks_per_ms;
if (previous_end_ticks != 0)
trace_outside_ms = (trace_start.QuadPart - previous_end_ticks) / trace_ticks_per_ms;
if (trace_gap_ms > trace_max_gap_ms)
trace_max_gap_ms = trace_gap_ms;
previous_start_ticks = trace_start.QuadPart;
}
d3d8_pump_host_messages();
++g_present_frame_count;
if (g_debug_present_callback)
g_debug_present_callback();
if (g_debug_force_capture || g_debug_armed_capture_path[0] ||
d3d8_cached_getenv("MERCENARIES_CAPTURE_FLIP_PATH") != NULL) {
g_debug_capture_at_flip = TRUE;
d3d8_debug_backbuffer_stats();
g_debug_capture_at_flip = FALSE;
}
/* Sample the actual new frame before Present. Capturing from the periodic
* vblank service when it has no new scanout observes a discarded DXGI
* back buffer rather than the image currently visible on screen. */
d3d8_debug_capture_display_refresh(start_ms);
/* Direct FLIP_STALL completion uses the shared guest-frame clock. A
* deferred AA resolve uses the same clock from the scanout service. V-Sync
* is opt-in: forcing it previously stalled XMV playback. Keep the limiter
* before Present so any presentation wait counts toward its next deadline. */
if (trace_timing)
QueryPerformanceCounter(&trace_prepared);
d3d8_WaitForGuestFrameSlot();
if (trace_timing)
QueryPerformanceCounter(&trace_waited);
if (g_device_state.swap_chain)
preview_present(g_device_state.swap_chain, 0);
if (trace_timing) {
double prepare_ms, wait_ms, present_ms, duration_ms;
uint32_t submitted_interval_us;
QueryPerformanceCounter(&trace_end);
prepare_ms = (trace_prepared.QuadPart - trace_start.QuadPart) / trace_ticks_per_ms;
wait_ms = (trace_waited.QuadPart - trace_prepared.QuadPart) / trace_ticks_per_ms;
present_ms = (trace_end.QuadPart - trace_waited.QuadPart) / trace_ticks_per_ms;
duration_ms = (trace_end.QuadPart - trace_start.QuadPart) / trace_ticks_per_ms;
previous_end_ticks = trace_end.QuadPart;
submitted_interval_us = g_frame_submissions > trace_submissions_before && g_frame_interval_count ?
g_frame_intervals_us[(g_frame_interval_next + 511u) & 511u] : 0u;
trace_other_submissions += trace_submissions_between;
if (duration_ms > trace_max_duration_ms) trace_max_duration_ms = duration_ms;
if (prepare_ms > trace_max_prepare_ms) trace_max_prepare_ms = prepare_ms;
if (wait_ms > trace_max_wait_ms) trace_max_wait_ms = wait_ms;
if (present_ms > trace_max_present_ms) trace_max_present_ms = present_ms;
/* Deferred scanout may submit between direct calls. Only actual
* submission intervals or expensive work identify a slow event;
* a long direct-call gap alone is not a missed frame. Include minor
* hitches (>18 ms at 60 Hz), and distinguish scheduler overshoot from
* intentional limiter waiting without changing the pacing policy. */
if (prepare_ms + present_ms >= 8.0 ||
submitted_interval_us > (g_frame_cap_fps ? 1080000u / g_frame_cap_fps : 18000u))
xbox_preview_log_sample("present-slow",
"frame=%u direct_gap_ms=%.3f outside_ms=%.3f prepare_ms=%.3f "
"wait_ms=%.3f present_ms=%.3f total_ms=%.3f other_submissions=%llu "
"submitted_interval_us=%u pacing_late_ms=%.3f",
g_present_frame_count, trace_gap_ms, trace_outside_ms,
prepare_ms, wait_ms, present_ms, duration_ms,
(unsigned long long)trace_submissions_between,
submitted_interval_us,
g_frame_pacing_late_ticks / trace_ticks_per_ms);
trace_previous_submissions = g_frame_submissions;
++trace_calls;
if (trace_period_ticks == 0)
trace_period_ticks = trace_start.QuadPart;
if ((trace_end.QuadPart - trace_period_ticks) / trace_ticks_per_ms >= 1000.0) {
fprintf(stderr,
"[D3D-PRESENT-TIMING] calls=%u max_duration_ms=%.3f "
"max_start_gap_ms=%.3f max_prepare_ms=%.3f "
"max_wait_ms=%.3f max_present_ms=%.3f alternate_submissions=%llu\n",
trace_calls, trace_max_duration_ms, trace_max_gap_ms,
trace_max_prepare_ms, trace_max_wait_ms, trace_max_present_ms,
(unsigned long long)trace_other_submissions);
fflush(stderr);
trace_period_ticks = trace_end.QuadPart;
trace_calls = 0u;
trace_other_submissions = 0u;
trace_max_duration_ms = trace_max_gap_ms = 0.0;
trace_max_prepare_ms = trace_max_wait_ms = trace_max_present_ms = 0.0;
}
}
}
void d3d8_DebugCaptureFrameNow(void)
{
fprintf(stderr, "D3D8: exact draw capture at present %u\n",
g_present_frame_count + 1u);
g_debug_force_capture = TRUE;
d3d8_PresentFrame();
g_debug_force_capture = FALSE;
}
void d3d8_DebugCaptureFrameToPath(const char *path)
{
if (!path || !path[0]) {
d3d8_DebugCaptureFrameNow();
return;
}
strncpy_s(g_debug_forced_capture_path,
sizeof(g_debug_forced_capture_path), path, _TRUNCATE);
fprintf(stderr, "D3D8: exact non-presenting capture at present %u\n",
g_present_frame_count + 1u);
g_debug_force_capture = TRUE;
d3d8_debug_backbuffer_stats();
g_debug_force_capture = FALSE;
g_debug_forced_capture_path[0] = '\0';
}
static int g_debug_display_capture_initialized;
static char g_debug_display_capture_prefix[1024];
static unsigned g_debug_display_capture_interval_ms;
static unsigned g_debug_display_capture_limit;
static unsigned g_debug_display_capture_count;
static ULONGLONG g_debug_display_capture_started_ms;
static ULONGLONG g_debug_display_capture_next_ms;
static char g_debug_queued_capture_path[MAX_PATH];
void d3d8_DebugQueueFrameCapture(const char *path)
{
if (!path || !path[0] || g_debug_queued_capture_path[0]) return;
strncpy_s(g_debug_queued_capture_path, sizeof(g_debug_queued_capture_path),
path, _TRUNCATE);
}
static void d3d8_debug_capture_queued_frame(void)
{
/* Input polling can occur after Present, when a DISCARD swap chain's
* back buffer no longer contains the displayed frame. Consume requests
* only at the next completed scanout, before either presentation path. */
if (!g_debug_queued_capture_path[0]) return;
d3d8_DebugCaptureFrameToPath(g_debug_queued_capture_path);
g_debug_queued_capture_path[0] = '\0';
}
void d3d8_DebugStartDisplayCapture(const char *prefix,
UINT interval_ms, UINT limit)
{
if (!prefix || !prefix[0] || limit == 0u)
return;
if (interval_ms > 60000u)
interval_ms = 60000u;
if (limit > 256u)
limit = 256u;
strncpy_s(g_debug_display_capture_prefix,
sizeof(g_debug_display_capture_prefix), prefix, _TRUNCATE);
g_debug_display_capture_initialized = 1;
g_debug_display_capture_interval_ms = interval_ms;
g_debug_display_capture_limit = limit;
g_debug_display_capture_count = 0u;
g_debug_display_capture_started_ms = GetTickCount64();
g_debug_display_capture_next_ms = g_debug_display_capture_started_ms;
}
static void d3d8_debug_capture_display_refresh(ULONGLONG now_ms)
{
char path[1024];
int length;
d3d8_debug_capture_queued_frame();
d3d8_debug_detect_present_flash(now_ms);
if (!g_debug_display_capture_initialized) {
const char *prefix;
const char *text;
g_debug_display_capture_initialized = 1;
prefix = getenv("MERCENARIES_CAPTURE_DISPLAY_PREFIX");
if (!prefix || !*prefix) return;
strncpy_s(g_debug_display_capture_prefix,
sizeof(g_debug_display_capture_prefix), prefix, _TRUNCATE);
text = getenv("MERCENARIES_CAPTURE_DISPLAY_INTERVAL_MS");
g_debug_display_capture_interval_ms =
text ? (unsigned)strtoul(text, NULL, 10) : 2000u;
text = getenv("MERCENARIES_CAPTURE_DISPLAY_COUNT");
g_debug_display_capture_limit =
text ? (unsigned)strtoul(text, NULL, 10) : 32u;
if (g_debug_display_capture_interval_ms < 250u)
g_debug_display_capture_interval_ms = 250u;
if (g_debug_display_capture_interval_ms > 60000u)
g_debug_display_capture_interval_ms = 60000u;
if (g_debug_display_capture_limit > 256u)
g_debug_display_capture_limit = 256u;
g_debug_display_capture_started_ms = now_ms;
g_debug_display_capture_next_ms =
now_ms + g_debug_display_capture_interval_ms;
}
if (!g_debug_display_capture_prefix[0] ||
g_debug_display_capture_count >= g_debug_display_capture_limit ||
now_ms < g_debug_display_capture_next_ms)
return;
++g_debug_display_capture_count;
g_debug_display_capture_next_ms =
now_ms + g_debug_display_capture_interval_ms;
length = snprintf(path, sizeof(path), "%s-%03u-%llu.bmp",
g_debug_display_capture_prefix,
g_debug_display_capture_count,
(unsigned long long)(now_ms -
g_debug_display_capture_started_ms));
if (length > 0 && (size_t)length < sizeof(path))
d3d8_DebugCaptureFrameToPath(path);
}
BOOL d3d8_ServiceDisplayRefresh(BOOL present_pending_scanout)
{
static LARGE_INTEGER refresh_frequency;
static LONGLONG next_refresh;
LARGE_INTEGER now;
LONGLONG interval;
ULONGLONG now_ms;
d3d8_pump_host_messages();
if (present_pending_scanout)
g_pending_scanout_present = TRUE;
if (refresh_frequency.QuadPart == 0)
QueryPerformanceFrequency(&refresh_frequency);
if (refresh_frequency.QuadPart <= 0)
return FALSE;
QueryPerformanceCounter(&now);
interval = refresh_frequency.QuadPart / 60;
if (interval <= 0)
interval = 1;
if (next_refresh == 0)
next_refresh = now.QuadPart;
if (now.QuadPart < next_refresh)
return FALSE;
if (now.QuadPart - next_refresh >= interval)
next_refresh = now.QuadPart + interval;
else
next_refresh += interval;
if (!g_device_state.swap_chain)
return FALSE;
/* A host vblank tick is not itself a new guest scanout. Re-presenting an
* unchanged DXGI_SWAP_EFFECT_DISCARD chain rotates to undefined/stale
* buffers; during XMV playback that replaced every decoded movie frame
* with the last front-end frame. Preserve the 60 Hz Xbox vblank clock,
* but submit to DXGI only after the deferred NV2A resolve copied a new
* scanout into the host back buffer. Direct FLIP_STALL frames already use
* d3d8_PresentFrame(). */
if (g_pending_scanout_present) {
d3d8_DebugSetSubmissionSource(5u);
now_ms = GetTickCount64();
d3d8_debug_capture_display_refresh(now_ms);
preview_present(g_device_state.swap_chain, 0);
g_pending_scanout_present = FALSE;
}
return TRUE;
}
void d3d8_UploadFrameX8R8G8B8(const void *pixels, UINT source_pitch,
UINT width, UINT height)
{
static BYTE *converted;
static size_t converted_capacity;
static UINT upload_samples;
D3D11_TEXTURE2D_DESC desc;
size_t required;
UINT y;
UINT nonblack_pixels = 0;
HRESULT hr;
if (!pixels || !g_device_state.swap_chain ||
!g_device_state.d3d11_device || !g_device_state.d3d11_context ||
!width || !height || width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION ||
height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION || source_pitch < width * 4u) {
return;
}
required = (size_t)width * height * 4u;
if (required > converted_capacity) {
BYTE *new_buffer = (BYTE *)realloc(converted, required);
if (!new_buffer) return;
converted = new_buffer;
converted_capacity = required;
}
for (y = 0; y < height; ++y) {
const BYTE *src = (const BYTE *)pixels + (size_t)y * source_pitch;
BYTE *dst = converted + (size_t)y * width * 4u;
UINT x;
for (x = 0; x < width; ++x) {
if ((src[x * 4u] | src[x * 4u + 1u] |
src[x * 4u + 2u]) != 0u)
++nonblack_pixels;
dst[x * 4u + 0u] = src[x * 4u + 2u];
dst[x * 4u + 1u] = src[x * 4u + 1u];
dst[x * 4u + 2u] = src[x * 4u + 0u];
dst[x * 4u + 3u] = 0xFFu;
}
}
if (nonblack_pixels == 0u) return;
/* UpdateSubresource with a null box consumes the destination's full
* extent. Upload into a source-sized texture, never the larger swap-chain
* buffer; presentation then handles scaling and aspect ratio normally. */
memset(&desc, 0, sizeof(desc));
if (g_device_state.cpu_frame_texture) {
ID3D11Texture2D_GetDesc(g_device_state.cpu_frame_texture, &desc);
if (desc.Width != width || desc.Height != height) {
ID3D11ShaderResourceView_Release(g_device_state.cpu_frame_srv);
ID3D11Texture2D_Release(g_device_state.cpu_frame_texture);
g_device_state.cpu_frame_srv = NULL;
g_device_state.cpu_frame_texture = NULL;
}
}
if (!g_device_state.cpu_frame_texture) {
memset(&desc, 0, sizeof(desc));
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
hr = ID3D11Device_CreateTexture2D(g_device_state.d3d11_device,
&desc, NULL, &g_device_state.cpu_frame_texture);
if (FAILED(hr)) return;
hr = ID3D11Device_CreateShaderResourceView(g_device_state.d3d11_device,
(ID3D11Resource *)g_device_state.cpu_frame_texture, NULL,
&g_device_state.cpu_frame_srv);
if (FAILED(hr)) {
ID3D11Texture2D_Release(g_device_state.cpu_frame_texture);
g_device_state.cpu_frame_texture = NULL;
return;
}
}
ID3D11DeviceContext_UpdateSubresource(g_device_state.d3d11_context,
(ID3D11Resource *)g_device_state.cpu_frame_texture, 0, NULL,
converted, width * 4u, 0);
d3d8_CopyTextureToBackbuffer(g_device_state.cpu_frame_texture,
g_device_state.cpu_frame_srv, width, height);
if (upload_samples < 5u) {
fprintf(stderr,
"D3D8: Uploaded Xbox framebuffer %ux%u pitch=%u pixels=%u\n",
width, height, source_pitch, nonblack_pixels);
++upload_samples;
}
}
static void d3d8_write_backbuffer_bmp(const char *path,
const D3D11_TEXTURE2D_DESC *desc,
const D3D11_MAPPED_SUBRESOURCE *mapped,
BOOL alpha_view)
{
FILE *fp;
uint8_t header[54] = {0};
uint8_t *row;
const uint32_t row_bytes = (desc->Width * 3u + 3u) & ~3u;
const uint32_t image_bytes = row_bytes * desc->Height;
const uint32_t file_bytes = 54u + image_bytes;
const uint32_t pixel_offset = 54u;
const uint32_t dib_size = 40u;
const uint16_t planes = 1u, bits_per_pixel = 24u;
uint32_t x, y;
if (!path || !*path || !mapped->pData)
return;
fp = fopen(path, "wb");
if (!fp) {
fprintf(stderr, "D3D8: could not write startup capture: %s\n", path);
return;
}
header[0] = 'B'; header[1] = 'M';
memcpy(header + 2, &file_bytes, sizeof(file_bytes));
memcpy(header + 10, &pixel_offset, sizeof(pixel_offset));
memcpy(header + 14, &dib_size, sizeof(dib_size));
memcpy(header + 18, &desc->Width, sizeof(desc->Width));
memcpy(header + 22, &desc->Height, sizeof(desc->Height));
memcpy(header + 26, &planes, sizeof(planes));
memcpy(header + 28, &bits_per_pixel, sizeof(bits_per_pixel));
memcpy(header + 34, &image_bytes, sizeof(image_bytes));
fwrite(header, 1, sizeof(header), fp);
row = (uint8_t *)calloc(1, row_bytes);
if (row) {
for (y = 0; y < desc->Height; ++y) {
const uint8_t *src = (const uint8_t *)mapped->pData +
(size_t)(desc->Height - 1u - y) * mapped->RowPitch;
memset(row, 0, row_bytes);
for (x = 0; x < desc->Width; ++x) {
/* Swap-chain format is R8G8B8A8; BMP stores B,G,R. */
row[x * 3u + 0u] = src[x * 4u + (alpha_view ? 3u : 2u)];
row[x * 3u + 1u] = src[x * 4u + (alpha_view ? 3u : 1u)];
row[x * 3u + 2u] = src[x * 4u + (alpha_view ? 3u : 0u)];
}
fwrite(row, 1, row_bytes, fp);
}
free(row);
}
fclose(fp);
fprintf(stderr, "D3D8: wrote startup GPU capture: %s\n", path);
}
#define PRESENT_FLASH_SAMPLE_WIDTH 64u
#define PRESENT_FLASH_SAMPLE_HEIGHT 36u
#define PRESENT_FLASH_SAMPLE_COUNT \
(PRESENT_FLASH_SAMPLE_WIDTH * PRESENT_FLASH_SAMPLE_HEIGHT)
/* Opt-in presentation diagnostic for the large, transient colour washes seen
* during Mercenaries gameplay. It samples the completed host back buffer
* rather than guessing which guest effect produced the image. A flash is
* reported only when a signed brightness change covers most of the screen,
* which rejects ordinary camera motion while catching the measured 98% red
* and grey transitions in the reference capture. Normal builds never map the
* back buffer because this diagnostic is disabled unless explicitly set. */
static void d3d8_debug_detect_present_flash(ULONGLONG now_ms)
{
static int initialized;
static int enabled;
static int previous_valid;
static uint8_t previous[PRESENT_FLASH_SAMPLE_COUNT][3];
static unsigned capture_count;
static unsigned capture_limit;
static ULONGLONG started_ms;
static const char *capture_prefix;
static const char *gate_path;
ID3D11Texture2D *back_buffer = NULL, *staging = NULL;
D3D11_TEXTURE2D_DESC desc;
D3D11_MAPPED_SUBRESOURCE mapped;
int64_t signed_sum = 0;
uint64_t absolute_sum = 0;
uint64_t channel_sum[3] = { 0u, 0u, 0u };
uint32_t positive = 0u, negative = 0u;
uint32_t sx, sy, sample = 0u;
HRESULT hr;
if (!initialized) {
const char *limit_text;
initialized = 1;
enabled = d3d8_cached_getenv(
"MERCENARIES_TRACE_PRESENT_FLASH") != NULL;
if (!enabled)
return;
capture_prefix = d3d8_cached_getenv(
"MERCENARIES_CAPTURE_PRESENT_FLASH_PREFIX");
gate_path = d3d8_cached_getenv(
"MERCENARIES_TRACE_PRESENT_FLASH_GATE_FILE");
limit_text = d3d8_cached_getenv(
"MERCENARIES_CAPTURE_PRESENT_FLASH_COUNT");
capture_limit = limit_text ?
(unsigned)strtoul(limit_text, NULL, 10) : 32u;
if (capture_limit > 64u)
capture_limit = 64u;
started_ms = now_ms;
}
if (!enabled || !g_device_state.swap_chain ||
!g_device_state.d3d11_device || !g_device_state.d3d11_context)
return;
if (gate_path && gate_path[0] &&
GetFileAttributesA(gate_path) == INVALID_FILE_ATTRIBUTES) {
previous_valid = 0;
return;
}
hr = IDXGISwapChain_GetBuffer(g_device_state.swap_chain, 0,
&IID_ID3D11Texture2D,
(void **)&back_buffer);
if (FAILED(hr) || !back_buffer)
return;
ID3D11Texture2D_GetDesc(back_buffer, &desc);
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0u;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.MiscFlags = 0u;
hr = ID3D11Device_CreateTexture2D(g_device_state.d3d11_device, &desc,
NULL, &staging);
if (SUCCEEDED(hr) && staging) {
ID3D11DeviceContext_CopyResource(g_device_state.d3d11_context,
(ID3D11Resource *)staging, (ID3D11Resource *)back_buffer);
memset(&mapped, 0, sizeof(mapped));
hr = ID3D11DeviceContext_Map(g_device_state.d3d11_context,
(ID3D11Resource *)staging, 0, D3D11_MAP_READ, 0, &mapped);
if (SUCCEEDED(hr)) {
for (sy = 0u; sy < PRESENT_FLASH_SAMPLE_HEIGHT; ++sy) {
const uint32_t y =
((sy * 2u + 1u) * desc.Height) /
(PRESENT_FLASH_SAMPLE_HEIGHT * 2u);
const uint8_t *row = (const uint8_t *)mapped.pData +
(size_t)y * mapped.RowPitch;
for (sx = 0u; sx < PRESENT_FLASH_SAMPLE_WIDTH; ++sx) {
const uint32_t x =
((sx * 2u + 1u) * desc.Width) /
(PRESENT_FLASH_SAMPLE_WIDTH * 2u);
const uint8_t *pixel = row + (size_t)x * 4u;
int delta = 0;
uint32_t channel;
for (channel = 0u; channel < 3u; ++channel) {
channel_sum[channel] += pixel[channel];
if (previous_valid)
delta += (int)pixel[channel] -
(int)previous[sample][channel];
previous[sample][channel] = pixel[channel];
}
if (previous_valid) {
delta /= 3;
signed_sum += delta;
absolute_sum += (uint64_t)abs(delta);
if (delta >= 8)
++positive;
else if (delta <= -8)
++negative;
}
++sample;
}
}
if (previous_valid) {
const uint32_t coherent =
positive > negative ? positive : negative;
const int64_t mean_delta =
signed_sum / (int64_t)PRESENT_FLASH_SAMPLE_COUNT;
const uint64_t mean_absolute =
absolute_sum / PRESENT_FLASH_SAMPLE_COUNT;
if (coherent * 100u >= PRESENT_FLASH_SAMPLE_COUNT * 72u &&
llabs(mean_delta) >= 10 && mean_absolute >= 12u) {
char path[1024] = { 0 };
int length = 0;
if (capture_prefix && capture_prefix[0] &&
capture_count < capture_limit) {
length = snprintf(path, sizeof(path),
"%s-%03u-%llu.bmp", capture_prefix,
capture_count + 1u,
(unsigned long long)(now_ms - started_ms));
if (length > 0 && (size_t)length < sizeof(path))
d3d8_write_backbuffer_bmp(
path, &desc, &mapped, FALSE);
}
++capture_count;
fprintf(stderr,
"[PRESENT-FLASH] tick=%llu elapsed=%llu n=%u "
"direction=%s coherent=%u/%u mean_delta=%lld "
"mean_abs=%llu mean_rgb=%.2f/%.2f/%.2f capture=%s\n",
(unsigned long long)now_ms,
(unsigned long long)(now_ms - started_ms),
capture_count, mean_delta >= 0 ? "up" : "down",
coherent, PRESENT_FLASH_SAMPLE_COUNT,
(long long)mean_delta,
(unsigned long long)mean_absolute,
(double)channel_sum[0] / PRESENT_FLASH_SAMPLE_COUNT,
(double)channel_sum[1] / PRESENT_FLASH_SAMPLE_COUNT,
(double)channel_sum[2] / PRESENT_FLASH_SAMPLE_COUNT,
path[0] ? path : "none");
fflush(stderr);
}
}
previous_valid = 1;
ID3D11DeviceContext_Unmap(g_device_state.d3d11_context,
(ID3D11Resource *)staging, 0);
}
ID3D11Texture2D_Release(staging);
}
ID3D11Texture2D_Release(back_buffer);
}
BOOL d3d8_DebugCaptureTextureToPath(ID3D11Texture2D *texture,
const char *path)
{
ID3D11Texture2D *staging = NULL;
D3D11_TEXTURE2D_DESC desc;
D3D11_MAPPED_SUBRESOURCE mapped;