-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
3021 lines (2605 loc) · 150 KB
/
main.cpp
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 "code/utility/logger.h"
#include "code/graphics/program.h"
#include "code/graphics/renderContext.h"
#include "code/utility/debugGraphics.h"
#include "code/graphics/uniformsBasic.h"
#include "code/graphics/texture.h"
#include "code/graphics/animation.h"
#include "code/graphics/camera.h"
#include "code/utility/inputMap.h"
#include "code/graphics/tessellation.h"
#include "code/graphics/instanced.h"
#include "code/graphics/renderTarget.h"
#include "code/graphics/environment.h"
#include "code/physics/terrain.h"
#include "code/physics/player.h"
#include <filesystem>
#include <glm/gtc/type_ptr.hpp>
#include "code/physics/bulletIncludes.h"
#include "code/graphics/printLoader.h"
#include "code/graphics/newBrickType.h"
#include "code/physics/brickPhysics.h"
#include "code/utility/ceguiHelper.h"
#include "code/gui/options.h"
#include "code/gui/brickSelector.h"
#include "code/gui/palette.h"
#include "code/physics/tempBrick.h"
#include "code/utility/brdfLookup.h"
#include "code/networking/common.h"
#include "code/networking/client.h"
#include "code/networking/recv.h"
#include "code/gui/evalWindow.h"
#include "code/gui/joinServer.h"
#include "code/gui/hud.h"
#include "code/graphics/fontRender.h"
#include "code/audio/audio.h"
#include "code/gui/wrenchDialog.h"
#include "code/gui/escape.h"
#include "code/gui/saveLoad.h"
#include "code/gui/avatarPicker.h"
#include "code/graphics/newModel.h"
#include "code/graphics/emitter.h"
#include <chrono>
#include "code/physics/selectionBox.h"
#include <curl/curl.h>
#include "code/gui/updater.h"
#include <bearssl/bearssl_hash.h>
#include "code/graphics/bulletTrails.h"
#include "code/gui/contentDownload.h"
#define hardCodedNetworkVersion 10018
#define cammode_firstPerson 0
#define cammode_thirdPerson 1
#define cammode_adminCam 2
using namespace syj;
using namespace std::filesystem;
using namespace std::chrono;
void gotKicked(client *theClient,unsigned int reason,void *userData)
{
clientStuff *clientEnvironment = (clientStuff*)userData;
if(clientEnvironment->serverData)
clientEnvironment->serverData->kicked = true;
clientEnvironment->fatalNotify("Disconnected!","Connection with server lost, reason: " + std::to_string(reason) + ".","Exit");
}
bool godRayButton(const CEGUI::EventArgs &e)
{
CEGUI::Window *godRayWindow = CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow()->getChild("GodRays");
clientStuff *clientEnvironment = (clientStuff*)godRayWindow->getUserData();
clientEnvironment->serverData->env->godRayDecay = atof(godRayWindow->getChild("Decay")->getText().c_str());
clientEnvironment->serverData->env->godRayDensity = atof(godRayWindow->getChild("Density")->getText().c_str());
clientEnvironment->serverData->env->godRayExposure = atof(godRayWindow->getChild("Exposure")->getText().c_str());
clientEnvironment->serverData->env->godRayWeight = atof(godRayWindow->getChild("Weight")->getText().c_str());
clientEnvironment->serverData->env->sunDistance = atof(godRayWindow->getChild("Distance")->getText().c_str());
return true;
}
enum gameState
{
STATE_MAINMENU,STATE_GETCONTENTLIST,STATE_GETCONTENT,STATE_DOWNLOADCONTENT,STATE_CONNECTING,STATE_PLAYING,STATE_AVATARPICKER,STATE_QUITTING,STATE_CLEANUP,STATE_LOADING
};
int main(int argc, char *argv[])
{
client *serverConnection = 0;
clientStuff clientEnvironment;
preferenceFile prefs;
clientEnvironment.prefs = &prefs;
clientEnvironment.settings = new options;
std::string ip = "127.0.0.1";
clientEnvironment.settings->prefs = &prefs;
clientEnvironment.settings->setDefaults(&prefs);
prefs.importFromFile("config.txt");
clientEnvironment.settings->loadFromFile(&prefs);
prefs.exportToFile("config.txt");
if(prefs.getPreference("IP"))
ip = prefs.getPreference("IP")->toString();
logger::setErrorFile("Logs/error.txt");
logger::setInfoFile("Logs/log.txt");
syj::log().setDebug(false);
scope("Main");
info("Starting up!");
if(argc > 0)
info(argv[0]);
create_directory("Logs"); //CEGUI on Linux needs the L to be capital
create_directory("saves");
create_directory("cache");
create_directory("assets");
create_directory("assets/brick");
create_directory("assets/brick/types");
create_directory("assets/brick/prints");
remove("oldlandofdran.exe");
int revisionVersion = -1;
int networkVersion = -1;
info("Retrieving version info from master server...");
getVersions(revisionVersion,networkVersion);
clientEnvironment.masterRevision = revisionVersion;
clientEnvironment.masterNetwork = networkVersion;
info("Most recent revision available on master server: " + std::to_string(revisionVersion));
int ourRevisionVersion = -1;
int ourNetworkVersion = -1;
if(prefs.getPreference("REVISION"))
ourRevisionVersion = prefs.getPreference("REVISION")->toInteger();
if(prefs.getPreference("NETWORK"))
ourNetworkVersion = prefs.getPreference("NETWORK")->toInteger();
info("Our revision: " + std::to_string(ourRevisionVersion));
renderContextOptions renderOptions;
renderOptions.name = "Rev " + std::to_string(ourRevisionVersion) + LOD_BUILD_AND_DATE;
renderOptions.startingResX = clientEnvironment.settings->resolutionX;
renderOptions.startingResY = clientEnvironment.settings->resolutionY;
renderOptions.useVSync = clientEnvironment.settings->vsync;
renderOptions.useFullscreen = clientEnvironment.settings->fullscreen;
switch(clientEnvironment.settings->antiAliasing)
{
case aaOff:
renderOptions.multiSampleSamples = 1;
break;
case aa2x:
renderOptions.multiSampleSamples = 2;
break;
default:
case aa4x:
renderOptions.multiSampleSamples = 4;
break;
case aa8x:
renderOptions.multiSampleSamples = 8;
break;
case aa16x:
renderOptions.multiSampleSamples = 16;
break;
}
renderContext context(renderOptions);
clientEnvironment.context = &context;
ALCdevice* device = alcOpenDevice(NULL);
if(!device)
{
error("Could not find/open OpenAL device.");
return 0;
}
ALCcontext *audioContext = alcCreateContext(device,NULL);
alcMakeContextCurrent(audioContext);
ALCenum err = alcGetError(device);
if(err != ALC_NO_ERROR)
error("OpenAL error: " + std::to_string(err));
clientEnvironment.speaker = new audioPlayer;
FT_Library ft;
if (FT_Init_FreeType(&ft))
{
error("FREETYPE: Could not init FreeType Library");
return -1;
}
fontRenderer defaultFont(ft,"gui/fonts/DejaVuSans.ttf");
printComputerStats();
inputMap playerInput;
playerInput.fromPrefs(&prefs);
playerInput.toPrefs(&prefs);
prefs.exportToFile("config.txt");
initLoadCEGUISkin("GWEN",context.getWidth(),context.getHeight());
//Default resolution is 800x800, this is needed to make the GUI work correctly on other resolutions:
CEGUI::System::getSingleton().getRenderer()->setDisplaySize(CEGUI::Size<float>(context.getResolution().x,context.getResolution().y));
CEGUI::Window *optionsWindow = loadOptionsGUI(clientEnvironment.settings,prefs,playerInput);
clientEnvironment.brickSelector = loadBrickSelector();
CEGUI::Window *hud = addGUIFromFile("hud.layout");
CEGUI::Window *brickHighlighter = hud->getChild("BrickPopup/Selector");
CEGUI::Window *chat = hud->getChild("Chat");
CEGUI::Window *updater = addUpdater(&clientEnvironment);
chat->moveToBack();
clientEnvironment.playerList = hud->getChild("PlayerList");
clientEnvironment.chat = (CEGUI::Listbox*)hud->getChild("Chat/Listbox");
clientEnvironment.whosTyping = hud->getChild("WhosTyping");
CEGUI::Window *chatEditbox = hud->getChild("Chat/Editbox");
CEGUI::Window *chatScrollArrow = hud->getChild("Chat/DidScroll");
clientEnvironment.inventoryBox = hud->getChild("Inventory");
setUpWrenchDialogs(hud,&clientEnvironment);
clientEnvironment.wrench = hud->getChild("Wrench");
clientEnvironment.wheelWrench = hud->getChild("WheelWrench");
clientEnvironment.steeringWrench = hud->getChild("SteeringWrench");
CEGUI::Window *stats = hud->getChild("Stats");
CEGUI::Window *crossHair = hud->getChild("Crosshair");
CEGUI::Window *evalWindow = configureEvalWindow(hud,&clientEnvironment);
CEGUI::Window *joinServer = loadJoinServer(&clientEnvironment);
CEGUI::Window *godRayDebug = addGUIFromFile("godRayDebug.layout");
godRayDebug->setUserData(&clientEnvironment);
godRayDebug->getChild("Button")->subscribeEvent(CEGUI::PushButton::EventClicked,CEGUI::Event::Subscriber(&godRayButton));
clientEnvironment.evalWindow = evalWindow;
clientEnvironment.messageBox = initHud(hud);
clientEnvironment.palette = new paletteGUI(hud);
clientEnvironment.bottomPrint.textBar = hud->getChild("BottomPrint");
CEGUI::Window *saveLoadWindow = loadSaveLoadWindow(&clientEnvironment);
CEGUI::Window *brickPopup = CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow()->getChild("HUD")->getChild("BrickPopup");
CEGUI::Window *contentMenu = loadContentMenu(&clientEnvironment);
if(ourRevisionVersion == -1 || ourRevisionVersion == 0)
{
joinServer->getChild("UpdateText")->setText("[colour='FFFF0000']New installs must run updater first ->");
CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow()->getChild("JoinServer/ConnectButton")->setDisabled(true);
}
else
{
if(revisionVersion == -1)
joinServer->getChild("UpdateText")->setText("[colour='FFFF0000']Could not retrieve version info!");
else
{
if(revisionVersion > ourRevisionVersion)
joinServer->getChild("UpdateText")->setText("[colour='FFFF9900']Your game may be out of date!");
else
joinServer->getChild("UpdateText")->setText("[colour='FF00CC00']Your game appears up to date!");
}
}
checkForSessionKey(&clientEnvironment,prefs);
if(SDLNet_Init())
error("Could not initalize SDLNet");
std::string shaderErrorStr = "";
std::vector<uniformsHolder*> programUnis = loadAllShaders(shaderErrorStr);
if(shaderErrorStr.length() > 0)
notify("Shader Failed to Compile",shaderErrorStr,"Close");
uniformsHolder *boxEdgesUnis=0,*brickUnis=0,*bulletUnis=0,
*emitterUnis=0,*fontUnis=0,*godPrePassBrickUnis=0,
*godPrePassSunUnis=0,*modelUnis=0,*modelShadowUnis=0,
*oldModelUnis=0,*rectToCubeUnis=0,*screenOverlaysUnis=0,
*shadowBrickUnis=0,*waterUnis=0,*modelDNCUnis=0;
info(std::to_string(programUnis.size()) + " shaders loaded.");
for(int a = 0; a<programUnis.size(); a++)
{
std::string programName = programUnis[a]->name;
if(programName == "boxEdges")
boxEdgesUnis = programUnis[a];
else if(programName == "brick")
brickUnis = programUnis[a];
else if(programName == "bullet")
bulletUnis = programUnis[a];
else if(programName == "emitter")
emitterUnis = programUnis[a];
else if(programName == "font")
fontUnis = programUnis[a];
else if(programName == "godPrePassBrick")
godPrePassBrickUnis = programUnis[a];
else if(programName == "godPrePassSun")
godPrePassSunUnis = programUnis[a];
else if(programName == "model")
modelUnis = programUnis[a];
else if(programName == "modelShadow")
modelShadowUnis = programUnis[a];
else if(programName == "oldModel")
oldModelUnis = programUnis[a];
else if(programName == "rectToCube")
rectToCubeUnis = programUnis[a];
else if(programName == "screenOverlays")
screenOverlaysUnis = programUnis[a];
else if(programName == "shadowBrick")
shadowBrickUnis = programUnis[a];
else if(programName == "water")
waterUnis = programUnis[a];
else if(programName == "modelDNC")
modelDNCUnis = programUnis[a];
else
{
error("Invalid program: " + programName);
continue;
}
}
CEGUI::Window *escapeMenu = addEscapeMenu(&clientEnvironment,modelUnis);
clientEnvironment.nonInstancedShader = oldModelUnis;
clientEnvironment.instancedShader = modelUnis;
clientEnvironment.rectToCubeUnis = rectToCubeUnis;
clientEnvironment.brickMat = new material("assets/brick/otherBrickMat.txt");
clientEnvironment.brickMatSide = new material("assets/brick/sideBrickMat.txt");
clientEnvironment.brickMatRamp = new material("assets/brick/rampBrickMat.txt");
clientEnvironment.brickMatBottom = new material("assets/brick/bottomBrickMat.txt");
GLuint quadVAO = createQuadVAO();
GLuint cubeVAO = createCubeVAO();
clientEnvironment.prints = new printLoader("./assets/brick/prints");
clientEnvironment.cubeVAO = cubeVAO;
texture *bdrf = generateBDRF(quadVAO);
material grass("assets/ground/grass1/grass.txt");
clientEnvironment.newWheelModel = new newModel("assets/ball/ball.txt");
renderTarget *waterReflection = 0;
renderTarget *waterRefraction = 0;
renderTarget *waterDepth = 0;
texture *dudvTexture = new texture;
dudvTexture->setWrapping(GL_REPEAT);
dudvTexture->createFromFile("assets/dudv.png");
tessellation water(0);
//blocklandCompatibility blocklandHolder("assets/brick/types/test.cs","./assets/brick/types",clientEnvironment.brickSelector,true);
blocklandCompatibility *blocklandHolder = 0;
CEGUI::Window *root = CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow();
clientEnvironment.picker = new avatarPicker();
CEGUI::Window *bounceText = addGUIFromFile("justText.layout");
bounceText->setVisible(true);
bounceText->moveToBack();
float hue = 0;
float lastTick = SDL_GetTicks();
float deltaT = 0;
float horBounceDir = 1;
float vertBounceDir = 1;
float bottomBarOpen = 0;
float bottomBarClose = 0.165;
float bottomBarOpenTime = 500;
float bottomBarLastAct = SDL_GetTicks();
bool bottomBarShouldBeOpen = false;
glm::vec3 lastCamPos = glm::vec3(0,0,0);
unsigned int last10Secs = SDL_GetTicks();
unsigned int frames = 0;
int waterFrame = 0;
int camMode = cammode_firstPerson;
float desiredFov = clientEnvironment.settings->fieldOfView;
float currentZoom = clientEnvironment.settings->fieldOfView;
double totalSteps = 0;
glm::vec3 lastPlayerDir = glm::vec3(0,0,0);
int lastPlayerControlMask = 0;
int transSendInterval = 30;
int lastSentTransData = 0;
bool doJump = false;
bool showPreview = false;
bool hitDebug = true;
bool justTurnOnChat = false;
float lastPhysicsStep = 0.0;
unsigned int debugMode = 3;
bool connected = false;
TCPsocket cdnClient = 0;
SDLNet_SocketSet cdnSocketSet = 0;
customFileDescriptor *downloading = 0;
std::ofstream currentDownloadFile;
btDefaultCollisionConfiguration *collisionConfiguration = 0;
btCollisionDispatcher* dispatcher = 0;
btBroadphaseInterface* broadphase = 0;
btSequentialImpulseConstraintSolver* solver = 0;
btDynamicsWorld *world = 0;
btCollisionShape *plane = 0;
btDefaultMotionState* planeState = 0;
btRigidBody *groundPlane = 0;
//Start connect screen
//Start-up has finished
context.setMouseLock(false);
gameState currentState = STATE_MAINMENU;
while(currentState != STATE_QUITTING)
{
switch(currentState)
{
case STATE_AVATARPICKER:
{
//TODO: To be moved from avatarPicker.cpp
break;
}
case STATE_CLEANUP:
{
info("Starting clean up...");
((CEGUI::Combobox *)clientEnvironment.wrench->getChild("MusicDropdown"))->resetList();
if(clientEnvironment.picker)
{
if(clientEnvironment.picker->pickingPlayer)
{
delete clientEnvironment.picker->pickingPlayer;
clientEnvironment.picker->pickingPlayer = 0;
}
for(int a = 0; a<clientEnvironment.picker->faceDecals.size(); a++)
delete clientEnvironment.picker->faceDecals[a];
clientEnvironment.picker->faceDecals.clear();
}
clientEnvironment.ignoreGamePackets = true;
serverStuff *serverData = clientEnvironment.serverData;
for(int a = 0; a<serverData->livingBricks.size(); a++)
{
for(int b = 0; b<serverData->livingBricks[a]->newWheels.size(); b++)
delete serverData->livingBricks[a]->newWheels[b];
serverData->livingBricks[a]->newWheels.clear();
}
//Clear chats:
CEGUI::Listbox* chat = (CEGUI::Listbox*)clientEnvironment.chat;
chat->resetList();
//Clear player list:
CEGUI::MultiColumnList *playerList = (CEGUI::MultiColumnList*)clientEnvironment.playerList->getChild("List");
playerList->resetList();
//Clear decal gui elements
CEGUI::ScrolledContainer *decalBox = (CEGUI::ScrolledContainer *)((CEGUI::ScrollablePane*)clientEnvironment.picker->decalPicker->getChild("Decals"))->getContentPane();
while(decalBox->getChildCount() > 0)
{
CEGUI::Window *child = decalBox->getChildAtIdx(0);
if(CEGUI::ImageManager::getSingleton().isDefined(child->getChild("Image")->getProperty("Image")))
{
if(child->getUserData())
delete child->getUserData();
std::string iconName = child->getChild("Image")->getProperty("Image").c_str();
CEGUI::ImageManager::getSingleton().destroy(iconName);
CEGUI::System::getSingleton().getRenderer()->destroyTexture(iconName);
}
decalBox->removeChild(child);
CEGUI::WindowManager::getSingleton().destroyWindow(child);
}
for(int a = 0; a<clientEnvironment.picker->faceDecals.size(); a++)
delete clientEnvironment.picker->faceDecals[a];
clientEnvironment.picker->faceDecals.clear();
clientEnvironment.picker->faceDecalFilepaths.clear();
//Decal gui elements clear
//Clear up brick type GUI elements
CEGUI::Window *brickPopup = CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow()->getChild("HUD")->getChild("BrickPopup");
for(int a = 1; a<=9; a++)
{
CEGUI::Window *cart = clientEnvironment.brickSelector->getChild("Cart" + std::to_string(a));
if(cart->getChild("BrickText")->getText() != "")
{
brickPopup->getChild("Cart" + std::to_string(a))->setProperty("Image","");
cart->getChild("BrickImage")->setProperty("Image","");
cart->getChild("BrickText")->setText("");
cart->setUserData(0);
}
}
CEGUI::ScrolledContainer *brickBox = (CEGUI::ScrolledContainer*)((CEGUI::ScrollablePane*)clientEnvironment.brickSelector->getChild("BasicBricks"))->getContentPane();
while(brickBox->getChildCount() > 0)
{
CEGUI::Window *child = brickBox->getChildAtIdx(0);
if(CEGUI::ImageManager::getSingleton().isDefined(child->getChild("BrickImage")->getProperty("Image")))
{
std::string iconName = child->getChild("BrickImage")->getProperty("Image").c_str();
CEGUI::ImageManager::getSingleton().destroy(iconName);
CEGUI::System::getSingleton().getRenderer()->destroyTexture(iconName);
if(child->getUserData())
delete child->getUserData();
}
brickBox->removeChild(child);
CEGUI::WindowManager::getSingleton().destroyWindow(child);
}
brickBox = (CEGUI::ScrolledContainer*)((CEGUI::ScrollablePane*)clientEnvironment.brickSelector->getChild("SpecialBricks"))->getContentPane();
while(brickBox->getChildCount() > 0)
{
CEGUI::Window *child = brickBox->getChildAtIdx(0);
if(CEGUI::ImageManager::getSingleton().isDefined(child->getChild("BrickImage")->getProperty("Image")))
{
std::string iconName = child->getChild("BrickImage")->getProperty("Image").c_str();
CEGUI::ImageManager::getSingleton().destroy(iconName);
CEGUI::System::getSingleton().getRenderer()->destroyTexture(iconName);
if(child->getUserData())
delete child->getUserData();
}
brickBox->removeChild(child);
CEGUI::WindowManager::getSingleton().destroyWindow(child);
}
//Brick type gui elements cleared
if(blocklandHolder)
delete blocklandHolder;
blocklandHolder = 0;
CEGUI::ScrolledContainer *box = (CEGUI::ScrolledContainer *)((CEGUI::ScrollablePane*)clientEnvironment.picker->decalPicker->getChild("Decals"))->getContentPane();
while(box->getChildCount() > 0)
box->removeChild(box->getChildAtIdx(0));
//Audio clean-up
while(clientEnvironment.speaker->allLoops.size() > 0)
clientEnvironment.speaker->removeLoop(clientEnvironment.speaker->allLoops[0].serverId);
for(int a = 0; a<32; a++)
{
alSourcei( clientEnvironment.speaker->generalSounds[a], AL_BUFFER, 0);
alSourceStop(clientEnvironment.speaker->generalSounds[a]);
}
for(int a = 0; a<clientEnvironment.speaker->sounds.size(); a++)
delete clientEnvironment.speaker->sounds[a];
clientEnvironment.speaker->sounds.clear();
//Finish audio clean-up
context.setMouseLock(false);
clientEnvironment.waitingToPickServer = true;
bounceText->setVisible(true);
bounceText->moveToBack();
delete serverData;
serverData = 0;
clientEnvironment.serverData = 0;
if(waterDepth)
delete waterDepth;
waterDepth=0;
if(waterReflection)
delete waterReflection;
waterReflection = 0;
if(waterRefraction)
delete waterRefraction;
waterRefraction = 0;
delete groundPlane;
delete plane;
delete planeState;
delete world;
delete collisionConfiguration;
delete dispatcher;
delete broadphase;
delete solver;
currentState = STATE_MAINMENU;
break;
}
case STATE_MAINMENU:
{
clientEnvironment.ignoreGamePackets = true;
if(clientEnvironment.serverData)
{
delete clientEnvironment.serverData;
clientEnvironment.serverData = 0;
}
hud->setVisible(false);
joinServer->setVisible(true);
const Uint8 *states = SDL_GetKeyboardState(NULL);
SDL_Event e;
while(SDL_PollEvent(&e))
{
if(e.type == SDL_QUIT)
{
currentState = STATE_QUITTING;
break;
}
processEventsCEGUI(e,states);
if(e.type == SDL_WINDOWEVENT)
{
if(e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
{
context.setSize(e.window.data1,e.window.data2);
}
}
}
deltaT = SDL_GetTicks() - lastTick;
//After auto-updating, land of dran text may dissapear without this:
if(deltaT > 20)
deltaT = 20;
lastTick = SDL_GetTicks();
CEGUI::UVector2 pos = bounceText->getPosition();
if(pos.d_x.d_scale > 0.75)
horBounceDir = -1;
if(pos.d_y.d_scale > 0.9)
vertBounceDir = -1;
if(pos.d_x.d_scale < -0.1)
horBounceDir = 1;
if(pos.d_y.d_scale < -0.05)
vertBounceDir = 1;
pos += CEGUI::UVector2(CEGUI::UDim(horBounceDir * deltaT * 0.0002,0),CEGUI::UDim(vertBounceDir * deltaT * 0.0001,0));
bounceText->setPosition(pos);
hue += deltaT * 0.00003;
if(hue > 1)
hue -= 1;
HsvColor hsv;
hsv.h = hue*255;
hsv.s = 0.5*255;
hsv.v = 0.5*255;
RgbColor rgb = HsvToRgb(hsv);
context.clear(((float)rgb.r)/255.0,((float)rgb.g)/255.0,((float)rgb.b)/255.0);
context.select();
CEGUI::System::getSingleton().getRenderer()->setDisplaySize(CEGUI::Size<float>(context.getResolution().x,context.getResolution().y));
glViewport(0,0,context.getResolution().x,context.getResolution().y);
glDisable(GL_DEPTH_TEST);
glActiveTexture(GL_TEXTURE0);
CEGUI::System::getSingleton().renderAllGUIContexts();
context.swap();
glEnable(GL_DEPTH_TEST);
if(clientEnvironment.clickedMainMenuExit)
{
currentState = STATE_QUITTING;
break;
}
SDL_Delay(1);
if(!clientEnvironment.waitingToPickServer)
{
bounceText->setVisible(false);
currentState = STATE_GETCONTENTLIST;
clientEnvironment.waitingOnContentList = true;
clientEnvironment.cancelCustomContent = false;
clientEnvironment.expectedCustomFiles = -1;
clientEnvironment.cancelCustomContentTimeoutTime = SDL_GetTicks() + 15000;
contentMenu->getChild("Join")->setText("Loading list...");
contentMenu->getChild("Join")->setDisabled(true);
((CEGUI::MultiColumnList*)contentMenu->getChild("List"))->clearAllSelections();
((CEGUI::MultiColumnList*)contentMenu->getChild("List"))->resetList();
contentMenu->moveToFront();
contentMenu->getChild("Size")->setText("");
contentMenu->getChild("Number")->setText("");
if(contentMenu->getUserData())
{
std::vector<customFileDescriptor*> *contentList = (std::vector<customFileDescriptor*> *)contentMenu->getUserData();
for(int a = 0; a<contentList->size(); a++)
delete contentList->at(a);
contentList->clear();
}
networkingPreferences netPrefs;
netPrefs.timeoutMS = 10000;
serverConnection = new client(netPrefs,clientEnvironment.wantedIP);
serverConnection->userData = &clientEnvironment;
serverConnection->receiveHandle = recvHandle;
serverConnection->kickHandle = gotKicked;
packet requestContent;
requestContent.writeUInt(clientPacketType_requestName,4);
requestContent.writeUInt(hardCodedNetworkVersion,32);
requestContent.writeBit(true);
serverConnection->send(&requestContent,true);
info("Retrieving custom content list...");
}
break;
}
case STATE_GETCONTENT:
{
const Uint8 *states = SDL_GetKeyboardState(NULL);
SDL_Event event;
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
{
currentState = STATE_QUITTING;
break;
}
processEventsCEGUI(event,states);
if(event.type == SDL_WINDOWEVENT)
{
if(event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
{
context.setSize(event.window.data1,event.window.data2);
}
}
}
std::vector<customFileDescriptor*> *contentList = ((std::vector<customFileDescriptor*> *)contentMenu->getUserData());
if(contentList)
{
if(contentList->size() > 0)
{
if(!downloading)
{
for(int a = 0; a<contentList->size(); a++)
{
if(!contentList->at(a)->selectable)
{
//std::cout<<"Not selectable...\n";
continue;
}
if(!contentList->at(a)->enabled)
{
//std::cout<<"Not enabled...\n";
continue;
}
if(contentList->at(a)->doneDownloading)
{
//std::cout<<"Done...\n";
continue;
}
downloading = contentList->at(a);
info("Downloading add-ons/"+downloading->path + " ID: " + std::to_string(contentList->at(a)->id));
std::filesystem::path pathToCreateFoldersFor("cache/"+downloading->path);
create_directories(pathToCreateFoldersFor.parent_path());
currentDownloadFile = std::ofstream("cache/"+downloading->path,std::ios::binary);
if(!currentDownloadFile.is_open())
error("Error opening file add-ons/" + downloading->path + " for write!");
break;
}
}
if(!downloading)
{
//error("No possible download candidate file.");
if(cdnClient)
{
SDLNet_TCP_Close(cdnClient);
cdnClient = 0;
}
if(cdnSocketSet)
{
SDLNet_FreeSocketSet(cdnSocketSet);
cdnSocketSet = 0;
}
delete serverConnection;
serverConnection = 0;
currentState = STATE_CONNECTING;
contentMenu->setVisible(false);
break;
}
int cdnReady = SDLNet_CheckSockets(cdnSocketSet,0);
if(cdnReady > 0)
{
int actualMax = std::min(1024,downloading->size-downloading->bytesReceived);
char *buf = new char[actualMax];
int recvBytes = SDLNet_TCP_Recv(cdnClient,buf,actualMax);
if(recvBytes < 1)
{
error("CDN Server closed connection!");
if(cdnClient)
{
SDLNet_TCP_Close(cdnClient);
cdnClient = 0;
}
if(cdnSocketSet)
{
SDLNet_FreeSocketSet(cdnSocketSet);
cdnSocketSet = 0;
}
delete serverConnection;
serverConnection = 0;
currentState = STATE_CONNECTING;
contentMenu->setVisible(false);
delete buf;
currentDownloadFile.close();
break;
}
else
{
//info("Downloaded: " + std::to_string(downloading->bytesReceived) + " / " + std::to_string(downloading->size));
currentDownloadFile.write(buf,recvBytes);
downloading->bytesReceived += recvBytes;
if(downloading->bytesReceived > downloading->size)
error("Somehow downloaded too many bytes: " + std::to_string(downloading->bytesReceived));
if(downloading->bytesReceived >= downloading->size)
{
currentDownloadFile.close();
downloading->doneDownloading = true;
downloading = 0;
}
}
delete buf;
}
else if(cdnReady == -1)
error("CDN CheckSockets failed!");
}
else
{
if(cdnClient)
{
SDLNet_TCP_Close(cdnClient);
cdnClient = 0;
}
if(cdnSocketSet)
{
SDLNet_FreeSocketSet(cdnSocketSet);
cdnSocketSet = 0;
}
delete serverConnection;
serverConnection = 0;
currentState = STATE_CONNECTING;
contentMenu->setVisible(false);
break;
}
}
else
{
error("No content list vector?");
if(cdnClient)
{
SDLNet_TCP_Close(cdnClient);
cdnClient = 0;
}
if(cdnSocketSet)
{
SDLNet_FreeSocketSet(cdnSocketSet);
cdnSocketSet = 0;
}
delete serverConnection;
serverConnection = 0;
currentState = STATE_CONNECTING;
contentMenu->setVisible(false);
break;
}
context.clear(0.5,0.5,1.0,1.0);
context.select();
CEGUI::System::getSingleton().getRenderer()->setDisplaySize(CEGUI::Size<float>(context.getResolution().x,context.getResolution().y));
glViewport(0,0,context.getResolution().x,context.getResolution().y);
glDisable(GL_DEPTH_TEST);
glActiveTexture(GL_TEXTURE0);
CEGUI::System::getSingleton().renderAllGUIContexts();
context.swap();
break;
}
case STATE_GETCONTENTLIST:
{
clientEnvironment.ignoreGamePackets = true;
serverConnection->run();
if(clientEnvironment.cancelCustomContent)
{
delete serverConnection;
serverConnection = 0;
clientEnvironment.cancelCustomContent = false;
clientEnvironment.waitingToPickServer = true;
currentState = STATE_MAINMENU;
break;
}
if(clientEnvironment.cancelCustomContentTimeoutTime < SDL_GetTicks())
{
error("Connection to server timed out!");
clientEnvironment.cancelCustomContent = true;
continue;
}
if(clientEnvironment.fatalNotifyStarted)
{
int *status = (int*)clientEnvironment.messageBox->getUserData();
if(status)
{
if(status[0] == 0)
{
delete serverConnection;
serverConnection = 0;
clientEnvironment.fatalNotifyStarted = false;
clientEnvironment.cancelCustomContent = false;
clientEnvironment.waitingToPickServer = true;
currentState = STATE_MAINMENU;
break;
}
}
}
if(!clientEnvironment.waitingOnContentList)
{
bool oneEnabled = false;
for(int a = 0; a<((std::vector<customFileDescriptor*> *)contentMenu->getUserData())->size(); a++)
{
if(((std::vector<customFileDescriptor*> *)contentMenu->getUserData())->at(a)->enabled)
{
oneEnabled = true;
break;
}
}
//We selected none of the available downloads...
if(!oneEnabled)
{
delete serverConnection;
serverConnection = 0;
currentState = STATE_CONNECTING;
contentMenu->setVisible(false);
break;
}
else
{
//gotta download at least one file...
IPaddress cdnServerAddr;
SDLNet_ResolveHost(&cdnServerAddr,clientEnvironment.wantedIP.c_str(),20000);
cdnClient = SDLNet_TCP_Open(&cdnServerAddr);
if(!cdnClient)
{
delete serverConnection;
serverConnection = 0;
error("Could not connect to content server! (Did the host port-forward UDP AND TCP?");
currentState = STATE_MAINMENU;
clientEnvironment.cancelCustomContent = false;
clientEnvironment.waitingToPickServer = true;
break;
}
cdnSocketSet = SDLNet_AllocSocketSet(1);
SDLNet_TCP_AddSocket(cdnSocketSet,cdnClient);
std::vector<customFileDescriptor*> *possibleFiles = ((std::vector<customFileDescriptor*> *)contentMenu->getUserData());
std::string contentRequest = "";
int numNeededFiles = 0;
for(int a = 0; a<possibleFiles->size(); a++)
{
//possibleFiles->at(a)->print();
if(possibleFiles->at(a)->enabled)
{
contentRequest += std::to_string(possibleFiles->at(a)->id) + "\n";
numNeededFiles++;
}
}
contentRequest = "FILES" + std::to_string(numNeededFiles) + "\n" + contentRequest + "END\n";
SDLNet_TCP_Send(cdnClient,contentRequest.c_str(),contentRequest.length());
currentState = STATE_GETCONTENT;
break;
}
}
//We don't actually have any new files we even *could* download if we wanted to, just skip to connecting...
if(clientEnvironment.expectedCustomFiles == ((std::vector<customFileDescriptor*> *)contentMenu->getUserData())->size())
{
contentMenu->getChild("Join")->setText("Confirm and Join");
contentMenu->getChild("Join")->setDisabled(false);
bool oneSelectable = false;
for(int a = 0; a<((std::vector<customFileDescriptor*> *)contentMenu->getUserData())->size(); a++)
{
if(((std::vector<customFileDescriptor*> *)contentMenu->getUserData())->at(a)->selectable)
{
oneSelectable = true;
break;
}
}
if(!oneSelectable)
{
info("There were no new custom files to download, skipping...");