summaryrefslogtreecommitdiff
path: root/src/port/Game.cpp
blob: 9804fe324c6bec7f22e043b3234ca7a41523730b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
#include <libultraship.h>
#include <typeinfo>

#include "Game.h"
#include "port/Engine.h"

#include <fast/Fast3dWindow.h>
#include <memory>
#include <atomic>
#include "engine/World.h"
#include "engine/AllTracks.h"

#include "engine/tracks/PodiumCeremony.h"

#include "engine/GarbageCollector.h"

#include "engine/TrainCrossing.h"
#include "engine/objects/BombKart.h"
#include "engine/objects/Lakitu.h"

#include "engine/Smoke.h"

#include "engine/HM_Intro.h"

#include "engine/editor/Editor.h"
#include "engine/editor/SceneManager.h"
#include "engine/registry/RegisterContent.h"

#include "engine/cameras/GameCamera.h"
#include "engine/cameras/FreeCamera.h"
#include "engine/cameras/TourCamera.h"
#include "engine/cameras/LookBehindCamera.h"

#include "engine/TrackBrowser.h"
#include "engine/RandomItemTable.h"
#include "engine/sky/Sky.h"

#ifdef _WIN32
#include <locale.h>
#endif

extern "C" {
#include "main.h"
#include "audio/load.h"
#include "audio/external.h"
#include "racing/render_courses.h"
#include "menus.h"
#include "update_objects.h"
#include "spawn_players.h"
#include "src/enhancements/collision_viewer.h"
#include "code_800029B0.h"
#include "code_80057C60.h"
// #include "engine/wasm.h"
}

extern "C" void Graphics_PushFrame(Gfx* pool) {
    GameEngine::ProcessGfxCommands(pool);
}

// Create the world instance
static World sWorldInstance;

// Deferred cleaning when clearing all actors in the editor
bool bCleanWorld = false;

std::unique_ptr<Cup> gMushroomCup;
std::unique_ptr<Cup> gFlowerCup;
std::unique_ptr<Cup> gStarCup;
std::unique_ptr<Cup> gSpecialCup;
std::unique_ptr<Cup> gBattleCup;

HarbourMastersIntro gMenuIntro;

TrackEditor::Editor gEditor;

s32 gTrophyIndex = NULL_OBJECT_ID;

/** Spawner Registries **/
Registry<TrackInfo> gTrackRegistry;
Registry<ActorInfo, const SpawnParams&> gActorRegistry;
Registry<ItemInfo> gItemRegistry;

/** Data Registries **/
DataRegistry<RandomItemTable> gItemTableRegistry;

std::unique_ptr<TrackBrowser> gTrackBrowser;
std::unique_ptr<Sky> gSky;

World* GetWorld() {
    return World::Instance;
}

void CustomEngineInit() {
    // Close the editor because lus remembers if it was open
    // This also turns off freecam
    gEditor.Disable();

    
    gSky = std::make_unique<Sky>();
    RegisterTracks(gTrackRegistry);
    gTrackBrowser = std::make_unique<TrackBrowser>(gTrackRegistry);
    TrackBrowser::Instance->FindCustomTracks();
    TrackBrowser::Instance->Refresh(gTrackRegistry);

    gMushroomCup = std::make_unique<Cup>("mk:mushroom_cup", "Mushroom Cup", std::vector<std::string>{
        "mk:luigi_raceway", 
        "mk:moo_moo_farm", 
        "mk:koopa_troopa_beach", 
        "mk:kalimari_desert"
    });

    gFlowerCup = std::make_unique<Cup>("mk:flower_cup", "Flower Cup", std::vector<std::string>{
        "mk:toads_turnpike", 
        "mk:frappe_snowland", 
        "mk:choco_mountain", 
        "mk:mario_raceway"
    });

    gStarCup = std::make_unique<Cup>("mk:star_cup", "Star Cup", std::vector<std::string>{
        "mk:wario_stadium", 
        "mk:sherbet_land", 
        "mk:royal_raceway", 
        "mk:bowsers_castle"
    });

    gSpecialCup = std::make_unique<Cup>("mk:special_cup", "Special Cup", std::vector<std::string>{
        "mk:dk_jungle", 
        "mk:yoshi_valley", 
        "mk:banshee_boardwalk", 
        "mk:rainbow_road"
    });

    gBattleCup = std::make_unique<Cup>("mk:battle_cup", "Battle Cup", std::vector<std::string>{
        "mk:big_donut", 
        "mk:block_fort", 
        "mk:double_deck", 
        "mk:skyscraper"
    });

    /* Validate Cup Track IDs */
    gMushroomCup->ValidateTrackIds(gTrackRegistry);
    gFlowerCup->ValidateTrackIds(gTrackRegistry);
    gStarCup->ValidateTrackIds(gTrackRegistry);
    gSpecialCup->ValidateTrackIds(gTrackRegistry);
    gBattleCup->ValidateTrackIds(gTrackRegistry);

    /* Instantiate Cups */
    GetWorld()->AddCup(gMushroomCup.get());
    GetWorld()->AddCup(gFlowerCup.get());
    GetWorld()->AddCup(gStarCup.get());
    GetWorld()->AddCup(gSpecialCup.get());
    GetWorld()->AddCup(gBattleCup.get());

    SetMarioRaceway();

    printf("[Game] Registering Game Content...\n");
    RegisterActors(gActorRegistry);
    RegisterItems(gItemRegistry);
    RegisterItemTables(gItemTableRegistry);
    printf("[Game] Game Content Registered!\n");
}

