Repository navigation
Expand file tree
/
Copy pathFlyChess.cpp
More file actions
4837 lines (4196 loc) · 124 KB
/
Copy pathFlyChess.cpp
File metadata and controls
4837 lines (4196 loc) · 124 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
////////////////////////////////////////////////////////////////////////////////
/// FlyChess -- Slim Win32 Host for NeuroMechFly
///
/// AUTHOR: Igor G. Tebelev (c) 2026
/// REPOSITORY: https://github.com/IgorTebelev/FlyChess
/// FRAMEWORK: Powered by WithExe (https://github.com/IgorTebelev/WithExe)
///
/// WHAT THIS CODE DOES:
/// This is a pure Win32, zero-CRT (freestanding) executable that hijacks the
/// Microsoft Games "Chess Titans" process by hosting it inproc not using
/// pemapping and it does it dynamically using `With.dll`. It uses a transparent
/// GDI overlay to render a procedural 3D-animated fly walking across the chess
/// board. It intercepts window messages, rewrites the host's menus, packs/unpacks
/// its own assets from its PE tail, and spams a custom glass-pane console with
/// sensorimotor telemetry—all without a single byte of the C Standard Library
/// and all utilizing inproc executed "Chess Titans" demonstrating simplicity
/// of inproc executable loading using `With.dll` (see GuestThread() implementation).
///
/// THE LORE:
/// There have been a lot of reports lately about the Drosophila Fly(муха)
/// opening her own BAR, reviewing SEX toys, and generally living a life of
/// pure, chaotic hedonism. We decided she needed a more refined, intellectual
/// pursuit to keep her out of trouble.
///
/// So, naturally... we decided to let the Drosophila start playing Chess.
/// She learned to play back in 2007 by playing Microsoft Games "Chess Titans"...
/// still compatible to recent Windows versions (10, 11) and available for
/// download from https://win7games.com and/or other sites.
////////////////////////////////////////////////////////////////////////////////
//
//#include "FlyChess.h"
////////////////////////////////////////////////////////////////////////////////
/// FlyChess -- slim Chess host: GDI fly overlay + With.dll dynamic loader.
/// No D3D hooks, no CreateMutex DR.
/// Chess from CardPack\Microsoft Games. Assets: webp\neuromechfly
///
/// REVISION HISTORY:
/// - Removed the CRT because stdlib is for cowards.
/// - Added section merging to trigger heuristic antivirus engines for fun.
////////////////////////////////////////////////////////////////////////////////
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <objbase.h>
#include <wincodec.h>
#include <shlwapi.h>
#include <shellapi.h>
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "shlwapi.lib")
#ifndef _DEBUG
/*
* THE CHAOS ZONE
* We are making all PE sections Read/Write/Execute (RWE) and then violently smashing
* them all into the .text section.
* Why? To minimize the file size by a few bytes, completely obliterate standard
* memory protections, confuse reverse engineers, and make dynamic analysis tools cry.
* Security is a myth. Embrace the soup.
*/
#pragma comment(linker, "/SECTION:.rdata,RWE")
#pragma comment(linker, "/SECTION:.data,RWE")
#pragma comment(linker, "/SECTION:.pdata,RWE")
#pragma comment(linker, "/SECTION:.xdata,RWE")
#pragma comment(linker, "/SECTION:.text,RWE")
#pragma comment(linker, "/MERGE:.xdata=.rdata")
#pragma comment(linker, "/MERGE:.pdata=.rdata")
#pragma comment(linker, "/MERGE:.rdata=.text")
#pragma comment(linker, "/MERGE:.data=.text")
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
* The compiler panics if it sees floating-point math without the CRT.
* By defining `_fltused = 0`, we are essentially patting MSVC on the head
* and saying, "Shhh, it's okay, I know what a float is. Go back to sleep."
*/
int _fltused = 0;
/*
* MSVC sneaks in invisible `memset` calls when we zero-initialize structs (like {0}).
* Since we fired the CRT, we have to do the janitorial work ourselves.
*/
#pragma function(memset)
void* __cdecl memset(void* dest, int c, size_t count)
{
char* bytes = (char*)dest;
while (count--) *bytes++ = (char)c;
return dest;
}
#ifdef __cplusplus
}
#endif
/* State of the sacrificial host process (Chess Titans) */
struct Game
{
WCHAR path[MAX_PATH]; /* Where the victim lives */
DWORD tid; /* Victim's thread ID */
HANDLE thread; /* Victim's thread handle */
HWND hwnd; /* The main window we are currently haunting */
BOOL hidden; /* Are we playing hide and seek? */
HHOOK hookCbt; /* Spying on window creation */
HHOOK hookCwp; /* Spying on window messages */
HHOOK hookGet; /* Spying on thread messages */
BOOL menuAtt; /* Did we successfully vandalize the menu yet? */
BOOL iconAtt; /* Did we swap their icon yet? */
};
static Game g_game;
static HANDLE g_menuEvent;
typedef UINT(WINAPI* PFN_RUN)(LPCWSTR, LPCWSTR);
static PFN_RUN g_pfnRun = NULL; /* The dark magic exported by With.dll */
/* GDI toplevel fly clip over Chess board center (not a D3D child). */
static HWND g_gdiFlyHwnd; /* The fly's invisible glass cage */
static BOOL g_gdiFlyClass;
enum { FLY_BANK_WALK = 0, FLY_BANK_FLY = 1, FLY_BANK_DIE = 2, FLY_BANK_COUNT = 3, FLY_SHADOW_PAD = 12 };
/* The fly sequence is generated/kept with recordings, separate from raw assets. */
static const WCHAR* g_flyBankFolder[FLY_BANK_COUNT] = { L"walk", L"fly", L"die" };
static WCHAR(*g_flyBankPath[FLY_BANK_COUNT])[MAX_PATH];
static int g_flyBankN[FLY_BANK_COUNT]; /* How many frames of animation we have */
/* Fly geometry and telemetry state */
static float* g_flyBankCx[FLY_BANK_COUNT];
static float* g_flyBankCy[FLY_BANK_COUNT];
static float* g_flyBankDx[FLY_BANK_COUNT];
static float* g_flyBankDy[FLY_BANK_COUNT];
static int g_flyBankSrcW[FLY_BANK_COUNT];
static int g_flyBankSrcH[FLY_BANK_COUNT];
static int g_flyBank; /* active bank */
static BOOL g_flyBanksLoaded;
static WCHAR(*g_gdiFlyPath)[MAX_PATH];
static int g_gdiFlyN;
static int g_gdiFlyFrame = -1;
static BOOL g_gdiFlyMirrorX; /* TRUE = fly is facing left, because we flip the matrix */
static float g_gdiFlyAngle; /* radians, small per-leg swing */
static float g_flyLegSwing; /* peak ±amp for current leg (radians) */
static float g_flyLegScale; /* walk: 0.7..1.0, flight peaks at 1.5 (fat fly) */
/* The fly's breathing/pulsing scale mechanics */
static DWORD g_flyScaleT0;
static DWORD g_flyScaleDuration;
static float g_flyWalkScaleFrom, g_flyWalkScaleTo;
static float g_flyFlightStartScale, g_flyFlightStartDist;
static float g_flyApproachVx, g_flyApproachVy; /* last hop heading for land continue */
static float g_gdiFlyRotCx, g_gdiFlyRotCy; /* COG in unrotated content pixels */
static int g_gdiFlyContentW, g_gdiFlyContentH;
static int g_gdiFlySrcW = 640;
static int g_gdiFlySrcH = 360;
/* Bitmap handles for the GDI blender */
static HBITMAP g_gdiFlyCurBmp;
static BYTE* g_gdiFlyCurBits;
static HBITMAP g_gdiFlyScaledBmp;
static BYTE* g_gdiFlyScaledBits;
static int g_gdiFlyScaledW, g_gdiFlyScaledH;
static BYTE* g_gdiFlyShadowAlpha;
static SIZE_T g_gdiFlyShadowAlphaCap;
static HDC g_gdiFlyMemDc;
/* Where the little bugger actually is */
static float* g_flyCx;
static float* g_flyCy;
static float* g_flyDx;
static float* g_flyDy;
static float g_flyPosX, g_flyPosY; /* screen COG (Center of Gravity) */
static float g_flyVx, g_flyVy; /* cardinal velocity px/tick (Speed) */
static float g_flyLegSpeed; /* How fast the legs are furiously pumping */
static BOOL g_flyResting; /* Is the fly taking a smoke break? */
static DWORD g_flyRestUntil; /* When the smoke break ends */
static DWORD g_flyRng; /* Our handcrafted random number generator seed */
static BOOL g_flyPosInit; /* Has the fly spawned into existence yet? */
static float g_flyTravelAngle; /* head-right bitmap faces travel (smoothable) */
static BOOL g_flyAngleEase; /* Are we smoothly rotating or violently snapping? */
static float g_flyAngleGoal;
static int g_flyRail; /* 0=freeroam, 1=top edge, 2=bottom edge, 3=left edge, 4=right edge */
static float g_flyPerp; /* ±60 wobble off the edge rail (drunk fly simulator) */
static int g_flyHabitat; /* 0=Chess Window, 1=Console Window */
static BOOL g_flyTransit; /* flying between habitats */
static float g_flyTx, g_flyTy; /* Target X and Y for flights */
static DWORD g_flyNextHop;
static DWORD g_flyNextConsoleHop;
/* Floodgate variables for our terminal spam */
static BOOL g_flyFloodUnlocked; /* first Chess→Console flight unlocked flood */
static BOOL g_flyFlooding; /* on console after unlock -- firehose ON */
static BOOL g_flyNeedBootFlood; /* one-shot full FlyBsBoot */
static BOOL g_flyBootDone; /* boot banner already queued once */
static BOOL g_flyWasFlooding;
static BOOL g_flyThink; /* paused, looking at chess board ominously */
static DWORD g_flyThinkUntil;
/* Mouse stalking mechanics */
static POINT g_flyLastMousePos;
static BOOL g_flyMouseSampled;
static DWORD g_flyMouseMovedAt;
static BOOL g_flyMouseIdleLook;
static BOOL g_flyMouseIdleExpired;
static DWORD g_flyMouseIdleStarted;
static DWORD g_flyMouseIdleUntil;
static DWORD g_flyMouseIdleNextPose;
static int g_flyMouseIdleFrames;
static BOOL g_flyClickPending;
static float g_flyClickX, g_flyClickY; /* The coordinates the fly is judging you for clicking */
static DWORD g_flyNextThink;
static float g_flyLookAngle; /* face board (cardinal) */
static float g_flySavedVx, g_flySavedVy; /* resume crawl */
static int g_flyTransitDest; /* habitat we're flying toward */
static BOOL g_flyGameLive; /* human started moving pieces */
static BOOL g_flyMyTurn; /* after human click -- fly "thinks" */
static DWORD g_flyMyTurnUntil;
static UINT g_flyBoardClicks; /* How many times the user poked the board */
static DWORD g_flyNextFlip; /* random mid-edge reverse to keep things chaotic */
/* Our fake terminal (not AllocConsole) -- habitat + flood text. */
static HWND g_flyLogHwnd; /* The glass pane of wisdom */
static HWND g_flyLogList; /* The actual listbox catching our text vomit */
static HFONT g_flyLogFont;
static HBRUSH g_flyLogBrush;
static BOOL g_flyLogClassReg;
static BOOL g_flyLogUserPlaced; /* user dragged/resized -- stop auto-dock (user taking control) */
static WNDPROC g_flyLogListPrev;
enum { FLYLOG_LIST_ID = 4201 };
enum { FLYLOG_ALPHA = 128 }; /* 50% opaque (see-through matrix vibes) */
enum { FLYLOG_TMR_HIDECHROME = 88 }; /* Timer ID to hide the ugly Windows borders */
/* Window docking and sliding math */
static BOOL g_flyLogPanning;
static BOOL g_flyLogPanArriving;
static BOOL g_flyLogRevealed;
static BOOL g_flyLogRevealValid;
static BOOL g_flyLogGlueRight; /* TRUE: right edge fixed (dock left of Chess) */
enum { FLYLOG_EDGE_AUTO = -1, FLYLOG_EDGE_LEFT, FLYLOG_EDGE_RIGHT, FLYLOG_EDGE_TOP, FLYLOG_EDGE_BOTTOM };
static int g_flyLogDockEdge = FLYLOG_EDGE_AUTO;
static int g_flyLogShownEdge = FLYLOG_EDGE_AUTO;
static int g_flyLogNextEdge = FLYLOG_EDGE_AUTO;
static BOOL g_flyLogFlyPending;
static int g_flyLogFlyEdge = FLYLOG_EDGE_AUTO;
static BOOL g_flyLogPanVertical;
static int g_flyLogGlueX;
static int g_flyLogGlueY;
static int g_flyLogRevealY, g_flyLogRevealW, g_flyLogRevealH;
static int g_flyLogPanW0, g_flyLogPanW1;
static int g_flyLogPanH0, g_flyLogPanH1;
static int g_flyLogPanX;
static int g_flyLogPanY, g_flyLogPanH;
static DWORD g_flyLogPanT0;
static int g_flyLogPanMs;
static BOOL g_flyLogPanPending;
static BOOL g_flyLogPanPendingArrive;
static float g_flyHopDist0;
static DWORD g_flyLogEdgeLeaveAt; /* collapse after mouse leaves edge/log */
static DWORD g_mainTid;
static WCHAR g_gamesDir[MAX_PATH];
static HWND g_scrollHwnd;
// --- PURE WIN32 CRT SUBSTITUTES ---
// Because `#include <string.h>` is for tourists.
/* Custom memcpy. Bytes go in, bytes go out. You can't explain that. */
static void CustomMemCpy(void* dst, const void* src, SIZE_T sz)
{
BYTE* d = (BYTE*)dst; const BYTE* s = (const BYTE*)src;
while (sz--) *d++ = *s++;
}
/* Custom memset-to-zero. Replaces ZeroMemory so we don't look lazy. */
static void CustomZeroMem(void* dst, SIZE_T sz)
{
BYTE* d = (BYTE*)dst;
while (sz--) *d++ = 0;
}
/* Custom memcmp. Returns difference. Just like the good old days. */
static int CustomMemCmp(const void* b1, const void* b2, SIZE_T sz)
{
const BYTE* p1 = (const BYTE*)b1; const BYTE* p2 = (const BYTE*)b2;
for (SIZE_T i = 0; i < sz; i++) { if (p1[i] != p2[i]) return p1[i] - p2[i]; }
return 0;
}
/* Custom string-to-float parser. Take that, _wtof. */
static float CustomWtof(const WCHAR* s)
{
float res = 0.0f, fact = 1.0f; BOOL minus = FALSE;
if (*s == L'-') { minus = TRUE; s++; }
while (*s >= L'0' && *s <= L'9') { res = res * 10.0f + (float)(*s - L'0'); s++; }
if (*s == L'.') { s++; while (*s >= L'0' && *s <= L'9') { fact *= 0.1f; res += (float)(*s - L'0') * fact; s++; } }
return minus ? -res : res;
}
/* Hardcoded syntax highlighter for our fake terminal. */
static WORD ConPickAttr(LPCWSTR s)
{
if (!s || s[0] != L'[')
return FOREGROUND_GREEN | FOREGROUND_INTENSITY; /* Default hacker green */
/* The RGB soup of logical tags */
if (StrStrIW(s, L"[engram]") || StrStrIW(s, L"[identity]"))
return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
if (StrStrIW(s, L"[target_1]") || StrStrIW(s, L"[target_2]"))
return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
if (StrStrIW(s, L"[MuJoCo]") || StrStrIW(s, L"[flygym]") || StrStrIW(s, L"[Warp]") || StrStrIW(s, L"[qpos]") || StrStrIW(s, L"[chess-sink]"))
return FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
if (StrStrIW(s, L"[VNC]") || StrStrIW(s, L"[CNS]") || StrStrIW(s, L"[odor]"))
return FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
if (StrStrIW(s, L"[sensorimotor]") || StrStrIW(s, L"[think]") || StrStrIW(s, L"[mech]"))
return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
/* The angry tags */
if (StrStrIW(s, L"[FATAL]") || StrStrIW(s, L"[warn]") || StrStrIW(s, L"[ERROR]"))
return FOREGROUND_RED | FOREGROUND_INTENSITY;
/* The boring tags */
if (StrStrIW(s, L"[boot]") || StrStrIW(s, L"[link]") || StrStrIW(s, L"[DoF]") || StrStrIW(s, L"[heartbeat]"))
return FOREGROUND_INTENSITY;
if (StrStrIW(s, L"[sys]") || StrStrIW(s, L"[system]") || StrStrIW(s, L"[mem]"))
return FOREGROUND_RED | FOREGROUND_INTENSITY;
if (StrStrIW(s, L"[adhesion]") || StrStrIW(s, L"[ommatidia]") || StrStrIW(s, L"[vision]"))
return FOREGROUND_GREEN | FOREGROUND_INTENSITY;
if (StrStrIW(s, L"[brain]") || StrStrIW(s, L"[ascend]"))
return FOREGROUND_BLUE | FOREGROUND_INTENSITY;
return FOREGROUND_GREEN | FOREGROUND_INTENSITY;
}
static COLORREF ConPickRgb(LPCWSTR s)
{
WORD a = ConPickAttr(s);
int bright = (a & FOREGROUND_INTENSITY) ? 1 : 0;
int r = (a & FOREGROUND_RED) ? (bright ? 255 : 170) : 0;
int g = (a & FOREGROUND_GREEN) ? (bright ? 255 : 170) : 0;
int b = (a & FOREGROUND_BLUE) ? (bright ? 255 : 170) : 0;
if (!(a & (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)))
{
int v = bright ? 185 : 130;
return RGB(v, v, v);
}
return RGB(r, g, b);
}
static HWND FlyLogListHwnd(void)
{
HWND pane;
if (g_flyLogList && IsWindow(g_flyLogList))
return g_flyLogList;
if (g_flyLogHwnd && IsWindow(g_flyLogHwnd))
{
g_flyLogList = GetDlgItem(g_flyLogHwnd, FLYLOG_LIST_ID);
if (g_flyLogList)
return g_flyLogList;
}
/* Search globally in case we lost track of our own child */
pane = FindWindowW(L"FlyChessLogPane", NULL);
if (pane)
{
g_flyLogHwnd = pane;
g_flyLogList = GetDlgItem(pane, FLYLOG_LIST_ID);
return g_flyLogList;
}
return NULL;
}
/* The great listbox stuffer. Shoves text in until it hits 600 lines, then starts throwing old data away. */
static void FlyLogAppend(LPCWSTR line)
{
HWND list;
int n;
WCHAR one[1024];
list = FlyLogListHwnd();
if (!list || !line || !line[0])
return;
lstrcpynW(one, line, 1000);
n = lstrlenW(one);
/* Trim trailing newlines because ListBox doesn't need them */
while (n > 0 && (one[n - 1] == L'\r' || one[n - 1] == L'\n'))
one[--n] = 0;
if (!one[0])
return;
SendMessageW(list, LB_ADDSTRING, 0, (LPARAM)one);
n = (int)SendMessageW(list, LB_GETCOUNT, 0, 0);
/* Memory management by deletion */
while (n > 600)
{
SendMessageW(list, LB_DELETESTRING, 0, 0);
n--;
}
if (n > 0)
SendMessageW(list, LB_SETTOPINDEX, (WPARAM)(n - 1), 0); /* Auto-scroll to bottom */
}
// --- PURE WIN32 LOGGING WRAPPERS ---
/*
* We killed wprintf and stdout. All text must now flow through wvsprintfW
* and into our GDI glass window.
*/
static void Con(LPCWSTR fmt, ...)
{
WCHAR buf[1024];
va_list ap;
va_start(ap, fmt);
wvsprintfW(buf, fmt, ap);
va_end(ap);
FlyLogAppend(buf);
}
enum { FLY_CONQ_CAP = 128, FLY_CONQ_LEN = 384 };
static WCHAR g_flyConQ[FLY_CONQ_CAP][FLY_CONQ_LEN];
static int g_flyConQHead;
static int g_flyConQCount;
static DWORD g_flyConQLast;
static UINT g_flyConQTone;
/* Queue up text to be printed slowly so it looks like someone is actually typing it. */
static void ConQ(LPCWSTR fmt, ...)
{
WCHAR buf[FLY_CONQ_LEN];
va_list ap;
int slot;
if (g_flyConQCount >= FLY_CONQ_CAP)
return; /* Buffer full. We drop packets like a cheap router. */
va_start(ap, fmt);
wvsprintfW(buf, fmt, ap);
va_end(ap);
slot = (g_flyConQHead + g_flyConQCount) % FLY_CONQ_CAP;
lstrcpynW(g_flyConQ[slot], buf, FLY_CONQ_LEN);
g_flyConQCount++;
}
/* The heartbeat of the fake terminal typist */
static void ConQTick(void)
{
DWORD now, gap;
if (g_flyConQCount <= 0)
return;
now = GetTickCount();
/* Variable typing speed for maximum realism */
gap = 480u + (DWORD)((g_flyConQTone % 7u) * 70u);
if (g_flyConQLast && now - g_flyConQLast < gap)
return;
g_flyConQLast = now;
LPCWSTR line = g_flyConQ[g_flyConQHead];
FlyLogAppend(line);
g_flyConQHead = (g_flyConQHead + 1) % FLY_CONQ_CAP;
g_flyConQCount--;
g_flyConQTone++;
}
static BOOL FileOk(LPCWSTR p)
{
DWORD a = GetFileAttributesW(p);
return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
}
/* Desperately looking for the chess executable */
static BOOL TryChessIn(LPCWSTR games)
{
WCHAR path[MAX_PATH];
if (!games || !games[0])
return FALSE;
wsprintfW(path, L"%s\\Chess\\chess.exe", games);
if (!FileOk(path))
wsprintfW(path, L"%s\\chess.exe", games);
if (!FileOk(path))
return FALSE;
lstrcpynW(g_gamesDir, games, MAX_PATH);
lstrcpynW(g_game.path, path, MAX_PATH);
return TRUE;
}
static BOOL FindChess(void)
{
WCHAR here[MAX_PATH], cand[MAX_PATH], env[MAX_PATH];
if (GetEnvironmentVariableW(L"ProgramFiles", env, MAX_PATH))
{
wsprintfW(cand, L"%s\\Microsoft Games", env);
if (TryChessIn(cand))
return TRUE;
}
if (GetEnvironmentVariableW(L"ProgramFiles(x86)", env, MAX_PATH))
{
wsprintfW(cand, L"%s\\Microsoft Games", env);
if (TryChessIn(cand))
return TRUE;
}
GetModuleFileNameW(NULL, here, MAX_PATH);
PathRemoveFileSpecW(here);
wsprintfW(cand, L"%s\\Microsoft Games", here);
if (TryChessIn(cand))
return TRUE;
return FALSE;
}
/* Rips the stupid ampersands out of menu items so we can actually read them */
static void StripAmp(WCHAR* d, LPCWSTR s)
{
while (*s)
{
if (*s != L'&')
*d++ = *s;
s++;
}
*d = 0;
}
static IWICImagingFactory* g_flyWicFactory;
/* Our highly sophisticated, proprietary, extremely secure custom pack file format */
typedef struct FlyPackEntry
{
WCHAR name[128];
ULONGLONG offset;
DWORD size;
} FlyPackEntry;
static FlyPackEntry g_flyPackEntries[1024];
static DWORD g_flyPackCount;
static BOOL g_flyPackChecked;
static BOOL g_flyPackValid;
/* Look for the magic bytes at the end of the EXE to see if we've been packed */
static BOOL FlyPackLoadIndex(void)
{
static const BYTE magic[8] = { 'F','L','Y','P','A','K','1',0 };
WCHAR exe[MAX_PATH];
HANDLE file;
LARGE_INTEGER fileSize, seek;
BYTE footer[24], * index = NULL;
DWORD rd, version, count, parsed, i;
ULONGLONG indexOffset;
BOOL ok = FALSE;
if (g_flyPackChecked)
return g_flyPackValid;
g_flyPackChecked = TRUE;
if (!GetModuleFileNameW(NULL, exe, MAX_PATH))
return FALSE;
file = CreateFileW(exe, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE)
return FALSE;
if (!GetFileSizeEx(file, &fileSize) || fileSize.QuadPart < (LONGLONG)sizeof(footer))
goto done;
seek.QuadPart = fileSize.QuadPart - (LONGLONG)sizeof(footer);
if (!SetFilePointerEx(file, seek, NULL, FILE_BEGIN) || !ReadFile(file, footer, sizeof(footer), &rd, NULL) || rd != sizeof(footer) || CustomMemCmp(footer, magic, sizeof(magic)) != 0)
goto done;
CustomMemCpy(&version, footer + 8, sizeof(version));
CustomMemCpy(&count, footer + 12, sizeof(count));
CustomMemCpy(&indexOffset, footer + 16, sizeof(indexOffset));
/* Sanity checks because parsing binary formats is scary */
if (version != 1 || count > 1024 || indexOffset > (ULONGLONG)(fileSize.QuadPart - sizeof(footer)) || (ULONGLONG)(fileSize.QuadPart - sizeof(footer)) - indexOffset > 1024u * 1024u)
goto done;
parsed = (DWORD)((ULONGLONG)(fileSize.QuadPart - sizeof(footer)) - indexOffset);
index = (BYTE*)HeapAlloc(GetProcessHeap(), 0, parsed ? parsed : 1);
if (!index)
goto done;
seek.QuadPart = (LONGLONG)indexOffset;
if (!SetFilePointerEx(file, seek, NULL, FILE_BEGIN) || !ReadFile(file, index, parsed, &rd, NULL) || rd != parsed)
goto done;
parsed = 0;
for (i = 0; i < count; ++i)
{
WORD nameLen;
ULONGLONG offset;
DWORD size, j;
if (parsed + sizeof(nameLen) > (DWORD)((ULONGLONG)(fileSize.QuadPart - sizeof(footer)) - indexOffset))
goto done;
CustomMemCpy(&nameLen, index + parsed, sizeof(nameLen));
parsed += sizeof(nameLen);
if (!nameLen || nameLen >= 128 || parsed + nameLen + sizeof(offset) + sizeof(size) > (DWORD)((ULONGLONG)(fileSize.QuadPart - sizeof(footer)) - indexOffset))
goto done;
for (j = 0; j < nameLen; ++j)
g_flyPackEntries[i].name[j] = (WCHAR)index[parsed + j];
g_flyPackEntries[i].name[nameLen] = 0;
parsed += nameLen;
CustomMemCpy(&offset, index + parsed, sizeof(offset));
parsed += sizeof(offset);
CustomMemCpy(&size, index + parsed, sizeof(size));
parsed += sizeof(size);
if (!size || offset > indexOffset || size > indexOffset - offset)
goto done;
g_flyPackEntries[i].offset = offset;
g_flyPackEntries[i].size = size;
}
if (parsed != (DWORD)((ULONGLONG)(fileSize.QuadPart - sizeof(footer)) - indexOffset))
goto done;
g_flyPackCount = count;
ok = TRUE;
done:
if (index)
HeapFree(GetProcessHeap(), 0, index);
CloseHandle(file);
g_flyPackValid = ok;
return ok;
}
static BOOL FlyPackReadEntry(const WCHAR* name, BYTE** outData, DWORD* outSize)
{
WCHAR exe[MAX_PATH];
HANDLE file;
LARGE_INTEGER seek;
BYTE* data;
DWORD i, rd;
if (outData) *outData = NULL;
if (outSize) *outSize = 0;
if (!outData || !outSize) return FALSE;
/* Look in our tail-appended payload first */
if (FlyPackLoadIndex() && g_flyPackCount > 0)
{
for (i = 0; i < g_flyPackCount; ++i)
{
if (lstrcmpiW(g_flyPackEntries[i].name, name) == 0)
break;
}
if (i < g_flyPackCount && GetModuleFileNameW(NULL, exe, MAX_PATH))
{
data = (BYTE*)HeapAlloc(GetProcessHeap(), 0, g_flyPackEntries[i].size);
if (data)
{
file = CreateFileW(exe, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file != INVALID_HANDLE_VALUE)
{
seek.QuadPart = (LONGLONG)g_flyPackEntries[i].offset;
if (SetFilePointerEx(file, seek, NULL, FILE_BEGIN) && ReadFile(file, data, g_flyPackEntries[i].size, &rd, NULL) && rd == g_flyPackEntries[i].size)
{
CloseHandle(file);
*outData = data;
*outSize = g_flyPackEntries[i].size;
return TRUE;
}
CloseHandle(file);
}
HeapFree(GetProcessHeap(), 0, data);
}
}
}
/* Fallback to checking the normal file system if it isn't packed */
if (GetModuleFileNameW(NULL, exe, MAX_PATH))
{
PathRemoveFileSpecW(exe);
WCHAR diskPath[MAX_PATH];
wsprintfW(diskPath, L"%s\\assets\\%s", exe, name);
/* Sanitize paths like a responsible citizen */
for (int j = 0; diskPath[j]; j++)
if (diskPath[j] == L'/')
diskPath[j] = L'\\';
file = CreateFileW(diskPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file != INVALID_HANDLE_VALUE)
{
DWORD sz = GetFileSize(file, NULL);
data = (BYTE*)HeapAlloc(GetProcessHeap(), 0, sz);
if (data)
{
if (ReadFile(file, data, sz, &rd, NULL) && rd == sz)
{
CloseHandle(file);
*outData = data;
*outSize = sz;
return TRUE;
}
HeapFree(GetProcessHeap(), 0, data);
}
CloseHandle(file);
}
}
return FALSE;
}
static BOOL FlyPackLoadBankPaths(int bank, int* outCount)
{
const WCHAR* prefix = bank == FLY_BANK_WALK ? L"WALK/" : L"FLY/";
int prefixLen = lstrlenW(prefix), n = 0, i;
if (outCount) *outCount = 0;
if (!FlyPackLoadIndex())
return FALSE;
for (i = 0; i < (int)g_flyPackCount; ++i)
{
if (StrCmpNIW(g_flyPackEntries[i].name, prefix, prefixLen) == 0 && lstrcmpiW(PathFindExtensionW(g_flyPackEntries[i].name), L".png") == 0)
n++;
}
if (!n)
return FALSE;
g_flyBankPath[bank] = (WCHAR(*)[MAX_PATH])HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (SIZE_T)n * MAX_PATH * sizeof(WCHAR));
if (!g_flyBankPath[bank])
return FALSE;
n = 0;
for (i = 0; i < (int)g_flyPackCount; ++i)
{
if (StrCmpNIW(g_flyPackEntries[i].name, prefix, prefixLen) == 0 && lstrcmpiW(PathFindExtensionW(g_flyPackEntries[i].name), L".png") == 0)
wsprintfW(g_flyBankPath[bank][n++], L"@PACK:%s", g_flyPackEntries[i].name); /* Tag it as a packed asset */
}
if (outCount) *outCount = n;
return n > 0;
}
/*
* The magic Microsoft WIC COM interface code.
* Replaces the need for libpng because depending on external DLLs is weakness.
*/
static HBITMAP LoadPngFileHBitmap(const WCHAR* path, int* outW, int* outH, BYTE** outBits)
{
IWICBitmapDecoder* decoder = NULL;
IWICBitmapFrameDecode* frame = NULL;
IWICFormatConverter* converter = NULL;
IWICStream* stream = NULL;
BITMAPINFO bmi;
HBITMAP dib = NULL;
BYTE* bits = NULL;
UINT w = 0, h = 0;
HRESULT hr;
HDC screen;
BYTE* packedData = NULL;
DWORD packedSize = 0;
if (outBits) *outBits = NULL;
if (!g_flyWicFactory)
{
hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if (FAILED(hr) && hr != RPC_E_CHANGED_MODE)
return NULL;
hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), (void**)&g_flyWicFactory);
if (FAILED(hr))
return NULL;
}
/* Is this coming from our secret EXE tail? */
if (path[0] == L'@' && path[1] == L'P' && path[2] == L'A' && path[3] == L'C' && path[4] == L'K' && path[5] == L':')
{
if (!FlyPackReadEntry(path + 6, &packedData, &packedSize))
goto done;
hr = g_flyWicFactory->CreateStream(&stream);
if (FAILED(hr)) goto done;
hr = stream->InitializeFromMemory(packedData, packedSize);
if (FAILED(hr)) goto done;
hr = g_flyWicFactory->CreateDecoderFromStream(stream, NULL, WICDecodeMetadataCacheOnLoad, &decoder);
}
else
{
hr = g_flyWicFactory->CreateDecoderFromFilename(path, NULL, GENERIC_READ, WICDecodeMetadataCacheOnLoad, &decoder);
}
if (FAILED(hr)) goto done;
hr = decoder->GetFrame(0, &frame);
if (FAILED(hr)) goto done;
hr = g_flyWicFactory->CreateFormatConverter(&converter);
if (FAILED(hr)) goto done;
hr = converter->Initialize(frame, GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone, NULL, 0.0, WICBitmapPaletteTypeCustom);
if (FAILED(hr)) goto done;
hr = converter->GetSize(&w, &h);
if (FAILED(hr) || !w || !h || w > 8192 || h > 8192 || (ULONGLONG)w * h * 4 > 64u * 1024u * 1024u)
goto done;
CustomZeroMem(&bmi, sizeof(bmi));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = (LONG)w;
bmi.bmiHeader.biHeight = -(LONG)h;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
screen = GetDC(NULL);
dib = CreateDIBSection(screen, &bmi, DIB_RGB_COLORS, (void**)&bits, NULL, 0);
ReleaseDC(NULL, screen);
if (!dib || !bits)
{
if (dib) DeleteObject(dib);
dib = NULL;
goto done;
}
hr = converter->CopyPixels(NULL, w * 4, w * h * 4, bits);
if (FAILED(hr))
{
DeleteObject(dib);
dib = NULL;
bits = NULL;
goto done;
}
if (outW) *outW = (int)w;
if (outH) *outH = (int)h;
if (outBits) *outBits = bits;
done:
if (converter) converter->Release();
if (frame) frame->Release();
if (decoder) decoder->Release();
if (stream) stream->Release();
if (packedData) HeapFree(GetProcessHeap(), 0, packedData);
return dib;
}
static void GdiFlySortBankPaths(int bank, int n)
{
int i, j;
WCHAR tmp[MAX_PATH];
/* Insertion sort. Because standard library qsort is bloated nonsense. */
for (i = 1; i < n; i++)
{
lstrcpyW(tmp, g_flyBankPath[bank][i]);
j = i;
while (j > 0 && lstrcmpiW(g_flyBankPath[bank][j - 1], tmp) > 0)
{
lstrcpyW(g_flyBankPath[bank][j], g_flyBankPath[bank][j - 1]);
j--;
}
lstrcpyW(g_flyBankPath[bank][j], tmp);
}
}
static void GdiFlyClearCurBitmap(void)
{
if (g_gdiFlyCurBmp)
{
DeleteObject(g_gdiFlyCurBmp);
g_gdiFlyCurBmp = NULL;
g_gdiFlyCurBits = NULL;
}
g_gdiFlyFrame = -1;
if (g_gdiFlyScaledBmp)
{
DeleteObject(g_gdiFlyScaledBmp);
g_gdiFlyScaledBmp = NULL;
g_gdiFlyScaledBits = NULL;
g_gdiFlyScaledW = g_gdiFlyScaledH = 0;
}
}
static void GdiFlySetBank(int bank)
{
if (bank < 0 || bank >= FLY_BANK_COUNT)
bank = FLY_BANK_WALK;
if (g_flyBankN[bank] <= 0)
bank = FLY_BANK_WALK;
if (bank == g_flyBank && g_gdiFlyPath == g_flyBankPath[bank])
return;
g_flyBank = bank;
g_gdiFlyPath = g_flyBankPath[bank];
g_gdiFlyN = g_flyBankN[bank];
g_flyCx = g_flyBankCx[bank];
g_flyCy = g_flyBankCy[bank];
g_flyDx = g_flyBankDx[bank];
g_flyDy = g_flyBankDy[bank];
if (g_flyBankSrcW[bank] > 0)
g_gdiFlySrcW = g_flyBankSrcW[bank];
if (g_flyBankSrcH[bank] > 0)
g_gdiFlySrcH = g_flyBankSrcH[bank];
GdiFlyClearCurBitmap();
}
static BOOL LoadGdiFlyBankFrames(const WCHAR* dir, int bank)
{
WCHAR pat[MAX_PATH], full[MAX_PATH];
WIN32_FIND_DATAW fd;
HANDLE find;
int n, cap, pw = 0, ph = 0;
HBITMAP probe;
BYTE* bits = NULL;
BOOL usePack = FALSE;
n = 0;
find = INVALID_HANDLE_VALUE;
if (bank == FLY_BANK_WALK || bank == FLY_BANK_FLY)
usePack = FlyPackLoadBankPaths(bank, &n);
if (!usePack)
{
if (bank == FLY_BANK_WALK || bank == FLY_BANK_FLY)
{
wsprintfW(pat, L"%s\\assets\\%s\\frame_*.png", dir, bank == FLY_BANK_WALK ? L"walk" : L"fly");
find = FindFirstFileW(pat, &fd);
}
if (find == INVALID_HANDLE_VALUE)
return FALSE;
cap = 1024;
g_flyBankPath[bank] = (WCHAR(*)[MAX_PATH])HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (SIZE_T)cap * MAX_PATH * sizeof(WCHAR));
if (!g_flyBankPath[bank])
{
FindClose(find);
return FALSE;
}
do {
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
continue;
if (n >= cap)
{
int ncap = cap * 2;
void* p = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, g_flyBankPath[bank], (SIZE_T)ncap * MAX_PATH * sizeof(WCHAR));
if (!p) break;
g_flyBankPath[bank] = (WCHAR(*)[MAX_PATH])p;
cap = ncap;
}
wsprintfW(full, L"%s\\assets\\%s\\%s", dir, bank == FLY_BANK_WALK ? L"walk" : L"fly", fd.cFileName);
lstrcpyW(g_flyBankPath[bank][n++], full);
} while (FindNextFileW(find, &fd));
FindClose(find);
}
if (n <= 0)
return FALSE;
GdiFlySortBankPaths(bank, n);
g_flyBankN[bank] = n;
probe = LoadPngFileHBitmap(g_flyBankPath[bank][0], &pw, &ph, &bits);
if (probe)
{
g_flyBankSrcW[bank] = pw;
g_flyBankSrcH[bank] = ph;
DeleteObject(probe);
}
return TRUE;
}
static BOOL LoadGdiFlyFrames(void)
{
WCHAR exe[MAX_PATH], dir[MAX_PATH];
int b, ok = 0;
if (g_flyBanksLoaded)
return g_flyBankN[FLY_BANK_WALK] > 0;
if (!GetModuleFileNameW(NULL, exe, MAX_PATH))
return FALSE;