forked from WerWolv/libtesla
-
Notifications
You must be signed in to change notification settings - Fork 5
/
tesla.hpp
2347 lines (1927 loc) · 80.8 KB
/
tesla.hpp
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
/**
* Copyright (C) 2020 werwolv
*
* This file is part of libtesla.
*
* libtesla is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* libtesla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with libtesla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#define KEY_A HidNpadButton_A
#define KEY_B HidNpadButton_B
#define KEY_X HidNpadButton_X
#define KEY_Y HidNpadButton_Y
#define KEY_L HidNpadButton_L
#define KEY_R HidNpadButton_R
#define KEY_ZL HidNpadButton_ZL
#define KEY_ZR HidNpadButton_ZR
#define KEY_PLUS HidNpadButton_Plus
#define KEY_MINUS HidNpadButton_Minus
#define KEY_DUP HidNpadButton_Up
#define KEY_DDOWN HidNpadButton_Down
#define KEY_DLEFT HidNpadButton_Left
#define KEY_DRIGHT HidNpadButton_Right
#define KEY_SL HidNpadButton_AnySL
#define KEY_SR HidNpadButton_AnySR
#define KEY_LSTICK HidNpadButton_StickL
#define KEY_RSTICK HidNpadButton_StickR
#define KEY_UP (HidNpadButton_Up | HidNpadButton_StickLUp | HidNpadButton_StickRUp)
#define KEY_DOWN (HidNpadButton_Down | HidNpadButton_StickLDown | HidNpadButton_StickRDown)
#define KEY_LEFT (HidNpadButton_Left | HidNpadButton_StickLLeft | HidNpadButton_StickRLeft)
#define KEY_RIGHT (HidNpadButton_Right | HidNpadButton_StickLRight | HidNpadButton_StickRRight)
#define touchPosition const HidTouchState
#define touchInput &touchPos
#define JoystickPosition HidAnalogStickState
#include <switch.h>
#include <stdlib.h>
#include <strings.h>
#include <math.h>
#include <algorithm>
#include <cstring>
#include <cwctype>
#include <string>
#include <functional>
#include <type_traits>
#include <mutex>
#include <memory>
#include <chrono>
#include <list>
#include <stack>
#include <map>
// Define this makro before including tesla.hpp in your main file. If you intend
// to use the tesla.hpp header in more than one source file, only define it once!
// #define TESLA_INIT_IMPL
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#ifdef TESLA_INIT_IMPL
#define STB_TRUETYPE_IMPLEMENTATION
#endif
#include "stb_truetype.h"
#pragma GCC diagnostic pop
#define ASSERT_EXIT(x) if (R_FAILED(x)) std::exit(1)
#define ASSERT_FATAL(x) if (Result res = x; R_FAILED(res)) fatalThrow(res)
u8 TeslaFPS = 60;
u8 alphabackground = 0xD;
bool FullMode = true;
PadState pad;
using namespace std::literals::chrono_literals;
namespace tsl {
// Constants
namespace cfg {
constexpr u32 ScreenWidth = 1920; ///< Width of the Screen
constexpr u32 ScreenHeight = 1080; ///< Height of the Screen
extern u16 LayerWidth; ///< Width of the Tesla layer
extern u16 LayerHeight; ///< Height of the Tesla layer
extern u16 LayerPosX; ///< X position of the Tesla layer
extern u16 LayerPosY; ///< Y position of the Tesla layer
extern u16 FramebufferWidth; ///< Width of the framebuffer
extern u16 FramebufferHeight; ///< Height of the framebuffer
}
namespace style {
constexpr u32 ListItemDefaultHeight = 72; ///< Height of a standard ListItem
namespace color {
constexpr u16 ColorTransparent = 0x0000; ///< Transparent color
}
}
// Declarations
/**
* @brief Direction in which focus moved before landing on
* the currently focused element
*/
enum class FocusDirection {
None, ///< Focus was placed on the element programatically without user input
Up, ///< Focus moved upwards
Down, ///< Focus moved downwards
Left, ///< Focus moved from left to rigth
Right ///< Focus moved from right to left
};
class Overlay;
namespace impl {
/**
* @brief Overlay launch parameters
*/
enum class LaunchFlags : u8 {
None = 0, ///< Do nothing special at launch
CloseOnExit = BIT(0) ///< Close the overlay the last Gui gets poped from the stack
};
[[maybe_unused]] static constexpr LaunchFlags operator|(LaunchFlags lhs, LaunchFlags rhs) {
return static_cast<LaunchFlags>(u8(lhs) | u8(rhs));
}
}
[[maybe_unused]] static void goBack();
[[maybe_unused]] static void setNextOverlay(std::string ovlPath, std::string args = "");
template<typename TOverlay, impl::LaunchFlags launchFlags = impl::LaunchFlags::CloseOnExit>
int loop(int argc, char** argv);
// Helpers
namespace hlp {
/**
* @brief Wrapper for service initialization
*
* @param f wrapped function
*/
static inline void doWithSmSession(std::function<void()> f) {
smInitialize();
f();
smExit();
}
/**
* @brief libnx hid:sys shim that gives or takes away frocus to or from the process with the given aruid
*
* @param enable Give focus or take focus
* @param aruid Aruid of the process to focus/unfocus
* @return Result Result
*/
static Result hidsysEnableAppletToGetInput(bool enable, u64 aruid) {
const struct {
u8 permitInput;
u64 appletResourceUserId;
} in = { enable != 0, aruid };
return serviceDispatchIn(hidsysGetServiceSession(), 503, in);
}
static Result viAddToLayerStack(ViLayer *layer, ViLayerStack stack) {
const struct {
u32 stack;
u64 layerId;
} in = { stack, layer->layer_id };
return serviceDispatchIn(viGetSession_IManagerDisplayService(), 6000, in);
}
/**
* @brief Toggles focus between the Tesla overlay and the rest of the system
*
* @param enabled Focus Tesla?
*/
static void requestForeground(bool enabled) {
u64 applicationAruid = 0, appletAruid = 0;
for (u64 programId = 0x0100000000001000ul; programId < 0x0100000000001020ul; programId++) {
pmdmntGetProcessId(&appletAruid, programId);
if (appletAruid != 0)
hidsysEnableAppletToGetInput(!enabled, appletAruid);
}
pmdmntGetApplicationProcessId(&applicationAruid);
hidsysEnableAppletToGetInput(!enabled, applicationAruid);
hidsysEnableAppletToGetInput(true, 0);
}
/**
* @brief Splits a string at the given delimeters
*
* @param str String to split
* @param delim Delimeter
* @return Vector containing the split tokens
*/
static std::vector<std::string> split(const std::string& str, char delim = ' ') {
std::vector<std::string> out;
std::size_t current, previous = 0;
current = str.find(delim);
while (current != std::string::npos) {
out.push_back(str.substr(previous, current - previous));
previous = current + 1;
current = str.find(delim, previous);
}
out.push_back(str.substr(previous, current - previous));
return out;
}
namespace ini {
/**
* @brief Ini file type
*/
using IniData = std::map<std::string, std::map<std::string, std::string>>;
/**
* @brief Parses a ini string
*
* @param str String to parse
* @return Parsed data
*/
static IniData parseIni(std::string &str) {
IniData iniData;
auto lines = split(str, '\n');
std::string lastHeader = "";
for (auto& line : lines) {
line.erase(std::remove_if(line.begin(), line.end(), ::isspace), line.end());
if (line[0] == '[' && line[line.size() - 1] == ']') {
lastHeader = line.substr(1, line.size() - 2);
iniData.emplace(lastHeader, std::map<std::string, std::string>{});
}
else if (auto keyValuePair = split(line, '='); keyValuePair.size() == 2) {
iniData[lastHeader].emplace(keyValuePair[0], keyValuePair[1]);
}
}
return iniData;
}
}
/**
* @brief Decodes a key string into it's key code
*
* @param value Key string
* @return Key code
*/
static u64 stringToKeyCode(std::string &value) {
if (strcasecmp(value.c_str(), "A") == 0)
return KEY_A;
else if (strcasecmp(value.c_str(), "B") == 0)
return KEY_B;
else if (strcasecmp(value.c_str(), "X") == 0)
return KEY_X;
else if (strcasecmp(value.c_str(), "Y") == 0)
return KEY_Y;
else if (strcasecmp(value.c_str(), "LS") == 0)
return KEY_LSTICK;
else if (strcasecmp(value.c_str(), "RS") == 0)
return KEY_RSTICK;
else if (strcasecmp(value.c_str(), "L") == 0)
return KEY_L;
else if (strcasecmp(value.c_str(), "R") == 0)
return KEY_R;
else if (strcasecmp(value.c_str(), "ZL") == 0)
return KEY_ZL;
else if (strcasecmp(value.c_str(), "ZR") == 0)
return KEY_ZR;
else if (strcasecmp(value.c_str(), "PLUS") == 0)
return KEY_PLUS;
else if (strcasecmp(value.c_str(), "MINUS") == 0)
return KEY_MINUS;
else if (strcasecmp(value.c_str(), "DLEFT") == 0)
return KEY_DLEFT;
else if (strcasecmp(value.c_str(), "DUP") == 0)
return KEY_DUP;
else if (strcasecmp(value.c_str(), "DRIGHT") == 0)
return KEY_DRIGHT;
else if (strcasecmp(value.c_str(), "DDOWN") == 0)
return KEY_DDOWN;
else if (strcasecmp(value.c_str(), "SL") == 0)
return KEY_SL;
else if (strcasecmp(value.c_str(), "SR") == 0)
return KEY_SR;
else return 0;
}
}
// Renderer
namespace gfx {
extern "C" u64 __nx_vi_layer_id;
/**
* @brief RGBA4444 Color structure
*/
struct Color {
union {
struct {
u16 r: 4, g: 4, b: 4, a: 4;
} PACKED;
u16 rgba;
};
inline Color(u16 raw): rgba(raw) {}
inline Color(u8 r, u8 g, u8 b, u8 a): r(r), g(g), b(b), a(a) {}
};
/**
* @brief Manages the Tesla layer and draws raw data to the screen
*/
class Renderer final {
public:
Renderer& operator=(Renderer&) = delete;
friend class tsl::Overlay;
/**
* @brief Handles opacity of drawn colors for fadeout. Pass all colors through this function in order to apply opacity properly
*
* @param c Original color
* @return Color with applied opacity
*/
static Color a(const Color &c) {
return (c.rgba & 0x0FFF) | (static_cast<u8>(c.a * Renderer::s_opacity) << 12);
}
/**
* @brief Enables scissoring, discarding of any draw outside the given boundaries
*
* @param x x pos
* @param y y pos
* @param w Width
* @param h Height
*/
inline void enableScissoring(u16 x, u16 y, u16 w, u16 h) {
this->m_scissoring = true;
this->m_scissorBounds[0] = x;
this->m_scissorBounds[1] = y;
this->m_scissorBounds[2] = w;
this->m_scissorBounds[3] = h;
}
/**
* @brief Disables scissoring
*/
inline void disableScissoring() {
this->m_scissoring = false;
}
// Drawing functions
/**
* @brief Draw a single pixel onto the screen
*
* @param x X pos
* @param y Y pos
* @param color Color
*/
inline void setPixel(s16 x, s16 y, Color color) {
if (x < 0 || y < 0 || x >= cfg::FramebufferWidth || y >= cfg::FramebufferHeight)
return;
static_cast<Color*>(this->getCurrentFramebuffer())[this->getPixelOffset(x, y)] = color;
}
/**
* @brief Blends two colors
*
* @param src Source color
* @param dst Destination color
* @param alpha Opacity
* @return Blended color
*/
inline u8 blendColor(u8 src, u8 dst, u8 alpha) {
u8 oneMinusAlpha = 0x0F - alpha;
return (dst * alpha + src * oneMinusAlpha) / float(0xF);
}
/**
* @brief Draws a single source blended pixel onto the screen
*
* @param x X pos
* @param y Y pos
* @param color Color
*/
inline void setPixelBlendSrc(s16 x, s16 y, Color color) {
if (x < 0 || y < 0 || x >= cfg::FramebufferWidth || y >= cfg::FramebufferHeight)
return;
Color src((static_cast<u16*>(this->getCurrentFramebuffer()))[this->getPixelOffset(x, y)]);
Color dst(color);
Color end(0);
end.r = this->blendColor(src.r, dst.r, dst.a);
end.g = this->blendColor(src.g, dst.g, dst.a);
end.b = this->blendColor(src.b, dst.b, dst.a);
end.a = src.a;
this->setPixel(x, y, end);
}
/**
* @brief Draws a single destination blended pixel onto the screen
*
* @param x X pos
* @param y Y pos
* @param color Color
*/
inline void setPixelBlendDst(s16 x, s16 y, Color color) {
if (x < 0 || y < 0 || x >= cfg::FramebufferWidth || y >= cfg::FramebufferHeight)
return;
Color src((static_cast<u16*>(this->getCurrentFramebuffer()))[this->getPixelOffset(x, y)]);
Color dst(color);
Color end(0);
end.r = this->blendColor(src.r, dst.r, dst.a);
end.g = this->blendColor(src.g, dst.g, dst.a);
end.b = this->blendColor(src.b, dst.b, dst.a);
end.a = dst.a;
this->setPixel(x, y, end);
}
/**
* @brief Draws a rectangle of given sizes
*
* @param x X pos
* @param y Y pos
* @param w Width
* @param h Height
* @param color Color
*/
inline void drawRect(s16 x, s16 y, s16 w, s16 h, Color color) {
for (s16 x1 = x; x1 < (x + w); x1++)
for (s16 y1 = y; y1 < (y + h); y1++)
this->setPixelBlendDst(x1, y1, color);
}
/**
* @brief Draws a RGBA8888 bitmap from memory
*
* @param x X start position
* @param y Y start position
* @param w Bitmap width
* @param h Bitmap height
* @param bmp Pointer to bitmap data
*/
void drawBitmap(s32 x, s32 y, s32 w, s32 h, const u8 *bmp) {
for (s32 y1 = 0; y1 < h; y1++) {
for (s32 x1 = 0; x1 < w; x1++) {
const Color color = { static_cast<u8>(bmp[1] >> 4), static_cast<u8>(bmp[2] >> 4), static_cast<u8>(bmp[3] >> 4), static_cast<u8>(bmp[0] >> 4) };
setPixelBlendSrc(x + x1, y + y1, a(color));
bmp += 4;
}
}
}
/**
* @brief Fills the entire layer with a given color
*
* @param color Color
*/
inline void fillScreen(Color color) {
std::fill_n(static_cast<Color*>(this->getCurrentFramebuffer()), this->getFramebufferSize() / sizeof(Color), color);
}
/**
* @brief Clears the layer (With transparency)
*
*/
inline void clearScreen() {
this->fillScreen({ 0x00, 0x00, 0x00, 0x00 });
}
/**
* @brief Draws a string
*
* @param string String to draw
* @param monospace Draw string in monospace font
* @param x X pos
* @param y Y pos
* @param fontSize Height of the text drawn in pixels
* @param color Text color. Use transparent color to skip drawing and only get the string's dimensions
* @return Dimensions of drawn string
*/
std::pair<u32, u32> drawString(const char* string, bool monospace, u32 x, u32 y, float fontSize, Color color) {
const size_t stringLength = strlen(string);
u32 maxX = x;
u32 currX = x;
u32 currY = y;
u32 prevCharacter = 0;
u32 i = 0;
do {
u32 currCharacter;
ssize_t codepointWidth = decode_utf8(&currCharacter, reinterpret_cast<const u8*>(string + i));
if (codepointWidth <= 0)
break;
i += codepointWidth;
stbtt_fontinfo *currFont = nullptr;
if (stbtt_FindGlyphIndex(&this->m_extFont, currCharacter))
currFont = &this->m_extFont;
else
currFont = &this->m_stdFont;
float currFontSize = stbtt_ScaleForPixelHeight(currFont, fontSize);
currX += currFontSize * stbtt_GetCodepointKernAdvance(currFont, prevCharacter, currCharacter);
int bounds[4] = { 0 };
stbtt_GetCodepointBitmapBoxSubpixel(currFont, currCharacter, currFontSize, currFontSize,
0, 0, &bounds[0], &bounds[1], &bounds[2], &bounds[3]);
int xAdvance = 0, yAdvance = 0;
stbtt_GetCodepointHMetrics(currFont, monospace ? 'W' : currCharacter, &xAdvance, &yAdvance);
if (currCharacter == '\n') {
maxX = std::max(currX, maxX);
currX = x;
currY += fontSize;
continue;
}
if (!std::iswspace(currCharacter) && fontSize > 0 && color.a != 0x0)
this->drawGlyph(currCharacter, currX + bounds[0], currY + bounds[1], color, currFont, currFontSize);
currX += xAdvance * currFontSize;
} while (i < stringLength);
maxX = std::max(currX, maxX);
return { maxX - x, currY - y };
}
private:
Renderer() {}
/**
* @brief Gets the renderer instance
*
* @return Renderer
*/
static Renderer& get() {
static Renderer renderer;
return renderer;
}
/**
* @brief Sets the opacity of the layer
*
* @param opacity Opacity
*/
static void setOpacity(float opacity) {
opacity = std::clamp(opacity, 0.0F, 1.0F);
Renderer::s_opacity = opacity;
}
bool m_initialized = false;
ViDisplay m_display;
ViLayer m_layer;
Event m_vsyncEvent;
NWindow m_window;
Framebuffer m_framebuffer;
void *m_currentFramebuffer = nullptr;
bool m_scissoring = false;
u16 m_scissorBounds[4];
stbtt_fontinfo m_stdFont, m_extFont;
static inline float s_opacity = 1.0F;
/**
* @brief Get the current framebuffer address
*
* @return Framebuffer address
*/
inline void* getCurrentFramebuffer() {
return this->m_currentFramebuffer;
}
/**
* @brief Get the next framebuffer address
*
* @return Next framebuffer address
*/
inline void* getNextFramebuffer() {
return static_cast<u8*>(this->m_framebuffer.buf) + this->getNextFramebufferSlot() * this->getFramebufferSize();
}
/**
* @brief Get the framebuffer size
*
* @return Framebuffer size
*/
inline size_t getFramebufferSize() {
return this->m_framebuffer.fb_size;
}
/**
* @brief Get the number of framebuffers in use
*
* @return Number of framebuffers
*/
inline size_t getFramebufferCount() {
return this->m_framebuffer.num_fbs;
}
/**
* @brief Get the currently used framebuffer's slot
*
* @return Slot
*/
inline u8 getCurrentFramebufferSlot() {
return this->m_window.cur_slot;
}
/**
* @brief Get the next framebuffer's slot
*
* @return Next slot
*/
inline u8 getNextFramebufferSlot() {
return (this->getCurrentFramebufferSlot() + 1) % this->getFramebufferCount();
}
/**
* @brief Waits for the vsync event
*
*/
inline void waitForVSync() {
eventWait(&this->m_vsyncEvent, UINT64_MAX);
}
/**
* @brief Decodes a x and y coordinate into a offset into the swizzled framebuffer
*
* @param x X pos
* @param y Y Pos
* @return Offset
*/
const u32 getPixelOffset(u32 x, u32 y) {
if (this->m_scissoring) {
if (x < this->m_scissorBounds[0] ||
y < this->m_scissorBounds[1] ||
x > this->m_scissorBounds[0] + this->m_scissorBounds[2] ||
y > this->m_scissorBounds[1] + this->m_scissorBounds[3])
return cfg::FramebufferWidth * cfg::FramebufferHeight * 2 + 1;
}
u32 tmpPos = ((y & 127) / 16) + (x / 32 * 8) + ((y / 16 / 8) * (((cfg::FramebufferWidth / 2) / 16 * 8)));
tmpPos *= 16 * 16 * 4;
tmpPos += ((y % 16) / 8) * 512 + ((x % 32) / 16) * 256 + ((y % 8) / 2) * 64 + ((x % 16) / 8) * 32 + (y % 2) * 16 + (x % 8) * 2;
return tmpPos / 2;
}
/**
* @brief Initializes the renderer and layers
*
*/
void init() {
cfg::LayerPosX = 0;
cfg::LayerPosY = 0;
cfg::FramebufferWidth = 448;
cfg::FramebufferHeight = 720;
cfg::LayerWidth = cfg::ScreenHeight * (float(cfg::FramebufferWidth) / float(cfg::FramebufferHeight));
cfg::LayerHeight = cfg::ScreenHeight;
if (this->m_initialized)
return;
tsl::hlp::doWithSmSession([this]{
ASSERT_FATAL(viInitialize(ViServiceType_Manager));
ASSERT_FATAL(viOpenDefaultDisplay(&this->m_display));
ASSERT_FATAL(viGetDisplayVsyncEvent(&this->m_display, &this->m_vsyncEvent));
ASSERT_FATAL(viCreateManagedLayer(&this->m_display, static_cast<ViLayerFlags>(0), 0, &__nx_vi_layer_id));
ASSERT_FATAL(viCreateLayer(&this->m_display, &this->m_layer));
ASSERT_FATAL(viSetLayerScalingMode(&this->m_layer, ViScalingMode_FitToLayer));
if (s32 layerZ = 0; R_SUCCEEDED(viGetZOrderCountMax(&this->m_display, &layerZ)) && layerZ > 0)
ASSERT_FATAL(viSetLayerZ(&this->m_layer, layerZ));
ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Default));
ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Screenshot));
ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Recording));
ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Arbitrary));
ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_LastFrame));
ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Null));
ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_ApplicationForDebug));
ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Lcd));
ASSERT_FATAL(viSetLayerSize(&this->m_layer, cfg::LayerWidth, cfg::LayerHeight));
ASSERT_FATAL(viSetLayerPosition(&this->m_layer, cfg::LayerPosX, cfg::LayerPosY));
ASSERT_FATAL(nwindowCreateFromLayer(&this->m_window, &this->m_layer));
ASSERT_FATAL(framebufferCreate(&this->m_framebuffer, &this->m_window, cfg::FramebufferWidth, cfg::FramebufferHeight, PIXEL_FORMAT_RGBA_4444, 2));
ASSERT_FATAL(this->initFonts());
});
this->m_initialized = true;
}
/**
* @brief Exits the renderer and layer
*
*/
void exit() {
if (!this->m_initialized)
return;
ViLayer layerCopy = this->m_layer;
framebufferClose(&this->m_framebuffer);
nwindowClose(&this->m_window);
viCloseLayer(&this->m_layer);
viDestroyManagedLayer(&layerCopy); // Copy is required because viCloseLayer wipes the passed layer object
viExit();
}
/**
* @brief Initializes Nintendo's shared fonts. Default and Extended
*
* @return Result
*/
Result initFonts() {
Result res;
static PlFontData stdFontData, extFontData;
// Nintendo's default font
if(R_FAILED(res = plGetSharedFontByType(&stdFontData, PlSharedFontType_Standard)))
return res;
u8 *fontBuffer = reinterpret_cast<u8*>(stdFontData.address);
stbtt_InitFont(&this->m_stdFont, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0));
// Nintendo's extended font containing a bunch of icons
if(R_FAILED(res = plGetSharedFontByType(&extFontData, PlSharedFontType_NintendoExt)))
return res;
fontBuffer = reinterpret_cast<u8*>(extFontData.address);
stbtt_InitFont(&this->m_extFont, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0));
return res;
}
/**
* @brief Start a new frame
* @warning Don't call this more than once before calling \ref endFrame
*/
inline void startFrame() {
this->m_currentFramebuffer = framebufferBegin(&this->m_framebuffer, nullptr);
}
/**
* @brief End the current frame
* @warning Don't call this before calling \ref startFrame once
*/
inline void endFrame() {
std::memcpy(this->getNextFramebuffer(), this->getCurrentFramebuffer(), this->getFramebufferSize());
svcSleepThread(1000*1000*1000 / TeslaFPS);
this->waitForVSync();
framebufferEnd(&this->m_framebuffer);
this->m_currentFramebuffer = nullptr;
}
/**
* @brief Draws a single font glyph
*
* @param codepoint Unicode codepoint to draw
* @param x X pos
* @param y Y pos
* @param color Color
* @param font STB Font to use
* @param fontSize Font size
*/
inline void drawGlyph(s32 codepoint, s32 x, s32 y, Color color, stbtt_fontinfo *font, float fontSize) {
int width = 10, height = 10;
u8 *glyphBmp = stbtt_GetCodepointBitmap(font, fontSize, fontSize, codepoint, &width, &height, nullptr, nullptr);
if (glyphBmp == nullptr)
return;
for (s16 bmpY = 0; bmpY < height; bmpY++) {
for (s16 bmpX = 0; bmpX < width; bmpX++) {
Color tmpColor = color;
tmpColor.a = (glyphBmp[width * bmpY + bmpX] >> 4) * (float(tmpColor.a) / 0xF);
this->setPixelBlendSrc(x + bmpX, y + bmpY, tmpColor);
}
}
std::free(glyphBmp);
}
};
}
// Elements
namespace elm {
/**
* @brief The top level Element of the libtesla UI library
* @note When creating your own elements, extend from this or one of it's sub classes
*/
class Element {
public:
Element() {}
virtual ~Element() {}
/**
* @brief Handles focus requesting
* @note This function should return the element to focus.
* When this element should be focused, return `this`.
* When one of it's child should be focused, return `this->child->requestFocus(oldFocus, direction)`
* When this element is not focusable, return `nullptr`
*
* @param oldFocus Previously focused element
* @param direction Direction in which focus moved. \ref FocusDirection::None is passed for the initial load
* @return Element to focus
*/
virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) {
return nullptr;
}
/**
* @brief Function called when a joycon button got pressed
*
* @param keys Keys pressed in the last frame
* @return true when button press has been consumed
* @return false when button press should be passed on to the parent
*/
virtual bool onClick(u64 keys) {
return m_clickListener(keys);
}
/**
* @brief Function called when the element got touched
* @todo Not yet implemented
*
* @param x X pos
* @param y Y pos
* @return true when touch input has been consumed
* @return false when touch input should be passed on to the parent
*/
virtual bool onTouch(u32 x, u32 y) {
return false;
}
/**
* @brief Called once per frame to draw the element
* @warning Do not call this yourself. Use \ref Element::frame(gfx::Renderer *renderer)
*
* @param renderer Renderer
*/
virtual void draw(gfx::Renderer *renderer) = 0;
/**
* @brief Called when the underlying Gui gets created and after calling \ref Gui::invalidate() to calculate positions and boundaries of the element
* @warning Do not call this yourself. Use \ref Element::invalidate()
*
* @param parentX Parent X pos
* @param parentY Parent Y pos
* @param parentWidth Parent Width
* @param parentHeight Parent Height
*/
virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) = 0;
/**
* @brief Draws highlighting and the element itself
* @note When drawing children of a element in \ref Element::draw(gfx::Renderer *renderer), use `this->child->frame(renderer)` instead of calling draw directly
*
* @param renderer
*/
virtual void frame(gfx::Renderer *renderer) final {
if (this->m_focused)
this->drawHighlight(renderer);
this->draw(renderer);
}
/**
* @brief Forces a layout recreation of a element
*
*/
virtual void invalidate() final {
const auto& parent = this->getParent();
if (parent == nullptr)
this->layout(0, 0, cfg::FramebufferWidth, cfg::FramebufferHeight);
else
this->layout(parent->getX(), parent->getY(), parent->getWidth(), parent->getHeight());
}
/**
* @brief Shake the highlight in the given direction to signal that the focus cannot move there
*
* @param direction Direction to shake highlight in
*/
virtual void shakeHighlight(FocusDirection direction) final {
this->m_highlightShaking = true;
this->m_highlightShakingDirection = direction;
this->m_highlightShakingStartTime = std::chrono::system_clock::now();
}
/**
* @brief Draws the blue boarder when a element is highlighted
* @note Override this if you have a element that e.g requires a non-rectangular focus
*
* @param renderer Renderer
*/
virtual void drawHighlight(gfx::Renderer *renderer) {
static float counter = 0;
const float progress = (std::sin(counter) + 1) / 2;
gfx::Color highlightColor = { static_cast<u8>((0x2 - 0x8) * progress + 0x8),
static_cast<u8>((0x8 - 0xF) * progress + 0xF),
static_cast<u8>((0xC - 0xF) * progress + 0xF),
0xF };
counter += 0.1F;
s32 x = 0, y = 0;
if (this->m_highlightShaking) {
auto t = (std::chrono::system_clock::now() - this->m_highlightShakingStartTime);
if (t >= 100ms)
this->m_highlightShaking = false;
else {
s32 amplitude = std::rand() % 5 + 5;
switch (this->m_highlightShakingDirection) {
case FocusDirection::Up:
y -= shakeAnimation(t, amplitude);
break;
case FocusDirection::Down:
y += shakeAnimation(t, amplitude);
break;
case FocusDirection::Left:
x -= shakeAnimation(t, amplitude);