void CustomEngineDestroy() {
    gTrackRegistry.Clear();
    gActorRegistry.Clear();
    gMushroomCup.reset();
    gFlowerCup.reset();
    gStarCup.reset();
    gSpecialCup.reset();
    gBattleCup.reset();
}

extern "C" {

void HM_InitIntro() {
    gMenuIntro.HM_InitIntro();
}

void HM_TickIntro() {
    gMenuIntro.HM_TickIntro();
}

void HM_DrawIntro() {
    gMenuIntro.HM_DrawIntro();
}

// Set default track; mario raceway
void SetMarioRaceway(void) {
    SelectMarioRaceway();
    GetWorld()->SetCurrentCup(gMushroomCup.get());
    GetWorld()->GetCurrentCup()->CursorPosition = 3;
    GetWorld()->CupIndex = 0;
}

u32 WorldNextCup(void) {
    return GetWorld()->NextCup();
}

u32 WorldPreviousCup(void) {
    return GetWorld()->PreviousCup();
}

void CM_SetCup(void* cup) {
    GetWorld()->SetCurrentCup((Cup*) cup);
}

void* GetCup() {
    return GetWorld()->GetCurrentCup();
}

u32 GetCupIndex(void) {
    return GetWorld()->GetCupIndex();
}

void CM_SetCupIndex(size_t index) {
    GetWorld()->SetCupIndex(index);
}

const char* GetCupName(void) {
    return GetWorld()->GetCurrentCup()->Name;
}

void LoadTrack() {
    GetWorld()->GetRaceManager().Load();
}

void CM_VehicleCollision(s32 playerId, Player* player) {
    for (auto& actor : GetWorld()->Actors) {
        if (actor) {
            actor->VehicleCollision(playerId, player);
        }
    }
}

void CM_BombKartsWaypoint(s32 cameraId) {
    for (auto& object : GetWorld()->Objects) {
        if (auto* kart = dynamic_cast<OBombKart*>(object.get())) {
            if (kart != nullptr) {
                kart->Waypoint(cameraId);
            }
        }
    }
}

void CM_DisplayBattleBombKart(s32 playerId, s32 primAlpha) {

    if ((playerId < 0) || (playerId > 4)) {
        return;
    }

    if (primAlpha == 0) {
        GetWorld()->mPlayerBombKart[playerId].state = PlayerBombKart::PlayerBombKartState::DISABLED;
        GetWorld()->mPlayerBombKart[playerId]._primAlpha = primAlpha;
    } else {
        GetWorld()->mPlayerBombKart[playerId].state = PlayerBombKart::PlayerBombKartState::ACTIVE;
        GetWorld()->mPlayerBombKart[playerId]._primAlpha = primAlpha;
    }
}

void CM_DrawBattleBombKarts(s32 cameraId) {
    for (size_t i = 0; i < gPlayerCount; i++) {
        GetWorld()->mPlayerBombKart[i].Draw(i, cameraId);
    }
}

void CM_ClearVehicles(void) {
    GetWorld()->Crossings.clear();
}

void CM_CrossingTrigger() {
    for (auto& crossing : GetWorld()->Crossings) {
        if (crossing) {
            crossing->CrossingTrigger();
        }
    }
}

void CM_AICrossingBehaviour(s32 playerId) {
    for (auto& crossing : GetWorld()->Crossings) {
        if (crossing) {
            crossing->AICrossingBehaviour(playerId);
        }
    }
}

s32 CM_GetCrossingOnTriggered(uintptr_t* crossing) {
    TrainCrossing* ptr = (TrainCrossing*) crossing;
    if (ptr) {
        return ptr->OnTriggered;
    }
}

/**
 * Tracks are rendered in two ways
 * 1) Track sections --> The scene is split into multiple sections and rendered piece by piece
 * 2) Full scene --> The entire scene is rendered at once
 * 
 * Custom tracks only use the Render() method, and they only render the full scene.
 * They do not use DrawCredits() and they do not use track sections.
 */
void CM_DrawTrack(ScreenContext* screen) {
    if (nullptr == GetWorld()->GetTrack()) {
        return;
    }

    // Check if collision mesh rendering is enabled via CVar
    if (CVarGetInteger("gRenderCollisionMesh", 0)) {
        render_collision();
        return;
    }

    // Custom tracks should never use DrawCredits();
    if (GetWorld()->GetTrack()->IsMod()) {
        switch(screen->camera->renderMode) {
            default:
                GetWorld()->GetTrack()->Draw(screen);
                break;
            case RENDER_COLLISION_MESH:
                render_collision();
                break;
        } 
    } else {
        switch(screen->camera->renderMode) {
            case RENDER_FULL_SCENE:
                if (gModeSelection == BATTLE) {
                    GetWorld()->GetTrack()->Draw(screen);
                } else {
                    GetWorld()->GetTrack()->DrawCredits();
                }
            case RENDER_TRACK_SECTIONS:
                GetWorld()->GetTrack()->Draw(screen);
                break;
            case RENDER_COLLISION_MESH:
                render_collision();
                break;
        }
    }
}

void CM_TickActors() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->TickActors();
    }
}

