-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.c
More file actions
1099 lines (937 loc) · 38 KB
/
main.c
File metadata and controls
1099 lines (937 loc) · 38 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
/*
* main.c - Responsive Win32 Render Thread (OpenGL demo)
*
* Purpose:
* Smooth, artifact-free window resizing and moving by delegating all
* rendering to a background thread and synchronizing WM_PAINT with the
* render-thread frame completion.
*
* Highlights:
* - Render thread performs all GL drawing; main thread only processes messages.
* - WM_PAINT blocks (BeginPaint -> wait) until the render thread finishes the requested frame.
* - Uses legacy OpenGL 1.1 pipeline with optional ARB_sync + vsync.
* - Complex demo content: particles, pulsing/rotating geometric shapes, color‑cycling quads, FPS counter.
* - Alt+Enter toggles borderless fullscreen (monitor fill).
* - Per‑monitor DPI awareness (V2 when available, fallback to system DPI).
* - Minimal synchronization: one CRITICAL_SECTION + one CONDITION_VARIABLE for bidirectional hand‑off.
*
* License: Unlicense (public domain). See README.md for full text.
* Original technique: CookedNick (JaiRenderThreadExample)
* C port / maintenance: Mounir IDRASSI
* Date: 2025-08-27
*/
#include <windows.h>
#include <windowsx.h>
#include <timeapi.h>
#include <stdint.h>
#include <stdbool.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
// Minimal ARB_sync compatibility for old (1.1) Windows OpenGL headers
#ifndef GL_SYNC_GPU_COMMANDS_COMPLETE
#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117
#endif
#ifndef GL_SYNC_FLUSH_COMMANDS_BIT
#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001
#endif
#ifndef PFNGLFENCESYNCPROC
typedef struct __GLsync *GLsync;
typedef uint64_t GLuint64;
typedef GLsync (APIENTRY *PFNGLFENCESYNCPROC)(GLenum condition, GLbitfield flags);
typedef GLenum (APIENTRY *PFNGLCLIENTWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout);
typedef void (APIENTRY *PFNGLDELETESYNCPROC)(GLsync sync);
#endif
#ifdef _MSC_VER
// Linker directives for MSVC
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "winmm.lib")
#endif
// ------------------------------------------------------------
// Config / constants
// ------------------------------------------------------------
static const float DEMO_QUAD_LENGTH = 100.0f;
static const wchar_t CLASS_NAME[] = L"ResponsiveRenderingWindowClass";
static const wchar_t WINDOW_NAME[] = L"ResponsiveRenderingWindow";
// Complex animation constants
#define MAX_PARTICLES 2000
#define MAX_GEOMETRIC_SHAPES 50
#define FPS_HISTORY_SIZE 60
// ------------------------------------------------------------
// WGL extensions we use
// ------------------------------------------------------------
typedef BOOL (WINAPI *PFNWGLSWAPINTERVALEXTPROC)(int interval);
static PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT_ = NULL;
typedef PFNGLFENCESYNCPROC glFenceSync_t;
typedef PFNGLCLIENTWAITSYNCPROC glClientWaitSync_t;
typedef PFNGLDELETESYNCPROC glDeleteSync_t;
static glFenceSync_t glFenceSync_ = NULL;
static glClientWaitSync_t glClientWaitSync_ = NULL;
static glDeleteSync_t glDeleteSync_ = NULL;
typedef BOOL (WINAPI *PFNWGLCHOOSEPIXELFORMATARBPROC)(HDC,const int*,const FLOAT*,UINT,int*,UINT*);
typedef const char* (WINAPI *PFNWGLGETEXTENSIONSSTRINGARBPROC)(HDC);
static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB_ = NULL;
static PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB_ = NULL;
static bool has_ext(HDC hdc, const char* name) {
if (!wglGetExtensionsStringARB_) return false;
const char* s = wglGetExtensionsStringARB_(hdc);
return s && strstr(s, name);
}
static bool choose_pf_arb(HDC hdc, int* out_pf, bool* out_is_srgb) {
wglGetExtensionsStringARB_ = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
wglChoosePixelFormatARB_ = (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB");
if (!wglChoosePixelFormatARB_) return false;
const BOOL want_srgb = has_ext(hdc, "WGL_ARB_framebuffer_sRGB");
const int attribs[] = {
0x2001/*WGL_DRAW_TO_WINDOW_ARB*/, TRUE,
0x2010/*WGL_SUPPORT_OPENGL_ARB*/, TRUE,
0x2011/*WGL_DOUBLE_BUFFER_ARB*/, TRUE,
0x2013/*WGL_PIXEL_TYPE_ARB*/, 0x202B/*WGL_TYPE_RGBA_ARB*/,
0x2014/*WGL_COLOR_BITS_ARB*/, 32,
0x2022/*WGL_ALPHA_BITS_ARB*/, 8,
0x2027/*WGL_DEPTH_BITS_ARB*/, 24,
0x2023/*WGL_STENCIL_BITS_ARB*/, 8,
0x2041/*WGL_SAMPLE_BUFFERS_ARB*/, 1,
0x2042/*WGL_SAMPLES_ARB*/, 4, // 4x MSAA
// sRGB if supported:
0x20A9/*WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB*/, want_srgb ? TRUE : FALSE,
0
};
int pf = 0; UINT count = 0;
if (!wglChoosePixelFormatARB_(hdc, attribs, NULL, 1, &pf, &count) || count == 0) return false;
*out_pf = pf;
*out_is_srgb = want_srgb ? true : false;
return true;
}
// ------------------------------------------------------------
// Time utilities (monotonic via QPC)
// ------------------------------------------------------------
static double g_qpc_inv_freq = 0.0;
static void init_time(void) {
LARGE_INTEGER f;
QueryPerformanceFrequency(&f);
g_qpc_inv_freq = 1.0 / (double)f.QuadPart;
}
static double now_seconds(void) {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return (double)t.QuadPart * g_qpc_inv_freq;
}
// ------------------------------------------------------------
// Complex Animation Structures
// ------------------------------------------------------------
typedef struct {
float x, y; // position
float vx, vy; // velocity
float r, g, b, a; // color
float size; // particle size
float rotation; // rotation angle
float rotSpeed; // rotation speed
float life; // 0.0 to 1.0, 1.0 = just born
float decay; // life decay rate per second
} Particle;
typedef struct {
float x, y; // center position
float radius; // size
float rotation; // current rotation
float rotSpeed; // rotation speed
float scalePhase; // for pulsing scale
float r, g, b; // color
int sides; // number of sides (3-8)
} GeometricShape;
typedef struct {
Particle particles[MAX_PARTICLES];
GeometricShape shapes[MAX_GEOMETRIC_SHAPES];
int numParticles;
int numShapes;
// FPS tracking
double frameHistory[FPS_HISTORY_SIZE];
int frameIndex;
double currentFPS;
// Animation time
double animTime;
// Font display list for FPS rendering
GLuint fontBase;
bool fontReady;
} ComplexAnimation;
// ------------------------------------------------------------
// Frame flags and structs
// ------------------------------------------------------------
enum FrameFlags {
FRAME_WINDOW_SIZE_CHANGED = 1 << 0,
FRAME_TERMINATE_RENDER_THREAD = 1 << 1,
FRAME_TOGGLE_ANIM_PLAYBACK = 1 << 2,
FRAME_WAKE_MAIN_WHEN_COMPLETED = 1 << 3,
};
typedef struct FrameInfo {
float w, h; // client size for rendering
double eventT; // time of input event (e.g., spacebar)
uint8_t flags; // FrameFlags
} FrameInfo;
typedef struct WindowState {
HWND hWnd;
int32_t w, h; // client size, kept updated by WM_SIZE
POINT minSize;
CRITICAL_SECTION cs;
CONDITION_VARIABLE cv;
FrameInfo nextFrame; // shared frame request to render thread
} WindowState;
enum PingPongAnimFlags {
ANIM_RUNNING = 1 << 0,
ANIM_BACKWARDS = 1 << 1,
};
typedef struct PingPongAnimation {
double lastUpdateT;
float progress; // 0-1 ping-pong
uint8_t flags; // PingPongAnimFlags
} PingPongAnimation;
// ------------------------------------------------------------
// OpenGL helpers
// ------------------------------------------------------------
typedef struct GLContext {
HDC hdc;
HGLRC hglrc;
int viewportW;
int viewportH;
} GLContext;
static bool set_pixel_format(HDC hdc, bool* out_is_srgb) {
// First create a temp legacy context so wglGetProcAddress works:
PIXELFORMATDESCRIPTOR legacy = { sizeof(PIXELFORMATDESCRIPTOR) };
legacy.nVersion = 1;
legacy.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER;
legacy.iPixelType = PFD_TYPE_RGBA;
legacy.cColorBits = 24;
int pf_legacy = ChoosePixelFormat(hdc, &legacy);
SetPixelFormat(hdc, pf_legacy, &legacy);
HGLRC temp = wglCreateContext(hdc);
wglMakeCurrent(hdc, temp);
int pf = 0; bool is_srgb = false;
bool ok = choose_pf_arb(hdc, &pf, &is_srgb);
if (ok) {
// Reset to chosen ARB format
wglMakeCurrent(NULL, NULL);
wglDeleteContext(temp);
PIXELFORMATDESCRIPTOR pfd;
DescribePixelFormat(hdc, pf, sizeof(pfd), &pfd);
if (!SetPixelFormat(hdc, pf, &pfd)) return false;
*out_is_srgb = is_srgb;
return true;
}
// Fallback: keep legacy
*out_is_srgb = false;
wglMakeCurrent(NULL, NULL);
wglDeleteContext(temp);
// Re-apply legacy with alpha/depth/stencil
PIXELFORMATDESCRIPTOR pfd2 = {0};
pfd2.nSize=sizeof(pfd2); pfd2.nVersion=1;
pfd2.dwFlags=PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER;
pfd2.iPixelType=PFD_TYPE_RGBA;
pfd2.cColorBits=24; pfd2.cAlphaBits=8; pfd2.cDepthBits=24; pfd2.cStencilBits=8;
int pf2 = ChoosePixelFormat(hdc, &pfd2);
if (pf2==0) return false;
return SetPixelFormat(hdc, pf2, &pfd2) ? true : false;
}
static void load_wgl_extensions(void) {
wglSwapIntervalEXT_ = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
glFenceSync_ = (PFNGLFENCESYNCPROC) wglGetProcAddress("glFenceSync");
glClientWaitSync_ = (PFNGLCLIENTWAITSYNCPROC) wglGetProcAddress("glClientWaitSync");
glDeleteSync_ = (PFNGLDELETESYNCPROC) wglGetProcAddress("glDeleteSync");
}
static bool setup_font_rendering(GLContext* glc, ComplexAnimation* anim) {
// Create a simple bitmap font for FPS display
anim->fontBase = glGenLists(96);
if (anim->fontBase == 0) return false;
// Create a font
HFONT hFont = CreateFontA(-12, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
ANSI_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS,
ANTIALIASED_QUALITY, FF_DONTCARE | DEFAULT_PITCH,
"Courier New");
if (!hFont) return false;
HFONT hOldFont = (HFONT)SelectObject(glc->hdc, hFont);
BOOL result = wglUseFontBitmaps(glc->hdc, 32, 96, anim->fontBase);
SelectObject(glc->hdc, hOldFont);
DeleteObject(hFont);
anim->fontReady = (result == TRUE);
return anim->fontReady;
}
static bool init_gl_for_window(HWND hWnd, GLContext* out) {
out->hdc = GetDC(hWnd);
if (!out->hdc) return false;
bool framebuffer_is_srgb = false;
if (!set_pixel_format(out->hdc, &framebuffer_is_srgb)) { /* ... */ }
out->hglrc = wglCreateContext(out->hdc);
if (!out->hglrc) { /* ... */ }
wglMakeCurrent(out->hdc, out->hglrc);
load_wgl_extensions();
if (wglSwapIntervalEXT_) wglSwapIntervalEXT_(1);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
if (framebuffer_is_srgb) {
// Gamma-correct blending (if GL_EXT_framebuffer_sRGB / GL2.1+)
#ifndef GL_FRAMEBUFFER_SRGB
#define GL_FRAMEBUFFER_SRGB 0x8DB9
#endif
glEnable(GL_FRAMEBUFFER_SRGB);
}
// Enable MSAA if pixel format provides it
#ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE 0x809D
#endif
glEnable(GL_MULTISAMPLE);
glClearColor(0,0,0,1);
out->viewportW = out->viewportH = 0;
return true;
}
static void destroy_gl(GLContext* ctx, HWND hWnd, ComplexAnimation* anim) {
if (anim && anim->fontReady) {
glDeleteLists(anim->fontBase, 96);
anim->fontReady = false;
}
if (wglGetCurrentContext() == ctx->hglrc) {
wglMakeCurrent(NULL, NULL);
}
if (ctx->hglrc) {
wglDeleteContext(ctx->hglrc);
ctx->hglrc = NULL;
}
if (ctx->hdc) {
ReleaseDC(hWnd, ctx->hdc);
ctx->hdc = NULL;
}
}
static void set_ortho(float w, float h) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, (GLdouble)w, (GLdouble)h, 0.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
// ------------------------------------------------------------
// Complex Animation Functions
// ------------------------------------------------------------
static float randf(void) {
return (float)rand() / RAND_MAX;
}
static float randf_range(float min, float max) {
return min + randf() * (max - min);
}
static void init_particle(Particle* p, float w, float h) {
p->x = randf() * w;
p->y = randf() * h;
p->vx = randf_range(-200.0f, 200.0f);
p->vy = randf_range(-200.0f, 200.0f);
p->r = randf();
p->g = randf();
p->b = randf();
p->a = randf_range(0.3f, 1.0f);
p->size = randf_range(2.0f, 8.0f);
p->rotation = randf() * 360.0f;
p->rotSpeed = randf_range(-180.0f, 180.0f);
p->life = 1.0f;
p->decay = randf_range(0.2f, 0.8f);
}
static void init_geometric_shape(GeometricShape* s, float w, float h) {
s->x = randf() * w;
s->y = randf() * h;
s->radius = randf_range(20.0f, 60.0f);
s->rotation = randf() * 360.0f;
s->rotSpeed = randf_range(-90.0f, 90.0f);
s->scalePhase = randf() * 6.28f; // 2*PI
s->r = randf();
s->g = randf();
s->b = randf();
s->sides = 3 + (rand() % 6); // 3-8 sides
}
static void init_complex_animation(ComplexAnimation* anim, float w, float h) {
srand((unsigned int)GetTickCount());
// Initialize particles
anim->numParticles = MAX_PARTICLES;
for (int i = 0; i < anim->numParticles; i++) {
init_particle(&anim->particles[i], w, h);
}
// Initialize geometric shapes
anim->numShapes = MAX_GEOMETRIC_SHAPES;
for (int i = 0; i < anim->numShapes; i++) {
init_geometric_shape(&anim->shapes[i], w, h);
}
// Initialize FPS tracking
for (int i = 0; i < FPS_HISTORY_SIZE; i++) {
anim->frameHistory[i] = 1.0 / 60.0; // assume 60fps initially
}
anim->frameIndex = 0;
anim->currentFPS = 60.0;
anim->animTime = 0.0;
anim->fontReady = false;
}
static void update_particle(Particle* p, float dt, float w, float h) {
// Update position
p->x += p->vx * dt;
p->y += p->vy * dt;
// Bounce off walls
if (p->x < 0 || p->x > w) p->vx = -p->vx;
if (p->y < 0 || p->y > h) p->vy = -p->vy;
// Keep in bounds
if (p->x < 0) p->x = 0;
if (p->x > w) p->x = w;
if (p->y < 0) p->y = 0;
if (p->y > h) p->y = h;
// Update rotation
p->rotation += p->rotSpeed * dt;
// Update life
p->life -= p->decay * dt;
if (p->life <= 0.0f) {
// Respawn particle
init_particle(p, w, h);
}
}
static void update_geometric_shape(GeometricShape* s, float dt, float w, float h, double animTime) {
// Update rotation
s->rotation += s->rotSpeed * dt;
// Update scale phase for pulsing
s->scalePhase += dt * 2.0f;
// Move shapes in complex patterns
s->x = w * 0.5f + cosf((float)animTime * 0.3f + s->scalePhase) * (w * 0.3f);
s->y = h * 0.5f + sinf((float)animTime * 0.4f + s->scalePhase * 0.7f) * (h * 0.3f);
// Color cycling
float colorPhase = (float)animTime * 0.5f + s->scalePhase;
s->r = 0.5f + 0.5f * cosf(colorPhase);
s->g = 0.5f + 0.5f * cosf(colorPhase + 2.1f);
s->b = 0.5f + 0.5f * cosf(colorPhase + 4.2f);
}
static void draw_particle(const Particle* p) {
glColor4f(p->r, p->g, p->b, p->a * p->life);
glPointSize(p->size);
glPushMatrix();
glTranslatef(p->x, p->y, 0);
glRotatef(p->rotation, 0, 0, 1);
// Draw as a small quad for better visibility
float hs = p->size * 0.5f;
glBegin(GL_QUADS);
glVertex2f(-hs, -hs);
glVertex2f(hs, -hs);
glVertex2f(hs, hs);
glVertex2f(-hs, hs);
glEnd();
glPopMatrix();
}
static void draw_geometric_shape(const GeometricShape* s) {
float scale = 1.0f + 0.3f * sinf(s->scalePhase);
float alpha = 0.7f;
glColor4f(s->r, s->g, s->b, alpha);
glPushMatrix();
glTranslatef(s->x, s->y, 0);
glRotatef(s->rotation, 0, 0, 1);
glScalef(scale, scale, 1.0f);
// Draw filled polygon
glBegin(GL_TRIANGLE_FAN);
glVertex2f(0, 0); // center
for (int i = 0; i <= s->sides; i++) {
float angle = 2.0f * 3.14159f * i / s->sides;
float x = s->radius * cosf(angle);
float y = s->radius * sinf(angle);
glVertex2f(x, y);
}
glEnd();
// Draw outline
glColor4f(1.0f - s->r, 1.0f - s->g, 1.0f - s->b, alpha);
glLineWidth(2.0f);
glBegin(GL_LINE_LOOP);
for (int i = 0; i < s->sides; i++) {
float angle = 2.0f * 3.14159f * i / s->sides;
float x = s->radius * cosf(angle);
float y = s->radius * sinf(angle);
glVertex2f(x, y);
}
glEnd();
glPopMatrix();
}
static void update_fps(ComplexAnimation* anim, double frameTime) {
anim->frameHistory[anim->frameIndex] = frameTime;
anim->frameIndex = (anim->frameIndex + 1) % FPS_HISTORY_SIZE;
// Calculate average frame time
double totalTime = 0.0;
for (int i = 0; i < FPS_HISTORY_SIZE; i++) {
totalTime += anim->frameHistory[i];
}
double avgFrameTime = totalTime / FPS_HISTORY_SIZE;
anim->currentFPS = (avgFrameTime > 0.0) ? (1.0 / avgFrameTime) : 0.0;
}
static void draw_fps(const ComplexAnimation* anim) {
if (!anim->fontReady) return;
char fpsText[128];
sprintf_s(fpsText, sizeof(fpsText), "FPS: %.1f | Particles: %d | Shapes: %d", anim->currentFPS, anim->numParticles, anim->numShapes);
// Set up for text rendering
glColor3f(1.0f, 1.0f, 0.0f); // Yellow text
glRasterPos2f(10.0f, 25.0f);
// Render text using bitmap font
glPushAttrib(GL_LIST_BIT);
glListBase(anim->fontBase - 32);
glCallLists((GLsizei)strlen(fpsText), GL_UNSIGNED_BYTE, fpsText);
glPopAttrib();
}
static void draw_quad(float x0, float y0, float x1, float y1, float r, float g, float b, float a) {
glColor4f(r, g, b, a);
glBegin(GL_QUADS);
glVertex2f(x0, y0);
glVertex2f(x1, y0);
glVertex2f(x1, y1);
glVertex2f(x0, y1);
glEnd();
}
// ------------------------------------------------------------
// Ping-Pong animation update (0-1) - kept for compatibility
// ------------------------------------------------------------
static void pingpong_update(PingPongAnimation* da, double t) {
double dt = t - da->lastUpdateT;
da->lastUpdateT = t;
float d = (float)dt;
if (da->flags & ANIM_BACKWARDS) {
da->progress -= d;
if (da->progress <= 0.0f) {
da->progress = -da->progress; // reflect
da->flags &= (uint8_t)(~ANIM_BACKWARDS);
}
} else {
da->progress += d;
if (da->progress >= 1.0f) {
// progress = 2 - progress; and flip direction
da->progress -= (da->progress - 1.0f) * 2.0f;
da->flags |= ANIM_BACKWARDS;
}
}
if (da->progress < 0.0f) da->progress = 0.0f;
if (da->progress > 1.0f) da->progress = 1.0f;
}
// ------------------------------------------------------------
// Forward declarations
// ------------------------------------------------------------
static LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static DWORD WINAPI RenderThreadProc(LPVOID lpParam);
static void set_minimum_size(WindowState* ws, POINT newMin);
// ------------------------------------------------------------
// Create/show window (client size control) and init state
// ------------------------------------------------------------
static void get_client_size(HWND hWnd, int32_t* outW, int32_t* outH) {
RECT rc;
GetClientRect(hWnd, &rc);
*outW = rc.right - rc.left;
*outH = rc.bottom - rc.top;
}
static HWND create_window(WindowState* ws, const wchar_t* title, int x, int y, int clientW, int clientH) {
HINSTANCE hInstance = GetModuleHandleW(NULL);
WNDCLASSEXW wc = {0};
wc.cbSize = sizeof(wc);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
wc.hbrBackground = NULL; // No background erase - we redraw full window
wc.lpszClassName = CLASS_NAME;
RegisterClassExW(&wc);
DWORD style = WS_OVERLAPPEDWINDOW;
RECT r = { 0, 0, clientW, clientH };
AdjustWindowRect(&r, style, FALSE);
int winW = r.right - r.left;
int winH = r.bottom - r.top;
HWND hWnd = CreateWindowExW(
0, CLASS_NAME, WINDOW_NAME, style,
x, y, winW, winH,
NULL, NULL, hInstance, ws
);
SetWindowTextW(hWnd, title);
return hWnd;
}
// ------------------------------------------------------------
// Globals
// ------------------------------------------------------------
static const uint8_t FLAG_INIT = FRAME_WAKE_MAIN_WHEN_COMPLETED;
// ------------------------------------------------------------
// Window procedure
// ------------------------------------------------------------
static LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
WindowState* ws = (WindowState*)GetWindowLongPtrW(hWnd, GWLP_USERDATA);
switch (uMsg) {
case WM_NCCREATE: {
// Store WindowState* passed via CreateWindowExW
CREATESTRUCTW* cs = (CREATESTRUCTW*)lParam;
WindowState* passed = (WindowState*)cs->lpCreateParams;
SetWindowLongPtrW(hWnd, GWLP_USERDATA, (LONG_PTR)passed);
return TRUE;
}
case WM_SIZE: {
if (!ws) break;
ws->w = LOWORD(lParam);
ws->h = HIWORD(lParam);
return 0;
}
case WM_DPICHANGED: {
if (!ws) break;
RECT* r = (RECT*)lParam;
SetWindowPos(hWnd, NULL, r->left, r->top, r->right - r->left, r->bottom - r->top,
SWP_NOZORDER | SWP_NOACTIVATE);
return 0;
}
case WM_PAINT: {
if (!ws) break;
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
EnterCriticalSection(&ws->cs);
if (ws->nextFrame.w != (float)ws->w || ws->nextFrame.h != (float)ws->h) {
ws->nextFrame.w = (float)ws->w;
ws->nextFrame.h = (float)ws->h;
ws->nextFrame.flags |= (FRAME_WINDOW_SIZE_CHANGED | FRAME_WAKE_MAIN_WHEN_COMPLETED);
} else {
ws->nextFrame.flags |= FRAME_WAKE_MAIN_WHEN_COMPLETED;
}
// Wake the render thread if it's sleeping.
WakeConditionVariable(&ws->cv);
// Sleep until the frame is done.
SleepConditionVariableCS(&ws->cv, &ws->cs, INFINITE);
LeaveCriticalSection(&ws->cs);
EndPaint(hWnd, &ps);
return 0;
}
case WM_GETMINMAXINFO: {
if (!ws) break;
MINMAXINFO* mmi = (MINMAXINFO*)lParam;
mmi->ptMinTrackSize = ws->minSize;
return 0;
}
case WM_CLOSE: {
if (!ws) break;
EnterCriticalSection(&ws->cs);
ws->nextFrame.flags |= (FRAME_TERMINATE_RENDER_THREAD | FRAME_WAKE_MAIN_WHEN_COMPLETED);
WakeConditionVariable(&ws->cv);
// Wait for render thread cleanup
SleepConditionVariableCS(&ws->cv, &ws->cs, INFINITE);
LeaveCriticalSection(&ws->cs);
DestroyWindow(hWnd);
return 0;
}
case WM_DESTROY: {
if (ws) {
DeleteCriticalSection(&ws->cs);
}
PostQuitMessage(0);
return 0;
}
default:
break;
}
return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}
// ------------------------------------------------------------
// Minimum size setter, also forces current size >= min
// ------------------------------------------------------------
static void set_minimum_size(WindowState* ws, POINT newMinClient) {
// If needed, resize client to be >= new min
int32_t w = ws->w, h = ws->h;
bool needResize = (w < newMinClient.x) || (h < newMinClient.y);
if (needResize) {
if (w < newMinClient.x) w = newMinClient.x;
if (h < newMinClient.y) h = newMinClient.y;
ws->w = w; ws->h = h;
EnterCriticalSection(&ws->cs);
ws->nextFrame.w = (float)w;
ws->nextFrame.h = (float)h;
ws->nextFrame.flags |= (FRAME_WINDOW_SIZE_CHANGED | FRAME_WAKE_MAIN_WHEN_COMPLETED);
WakeConditionVariable(&ws->cv); // wake render thread if sleeping
LeaveCriticalSection(&ws->cs);
// SetWindowPos with SWP_NOMOVE|NOZORDER to adjust size only
SetWindowPos(ws->hWnd, NULL, 0, 0, w, h, SWP_NOMOVE | SWP_NOZORDER);
}
// Adjust for non-client area to set min track size
RECT rc = {0, 0, newMinClient.x, newMinClient.y};
AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
ws->minSize.x = rc.right - rc.left;
ws->minSize.y = rc.bottom - rc.top;
}
// ------------------------------------------------------------
// Render thread
// ------------------------------------------------------------
static DWORD WINAPI RenderThreadProc(LPVOID lpParam) {
WindowState* ws = (WindowState*)lpParam;
GLContext glc = {0};
if (!init_gl_for_window(ws->hWnd, &glc)) {
// If GL init fails, notify main thread so it doesn't hang in a paint wait.
EnterCriticalSection(&ws->cs);
WakeConditionVariable(&ws->cv);
LeaveCriticalSection(&ws->cs);
return 0;
}
// Complex animation state
ComplexAnimation complexAnim = {0};
init_complex_animation(&complexAnim, 800.0f, 600.0f);
setup_font_rendering(&glc, &complexAnim);
// Ping-Pong Animation state
PingPongAnimation anim = {0};
FrameInfo thisFrame = {0};
double prevDrawT = now_seconds();
double prevDeltaT = 1.0 / 60.0;
double estimatedNextDrawT = prevDrawT + prevDeltaT;
// Start animation immediately (don't wait for Space)
anim.flags |= ANIM_RUNNING;
anim.lastUpdateT = estimatedNextDrawT;
for (;;) {
// Synchronize with main thread and decide what to do
EnterCriticalSection(&ws->cs);
// If no pending frame flags and not animating, sleep until signaled.
if (!(anim.flags & ANIM_RUNNING) && ws->nextFrame.flags == 0) {
double before = now_seconds();
SleepConditionVariableCS(&ws->cv, &ws->cs, INFINITE);
double after = now_seconds();
// Adjust so "time stopped" while sleeping
prevDrawT += (after - before);
}
// Copy frame request and clear flags
thisFrame = ws->nextFrame; // struct copy
uint8_t requestedFlags = ws->nextFrame.flags;
ws->nextFrame.flags = 0;
LeaveCriticalSection(&ws->cs);
// Check termination
if (requestedFlags & FRAME_TERMINATE_RENDER_THREAD) {
break;
}
estimatedNextDrawT = prevDrawT + prevDeltaT;
// Update viewport on size changes
if (requestedFlags & FRAME_WINDOW_SIZE_CHANGED) {
int vw = (int)thisFrame.w;
int vh = (int)thisFrame.h;
if (vw < 1) vw = 1;
if (vh < 1) vh = 1;
if (glc.viewportW != vw || glc.viewportH != vh) {
glViewport(0, 0, vw, vh);
glc.viewportW = vw;
glc.viewportH = vh;
}
}
// Handle playback toggle
if (requestedFlags & FRAME_TOGGLE_ANIM_PLAYBACK) {
if (anim.flags & ANIM_RUNNING) {
// Stop playback; update up to event time
anim.flags &= (uint8_t)(~ANIM_RUNNING);
pingpong_update(&anim, thisFrame.eventT);
} else {
// Start playback from event time, then catch up to estimated draw time
anim.flags |= ANIM_RUNNING;
anim.lastUpdateT = thisFrame.eventT;
pingpong_update(&anim, estimatedNextDrawT);
}
} else {
if (anim.flags & ANIM_RUNNING) {
pingpong_update(&anim, estimatedNextDrawT);
}
}
// Update complex animation
complexAnim.animTime = estimatedNextDrawT;
float dt = (float)prevDeltaT;
// Update particles
for (int i = 0; i < complexAnim.numParticles; i++) {
update_particle(&complexAnim.particles[i], dt, thisFrame.w, thisFrame.h);
}
// Update geometric shapes
for (int i = 0; i < complexAnim.numShapes; i++) {
update_geometric_shape(&complexAnim.shapes[i], dt, thisFrame.w, thisFrame.h, complexAnim.animTime);
}
// Render
// Dynamic background based on animation time
float bg = 0.1f + 0.1f * sinf((float)complexAnim.animTime * 0.5f);
glClearColor(bg, bg * 0.8f, bg * 1.2f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
set_ortho(thisFrame.w, thisFrame.h);
// Draw complex animation
// 1. Draw geometric shapes first (background layer)
for (int i = 0; i < complexAnim.numShapes; i++) {
draw_geometric_shape(&complexAnim.shapes[i]);
}
// 2. Draw ping-pong quads (middle layer)
// Background gradient overlay
float gradientAlpha = 0.3f + 0.2f * sinf((float)complexAnim.animTime * 0.3f);
// Red/Cyan quad (bottom third)
{
float x0 = anim.progress * (thisFrame.w - DEMO_QUAD_LENGTH);
float x1 = x0 + DEMO_QUAD_LENGTH;
float y0 = thisFrame.h * 2.0f / 3.0f;
float y1 = thisFrame.h;
float r = 1.0f - anim.progress;
float g = anim.progress;
float b = anim.progress;
draw_quad(x0, y0, x1, y1, r, g, b, gradientAlpha);
}
// Green/Magenta quad (middle third)
{
float p = 1.0f - anim.progress;
float x0 = p * (thisFrame.w - DEMO_QUAD_LENGTH);
float x1 = x0 + DEMO_QUAD_LENGTH;
float y0 = thisFrame.h / 3.0f;
float y1 = thisFrame.h * 2.0f / 3.0f;
float r = anim.progress;
float g = 1.0f - anim.progress;
float b = anim.progress;
draw_quad(x0, y0, x1, y1, r, g, b, gradientAlpha);
}
// Blue/Yellow quad (top third)
{
float x0 = anim.progress * (thisFrame.w - DEMO_QUAD_LENGTH);
float x1 = x0 + DEMO_QUAD_LENGTH;
float y0 = 0.0f;
float y1 = thisFrame.h / 3.0f;
float r = anim.progress;
float g = anim.progress;
float b = 1.0f - anim.progress;
draw_quad(x0, y0, x1, y1, r, g, b, gradientAlpha);
}
// 3. Draw particles (foreground layer)
for (int i = 0; i < complexAnim.numParticles; i++) {
draw_particle(&complexAnim.particles[i]);
}
// 4. Draw FPS counter
update_fps(&complexAnim, prevDeltaT);
draw_fps(&complexAnim);
// Present
SwapBuffers(glc.hdc);
// Optional GPU sync, if ARB_sync available (helps align to when it is actually shown)
if (glFenceSync_ && glClientWaitSync_ && glDeleteSync_) {
GLsync fence = glFenceSync_(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
if (fence) {
glClientWaitSync_(fence, GL_SYNC_FLUSH_COMMANDS_BIT, 1000000000ULL);
glDeleteSync_(fence);
}
}
// Frame timing
double now = now_seconds();
prevDeltaT = now - prevDrawT;
prevDrawT = now;
// Wake the main thread if this frame was requested by WM_PAINT
if (requestedFlags & FRAME_WAKE_MAIN_WHEN_COMPLETED) {
WakeConditionVariable(&ws->cv);
}
}
// Cleanup GL
destroy_gl(&glc, ws->hWnd, &complexAnim);
// Report finished termination so WM_CLOSE can proceed
EnterCriticalSection(&ws->cs);
WakeConditionVariable(&ws->cv);
LeaveCriticalSection(&ws->cs);
return 0;
}
static bool g_fullscreen = false; static RECT g_windowedRect; static DWORD g_windowedStyle, g_windowedEx;
static void toggle_fullscreen(WindowState* ws) {
HWND hWnd = ws->hWnd;
if (!g_fullscreen) {
g_windowedStyle = GetWindowLongW(hWnd, GWL_STYLE);
g_windowedEx = GetWindowLongW(hWnd, GWL_EXSTYLE);
GetWindowRect(hWnd, &g_windowedRect);
MONITORINFO mi = { .cbSize = sizeof(mi) };
GetMonitorInfoW(MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST), &mi);
SetWindowLongW(hWnd, GWL_STYLE, g_windowedStyle & ~(WS_OVERLAPPEDWINDOW));
SetWindowLongW(hWnd, GWL_EXSTYLE, g_windowedEx);
SetWindowPos(hWnd, HWND_TOP,
mi.rcMonitor.left, mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
g_fullscreen = true;
} else {
SetWindowLongW(hWnd, GWL_STYLE, g_windowedStyle);
SetWindowLongW(hWnd, GWL_EXSTYLE, g_windowedEx);
SetWindowPos(hWnd, NULL,
g_windowedRect.left, g_windowedRect.top,
g_windowedRect.right - g_windowedRect.left,
g_windowedRect.bottom - g_windowedRect.top,
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
g_fullscreen = false;
}
}
// ------------------------------------------------------------
// Message pump helper (Peek/Dispatch + handle spacebar toggle)
// ------------------------------------------------------------