-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.cpp
More file actions
1956 lines (1688 loc) · 67.2 KB
/
game.cpp
File metadata and controls
1956 lines (1688 loc) · 67.2 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
#include <SDL3/SDL.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <SDL3_mixer/SDL_mixer.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <cstring>
#include <algorithm>
#include "defines.h"
#include "game.h"
#include "space.h"
#include "ship.h"
#include "loot.h"
#include "pdaudio.h"
#include "body.h"
#include "starfield.h"
#include "sdl_compat.h"
#include "platform.h"
using namespace std;
Game::Game()
:done(false), difficulty(1),
window(nullptr), renderer(nullptr), font(nullptr), mixer(nullptr),
music_audio(nullptr), music_track(nullptr),
buffer(nullptr), trailBuffer(nullptr), lastFireTime(0), fireRate(200),
state(STATE_MENU), menu_selection(2), pause_selection(0), ship(nullptr),
chunk_w(0), chunk_h(0),
camera_x(0), camera_y(0), camera_zoom(1.0f), camera_target_zoom(1.0f),
camera_target_x(0), camera_target_y(0){
}
Game::~Game(){
if (ship) {
delete ship;
}
for (auto* body : world_bodies) delete body;
world_bodies.clear();
world_asteroids.clear();
world_cuzers.clear();
world_loots.clear();
world_duders.clear();
projectiles.clear();
loaded_chunks.clear();
physicsWorld.destroy();
}
void Game::init_graphics(void){
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO))
abort("Failed to initialize SDL");
// Get display bounds for window sizing
SDL_DisplayID display_id = SDL_GetPrimaryDisplay();
const SDL_DisplayMode* mode = SDL_GetCurrentDisplayMode(display_id);
#ifdef SDL_PLATFORM_ANDROID
if (mode) {
window_width = mode->w;
window_height = mode->h;
} else {
window_width = 1920;
window_height = 1080;
}
#else
if (mode) {
window_width = (int)(mode->w * fullscreen);
window_height = (int)(mode->h * fullscreen);
} else {
window_width = 1280;
window_height = 720;
}
#endif
// Initialize SDL_ttf
if (!TTF_Init())
abort("Failed to initialize SDL_ttf");
// Initialize SDL_mixer
if (!MIX_Init())
abort("Failed to initialize SDL_mixer");
SDL_AudioSpec spec;
spec.freq = 44100;
spec.format = SDL_AUDIO_S16;
spec.channels = 2;
mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec);
if (!mixer)
abort("Failed to create SDL_mixer device");
// Create window
#ifdef SDL_PLATFORM_ANDROID
Uint32 window_flags = SDL_WINDOW_FULLSCREEN | SDL_WINDOW_HIGH_PIXEL_DENSITY;
#else
Uint32 window_flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY;
#endif
window = SDL_CreateWindow("Shippy", window_width, window_height, window_flags);
if (!window)
abort("Failed to create window");
// Create renderer with vsync
renderer = SDL_CreateRenderer(window, NULL);
if (!renderer)
abort("Failed to create renderer");
// Enable VSync
SDL_SetRenderVSync(renderer, 1);
// Get actual render output size (may differ from window size on HiDPI)
SDL_GetRenderOutputSize(renderer, &window_width, &window_height);
// Set global renderer for drawing functions
g_renderer = renderer;
// Load font
std::string font_path = asset_path("DejaVuSans.ttf");
font = TTF_OpenFont(font_path.c_str(), 24);
if (!font)
abort("Failed to load font!");
// Create render target texture for double buffering
buffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET,
window_width, window_height);
SDL_SetTextureBlendMode(buffer, SDL_BLENDMODE_BLEND);
// Create trail buffer for tracer effect (persistent between frames)
trailBuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET,
window_width, window_height);
SDL_SetTextureBlendMode(trailBuffer, SDL_BLENDMODE_BLEND);
// Clear trail buffer initially
SDL_SetRenderTarget(renderer, trailBuffer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_SetRenderTarget(renderer, NULL);
done = false;
last_frame_time = SDL_GetTicks();
// Init starfield here so it's available for the menu background
starfield.init(window_width, window_height);
// Init camera screen center
g_screen_cx = window_width / 2.0f;
g_screen_cy = window_height / 2.0f;
g_camera_x = g_screen_cx;
g_camera_y = g_screen_cy;
g_camera_zoom = 1.0f;
// Init touch input zones
touchInput.init(window_width, window_height);
}
void Game::init_game(void){
// Clean up previous game state
if (ship) { delete ship; ship = nullptr; }
for (auto* body : world_bodies) {
body->destroyPhysics(physicsWorld);
delete body;
}
world_bodies.clear();
for (auto& a : world_asteroids) a.destroyPhysics(physicsWorld);
world_asteroids.clear();
for (auto& c : world_cuzers) c.destroyPhysics(physicsWorld);
world_cuzers.clear();
for (auto& l : world_loots) l.destroyPhysics(physicsWorld);
world_loots.clear();
for (auto& d : world_duders) d.destroyPhysics(physicsWorld);
world_duders.clear();
for (auto& p : projectiles) p.destroyPhysics(physicsWorld);
projectiles.clear();
loaded_chunks.clear();
// Fresh world seed per restart so chunk content differs between runs.
world_seed = (unsigned int)time(NULL);
biases_groked.clear();
lastFireTime = 0;
lastFireTapTime = 0;
fireWasReleased = true;
camera_zoom = 1.0f;
camera_target_zoom = 1.0f;
trippyTimer = 0.0f;
tracerTimer = 0.0f;
tracerTimerMax = 0.0f;
tracerLengthMax = 0;
g_trippyLevel = 0;
g_tracerLength = 0;
g_hueShift = 0.0f;
particles.clear();
chunk_w = window_width;
chunk_h = window_height;
// Clean up previous music
if (music_track) { MIX_DestroyTrack(music_track); music_track = nullptr; }
if (music_audio) { MIX_DestroyAudio(music_audio); music_audio = nullptr; }
if (music_mode == MUSIC_ON) {
std::string music_path = asset_path("Power_Glove-Clutch.ogg");
music_audio = MIX_LoadAudio(mixer, music_path.c_str(), true);
if (music_audio) {
music_track = MIX_CreateTrack(mixer);
if (music_track) {
MIX_SetTrackAudio(music_track, music_audio);
SDL_PropertiesID props = SDL_CreateProperties();
SDL_SetNumberProperty(props, MIX_PROP_PLAY_LOOPS_NUMBER, -1);
MIX_PlayTrack(music_track, props);
SDL_DestroyProperties(props);
}
}
}
// MUSIC_CUSTOM: no file music, sounds come from our synth system
// MUSIC_OFF: no music at all
physicsWorld.init(0.6f);
// Ship starts at world origin
ship = new Ship(chunk_w / 2.0f, chunk_h / 2.0f, FUEL_START, SHIP_MASS);
ship->initPhysics(physicsWorld);
// Load initial chunks around the ship
update_chunks();
biases.load();
}
// ---- Chunk management ----
void Game::load_chunk(int cx, int cy) {
auto key = make_pair(cx, cy);
if (loaded_chunks.count(key)) return; // Already loaded
// Seed RNG deterministically for this chunk
unsigned int saved = rand();
srand((unsigned int)(cx * 73856093u) ^ (unsigned int)(cy * 19349663u)
^ (unsigned int)(difficulty * 83492791u) ^ world_seed);
SpaceTraits traits = generateTraitsForChunk(cx, cy, difficulty);
Chunk chunk;
chunk.cx = cx;
chunk.cy = cy;
chunk.traits = traits;
float base_x = cx * chunk_w;
float base_y = cy * chunk_h;
// Spawn bodies
for (int i = 0; i < traits.numBodies; i++) {
float w = MIN_BODY_SIZE + rand() % MAX_BODY_SIZE;
// Keep h within 70-130% of w so bodies stay near-circular
// (eccentricity capped at ~0.71 instead of uncapped).
float ratio = 0.7f + (rand() % 61) / 100.0f;
float h = w * ratio;
float px = base_x + (rand() % (int)(chunk_w - w/2));
float py = base_y + (rand() % (int)(chunk_h - h/2));
Body* body = new Body(px, py, w, h,
map_rgb(rand()%255, rand()%255, rand()%255));
body->chunk_cx = cx;
body->chunk_cy = cy;
body->initPhysics(physicsWorld);
// Gravity wells
if (i > 0 && traits.numGravityWells > 0) {
int interval = traits.numBodies / (traits.numGravityWells + 1);
if (interval > 0 && i % interval == 0) {
body->isGravityWell = true;
float avgSize = (w + h) / 2;
body->gravityStrength = avgSize * 0.5f;
body->width = avgSize;
body->height = avgSize;
body->width2 = avgSize / 2;
body->height2 = avgSize / 2;
}
}
chunk.bodies.push_back(body);
world_bodies.push_back(body);
}
// Spawn loot in structured patterns around bodies
// Fuel: orbital rings around bodies
// Mushrooms: clustered close to bodies
// Boosts: scattered far from bodies (open space)
auto spawnLoot = [&](float px, float py, float w, float h, GameColor color,
LootType type, float value) {
world_loots.emplace_back(px, py, w, h, color, type);
Loot& loot = world_loots.back();
loot.value = value;
loot.chunk_cx = cx;
loot.chunk_cy = cy;
loot.initPhysics(physicsWorld);
};
// Fuel: orbit around bodies in rings
{
int fuel_per_body = (chunk.bodies.size() > 0) ?
std::max(1, traits.numFuel / (int)chunk.bodies.size()) : traits.numFuel;
int fuel_placed = 0;
for (auto* body : chunk.bodies) {
if (fuel_placed >= traits.numFuel) break;
float orbit_r = (body->width2 + body->height2) / 2.0f + 40.0f + rand() % 40;
int count = std::min(fuel_per_body, traits.numFuel - fuel_placed);
float angle_offset = (rand() % 360) * M_PI / 180.0f;
for (int i = 0; i < count; i++) {
float angle = angle_offset + i * 2.0f * M_PI / count;
float fuel_value = 100 + rand() % (int)FUEL_START/2;
float fuel_scale = (fuel_value - 100) / 5000.0f;
float w = 15 + fuel_scale * 20;
float h = 22 + fuel_scale * 30;
float px = body->pos.x + cosf(angle) * orbit_r;
float py = body->pos.y + sinf(angle) * orbit_r;
spawnLoot(px, py, w, h, map_rgb(255, 20, 20), FUEL, fuel_value);
fuel_placed++;
}
}
// Any remaining fuel if no bodies
for (int i = fuel_placed; i < traits.numFuel; i++) {
float fuel_value = 100 + rand() % (int)FUEL_START/2;
float fuel_scale = (fuel_value - 100) / 5000.0f;
float w = 15 + fuel_scale * 20;
float h = 22 + fuel_scale * 30;
spawnLoot(base_x + rand() % chunk_w, base_y + rand() % chunk_h,
w, h, map_rgb(255, 20, 20), FUEL, fuel_value);
}
}
// Mushrooms: clustered close to bodies (on the surface or just outside)
{
int shroom_placed = 0;
for (auto* body : chunk.bodies) {
if (shroom_placed >= traits.numMushroom) break;
float body_r = (body->width2 + body->height2) / 2.0f;
float close_r = body_r + 15.0f + rand() % 20;
float angle = (rand() % 360) * M_PI / 180.0f;
float shroom_value = 1 + rand() % 3;
float shroom_scale = (shroom_value - 1) / 2.0f;
float w = 40 + shroom_scale * 30;
float h = w * 1.2f;
float px = body->pos.x + cosf(angle) * close_r;
float py = body->pos.y + sinf(angle) * close_r;
spawnLoot(px, py, w, h, map_rgb(180, 50, 220), MUSHROOM, shroom_value);
shroom_placed++;
}
// Any remaining mushrooms near random bodies
for (int i = shroom_placed; i < traits.numMushroom; i++) {
if (!chunk.bodies.empty()) {
Body* body = chunk.bodies[rand() % chunk.bodies.size()];
float body_r = (body->width2 + body->height2) / 2.0f;
float close_r = body_r + 15.0f + rand() % 25;
float angle = (rand() % 360) * M_PI / 180.0f;
float shroom_value = 1 + rand() % 3;
float shroom_scale = (shroom_value - 1) / 2.0f;
float w = 40 + shroom_scale * 30;
float h = w * 1.2f;
spawnLoot(body->pos.x + cosf(angle) * close_r,
body->pos.y + sinf(angle) * close_r,
w, h, map_rgb(180, 50, 220), MUSHROOM, shroom_value);
} else {
float shroom_value = 1 + rand() % 3;
float shroom_scale = (shroom_value - 1) / 2.0f;
float w = 40 + shroom_scale * 30;
float h = w * 1.2f;
spawnLoot(base_x + rand() % chunk_w, base_y + rand() % chunk_h,
w, h, map_rgb(180, 50, 220), MUSHROOM, shroom_value);
}
}
}
// Boosts: scattered in open space, far from bodies
for (int i = 0; i < traits.numBoost; i++) {
float boost_value = rand() % 5 + 2;
float boost_scale = (boost_value - 2) / 4.0f;
float w = 25 + boost_scale * 30;
float h = w;
// Try to place far from any body
float best_px = base_x + rand() % chunk_w;
float best_py = base_y + rand() % chunk_h;
float best_dist = 0;
for (int attempt = 0; attempt < 8; attempt++) {
float px = base_x + rand() % chunk_w;
float py = base_y + rand() % chunk_h;
float min_dist = 1e9f;
for (auto* body : chunk.bodies) {
float dx = px - body->pos.x;
float dy = py - body->pos.y;
float d = sqrtf(dx*dx + dy*dy) - (body->width2 + body->height2) / 2.0f;
if (d < min_dist) min_dist = d;
}
if (min_dist > best_dist) {
best_dist = min_dist;
best_px = px;
best_py = py;
}
}
spawnLoot(best_px, best_py, w, h, map_rgb(255, 200, 20), BOOST, boost_value);
}
// Spawn duders
for (int i = 0; i < traits.numDuders; i++) {
float px = base_x + rand() % chunk_w;
float py = base_y + rand() % chunk_h;
world_duders.emplace_back(px, py, rand()%20 + 20, rand()%15 + 15);
Duder& duder = world_duders.back();
duder.chunk_cx = cx;
duder.chunk_cy = cy;
duder.initPhysics(physicsWorld);
}
// Spawn asteroids
for (int i = 0; i < traits.numAsteroids; i++) {
AsteroidSize sz;
int sizeRoll = rand() % 100;
if (sizeRoll < 50) sz = AsteroidSize::SMALL;
else if (sizeRoll < 85) sz = AsteroidSize::MEDIUM;
else sz = AsteroidSize::LARGE;
float px = base_x + rand() % chunk_w;
float py = base_y + rand() % chunk_h;
world_asteroids.emplace_back(px, py, sz);
Asteroid& asteroid = world_asteroids.back();
float a = (rand() % 360) * M_PI / 180.0f;
float speed = (5.0f + (rand() % 400) / 10.0f) * traits.asteroidSpeed;
asteroid.vel.x = cos(a) * speed;
asteroid.vel.y = sin(a) * speed;
asteroid.chunk_cx = cx;
asteroid.chunk_cy = cy;
asteroid.initPhysics(physicsWorld);
}
// Spawn cuzers
for (int i = 0; i < traits.numCuzers; i++) {
CuzerSize sz;
int sizeRoll = rand() % 100;
if (sizeRoll < 40) sz = CuzerSize::SMALL;
else if (sizeRoll < 80) sz = CuzerSize::MEDIUM;
else sz = CuzerSize::LARGE;
float px = base_x + rand() % chunk_w;
float py = base_y + rand() % chunk_h;
world_cuzers.emplace_back(px, py, sz);
Cuzer& cuzer = world_cuzers.back();
float a = (rand() % 360) * M_PI / 180.0f;
float speed = (2.0f + (rand() % 300) / 10.0f) * traits.cuzerSpeed;
cuzer.vel.x = cos(a) * speed;
cuzer.vel.y = sin(a) * speed;
cuzer.chunk_cx = cx;
cuzer.chunk_cy = cy;
cuzer.initPhysics(physicsWorld);
}
loaded_chunks[key] = chunk;
srand(saved); // Restore RNG
}
void Game::unload_chunk(int cx, int cy) {
auto key = make_pair(cx, cy);
auto it = loaded_chunks.find(key);
if (it == loaded_chunks.end()) return;
// Remove bodies
for (Body* body : it->second.bodies) {
body->destroyPhysics(physicsWorld);
world_bodies.remove(body);
delete body;
}
// Remove entities belonging to this chunk
for (auto eit = world_loots.begin(); eit != world_loots.end(); ) {
if (eit->chunk_cx == cx && eit->chunk_cy == cy) {
eit->destroyPhysics(physicsWorld);
eit = world_loots.erase(eit);
} else ++eit;
}
for (auto eit = world_duders.begin(); eit != world_duders.end(); ) {
if (eit->chunk_cx == cx && eit->chunk_cy == cy && !eit->is_following) {
eit->destroyPhysics(physicsWorld);
eit = world_duders.erase(eit);
} else ++eit;
}
for (auto eit = world_asteroids.begin(); eit != world_asteroids.end(); ) {
if (eit->chunk_cx == cx && eit->chunk_cy == cy) {
eit->destroyPhysics(physicsWorld);
eit = world_asteroids.erase(eit);
} else ++eit;
}
for (auto eit = world_cuzers.begin(); eit != world_cuzers.end(); ) {
if (eit->chunk_cx == cx && eit->chunk_cy == cy) {
eit->destroyPhysics(physicsWorld);
eit = world_cuzers.erase(eit);
} else ++eit;
}
loaded_chunks.erase(it);
}
void Game::update_chunks(void) {
if (!ship) return;
int ship_cx = (int)floor(ship->pos.x / chunk_w);
int ship_cy = (int)floor(ship->pos.y / chunk_h);
int load_radius = 2;
int unload_radius = 3;
// Load chunks within radius
for (int dy = -load_radius; dy <= load_radius; dy++) {
for (int dx = -load_radius; dx <= load_radius; dx++) {
load_chunk(ship_cx + dx, ship_cy + dy);
}
}
// Unload chunks beyond unload radius
vector<pair<int,int>> to_unload;
for (auto& kv : loaded_chunks) {
int dcx = abs(kv.first.first - ship_cx);
int dcy = abs(kv.first.second - ship_cy);
if (dcx > unload_radius || dcy > unload_radius) {
to_unload.push_back(kv.first);
}
}
for (auto& key : to_unload) {
unload_chunk(key.first, key.second);
}
}
SpaceTraits& Game::get_chunk_traits(int cx, int cy) {
auto key = make_pair(cx, cy);
return loaded_chunks[key].traits;
}
void Game::update_graphics(void){
// Starfield handles its own parallax using camera globals
starfield.draw();
// Draw all world entities (camera handles viewport)
for (auto* body : world_bodies) body->draw();
for (auto& loot : world_loots) loot.draw();
for (auto& duder : world_duders) duder.draw();
for (auto& asteroid : world_asteroids) asteroid.draw();
for (auto& cuzer : world_cuzers) cuzer.draw();
ship->draw();
for (auto& proj : projectiles)
proj.draw();
drawParticles();
for (auto& duder : world_duders)
draw_duder_bias(&duder);
}
void Game::draw_hud(void){
float save_zoom = g_camera_zoom;
float save_cx = g_camera_x, save_cy = g_camera_y;
g_camera_zoom = 1.0f;
g_camera_x = g_screen_cx;
g_camera_y = g_screen_cy;
draw_info();
draw_sound_labels();
#ifdef SDL_PLATFORM_ANDROID
touchInput.draw();
#endif
g_camera_zoom = save_zoom;
g_camera_x = save_cx;
g_camera_y = save_cy;
}
void Game::update_game(void){
update_camera();
// Zone-based color theme from ship's current chunk (with smooth blending)
int ship_cx = (int)floor(ship->pos.x / chunk_w);
int ship_cy = (int)floor(ship->pos.y / chunk_h);
auto key = make_pair(ship_cx, ship_cy);
if (loaded_chunks.count(key)) {
int newTheme = static_cast<int>(loaded_chunks[key].traits.theme);
if (newTheme != g_colorTheme) {
g_colorThemePrev = g_colorTheme;
g_colorTheme = newTheme;
g_colorThemeBlend = 0.0f;
}
}
if (g_colorThemeBlend < 1.0f) {
g_colorThemeBlend += 0.01f; // ~1.7 second transition at 60fps
if (g_colorThemeBlend > 1.0f) g_colorThemeBlend = 1.0f;
}
float dt = 1.0f / 60.0f;
// Decay loot effect timers
if (trippyTimer > 0.0f) {
trippyTimer -= dt;
if (trippyTimer <= 0.0f) {
trippyTimer = 0.0f;
g_trippyLevel = 0;
}
}
if (tracerTimer > 0.0f) {
tracerTimer -= dt;
if (tracerTimer <= 0.0f) {
tracerTimer = 0.0f;
g_tracerLength = 0;
} else {
float ratio = tracerTimer / tracerTimerMax;
g_tracerLength = (int)(tracerLengthMax * ratio);
}
}
// Increment hue shift for trippy effect (speed based on level)
if (g_trippyLevel > 0) {
g_hueShift += g_trippyLevel * 2.0f; // 2-6 degrees per frame
if (g_hueShift >= 360.0f) g_hueShift -= 360.0f;
} else {
g_hueShift = 0.0f;
}
starfield.update();
applyGravityWells();
// Single physics world step
if (physicsWorld.isValid())
physicsWorld.step(1.0f / 60.0f);
if (ship) ship->update();
updateProjectiles();
updateAsteroids();
updateCuzers();
processCollisions();
// Update duders
for (auto& duder : world_duders)
duder.update(chunk_w, chunk_h, ship->pos.x, ship->pos.y, ship->vel.x, ship->vel.y);
updateParticles();
// Load/unload chunks AFTER physics+collisions to avoid stale pointers
update_chunks();
}
// update_space removed — continuous world has no space boundaries
void Game::applyGravityWells(void){
const float G = 30.0f;
const float maxForce = 8.0f;
for (auto* body : world_bodies) {
if (!body->isGravityWell) continue;
// Calculate direction from ship to gravity well
float dx = body->pos.x - ship->pos.x;
float dy = body->pos.y - ship->pos.y;
float distSq = dx * dx + dy * dy;
float dist = sqrt(distSq);
// Avoid division by zero and limit force at very close distances
if (dist < 80.0f) dist = 80.0f;
// Calculate gravitational force: F = G * strength / r^2
float force = G * body->gravityStrength / distSq;
// Cap the force so gravity wells are escapable with thrust
if (force > maxForce) force = maxForce;
// Normalize direction and apply force
float fx = (dx / dist) * force;
float fy = (dy / dist) * force;
if (physicsWorld.isValid() && b2Body_IsValid(ship->physicsBody)) {
physicsWorld.applyForceToCenter(ship->physicsBody,
fx * PIXELS_PER_METER * 60.0f,
fy * PIXELS_PER_METER * 60.0f);
} else {
ship->accel.x += fx;
ship->accel.y += fy;
}
}
}
void Game::fireProjectile(void) {
Uint64 currentTime = SDL_GetTicks();
if (currentTime - lastFireTime < fireRate) return;
lastFireTime = currentTime;
// Create projectile at ship's nose position
float noseX = ship->pos.x + cos(ship->angle) * ship->height2;
float noseY = ship->pos.y + sin(ship->angle) * ship->height2;
projectiles.emplace_back(noseX, noseY, ship->angle, PHOTON_SPEED);
Projectile& proj = projectiles.back();
// Add ship velocity so the photon moves away from the ship at c,
// regardless of how fast the ship itself is moving.
proj.vel.x += ship->vel.x;
proj.vel.y += ship->vel.y;
proj.initPhysics(physicsWorld);
}
void Game::launchDuder(void) {
// Find a following duder to launch
Duder* toLaunch = nullptr;
for (auto& duder : world_duders) {
if (duder.is_following && !duder.is_launched && !duder.is_killed) {
toLaunch = &duder;
break;
}
}
if (!toLaunch) return;
toLaunch->is_following = false;
toLaunch->is_launched = true;
toLaunch->launch_life = 3.0f;
// Launch from ship nose in ship's facing direction
float launchSpeed = 10.0f;
float noseX = ship->pos.x + cosf(ship->angle) * ship->height2;
float noseY = ship->pos.y + sinf(ship->angle) * ship->height2;
toLaunch->pos.x = noseX;
toLaunch->pos.y = noseY;
toLaunch->vel.x = cosf(ship->angle) * launchSpeed + ship->vel.x * 0.2f;
toLaunch->vel.y = sinf(ship->angle) * launchSpeed + ship->vel.y * 0.2f;
if (b2Body_IsValid(toLaunch->physicsBody)) {
b2Body_SetTransform(toLaunch->physicsBody,
{noseX / PIXELS_PER_METER, noseY / PIXELS_PER_METER},
b2Body_GetRotation(toLaunch->physicsBody));
physicsWorld.setLinearVelocity(
toLaunch->physicsBody,
toLaunch->vel.x * FRAME_RATE,
toLaunch->vel.y * FRAME_RATE);
}
play_croak();
}
void Game::play_impact_sound(Object* obj, GameColor color, SynthRole role) {
if (music_mode != MUSIC_CUSTOM) return;
GameColor tc = transform_color(color);
float hue, sat, val;
rgb_to_hsv(tc.r, tc.g, tc.b, hue, sat, val);
const char* recv = "impact-mid";
float basePitch = 60.0f;
switch (role) {
case SynthRole::BASS: recv = "impact-bass"; basePitch = 36.0f; break;
case SynthRole::MID: recv = "impact-mid"; basePitch = 60.0f; break;
case SynthRole::HIHAT: recv = "impact-hihat"; basePitch = 0.0f; break;
case SynthRole::GENERAL: recv = "impact-general"; basePitch = 48.0f; break;
}
float pitch = basePitch + hue * 24.0f;
pd_send_float(recv, pitch);
char buf[64];
snprintf(buf, sizeof(buf), "%s %.0f", recv, pitch);
log_sound_trigger(buf);
}
void Game::log_sound_trigger(const char* name) {
recent_sounds.push_back({std::string(name), SDL_GetTicks()});
if (recent_sounds.size() > 12) {
recent_sounds.erase(recent_sounds.begin(),
recent_sounds.begin() + (recent_sounds.size() - 12));
}
}
void Game::draw_sound_labels(void) {
const Uint64 LIFETIME_MS = 1500;
Uint64 now = SDL_GetTicks();
recent_sounds.erase(
std::remove_if(recent_sounds.begin(), recent_sounds.end(),
[&](const SoundLabel& s){ return now - s.start_ms > LIFETIME_MS; }),
recent_sounds.end());
float s = std::min(window_width, window_height) / 720.0f;
float x = 20.0f * s;
float y_base = 20.0f * s;
int i = 0;
for (auto it = recent_sounds.rbegin(); it != recent_sounds.rend(); ++it, ++i) {
Uint64 age = now - it->start_ms;
float alpha_f = 1.0f - (float)age / (float)LIFETIME_MS;
if (alpha_f < 0) alpha_f = 0;
Uint8 a = (Uint8)(alpha_f * 255);
SDL_Color col = {220, 240, 255, a};
draw_text_scaled(it->name.c_str(), x, y_base + i * 18.0f * s, col, 1.0f * s, false);
}
}
void Game::updateProjectiles(void) {
// Update all projectiles (no wrapping — they fly freely)
for (auto& proj : projectiles) {
proj.update();
}
// Remove only expired projectiles
for (auto it = projectiles.begin(); it != projectiles.end(); ) {
if (it->isExpired()) {
it->destroyPhysics(physicsWorld);
it = projectiles.erase(it);
} else {
++it;
}
}
}
void Game::updateAsteroids(void) {
for (auto& asteroid : world_asteroids) {
if (!asteroid.isDestroyed())
asteroid.update();
}
for (auto it = world_asteroids.begin(); it != world_asteroids.end(); ) {
if (it->isDestroyed()) {
it->destroyPhysics(physicsWorld);
it = world_asteroids.erase(it);
} else {
++it;
}
}
}
void Game::updateCuzers(void) {
for (auto& cuzer : world_cuzers) {
if (!cuzer.isDestroyed())
cuzer.update(ship->pos.x, ship->pos.y);
}
for (auto it = world_cuzers.begin(); it != world_cuzers.end(); ) {
if (it->isDestroyed()) {
it->destroyPhysics(physicsWorld);
it = world_cuzers.erase(it);
} else {
++it;
}
}
}
void Game::spawnChildAsteroids(Asteroid& parent) {
AsteroidSize childSize;
int childCount;
switch (parent.getSize()) {
case AsteroidSize::LARGE:
childSize = AsteroidSize::MEDIUM;
childCount = 2 + rand() % 2;
break;
case AsteroidSize::MEDIUM:
childSize = AsteroidSize::SMALL;
childCount = 2 + rand() % 2;
break;
case AsteroidSize::SMALL:
return;
}
for (int i = 0; i < childCount; i++) {
float offsetX = ((rand() % 40) - 20);
float offsetY = ((rand() % 40) - 20);
world_asteroids.emplace_back(parent.pos.x + offsetX, parent.pos.y + offsetY, childSize);
Asteroid& child = world_asteroids.back();
child.chunk_cx = parent.chunk_cx;
child.chunk_cy = parent.chunk_cy;
float angle = (float)i * 2.0f * M_PI / childCount + ((rand() % 100) / 100.0f);
float speed = 2.0f + (rand() % 30) / 10.0f;
child.vel.x = cos(angle) * speed;
child.vel.y = sin(angle) * speed;
child.initPhysics(physicsWorld);
}
}
void Game::draw_info(void){
GameColor color = map_rgb(255, 255, 255);
float speed = sqrt(ship->vel.x*ship->vel.x + ship->vel.y*ship->vel.y);
// Build effects string
char effects[64] = "";
if (g_trippyLevel > 0 || g_tracerLength > 0) {
int pos = 0;
pos += snprintf(effects + pos, sizeof(effects) - pos, " |");
if (g_trippyLevel > 0) pos += snprintf(effects + pos, sizeof(effects) - pos, " Trippy:%d", g_trippyLevel);
if (g_tracerLength > 0) pos += snprintf(effects + pos, sizeof(effects) - pos, " Tracers:%d", g_tracerLength);
}
char buf[512];
snprintf(buf, sizeof(buf),
"(%.0f, %.0f) | Biases: %ld/%ld | Speed: %.1f | Fuel: %.1f%s",
ship->pos.x, ship->pos.y, biases_groked.size(), biases.biases.size(), speed, ship->fuel, effects
);
// Render text to surface, then create texture
SDL_Color sdl_color = {255, 255, 255, 255};
SDL_Surface* surface = TTF_RenderText_Blended(font, buf, 0, sdl_color);
if (surface) {
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
if (texture) {
SDL_FRect dst = {10, 10, (float)surface->w, (float)surface->h};
SDL_RenderTexture(renderer, texture, NULL, &dst);
SDL_DestroyTexture(texture);
}
SDL_DestroySurface(surface);
}
(void)color; // Suppress unused variable warning
}
// initSpacePhysics/enableSpacePhysics/disableSpacePhysics removed
// Each Space now manages its own PhysicsWorld via space->initPhysics()
void Game::processCollisions(void) {
if (!physicsWorld.isValid()) return;
// Collect items to remove (defer removal until after processing all events)
vector<Loot*> lootsToRemove;
vector<Asteroid*> asteroidsToDestroy;
vector<Cuzer*> cuzersToDestroy;
vector<Projectile*> projectilesToDestroy;
// SENSOR events for loot pickup (sensors don't generate contact events)
b2SensorEvents sensorEvents = b2World_GetSensorEvents(physicsWorld.getWorldId());
for (int i = 0; i < sensorEvents.beginCount; i++) {
b2SensorBeginTouchEvent* event = sensorEvents.beginEvents + i;
// Check if shapes are still valid (might have been destroyed)
if (!b2Shape_IsValid(event->sensorShapeId) || !b2Shape_IsValid(event->visitorShapeId)) {
continue;
}
b2BodyId sensorBody = b2Shape_GetBody(event->sensorShapeId);
b2BodyId visitorBody = b2Shape_GetBody(event->visitorShapeId);
// Check if bodies are still valid
if (!b2Body_IsValid(sensorBody) || !b2Body_IsValid(visitorBody)) {
continue;
}
Object* sensorObj = (Object*)b2Body_GetUserData(sensorBody);
Object* visitorObj = (Object*)b2Body_GetUserData(visitorBody);
if (!sensorObj || !visitorObj) continue;
// Check for ship + loot
Ship* shipObj = dynamic_cast<Ship*>(visitorObj);
Loot* lootObj = dynamic_cast<Loot*>(sensorObj);
if (shipObj && lootObj) {
// Check if already marked for removal
bool alreadyMarked = false;
for (Loot* l : lootsToRemove) {
if (l == lootObj) {
alreadyMarked = true;
break;
}
}
if (!alreadyMarked) {
apply_loot(lootObj);
lootsToRemove.push_back(lootObj);
}
}
}
// CONTACT events for physical collisions (ship/duder, duder/body)
b2ContactEvents contactEvents = b2World_GetContactEvents(physicsWorld.getWorldId());
for (int i = 0; i < contactEvents.beginCount; i++) {
b2ContactBeginTouchEvent* beginEvent = contactEvents.beginEvents + i;
// Check if shapes are still valid
if (!b2Shape_IsValid(beginEvent->shapeIdA) || !b2Shape_IsValid(beginEvent->shapeIdB)) {
continue;
}
Object* objA = (Object*)b2Shape_GetUserData(beginEvent->shapeIdA);
Object* objB = (Object*)b2Shape_GetUserData(beginEvent->shapeIdB);
if (!objA || !objB) continue;
Ship* shipObj = dynamic_cast<Ship*>(objA);
if (!shipObj) shipObj = dynamic_cast<Ship*>(objB);
Duder* duderObj = dynamic_cast<Duder*>(objA);
if (!duderObj) duderObj = dynamic_cast<Duder*>(objB);
Body* bodyObj = dynamic_cast<Body*>(objA);
if (!bodyObj) bodyObj = dynamic_cast<Body*>(objB);
Asteroid* asteroidObj = dynamic_cast<Asteroid*>(objA);
if (!asteroidObj) asteroidObj = dynamic_cast<Asteroid*>(objB);
Projectile* projectileObj = dynamic_cast<Projectile*>(objA);
if (!projectileObj) projectileObj = dynamic_cast<Projectile*>(objB);