void CM_DrawActors(Camera* camera) {
    //AActor* a = GetWorld()->ConvertActorToAActor(actor);
    for (const auto& actor : GetWorld()->Actors) {
        if (actor->IsMod()) {
            actor->Draw(camera);
        }
    }

    for (auto& camera : GetWorld()->Cameras) {
        if (auto* tourCam = dynamic_cast<TourCamera*>(camera.get())) {
            if (tourCam->IsActive()) {
                tourCam->Draw();
            }
        }
    }
}

void CM_DrawStaticMeshActors() {
    GetWorld()->DrawStaticMeshActors();
}

void CM_BeginPlay() {
    static bool tour = false;
    auto track = GetWorld()->GetTrack();
    GetWorld()->CleanActors();
    
    if (nullptr == track) {
        return; 
    }

    if (tour) {
      //  GetWorld()->Cameras[2]->SetActive(true);
       // gScreenOneCtx->camera = GetWorld()->Cameras[2]->Get();
        if (reinterpret_cast<TourCamera*>(GetWorld()->Cameras[2].get())->IsTourComplete()) {
            tour = false;
            gScreenOneCtx->pendingCamera = &cameras[0];
        }
    }

    GetWorld()->GetRaceManager().PreInit();
    GetWorld()->GetRaceManager().BeginPlay();
    GetWorld()->GetRaceManager().PostInit();
}

Camera* CM_GetPlayerCamera(s32 playerIndex) {
    for (auto& cam : GetWorld()->Cameras) {
        // Make sure this is a player camera and not a different type of camera
        if (typeid(*cam) == typeid(GameCamera)) {
            Camera* camera = cam->Get();
            if (camera->playerId == playerIndex) {
                return camera;
            }
        }
    }
    return nullptr;
}

void CM_SetViewProjection(Camera* camera) {
    for (auto& gameCamera : GetWorld()->Cameras) {
        if (camera == gameCamera->Get()) {
            gameCamera->SetViewProjection();
        }
    }
}

void CM_TickCameras() {
    GetWorld()->TickCameras();
}

Camera* CM_AddCamera(Vec3f spawn, s16 rot, u32 mode) {
    if (GetWorld()->Cameras.size() >= NUM_CAMERAS) {
        printf("Reached the max number of cameras, %d\n", NUM_CAMERAS);
        return nullptr;
    }
    GetWorld()->Cameras.push_back(std::make_unique<GameCamera>(FVector(spawn[0], spawn[1], spawn[2]), rot, mode));
    return GetWorld()->Cameras.back()->Get();
}

Camera* CM_AddFreeCamera(Vec3f spawn, s16 rot, u32 mode) {
    if (GetWorld()->Cameras.size() >= NUM_CAMERAS) {
        printf("Reached the max number of cameras, %d\n", NUM_CAMERAS);
        return nullptr;
    }
    GetWorld()->Cameras.push_back(std::make_unique<FreeCamera>(FVector(spawn[0], spawn[1], spawn[2]), rot, mode));
    return GetWorld()->Cameras.back()->Get();
}

