-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUI.ixx
2133 lines (1764 loc) · 69.5 KB
/
UI.ixx
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
/*
* Basic UI elements.
* The UI class will be a singleton which is shared between all Screen modules.
* Main script creates it and hands it to the active Screen.
*
* A SCREEN can have PANELS, and PANELS can have BUTTONS (no panels outside of screens, no buttons outside of panels).
* This module will also include functions to check if a screen's panel's buttons are being hovered over or clicked.
* But the onclick action function will be in the SCREEN object (or at least will originate there and be fed in).
* There are some Panels which should be available to multiple Screens.
*
* UI holds no state. This object can be created and destroyed for each Screen, within the run function.
* It goes out of scope and dies when the run function is finished.
*
* How do we apply functionality to the buttons?
* Maybe we make our own event queue?
*
* TO DO:
* - Add "EXIT" button to main menu.
* - modular design for buttons (and possibly background... LATER... number of modular rects depend on height & width of rect)
*/
module;
export module UI;
import "include/json.hpp";
import "SDL.h";
import "SDL_image.h";
import "SDL_ttf.h";
import <stdio.h>;
import <string>;
import <iostream>;
import <vector>;
import <unordered_map>;
import <cmath>;
import <time.h>;
import <cstdlib>; /* Needed for rand() and srand() */
import <ctime>; /* Needed for time() */
import Resources;
import TypeStorage;
using namespace std;
class Panel;
class Button;
struct PreButtonStruct;
Uint32 convertSDL_ColorToUint32(const SDL_PixelFormat* format, SDL_Color color);
bool isInRect(SDL_Rect rect, int mouseX, int mouseY);
SDL_Surface* flipSurface(SDL_Surface* surface, bool horizontal);
vector<SDL_Rect> createSurfaceOverlay(SDL_Rect bgRect);
SDL_Surface* createTransparentSurface(int w, int h);
export struct LimbButtonData {
LimbButtonData(string texturePath, string name, int id) :
texturePath(texturePath), name(name), id(id) { }
string texturePath;
string name;
int id;
};
/*
*
*
*
*
* UI CLASS
*
*
*
*
*
*/
/* UI (singleton) class holds basic reusable SDL objects.
* It's also responsible for creating panels and buttons,
* but does not HOLD panels and buttons.
* Screen objects instead will hold panels. */
export class UI {
public:
// Deleted copy constructor and assignment operator to prevent copies
UI(const UI&) = delete;
UI& operator=(const UI&) = delete;
// Static method to get the instance of the singleton (so we don't call the constructor... we call getInstance())
static UI& getInstance() {
// THIS is the key moment where we create the actual object
static UI instance; // will be destroyed when program exits
return instance;
}
bool isInitialized() { return initialized; }
SDL_Renderer* getMainRenderer() { return mainRenderer; }
SDL_Surface* getWindowSurface() { return mainWindowSurface; }
SDL_Window* getMainWindow() { return mainWindow; }
TTF_Font* getButtonFont() { return buttonFont; }
TTF_Font* getTitleFont() { return titleFont; }
TTF_Font* getBodyFont() { return bodyFont; }
unordered_map<string, SDL_Color> getColors() { return colorsByFunction; }
/* MAIN MENU PANEL. */
Panel createMainMenuPanel();
void rebuildMainMenuPanel(Panel& mainMenuPanel);
Panel createSettingsPanel(ScreenType context = ScreenType::Menu);
void rebuildSettingsPanel(Panel& settingsPanel, ScreenType context = ScreenType::Menu);
Panel createGameMenuPanel();
void rebuildGameMenuPanel(Panel& gameMenuPanel);
/* CHARACTER CREATION PANELS. */
Panel createReviewModePanel();
Panel createLimbLoadedModePanel(bool loadedLimbHasExtraJoints, bool characterHasExtraJoints); /* Does this need a limb id? */
Panel createChooseLimbModePanel(vector<LimbButtonData> limbBtnDataStructs);
/* NEXT: make rebuildPanel functions for Character Creation screen. */
/* Confirmation Text Panel. */
Panel createConfirmationPanel(
string confirmationText,
ConfirmationButtonType confirmationType = ConfirmationButtonType::OkCancel,
bool includeRefuseButton = true
);
int getWindowHeight() { return windowHeight; }
int getWindowWidth() { return windowWidth; }
void resizeWindow(WindowResType newResType);
void refreshFonts(Resources& resources);
/* Background with overlay */
SDL_Texture* createBackgroundTexture();
/* get title texture for any screen */
tuple<SDL_Texture*, SDL_Rect> createTitleTexture(string title);
unordered_map<string, SDL_Color> getColorsByFunction() { return colorsByFunction; }
private:
// Constructor is private to prevent instantiation from outside the class
UI() {
/* DEV BLOCK START. set screen size (for dev purposes) */
if (windowResType == WindowResType::Mobile) {
setWindowSize(360, 800);
}
else if (windowResType == WindowResType::Tablet) {
setWindowSize(810, 1080);
}
else if (windowResType == WindowResType::Desktop) {
setWindowSize(1600, 900);
}
/* DEV BLOCK OVER. we assume res type is Fullscreen */
// fullscreen will be dealt with in initialize()
initialized = initialize();
prepareColors();
/* set the height and width values for items depending on those values */
getAndStoreWindowSize();
}
// Private destructor to prevent deletion through a pointer to the base class
~UI() = default;
/* Only for initial display. */
const WindowResType windowResType = WindowResType::Desktop;
int buttonPadding = 10;
const int PANEL_PADDING = 10;
/* Window will actually be full size.These make the numbers available for the UI to calculate things. */
int windowWidth = 720;
int windowHeight = 960;
int initialized = false;
SDL_Window* mainWindow = NULL;
SDL_Renderer* mainRenderer = NULL;
SDL_Surface* mainWindowSurface = NULL;
TTF_Font* titleFont = NULL;
TTF_Font* buttonFont = NULL;
TTF_Font* bodyFont = NULL;
TTF_Font* dialogFont = NULL;
PreButtonStruct buildPreButtonStruct(string text, ButtonOption buttonOption, int optionID = -1);
SDL_Rect buildVerticalPanelRectFromButtonTextRects(vector<PreButtonStruct> preButtonStructs);
vector<Button> buildButtonsFromPreButtonStructsAndPanelRect(vector<PreButtonStruct> preButtonStructs, SDL_Rect panelRect);
vector<Button> buildLimbButtonsFromPreButtonStructsAndPanelRect(vector<PreButtonStruct> preButtonStructs, SDL_Rect panelRect);
/* settings panel building functions */
tuple<SDL_Rect, vector<Button>> createSettingsPanelComponents(ScreenType context = ScreenType::Menu);
vector<PreButtonStruct> getSettingsPreButtonStructs(ScreenType context = ScreenType::Menu);
/* main menu panel building functions */
tuple<SDL_Rect, vector<Button>> createMainMenuPanelComponents();
vector<PreButtonStruct> getMainMenuPreButtonStructs();
/* Map Menu panel building functions */
tuple<SDL_Rect, vector<Button>> createGameMenuPanelComponents();
vector<PreButtonStruct> getGameMenuPreButtonStructs();
/* Character Creation panel building functions. */
tuple<SDL_Rect, vector<Button>> createReviewModePanelComponents();
tuple<SDL_Rect, vector<Button>> createLimbLoadedModePanelComponents(bool loadedLimbHasExtraJoints, bool characterHasExtraJoints);
tuple<SDL_Rect, vector<Button>> createChooseLimbModePanelComponents(vector<LimbButtonData> limbBtnDataStructs);
vector<PreButtonStruct> getReviewModePreButtonStructs();
vector<PreButtonStruct> getLimbLoadedModePreButtonStructs(bool loadedLimbHasExtraJoints, bool characterHasExtraJoints);
void prepareColors();
void getAndStoreWindowSize();
/* when you need to dictate dimensions (for dev purposes) */
void setWindowSize(int x, int y) {
windowWidth = x;
windowHeight = y; }
// color maps
unordered_map<string, SDL_Color> colorsByFunction; /* colors by function, which reference colors by name. */
unordered_map<string, SDL_Color> colorsByName; /* raw colors. */
bool initialize();
bool initializeFonts(Resources& resources);
};
/*
*
*
*
*
* BUTTON CLASS
*
*
*
*
*
*/
/* Buttons contain a Rect, but also must contain clickStruct data to send to the calling Screen.
Buttons make a Rect clickable and allow us to perform other actions on them.
text texture should be saved in the button */
export class Button {
public:
/* Constructor to make a button the length of its text (must send in padding)
* Constructor receives the position of the button, text string, and font.
* Will receive anonymous function too.
* NOT CURRENTLY USING THIS ONE... WILL HAVE TO UPDATE IF/WHEN USED (for horizontal screen?)
*/
Button(int x, int y, string incomingText, TTF_Font* buttonFont, SDL_Color fontColor, SDL_Renderer* mainRenderer) {
//mouseOver = false;
///* constants for the creation of the button*/
//const int buttonPadding = 20;
//text = incomingText;
///*setTextRect(rect, text, buttonFont);
//Somehow we must pass in a function as an action
//use the Standard library header <functional> for lambdas and anoymous fuctions*/
//int textRectWidth, textRectHeight;
///* get height and width of text based on string(set those values into ints)*/
//TTF_SizeUTF8(buttonFont, text.c_str(), &textRectWidth, &textRectHeight);
///* make the textRect with the appropriate borders*/
//textRect = {
// x + (buttonPadding / 2),
// y + (buttonPadding / 2),
// textRectWidth,
// textRectHeight
//};
///* the actual button rect*/
//rect = {
// x,
// y,
// textRectWidth + buttonPadding,
// textRectHeight + buttonPadding
//};
///* make the textTexture*/
//SDL_Surface* buttonTextSurface = TTF_RenderText_Blended(buttonFont, text.c_str(), fontColor);
//textTexture = SDL_CreateTextureFromSurface(mainRenderer, buttonTextSurface);
//SDL_FreeSurface(buttonTextSurface);
}
/* Constructor for when we already have both SDL_Rects (used buttons have pre-set sizes) */
Button(
SDL_Rect buttonRect,
SDL_Rect textRect,
string text,
TTF_Font* buttonFont,
unordered_map<string, SDL_Color> colors,
SDL_Renderer* mainRenderer,
ButtonClickStruct clickStruct
) : text(text), clickStruct(clickStruct), rect(buttonRect)
{
mouseOver = false;
createButtonTextures(buttonRect, textRect, text, buttonFont, colors, mainRenderer);
}
/*
* CONSTRUCTOR FOR PRE-BUILT TEXTURES.
* Constructor for when you created the two textures beforehand, and are just handing them in.
* Specifically for the LIMB BUTTONS, but can be used for others too.
*/
Button(SDL_Rect rect, SDL_Texture* hoverTexture, SDL_Texture* normalTexture, string text, ButtonClickStruct clickStruct) :
rect(rect), hoverTexture(hoverTexture), normalTexture(normalTexture),
text(text), clickStruct(clickStruct), mouseOver(false) { }
// Might turn this private since we should only operate on it internally
SDL_Rect getRect() { return rect; }
string getText() { return text; } // turn this completely into char for the printing
SDL_Texture* getHoverTexture() { return hoverTexture; }
SDL_Texture* getNormalTexture() { return normalTexture; }
// check if mouse location has hit the panel
bool isInButton(int mouseX, int mouseY) { return isInRect(getRect(), mouseX, mouseY); }
void setMouseOver(bool incomingMouseOver) { mouseOver = incomingMouseOver; }
bool isMouseOver() { return mouseOver; }
ButtonClickStruct getClickStruct() { return clickStruct; }
private:
// REMOVE textRect and textTexture
// Replace with hoverTexture and normalTexture
SDL_Rect rect;
SDL_Texture* hoverTexture = NULL;
SDL_Texture* normalTexture = NULL;
string text = "";
bool mouseOver;
ButtonClickStruct clickStruct;
SDL_Rect createTextRect(SDL_Rect buttonRect, string buttonText, TTF_Font* buttonFont); /* For normal all-text buttons. */
SDL_Surface* createButtonSurfaceBG(SDL_Rect buttonRect, SDL_Color color, SDL_Color overlayColor, SDL_Renderer* mainRenderer, vector<SDL_Rect> overlayRects);
void createButtonTextures(SDL_Rect buttonRect, SDL_Rect textRect, string incomingText, TTF_Font* buttonFont, unordered_map<string, SDL_Color> colors, SDL_Renderer* mainRenderer);
};
/* build inner textRect based on other button information */
SDL_Rect Button::createTextRect(SDL_Rect buttonRect, string buttonText, TTF_Font* buttonFont) {
rect = buttonRect;
// get height and width of textRect
int textRectWidth, textRectHeight;
TTF_SizeUTF8(buttonFont, buttonText.c_str(), &textRectWidth, &textRectHeight);
int xPadding = (buttonRect.w - textRectWidth) / 2;
int yPadding = (buttonRect.h - textRectHeight) / 2;
// finally make the textRect with the appropriate borders
return {
buttonRect.x + xPadding,
buttonRect.y + yPadding,
textRectWidth,
textRectHeight
};
}
/* Generate a randomized overlay for button backgrounds */
vector<SDL_Rect> createSurfaceOverlay(SDL_Rect bgRect) {
/*
* TODO: Simplify the variable sized blocks.
*/
/* we will store all the rects here and later draw them */
vector<SDL_Rect> rects;
/* Pick a random starting point */
enum StartingRect { WholeSide, Corner, Top };
int startingRectNumber = (rand() % 3) + 1;
StartingRect startingRect = startingRectNumber == 3 ? WholeSide :
startingRectNumber == 2 ? Corner : Top;
float whRatio = (float)bgRect.w / (float)bgRect.h;
/* not totally random dimensions. Always in increments, defined as blocks (of pixels) based on resolution.
* Resolution variable based on dimensions. */
int xRes = bgRect.w < 350 ? 10 : bgRect.w < 800 ? 6 : 8;
//int yRes = bgRect.h < 200 ? 4 : bgRect.h < 350 ? 10 : bgRect.h < 800 ? 6 : bgRect.h < 900 ? 15 : 12;
float yResFloat = xRes / whRatio;
int yRes = (int)yResFloat;
if (yRes == 0) { yRes = 1; }
if (xRes == 0) { xRes = 1; }
/* resolution */
/* Minimum sizes */
int blockWidth = bgRect.w / xRes;
int blockHeight = bgRect.h / yRes;
/* create a map of false bools corresponding to a grid over the buttons */
vector<vector<bool>> rows(yRes);
for (int i = 0; i < yRes; ++i) {
vector<bool> blocks(xRes);
for (int k = 0; k < xRes; ++k) {
blocks[k] = false;
}
rows[i] = blocks;
}
/* pick a max number of blocks to color */
int totalBlocks = xRes * yRes;
int minBlocks = totalBlocks / 2;
int maxBlocks = (totalBlocks / 4) * 3;
int seeds = (rand() % (totalBlocks - maxBlocks)) + minBlocks + 1;
/* get any remaining height & width to tack onto edge blocks */
int widthOfAllBlocks = xRes + blockWidth;
int heightOfAllBlocks = yRes * blockHeight;
int remainderX = bgRect.w - widthOfAllBlocks;
int remainderY = bgRect.h - heightOfAllBlocks;
/* NON-RANDOM START: Fill a few blocks on the left. */
int columnsToFill = bgRect.w < 350 ? 3 : 0;
for (int i = 0; i < rows.size(); ++i) {
for (int k = 0; k < columnsToFill; ++k) {
/* add the block and decrement the seeds */
rows[i][k] = true;
SDL_Rect newRect = {
k * blockWidth,
i * blockHeight,
blockWidth,
blockHeight
};
/* If it's the last block, make sure it reaches the edge */
if (i == yRes - 1) { newRect.h += remainderY; }
if (k == xRes - 1) { newRect.w += remainderX; }
rects.push_back(newRect);
--seeds;
}
}
/* Start the path on the top left. */
int currX = columnsToFill;
int currY = 0;
rows[currY][currX] = true;
SDL_Rect firstRect = {
currX * blockWidth,
currY * blockHeight,
blockWidth,
blockHeight
};
rects.push_back(firstRect);
--seeds;
/* create the rest of the rects by crawling around and turning blocks true */
enum Direction { Up, Down, Left, Right, NoDirection};
int reStarts = bgRect.w < 350 ? 0 : bgRect.w < 1000 ? 2 :3;
while (seeds > 0) {
/* check how many directions are available */
vector<Direction> availableDirections;
bool nowhereToGo = true;
/* look UP */
if (currY > 0 && rows[currY -1][currX] == false) {
availableDirections.push_back(Direction::Up);
nowhereToGo = false;
}
/* look DOWN */
if (currY < (yRes - 2) && rows[currY + 1][currX] == false) {
availableDirections.push_back(Direction::Down);
nowhereToGo = false;
}
/* look LEFT */
if (currX > 0 && rows[currY][currX - 1] == false) {
availableDirections.push_back(Direction::Left);
nowhereToGo = false;
}
/* look RIGHT */
if (currX < (xRes - 1) && rows[currY][currX + 1] == false) {
availableDirections.push_back(Direction::Right);
nowhereToGo = false;
}
/* If we can't move, break the loop (try to find a new place first) */
if (nowhereToGo) {
/* don't restart if it's close to the end anyway */
if (reStarts < 1 || seeds < 5) {
seeds = 0;
break;
}
/* make some attempt to pick a random false block */
int attempts = 5;
while (attempts > 0) {
/* get random X and Y */
int randX = rand() % rows[0].size();
int randY = rand() % rows.size();
if (!rows[randY][randX]) {
currY = randY;
currX = randX;
rows[randY][randX] = true;
++seeds; /* give this new cluster a little extra */
}
--attempts;
}
--reStarts;
continue;
}
int numberOfAvailableDirections = (unsigned int)availableDirections.size();
Direction newDirection = Direction::NoDirection;
if (numberOfAvailableDirections == 1) {
newDirection = availableDirections[0];
}
else {
/* Pick a direction from those available */
int directionIndex = rand() % numberOfAvailableDirections;
newDirection = availableDirections[directionIndex];
}
/* If we can't move, break the loop */
if (newDirection == Direction::NoDirection) {
seeds = 0;
break;
}
/* move in that direction (change current X and Y) */
switch (newDirection) {
case Direction::Up:
--currY;
break;
case Direction::Down:
++currY;
break;
case Direction::Right:
++currX;
break;
case Direction::Left:
--currX;
break;
default:
currY = -1;
currX = -1;
break;
}
/* just double check that we really moved */
if (currY < 0 || currX < 0) {
seeds = 0;
break;
}
/* add the block and decrement the seeds */
rows[currY][currX] = true;
SDL_Rect newRect = {
currX * blockWidth,
currY * blockHeight,
blockWidth,
blockHeight
};
/* If it's the last block, make sure it reaches the edge */
if (currY == yRes - 1) { newRect.h += remainderY; }
if (currX == xRes - 1) { newRect.w += remainderX; }
rects.push_back(newRect);
--seeds;
}
return rects;
}
/* Button textures must start with a surface. Create and get it here. */
SDL_Surface* Button::createButtonSurfaceBG(
SDL_Rect buttonRect,
SDL_Color color,
SDL_Color overlayColor,
SDL_Renderer* mainRenderer,
vector<SDL_Rect> overlayRects
) {
UI& ui = UI::getInstance();
SDL_Surface* buttonSurface = SDL_CreateRGBSurface(0, buttonRect.w, buttonRect.h, 32, 0, 0, 0, 0xFF000000);
// fill the rects with beautiful color
SDL_FillRect(buttonSurface, NULL, convertSDL_ColorToUint32(buttonSurface->format, color));
/* draw the overlay */
if (overlayRects.size() > 0) {
for (SDL_Rect rect : overlayRects) {
SDL_FillRect(buttonSurface, &rect, convertSDL_ColorToUint32(buttonSurface->format, overlayColor));
}
}
return buttonSurface;
}
/* A button must have both NORMAL and HOVER textures. Create them both here. */
void Button::createButtonTextures(
SDL_Rect buttonRect,
SDL_Rect textRect,
string incomingText,
TTF_Font* buttonFont,
unordered_map<string, SDL_Color> colors,
SDL_Renderer* mainRenderer
) {
SDL_Surface* hoverButtonTextSurface = TTF_RenderUTF8_Blended(buttonFont, text.c_str(), colors["DARK_TEXT"]);
SDL_Surface* normalButtonTextSurface = TTF_RenderUTF8_Blended(buttonFont, text.c_str(), colors["BTN_TEXT"]);
/* make the overlay which normal and hover buttons will share */
vector<SDL_Rect> overlayRects = createSurfaceOverlay(buttonRect);
/* make two button surfaces with the correct BG colors, to blit the text surfaces onto */
SDL_Surface* hoverButtonSurface = createButtonSurfaceBG(buttonRect, colors["BTN_HOVER_BG"], colors["BTN_HOVER_BRDR"], mainRenderer, overlayRects);
SDL_Surface* normalButtonSurface = createButtonSurfaceBG(buttonRect, colors["BTN_BG"], colors["BTN_BRDR"], mainRenderer, overlayRects);
/* possibility of flipping */
int hFlipInt = rand() % 2;
int vFlipInt = rand() % 2;
if (hFlipInt == 0) {
hoverButtonSurface = flipSurface(hoverButtonSurface, true);
normalButtonSurface = flipSurface(normalButtonSurface, true);
}
if (vFlipInt == 0) {
hoverButtonSurface = flipSurface(hoverButtonSurface, false);
normalButtonSurface = flipSurface(normalButtonSurface, false);
}
/* blit the text */
SDL_BlitSurface(hoverButtonTextSurface, NULL, hoverButtonSurface, &textRect);
SDL_BlitSurface(normalButtonTextSurface, NULL, normalButtonSurface, &textRect);
hoverTexture = SDL_CreateTextureFromSurface(mainRenderer, hoverButtonSurface);
normalTexture = SDL_CreateTextureFromSurface(mainRenderer, normalButtonSurface);
// free the surfaces
SDL_FreeSurface(hoverButtonTextSurface);
SDL_FreeSurface(normalButtonTextSurface);
SDL_FreeSurface(hoverButtonSurface);
SDL_FreeSurface(normalButtonSurface);
}
/*
*
*
*
*
* PANEL CLASS
*
*
*
*
*
*/
/* Panels contain buttons. There can be no buttons without a Panel container.
* Panels do not belong to a screen. They are created inside the screen's run() function.
*/
export class Panel {
public:
/* constructor */
Panel(SDL_Rect incomingRect, vector<Button> incomingButtons, SDL_Texture* texture = NULL) {
rect = incomingRect;
buttons = incomingButtons;
mouseOver = false;
show = false;
bgTexture = texture;
}
Panel() {}
vector<Button>& getButtons() { return buttons; }
/* check if mouse location has hit the panel */
bool isInPanel(int mouseX, int mouseY) { return isInRect(getRect(), mouseX, mouseY); }
void setMouseOver(bool incomingMouseOver) { mouseOver = incomingMouseOver; }
bool getShow() { return show; }
void setShow(bool incomingShow) { show = incomingShow; }
void checkMouseOver(int mouseX, int mouseY) {
if (isInRect(getRect(), mouseX, mouseY)) {
/* Panel mouseOver helps manage button mouseOver */
mouseOver = true;
for (Button &button : buttons) {
button.setMouseOver(button.isInButton(mouseX, mouseY));
}
}
else if (mouseOver) {
/* this checks if mouse recently LEFT the panel, and resets all buttons to "false" */
mouseOver = false;
/* change button mouseOver to false. */
for (Button &button : buttons) {
button.setMouseOver(false);
}
}
}
ButtonClickStruct checkButtonClick(int mouseX, int mouseY) {
for (Button &button : buttons) {
if (button.isInButton(mouseX, mouseY)) {
cout << "Button clicked!\n";
return button.getClickStruct();
}
}
return ButtonClickStruct();
}
void rebuildSelf(SDL_Rect incomingRect, vector<Button> incomingButtons) {
rect = incomingRect;
buttons = incomingButtons;
}
void draw(UI& ui = UI::getInstance()) {
if (!getShow()) { return; }
if (bgTexture != NULL) {
SDL_RenderCopyEx(
ui.getMainRenderer(),
bgTexture,
NULL, &rect,
0, NULL, SDL_FLIP_NONE
);
}
for (Button& button : buttons) {
/* get the rect, send it a reference(to be converted to a pointer) */
SDL_Rect buttonRect = button.getRect();
/* now draw the button texture */
SDL_RenderCopyEx(
ui.getMainRenderer(),
button.isMouseOver() ? button.getHoverTexture() : button.getNormalTexture(),
NULL, &buttonRect,
0, NULL, SDL_FLIP_NONE
);
}
}
void destroyTextures() {
for (Button& button : buttons) {
if (button.getHoverTexture() != NULL) {
SDL_DestroyTexture(button.getHoverTexture()); }
if (button.getNormalTexture() != NULL) {
SDL_DestroyTexture(button.getNormalTexture()); }
}
buttons = {};
if (bgTexture != NULL) { SDL_DestroyTexture(bgTexture); }
}
void setRect(SDL_Rect newRect) { rect = newRect; }
SDL_Rect getRect() { return rect; }
private:
SDL_Rect rect;
vector<Button> buttons;
bool mouseOver;
bool show;
SDL_Texture* bgTexture = NULL;
};
/* Stores initial data to assist construction of the panel.
* Panel uses this data to help construct itself.
* Then buttons use this data AND panel data to construct THEMselves. */
struct PreButtonStruct {
int textRectWidth;
int textRectHeight;
string text;
ButtonClickStruct clickStruct;
PreButtonStruct(int iWidth, int iHeight, string iText, ButtonClickStruct iClickStruct) {
textRectWidth = iWidth;
textRectHeight = iHeight;
text = iText;
clickStruct = iClickStruct;
}
};
/*
*
*
*
*
* EXTRA MEMBER FUNCTIONS FOR UI CLASS
*
*
*
*
* Building panels is complicated.
* We must build buttons to populate the panels,
* and the size of the panels depends on the dimensions of the buttons.
* But sometimes a button's size depends on the size of other buttons.
* So we build PreButtonStructs with SOME button data,
* and use that to build the panel's rect(angle),
* then use that panel's rect to build the ACTUAL buttons.
* Once we have the ACTUAL buttons and the panel's rect,
* then we can construct (and return) the actual panel.
*
* Some panels follow a similar pattern, but others are more unique.
* The panel of limbs on the character creation screen has rows AND columns.
* Its buttons have pictures. Will they have text too??
*/
/* Buttons need their parent panel rect before they can be built.
* Yet panel rects need information about their child buttons before they can be built.
* So we build PART of the button first, for the panel rects which let us finish the buttons.*/
PreButtonStruct UI::buildPreButtonStruct(string text, ButtonOption buttonOption, int optionID) {
int textRectWidth, textRectHeight;
// get height and width of text based on string (set those values into ints)
TTF_SizeUTF8(buttonFont, text.c_str(), &textRectWidth, &textRectHeight);
return PreButtonStruct(textRectWidth, textRectHeight, text, ButtonClickStruct(buttonOption, optionID));
}
/* Now that we have some information about the buttons (via struct), we can build the Panel's RECT. */
SDL_Rect UI::buildVerticalPanelRectFromButtonTextRects(vector<PreButtonStruct> preButtonStructs) {
int panelHeight = PANEL_PADDING; // start with one padding
int longestButtonTextLength = 0;
for (PreButtonStruct preButtonStruct : preButtonStructs) {
// add up the heights of the buttons plus padding
panelHeight += preButtonStruct.textRectHeight + (buttonPadding * 2) + PANEL_PADDING;
// set the longest text length
if (preButtonStruct.textRectWidth > longestButtonTextLength) {
longestButtonTextLength = preButtonStruct.textRectWidth;
}
}
return {
/* x is always 0 */
0,
windowHeight - panelHeight,
/* panel is just wide enough to accomodate the longest button */
longestButtonTextLength + (buttonPadding * 2) + (PANEL_PADDING * 2),
panelHeight
};
}
/* NOW that we have both some info about the buttons, plus the panel rect, make the actual buttons. */
vector<Button> UI::buildButtonsFromPreButtonStructsAndPanelRect(vector<PreButtonStruct> preButtonStructs, SDL_Rect panelRect) {
vector<Button> buttons;
const int xForAll = PANEL_PADDING;
int widthForAll = panelRect.w - (PANEL_PADDING * 2);
int heightSoFar = panelRect.y + PANEL_PADDING;
for (int i = 0; i < preButtonStructs.size(); ++i) {
PreButtonStruct thisStruct = preButtonStructs[i];
/* start at the top of the panelRect PLUS panelPadding */
SDL_Rect thisButtonRect = {
xForAll,
heightSoFar,
widthForAll,
thisStruct.textRectHeight + (buttonPadding * 2)
};
/* RELATIVE rect to be later painted onto the button itself (when fed into the constructor)*/
SDL_Rect thisTextRect = {
// text x position is HALF of the difference b/w button width and text width
(thisButtonRect.w - thisStruct.textRectWidth) / 2,
buttonPadding,
thisStruct.textRectWidth,
thisStruct.textRectHeight
};
buttons.push_back(
Button(
thisButtonRect,
thisTextRect,
thisStruct.text,
buttonFont,
colorsByFunction,
mainRenderer,
thisStruct.clickStruct));
/* increment heightSoFar */
heightSoFar += thisButtonRect.h + PANEL_PADDING;
}
return buttons;
}
/*
* Building buttons specifically for the Inventory Limbs button panel.
*/
vector<Button> UI::buildLimbButtonsFromPreButtonStructsAndPanelRect(vector<PreButtonStruct> preButtonStructs, SDL_Rect panelRect) {
vector<Button> buttons;
const int xForAll = PANEL_PADDING;
int widthForAll = panelRect.w - (PANEL_PADDING * 2);
int heightSoFar = panelRect.y + PANEL_PADDING;
for (int i = 0; i < preButtonStructs.size(); ++i) {
/* start at the top of the panelRect PLUS panelPadding */
SDL_Rect thisButtonRect = {
xForAll,
heightSoFar,
widthForAll,
preButtonStructs[i].textRectHeight + (buttonPadding * 2)
};
/* RELATIVE rect to be later painted onto the button itself (when fed into the constructor)*/
SDL_Rect thisTextRect = {
// text x position is HALF of the difference b/w button width and text width
(thisButtonRect.w - preButtonStructs[i].textRectWidth) / 2,
buttonPadding,
preButtonStructs[i].textRectWidth,
preButtonStructs[i].textRectHeight
};
buttons.push_back(
Button(
thisButtonRect,
thisTextRect,
preButtonStructs[i].text,
buttonFont,
colorsByFunction,
mainRenderer,
preButtonStructs[i].clickStruct));
/* increment heightSoFar */
heightSoFar += thisButtonRect.h + PANEL_PADDING;
}
return buttons;
}
/* UI EXTRA FUNCTIONS */
/* Prepare the color scheme for the whole app to use */
void UI::prepareColors() {
/* NESTED COLOR SCHEME:
* colors are stored internally by name.
* colorsByFunction access the colorsByName values.
* colorsByFunction are accessible to the outside.
* This allows to easily change the colors in this function, without having to change
* the accessors at all.
*/
/* THEME COLORS */
/* Three yellows might seem crazy but it's good, actually.
* I will probably also add a third, lighter blue as well */
colorsByName["PERIDOT"] = { 242, 222, 6 }; /* THEME */ /* yellow orangey */
colorsByName["PERIDOT_DEMI"] = { 242, 222, 6, 50 }; /* THEME */ /* yellow orangey */
colorsByName["VIVID_YELLOW"] = { 217, 168, 6 }; /* THEME */ /* brighter yellow */
colorsByName["GOLD"] = { 255,214, 10 }; /* bright yellowish */
colorsByName["YALE_BLUE"] = { 0, 53, 102 }; /* slightly lighter blue */
colorsByName["OXFORD_BLUE"] = { 0, 29, 61 }; /* slightly darker blue */
colorsByName["FRENCH_BLUE"] = { 0, 99, 191 }; // almost light (normal) blue-green
/* NOT SURE YET */
colorsByName["ONYX"] = { 14, 14, 14 }; // almost black
colorsByName["FERN_GREEN"] = { 79, 119, 45 };
colorsByName["MIKADO_YELLOW"] = { 255, 195, 0 };
colorsByName["RICH_BLACK"] = { 0, 8, 20 }; // blue tinted dark
colorsByName["BLACK"] = { 3, 3, 3 }; // almost absolute... not quite
colorsByName["WHITE"] = { 250, 250, 250 }; // almost white
colorsByName["PAPAYA_WHIP"] = { 253, 240, 213 }; // beige
colorsByName["DESAT_ORANGE"] = { 213, 194, 154 }; // Slightly desaturated orange.
colorsByName["SCARLET"] = { 193, 18, 31 }; // red
colorsByName["WOODLAND"] = { 97, 89, 30 }; // brown-green
colorsByName["SMOKEY_GREY"] = { 117, 117, 113 };
colorsByName["DARKISH_GRAYISH_BLUE"] = {142, 146, 169};
/* COLORS BY FUNCTION */
colorsByFunction["BTN_HOVER_BG"] = colorsByName["PERIDOT"];
colorsByFunction["BTN_HOVER_BG_DEMI"] = colorsByName["PERIDOT_DEMI"];
colorsByFunction["BTN_BG"] = colorsByName["OXFORD_BLUE"];
colorsByFunction["BTN_HOVER_BRDR"] = colorsByName["VIVID_YELLOW"];
colorsByFunction["BTN_BRDR"] = colorsByName["YALE_BLUE"];
/* STILL DECIDING */
colorsByFunction["DARK_TEXT"] = colorsByName["BLACK"];
colorsByFunction["LIGHT_TEXT"] = colorsByName["WHITE"];
colorsByFunction["WARNING_RED"] = colorsByName["SCARLET"];
colorsByFunction["LOGO_COLOR"] = colorsByName["PERIDOT"];
colorsByFunction["OK_GREEN"] = colorsByName["FERN_GREEN"];
colorsByFunction["BTN_TEXT"] = colorsByName["GOLD"];
colorsByFunction["BG_LIGHT"] = colorsByName["FRENCH_BLUE"];
colorsByFunction["BG_MED"] = colorsByName["YALE_BLUE"];
}
void UI::getAndStoreWindowSize() {
// set screen size ints based on new resolution, for the sake of building the UI.
int w, h;
SDL_GetWindowSize(mainWindow, &w, &h);
setWindowSize(w, h);
}
/* Initialize all the SDL */
bool UI::initialize() {
Resources& resources = Resources::getInstance();