Camera* CM_AddTourCamera(Vec3f spawn, s16 rot, u32 mode) {
    if (GetWorld()->Cameras.size() >= NUM_CAMERAS) {
        // This is to prevent soft locking the game
        printf("Reached the max number of cameras, %d\n", NUM_CAMERAS);
        if (GetWorld()->GetTrack()->bTourEnabled) {
            spawn_and_set_player_spawns();
        }
        return nullptr;
    }

    if (nullptr == GetWorld()->GetTrack()) {
        // This is to prevent soft locking the game
        if (GetWorld()->GetTrack()->bTourEnabled) {
            spawn_and_set_player_spawns();
        }
        return nullptr;
    }

    if (GetWorld()->GetTrack()->TourShots.size() == 0) {
        // This is to prevent soft locking the game
        if (GetWorld()->GetTrack()->bTourEnabled) {
            spawn_and_set_player_spawns();
        }
        return nullptr;
    }

    GetWorld()->Cameras.push_back(std::make_unique<TourCamera>(FVector(spawn[0], spawn[1], spawn[2]), rot, mode));
    TourCamera* tour = static_cast<TourCamera*>(GetWorld()->Cameras.back().get());
    tour->SetActive(true);
    return tour->Get();
}

bool CM_IsTourEnabled() {
    if (nullptr != GetWorld()->GetTrack()) {
        if ((GetWorld()->GetTrack()->bTourEnabled) && (gTourComplete == false)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Camera* CM_AddLookBehindCamera(Vec3f spawn, s16 rot, u32 mode) {
    if (GetWorld()->Cameras.size() >= NUM_CAMERAS) {
        printf("Reached the max number of cameras, %d\n", NUM_CAMERAS);
        return nullptr;
    }
    GetWorld()->Cameras.push_back(std::make_unique<LookBehindCamera>(FVector(spawn[0], spawn[1], spawn[2]), rot, mode));
    return GetWorld()->Cameras.back()->Get();
}

void CM_AttachCamera(Camera* camera, s32 playerIdx) {
    camera->playerId = playerIdx;
}

void CM_CameraSetActive(size_t idx, bool state) {
    if (idx < GetWorld()->Cameras.size()) {
        GetWorld()->Cameras[idx]->SetActive(state);
    }
}

void CM_SetFreeCamera(bool state) {
    for (auto& cam : GetWorld()->Cameras) {
        if (cam->Get() == gScreenOneCtx->freeCamera) {
            if (state) {
                gScreenOneCtx->pendingCamera = gScreenOneCtx->freeCamera;
                cam->SetActive(true);
            } else {
                if (nullptr != gScreenOneCtx->raceCamera) {
                    if (gGamestate == RACING) {
                        gScreenOneCtx->pendingCamera = gScreenOneCtx->raceCamera;
                        cam->SetActive(false);
                    } else {
                        cam->SetActive(false);
                    }
                }
            }
        }
    }
}

void CM_ActivateTourCamera(Camera* camera) {
    for (auto& cam : GetWorld()->Cameras) {
        if (cam->Get() == camera) {
            cam->SetActive(true);
        }
    }
}

void CM_TickObjects() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->TickObjects();
    }
}

// A couple objects such as lakitu are ticked inside of process_game_tick which support 60fps.
// This is a fallback to support that.
void CM_TickObjects60fps() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->TickObjects60fps();
    }
}

void CM_DrawObjects(s32 cameraId) {
    if (GetWorld()->GetTrack()) {
        GetWorld()->DrawObjects(cameraId);
    }
}

void CM_TickEditor() {
    gEditor.Tick();
}

void CM_DrawEditor() {
    gEditor.Draw();
}

void CM_TickParticles() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->TickParticles();
    }
}

void CM_DrawParticles(s32 cameraId) {
    if (GetWorld()->GetTrack()) {
        GetWorld()->DrawParticles(cameraId);
    }
}

void CM_RaceDrawSky(ScreenContext* screen, s32 someId) {
    // if (bDrawSkybox) {
    if (CVarGetInteger("gDrawSky", true) == true) {
        Sky::Instance->Draw(screen);
        if (gGamestate != CREDITS_SEQUENCE) {
            func_80057FC4(screen, someId); // DrawSkyActors
        }
        Sky::Instance->DrawFloor(screen);
    }
}

void CM_Waypoints(Player* player, int8_t playerId) {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->Waypoints(player, playerId);
    }
}

void CM_SomeCollisionThing(Player* player, Vec3f arg1, Vec3f arg2, Vec3f arg3, f32* arg4, f32* arg5, f32* arg6,
                           f32* arg7) {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->SomeCollisionThing(player, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
    }
}

void CM_InitTrackObjects() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->InitTrackObjects();
    }
}

void CM_TickTrackObjects() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->TickTrackObjects();
    }
    TrainSmokeTick();
}

void CM_DrawTrackObjects(s32 cameraId) {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->DrawTrackObjects(cameraId);
    }

    TrainSmokeDraw(cameraId);
}

void CM_SomeSounds() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->SomeSounds();
    }
}

void CM_CreditsSpawnActors() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->CreditsSpawnActors();
    }
}

void CM_WhatDoesThisDo(Player* player, int8_t playerId) {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->WhatDoesThisDo(player, playerId);
    }
}

void CM_WhatDoesThisDoAI(Player* player, int8_t playerId) {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->WhatDoesThisDoAI(player, playerId);
    }
}

void CM_SetStaffGhost() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->SetStaffGhost();
    }
}

// This should only be used for checking if the track has changed
uintptr_t CM_GetTrack() {
    return (uintptr_t) (void*) GetWorld()->GetTrack();
}

Properties* CM_GetProps() {
    if (GetWorld()->GetTrack()) {
        return &GetWorld()->GetTrack()->Props;
    }
    return NULL;
}

void CM_TickTrack() {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->Tick();
    }
}

void CM_DrawTransparency(ScreenContext* screen, uint16_t pathCounter, uint16_t cameraRot,
                  uint16_t playerDirection) {
    if (GetWorld()->GetTrack()) {
        GetWorld()->GetTrack()->DrawTransparency(screen, pathCounter, cameraRot, playerDirection);
    }
}

/**
 * This should only be ran once per track, otherwise animation/timings might become sped up.
 */
void CM_SpawnStarterLakitu() {
    if ((gDemoMode) || (gGamestate == CREDITS_SEQUENCE)) {
        return;
    }

    for (size_t i = 0; i < gPlayerCountSelection1; i++) {
        // Retry does not respawn actors, therefore, re-use lakitu.
        if (auto it = GetWorld()->Lakitus.find(i); it != GetWorld()->Lakitus.end()) {
            if (it->second) {
                it->second->Activate(OLakitu::STARTER);
            }
            continue; // Already exists, skip spawning
        }

        auto lakitu = std::make_unique<OLakitu>(i, OLakitu::LakituType::STARTER);
        GetWorld()->Lakitus[i] = lakitu.get();
        GetWorld()->AddObject(std::move(lakitu));
    }
}

// Checkered flag lakitu
void CM_ActivateFinishLakitu(s32 playerId) {
    if ((gDemoMode) || (gGamestate == CREDITS_SEQUENCE)) {
        return;
    }
    GetWorld()->Lakitus[playerId]->Activate(OLakitu::LakituType::FINISH);
}

void CM_ActivateSecondLapLakitu(s32 playerId) {
    if ((gDemoMode) || (gGamestate == CREDITS_SEQUENCE)) {
        return;
    }
    GetWorld()->Lakitus[playerId]->Activate(OLakitu::LakituType::SECOND_LAP);
}

void CM_ActivateFinalLapLakitu(s32 playerId) {
    if ((gDemoMode) || (gGamestate == CREDITS_SEQUENCE)) {
        return;
    }
    GetWorld()->Lakitus[playerId]->Activate(OLakitu::LakituType::FINAL_LAP);
}

void CM_ActivateReverseLakitu(s32 playerId) {
    if ((gDemoMode) || (gGamestate == CREDITS_SEQUENCE)) {
        return;
    }
    GetWorld()->Lakitus[playerId]->Activate(OLakitu::LakituType::REVERSE);
}

size_t GetCupCursorPosition() {
    return GetWorld()->GetCurrentCup()->CursorPosition;
}

void SetCupCursorPosition(size_t position) {
    GetWorld()->GetCurrentCup()->SetTrack(position);
    // GetWorld()->CurrentCup->CursorPosition = position;
}

size_t GetCupSize() {
    return GetWorld()->GetCurrentCup()->GetSize();
}

void* GetTrack(void) {
    return GetWorld()->GetTrack();
}

struct Actor* CM_GetActor(size_t index) {
    if (index >= 0 && index < GetWorld()->Actors.size()) {
        AActor* actor = GetWorld()->Actors[index].get();
        return reinterpret_cast<struct Actor*>(reinterpret_cast<char*>(actor) + sizeof(void*));
    } else {
        throw std::runtime_error("GetActor() index out of bounds");
        return NULL;
    }
}

size_t CM_FindActorIndex(Actor* actor) {
    // Move the ptr back to look at the vtable.
    // This gets us the proper C++ class instead of just the variables used in C.
    AActor* a = reinterpret_cast<AActor*>(reinterpret_cast<char*>(actor) - sizeof(void*));
    auto& actors = GetWorld()->Actors;

    auto it = std::find_if(actors.begin(), actors.end(), [a](const std::unique_ptr<AActor>& ptr) {
        return ptr.get() == a;
    });

    if (it != actors.end()) {
        return std::distance(actors.begin(), it);
    }
    printf("FindActorIndex() actor not found\n");
    return -1;
}

void CM_DeleteActor(size_t index) {
    auto& actors = GetWorld()->Actors;
    if (index < actors.size()) {
        actors.erase(actors.begin() + index);
    }
}

/**
 * Clean up actors and other game objects.
 */
void CM_CleanWorld(void) {
    GetWorld()->CleanWorld();
}

void CM_CleanCameras(void) {
    GetWorld()->Cameras.clear();
}

struct Actor* CM_AddBaseActor() {
    return (struct Actor*) GetWorld()->AddBaseActor();
}

void CM_ActorBeginPlay(struct Actor* actor) {
    GetWorld()->ActorBeginPlay(actor);
}

void CM_ActorGenerateCollision(struct Actor* actor) {
    AActor* act = GetWorld()->ConvertActorToAActor(actor);

    if ((nullptr != act->Model) && (act->Model[0] != '\0')) {
        if (act->Triangles.size() == 0) {
            TrackEditor::GenerateCollisionMesh(act, (Gfx*)LOAD_ASSET_RAW(act->Model), 1.0f);
        }
    }
}

void Editor_AddLight(s8* direction) {
    static size_t i = 0;
    gEditor.AddLight(("Light "+std::to_string(i)).c_str(), nullptr, direction);
    i += 1;
}

void Editor_ClearMatrix() {
    gEditor.ClearMatrixPool();
}

void Editor_CleanWorld() {
    if (bCleanWorld) {
        CM_CleanWorld();
        bCleanWorld = false;
    }
}

size_t CM_GetActorSize() {
    return GetWorld()->Actors.size();
}

void CM_ActorCollision(Player* player, Actor* actor) {
    AActor* a = GetWorld()->ConvertActorToAActor(actor);

    if (a->IsMod()) {
        a->Collision(player, a);
    }
}

f32 CM_GetWaterLevel(Vec3f pos, struct Collision* collision) {
    FVector fPos = {pos[0], pos[1], pos[2]};
    return GetWorld()->GetTrack()->GetWaterLevel(fPos, collision);
}

// clang-format off
bool IsMarioRaceway()     { return dynamic_cast<MarioRaceway*>(GetWorld()->GetTrack()) != nullptr; }
bool IsLuigiRaceway()     { return dynamic_cast<LuigiRaceway*>(GetWorld()->GetTrack()) != nullptr; }
bool IsChocoMountain()    { return dynamic_cast<ChocoMountain*>(GetWorld()->GetTrack()) != nullptr; }
bool IsBowsersCastle()    { return dynamic_cast<BowsersCastle*>(GetWorld()->GetTrack()) != nullptr; }
bool IsBansheeBoardwalk() { return dynamic_cast<BansheeBoardwalk*>(GetWorld()->GetTrack()) != nullptr; }
bool IsYoshiValley()      { return dynamic_cast<YoshiValley*>(GetWorld()->GetTrack()) != nullptr; }
bool IsFrappeSnowland()   { return dynamic_cast<FrappeSnowland*>(GetWorld()->GetTrack()) != nullptr; }
bool IsKoopaTroopaBeach() { return dynamic_cast<KoopaTroopaBeach*>(GetWorld()->GetTrack()) != nullptr; }
bool IsRoyalRaceway()     { return dynamic_cast<RoyalRaceway*>(GetWorld()->GetTrack()) != nullptr; }
bool IsMooMooFarm()       { return dynamic_cast<MooMooFarm*>(GetWorld()->GetTrack()) != nullptr; }
bool IsToadsTurnpike()    { return dynamic_cast<ToadsTurnpike*>(GetWorld()->GetTrack()) != nullptr; }
bool IsKalimariDesert()   { return dynamic_cast<KalimariDesert*>(GetWorld()->GetTrack()) != nullptr; }
bool IsSherbetLand()      { return dynamic_cast<SherbetLand*>(GetWorld()->GetTrack()) != nullptr; }
bool IsRainbowRoad()      { return dynamic_cast<RainbowRoad*>(GetWorld()->GetTrack()) != nullptr; }
bool IsWarioStadium()     { return dynamic_cast<WarioStadium*>(GetWorld()->GetTrack()) != nullptr; }
bool IsBlockFort()        { return dynamic_cast<BlockFort*>(GetWorld()->GetTrack()) != nullptr; }
bool IsSkyscraper()       { return dynamic_cast<Skyscraper*>(GetWorld()->GetTrack()) != nullptr; }
bool IsDoubleDeck()       { return dynamic_cast<DoubleDeck*>(GetWorld()->GetTrack()) != nullptr; }
bool IsDkJungle()         { return dynamic_cast<DKJungle*>(GetWorld()->GetTrack()) != nullptr; }
bool IsBigDonut()         { return dynamic_cast<BigDonut*>(GetWorld()->GetTrack()) != nullptr; }
bool IsPodiumCeremony()   { return dynamic_cast<PodiumCeremony*>(GetWorld()->GetTrack()) != nullptr; }

void SelectMarioRaceway()       { GetWorld()->SetCurrentTrack(std::make_unique<MarioRaceway>()); }
void SelectLuigiRaceway()       { GetWorld()->SetCurrentTrack(std::make_unique<LuigiRaceway>()); }
void SelectChocoMountain()      { GetWorld()->SetCurrentTrack(std::make_unique<ChocoMountain>()); }
void SelectBowsersCastle()      { GetWorld()->SetCurrentTrack(std::make_unique<BowsersCastle>()); }
void SelectBansheeBoardwalk()   { GetWorld()->SetCurrentTrack(std::make_unique<BansheeBoardwalk>()); }
void SelectYoshiValley()        { GetWorld()->SetCurrentTrack(std::make_unique<YoshiValley>()); }
void SelectFrappeSnowland()     { GetWorld()->SetCurrentTrack(std::make_unique<FrappeSnowland>()); }
void SelectKoopaTroopaBeach()   { GetWorld()->SetCurrentTrack(std::make_unique<KoopaTroopaBeach>()); }
void SelectRoyalRaceway()       { GetWorld()->SetCurrentTrack(std::make_unique<RoyalRaceway>()); }
void SelectMooMooFarm()         { GetWorld()->SetCurrentTrack(std::make_unique<MooMooFarm>()); }
void SelectToadsTurnpike()      { GetWorld()->SetCurrentTrack(std::make_unique<ToadsTurnpike>()); }
void SelectKalimariDesert()     { GetWorld()->SetCurrentTrack(std::make_unique<KalimariDesert>()); }
void SelectSherbetLand()        { GetWorld()->SetCurrentTrack(std::make_unique<SherbetLand>()); }
void SelectRainbowRoad()        { GetWorld()->SetCurrentTrack(std::make_unique<RainbowRoad>()); }
void SelectWarioStadium()       { GetWorld()->SetCurrentTrack(std::make_unique<WarioStadium>()); }
void SelectBlockFort()          { GetWorld()->SetCurrentTrack(std::make_unique<BlockFort>()); }
void SelectSkyscraper()         { GetWorld()->SetCurrentTrack(std::make_unique<Skyscraper>()); }
void SelectDoubleDeck()         { GetWorld()->SetCurrentTrack(std::make_unique<DoubleDeck>()); }
void SelectDkJungle()           { GetWorld()->SetCurrentTrack(std::make_unique<DKJungle>()); }
void SelectBigDonut()           { GetWorld()->SetCurrentTrack(std::make_unique<BigDonut>()); }
void SelectPodiumCeremony()     { GetWorld()->SetCurrentTrack(std::make_unique<PodiumCeremony>()); }
// clang-format on

void* GetMushroomCup(void) {
    return gMushroomCup.get();
}

void* GetFlowerCup(void) {
    return gFlowerCup.get();
}

void* GetStarCup(void) {
    return gStarCup.get();
}

void* GetSpecialCup(void) {
    return gSpecialCup.get();
}

void* GetBattleCup(void) {
    return gBattleCup.get();
}

// End of frame cleanup of actors, objects, etc.
void CM_RunGarbageCollector(void) {
    RunGarbageCollector();
}

void CM_ResetAudio(void) {
    if(HMAS_IsPlaying(HMAS_MUSIC)){
        HMAS_AddEffect(HMAS_MUSIC, HMAS_EFFECT_VOLUME, HMAS_LINEAR, 10, 0);
        HMAS_AddEffect(HMAS_MUSIC, HMAS_EFFECT_STOP,   HMAS_INSTANT, 1, 0);
    }

    // Fade out music for all sequences and music player indexes 0, and 1
    for (size_t soundId = 0; soundId < MUSIC_SEQ_MAX; soundId++) {
        func_800C3448(0x10100000 | soundId);
        func_800C3448(0x11100000 | soundId);
    }
}
}

static std::atomic<bool> sResetRequested{ false };

void CM_RequestReset(void) {
    sResetRequested.store(true);
}

// The reset widget only requests; the reset is applied here at the top of the
// game frame. Applying it from the widget raced the menu state machine: a
// press landing mid-fade was re-advanced by the in-flight transition, and a
// repeat press rewrote the gamestate it had already set, which the != guard
// in main.c swallows while the audio fade still runs (silent no-op).
static void ApplyPendingReset() {
    if (!sResetRequested.exchange(false)) {
        return;
    }

    // The FROM_QUIT gamestates run identical inits; alternating keeps
    // gGamestateNext != gGamestate true so every press re-enters the menus.
    gGamestateNext = (gGamestate == MAIN_MENU_FROM_QUIT) ? START_MENU_FROM_QUIT : MAIN_MENU_FROM_QUIT;
    gIsGamePaused = 0;
    // Reset credits
    D_800DC5E4 = 0;
    gTourComplete = false;
    SetMarioRaceway();
    memset(&gGameModeMenuColumn, 0, sizeof(s8) * NUM_ROWS_GAME_MODE_MENU);
    memset(&gGameModeSubMenuColumn, 0, sizeof(s8) * NUM_COLUMN_GAME_MODE_SUB_MENU * NUM_ROWS_GAME_MODE_SUB_MENU);

    CM_ResetAudio();

    // Close the editor.
    if (gEditor.IsEnabled()) {
        gEditor.Disable();
    }

    // Set the debug menu track browsing index back to zero
    TrackBrowser::Instance->Reset();

    // Land on the same screen the gSkipIntro setting picks at boot.
    switch (CVarGetInteger("gSkipIntro", 0)) {
        case 0:
            gMenuSelection = HARBOUR_MASTERS_MENU;
            break;
        case 1:
            gMenuSelection = LOGO_INTRO_MENU;
            break;
        case 2:
            gMenuSelection = START_MENU;
            break;
        case 3:
            gMenuSelection = MAIN_MENU;
            break;
    }

    // Debug mode override gSkipIntro
    if (CVarGetInteger("gEnableDebugMode", 0) == true) {
        gMenuSelection = START_MENU;
    }
    // Re-enter through the intro's own transition protocol (see HM_TickIntro):
    // FADE_MODE_LOGO makes setup_menus rebuild the menu items and start a
    // fresh fade-in, replacing any in-flight transition that would otherwise
    // advance the stale screen right after the reset.
    gMenuFadeType = 0;
    gFadeModeSelection = FADE_MODE_LOGO;
}

void push_frame() {
    ApplyPendingReset();
    GameEngine::StartAudioFrame();
    GameEngine::Instance->StartFrame();
    thread5_iteration();
    GameEngine::EndAudioFrame();
    // thread5_game_loop();
    // Graphics_ThreadUpdate();w
}

void CM_ThrowRuntimeError(const char* fmt, ...) {
    char error_mesg[2048];

    va_list args;
    va_start(args, fmt);
    vsnprintf(error_mesg, sizeof(error_mesg), fmt, args);
    va_end(args);

    const char* crash_desc = "\nSpaghettiKart has crashed! Please upload the logs to the support channel in Discord.";
    strncat(error_mesg, crash_desc, sizeof(error_mesg) - strlen(error_mesg) - 1);

    SPDLOG_ERROR(error_mesg);

    SDL_ShowSimpleMessageBox(
        SDL_MESSAGEBOX_ERROR,
        "You dropped your plate of Spaghetti!",
        error_mesg,
        NULL
    );

    exit(EXIT_FAILURE);
}

#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#endif

#ifdef _WIN32
int SDL_main(int argc, char** argv) {
#else
#if defined(__cplusplus) && defined(PLATFORM_IOS)
extern "C"
#endif
    int
    main(int argc, char* argv[]) {
#endif
#ifdef _WIN32
    // Allow non-ascii characters for Windows
    setlocale(LC_ALL, ".UTF8");
#endif
#if defined(__APPLE__)
    // Disable the macOS "press and hold" accent/diacritic popup for this app. SDL keeps a Cocoa text
    // input context active, so holding a movement key is interpreted as holding a letter key in a text
    // field, and macOS shows the accent picker instead of repeating it. Per-app equivalent of
    // `defaults write -app <App> ApplePressAndHoldEnabled -bool false`; key repeat still works.
    CFPreferencesSetAppValue(CFSTR("ApplePressAndHoldEnabled"), kCFBooleanFalse, kCFPreferencesCurrentApplication);
    CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
#endif
    // load_wasm();
    GameEngine::Create();
    audio_init();
    sound_init();

    CustomEngineInit();

    switch(CVarGetInteger("gSkipIntro", 0)) {
        case 0:
            gMenuSelection = HARBOUR_MASTERS_MENU;
            break;
        case 1:
            gMenuSelection = LOGO_INTRO_MENU;
            break;
        case 2:
            gMenuSelection = START_MENU;
            break;
        case 3:
            gMenuSelection = MAIN_MENU;
            break;
    }

    // Debug mode override gSkipIntro
    if (CVarGetInteger("gEnableDebugMode", 0) == true) {
        gMenuSelection = START_MENU;
    }

    thread5_game_loop();
    gEditor.Load();
    while (WindowIsRunning()) {
        push_frame();
    }
    CustomEngineDestroy();
    // GameEngine::Instance->ProcessFrame(push_frame);
    GameEngine::Instance->Destroy();
    // Everything user-visible (config, saves) is persisted by Destroy(). Skip the
    // remaining static destructors: their order is unspecified and some log after
    // spdlog's own statics are gone, crashing on quit (same class as issue #689).
    // Mirrors the _Exit precedent on the extraction error paths.
    _Exit(0);
}