-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathui_api.cpp
2147 lines (1940 loc) · 69.2 KB
/
ui_api.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
// DyLua: SimpleGraphic
// (c) David Gowor, 2014
//
// Module: UI API
//
#include "ui_local.h"
#include <filesystem>
#include <fstream>
#include <zlib.h>
#include "core/core_tex_manipulation.h"
/* OnFrame()
** OnChar("<char>")
** OnKeyDown("<keyName>")
** OnKeyUp("<keyName>")
** canExit = CanExit()
** OnExit()
** OnSubCall("<name>", ...)
** OnSubError(ssID, "<errorMsg>")
** OnSubFinished(ssID, ...)
**
** SetCallback("<name>"[, func])
** func = GetCallback("<name>")
** SetMainObject(object)
**
** artHandle = NewArtHandle("<filename>")
** width, height = artHandle:Size()
**
** imgHandle = NewImageHandle()
** imgHandle:Load("<fileName>"[, "flag1"[, "flag2"...]]) flag:{"ASYNC"|"CLAMP"|"MIPMAP"}
** imgHandle:LoadArtRectangle(art, x1, y1, x2, y2[, "flag1"[, "flag2"... ]]) flag:{"CLAMP"|"MIPMAP"}
** imgHandle:LoadArtArcBand(art, xC, yC, rMin, rMax[, "flag1"[, "flag2"... ]]) flag:{"CLAMP"|"MIPMAP"}
** imgHandle:Unload()
** isValid = imgHandle:IsValid()
** isLoading = imgHandle:IsLoading()
** imgHandle:SetLoadingPriority(pri)
** width, height = imgHandle:ImageSize()
**
** texHandle = NewTexHandle()
** texHandle:Allocate(format, width, height, layerCount, mipCount)
** texHandle:Load("<fileName>")
** texHandle:Save("<fileName>")
** info = texHandle:Info()
** isvalid = texHandle:IsValid()
** texHandle:StackTextures({tex1, tex2, .. texN}) -- all textures must be same shape and format
** -- texHandle:SetLayer(srcTexHandle, layer)
** -- texHandle:CopyImage(srcTexHandle, targetX, targetY)
** -- texHandle:Transcode(newFormat)
** -- texHandle:GenerateMipmaps()
**
** RenderInit(["flag1"[, "flag2"...]]) flag:{"DPI_AWARE"}
** width, height = GetScreenSize()
** scaleFactor = GetScreenScale()
** SetClearColor(red, green, blue[, alpha])
** SetDrawLayer({layer|nil}[, subLayer)
** GetDrawLayer()
** SetViewport([x, y, width, height])
** SetDrawColor(red, green, blue[, alpha]) / SetDrawColor("<escapeStr>")
** DrawImage({imgHandle|nil}, left, top, width, height[, tcLeft, tcTop, tcRight, tcBottom][, stackIdx[, maskIdx]]) maskIdx: use a stack layer as multiplicative mask
** DrawImageQuad({imgHandle|nil}, x1, y1, x2, y2, x3, y3, x4, y4[, s1, t1, s2, t2, s3, t3, s4, t4][, stackIdx[, maskIdx]])
** DrawString(left, top, align{"LEFT"|"CENTER"|"RIGHT"|"CENTER_X"|"RIGHT_X"}, height, font{"FIXED"|"VAR"|"VAR BOLD"}, "<text>")
** width = DrawStringWidth(height, font{"FIXED"|"VAR"|"VAR BOLD"}, "<text>")
** index = DrawStringCursorIndex(height, font{"FIXED"|"VAR"|"VAR BOLD"}, "<text>", cursorX, cursorY)
** str = StripEscapes("<string>")
** count = GetAsyncCount()
**
** searchHandle = NewFileSearch("<spec>"[, findDirectories])
** found = searchHandle:NextFile()
** fileName = searchHandle:GetFileName()
** fileSize = searchHandle:GetFileSize()
** modified, date, time = searchHande:GetFileModifiedTime()
**
** provider, version, status = GetCloudProvider(path)
**
** SetWindowTitle("<title>")
** x, y = GetCursorPos()
** SetCursorPos(x, y)
** ShowCursor(doShow)
** down = IsKeyDown("<keyName>")
** Copy("<string>")
** string = Paste()
** compressed = Deflate(uncompressed)
** uncompressed = Inflate(compressed)
** msec = GetTime()
** path = GetScriptPath()
** path = GetRuntimePath()
** path = GetUserPath() -- may return nil if the user path could not be determined
** SetWorkDir("<path>")
** path = GetWorkDir()
** ssID = LaunchSubScript("<scriptText>", "<funcList>", "<subList>"[, ...])
** AbortSubScript(ssID)
** isRunning = IsSubScriptRunning(ssID)
** ... = LoadModule("<modName>"[, ...])
** err, ... = PLoadModule("<modName>"[, ...])
** err, ... = PCall(func[, ...])
** ConPrintf("<format>"[, ...])
** ConPrintTable(table[, noRecurse])
** ConExecute("<cmd>")
** SpawnProcess("<cmdName>"[, "<args>"])
** err = OpenURL("<url>")
** SetProfiling(isEnabled)
** Restart()
** Exit(["<message>"])
** SetForeground()
*/
// Grab UI main pointer from the registry
static ui_main_c* GetUIPtr(lua_State* L)
{
lua_geti(L, LUA_REGISTRYINDEX, ui_main_c::REGISTRY_KEY);
ui_main_c* ui = (ui_main_c*)lua_touserdata(L, -1);
lua_pop(L, 1);
return ui;
}
// ===============
// C++ scaffolding
// ===============
/*
* ui->LAssert transfers control immediately out of the function without destroying
* any C++ objects. To support RAII this scaffolding serves as a landing pad for
* ui->LExpect, to transfer control to Lua but only after the call stack has been
* unwound with normal C++ exception semantics.
*
* Example use site:
* SG_LUA_CPP_FUN_BEGIN(DoTheThing)
* {
* ui_main_c* ui = GetUIPtr(L);
* auto foo = std::make_shared<Foo>();
* ui->LExpect(L, lua_gettop(L) >= 1), "Usage: DoTheThing(x)");
* ui->LExpect(L, lua_isstring(L, 1), "DoTheThing() argument 1: expected string, got %s", luaL_typename(L, 1));
* return 0;
* }
* SG_LUA_CPP_FUN_END()
*/
#ifdef _WIN32
#define SG_NOINLINE __declspec(noinline)
#else
#define SG_NOINLINE [[gnu::noinline]]
#endif
#define SG_NORETURN [[noreturn]]
SG_NORETURN static void LuaErrorWrapper(lua_State* L)
{
lua_error(L);
}
#define SG_LUA_CPP_FUN_BEGIN(Name) \
static int l_##Name(lua_State* L) { \
int (*fun)(lua_State*) = [](lua_State* L) SG_NOINLINE -> int { \
try
#define SG_LUA_CPP_FUN_END() \
catch (ui_expectationFailed_s) { return -1; } \
catch (std::exception& e) { \
lua_pushfstring(L, "C++ exception:\n%s", e.what()); \
return -1; \
} \
}; \
int rc = fun(L); \
if (rc < 0) { LuaErrorWrapper(L); } \
return rc; }
// ===============
// Data validation
// ===============
/*
* ui_luaReader_c wraps the common validation of arguments or values from Lua in a class
* that ensures a consistent assertion message and reduces the risk of mistakes in
* parameter validation.
*
* As it has scoped RAII resources and uses ui->LExcept() it must only be used in functions
* exposed to Lua through the SG_LUA_CPP_FUN_BEGIN/END scheme as that ensures proper cleanup
* when unwinding.
*
* Example use site:
* SG_LUA_CPP_FUN_BEGIN(DoTheThing)
* {
* ui_main_c* ui = GetUIPtr(L);
* ui_luaReader_c reader(ui, L, "DoTheThing");
* ui->LExpect(L, lua_gettop(L) >= 2), "Usage: DoTheThing(table, number)");
* reader.ArgCheckTable(1); // short-hand to validate formal arguments to function
* reader.ArgCheckNumber(2); // -''-
* reader.ValCheckNumber(-1, "descriptive name"); // validates any value on the Lua stack, indicating what the value represents
* // Do the thing
* return 0;
* }
* SG_LUA_CPP_FUN_END()
*/
class ui_luaReader_c {
public:
ui_luaReader_c(ui_main_c* ui, lua_State* L, std::string funName) : ui(ui), L(L), funName(funName) {}
// Always zero terminated as all regular strings are terminated in Lua.
std::string_view ArgToString(int k) {
ui->LExpect(L, lua_isstring(L, k), "%s() argument %d: expected string, got %s",
funName.c_str(), k, luaL_typename(L, k));
return lua_tostring(L, k);
}
void ArgCheckTable(int k) {
ui->LExpect(L, lua_istable(L, k), "%s() argument %d: expected table, got %s",
funName.c_str(), k, luaL_typename(L, k));
}
void ArgCheckNumber(int k) {
ui->LExpect(L, lua_isnumber(L, k), "%s() argument %d: expected number, got %s",
funName.c_str(), k, luaL_typename(L, k));
}
void ValCheckNumber(int k, char const* ctx) {
ui->LExpect(L, lua_isnumber(L, k), "%s() %s: expected number, got %s",
funName.c_str(), ctx, k, luaL_typename(L, k));
}
private:
ui_main_c* ui;
lua_State* L;
std::string funName;
};
// =========
// Callbacks
// =========
static int l_SetCallback(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
int n = lua_gettop(L);
ui->LAssert(L, n >= 1, "Usage: SetCallback(name[, func])");
ui->LAssert(L, lua_isstring(L, 1), "SetCallback() argument 1: expected string, got %s", luaL_typename(L, 1));
lua_pushvalue(L, 1);
if (n >= 2) {
ui->LAssert(L, lua_isfunction(L, 2) || lua_isnil(L, 2), "SetCallback() argument 2: expected function or nil, got %s", luaL_typename(L, 2));
lua_pushvalue(L, 2);
}
else {
lua_pushnil(L);
}
lua_settable(L, lua_upvalueindex(1));
return 0;
}
static int l_GetCallback(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
int n = lua_gettop(L);
ui->LAssert(L, n >= 1, "Usage: GetCallback(name)");
ui->LAssert(L, lua_isstring(L, 1), "GetCallback() argument 1: expected string, got %s", luaL_typename(L, 1));
lua_pushvalue(L, 1);
lua_gettable(L, lua_upvalueindex(1));
return 1;
}
static int l_SetMainObject(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
int n = lua_gettop(L);
lua_pushstring(L, "MainObject");
if (n >= 1) {
ui->LAssert(L, lua_istable(L, 1) || lua_isnil(L, 1), "SetMainObject() argument 1: expected table or nil, got %s", luaL_typename(L, 1));
lua_pushvalue(L, 1);
}
else {
lua_pushnil(L);
}
lua_settable(L, lua_upvalueindex(1));
return 0;
}
// ===========
// Art Handles
// ===========
/*
* An art handle contains CPU-side image data, typically sourced from a file on disk.
* This differs from image handles that represent a texture resident on the GPU.
*
* Art handles can be used to produce image handles by slicing out masked subimages.
* Their primary intent is to decompose nested artwork like the connector art for
* modern revisions of the passive skill tree which has multiple orbit arcs inside
* of each other in a single image file.
*/
struct artHandle_s {
std::unique_ptr<image_c> img;
};
SG_LUA_CPP_FUN_BEGIN(NewArtHandle)
{
ui_main_c* ui = GetUIPtr(L);
ui_luaReader_c reader(ui, L, "NewArtHandle");
int n = lua_gettop(L);
ui->LExpect(L, n >= 1, "Usage: NewArtHandle(fileName)");
std::filesystem::path filePath = std::filesystem::u8path(reader.ArgToString(1));
if (filePath.is_relative())
filePath = ui->scriptWorkDir / filePath;
std::unique_ptr<image_c> img(image_c::LoaderForFile(ui->sys->con, filePath));
if (!img)
return 0;
if (img->Load(filePath))
return 0;
const auto format = img->tex.format();
if (is_compressed(format) || !is_unsigned(format))
return 0;
const auto comp = component_count(format);
if (comp != 1 && comp != 3 && comp != 4)
return 0;
artHandle_s* artHandle = (artHandle_s*)lua_newuserdata(L, sizeof(artHandle_s));
new(artHandle) artHandle_s();
artHandle->img = std::move(img);
lua_pushvalue(L, lua_upvalueindex(1));
lua_setmetatable(L, -2);
return 1;
}
SG_LUA_CPP_FUN_END()
static artHandle_s* GetArtHandle(lua_State* L, ui_main_c* ui, const char* method)
{
ui->LAssert(L, ui->IsUserData(L, 1, "uiarthandlemeta"), "artHandle:%s() must be used on an image handle", method);
artHandle_s* artHandle = (artHandle_s*)lua_touserdata(L, 1);
lua_remove(L, 1);
return artHandle;
}
static int l_artHandleGC(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
artHandle_s* artHandle = GetArtHandle(L, ui, "__gc");
artHandle->~artHandle_s();
return 0;
}
static int l_artHandleSize(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
artHandle_s* artHandle = GetArtHandle(L, ui, "Size");
const auto extent = artHandle->img ? artHandle->img->tex.extent() : gli::texture2d_array::extent_type{0, 0};
lua_pushinteger(L, extent.x);
lua_pushinteger(L, extent.y);
return 2;
}
// =============
// Image Handles
// =============
struct imgHandle_s {
r_shaderHnd_c* hnd;
};
static int l_NewImageHandle(lua_State* L)
{
imgHandle_s* imgHandle = (imgHandle_s*)lua_newuserdata(L, sizeof(imgHandle_s));
imgHandle->hnd = NULL;
lua_pushvalue(L, lua_upvalueindex(1));
lua_setmetatable(L, -2);
return 1;
}
static imgHandle_s* GetImgHandle(lua_State* L, ui_main_c* ui, const char* method, bool loaded)
{
ui->LAssert(L, ui->IsUserData(L, 1, "uiimghandlemeta"), "imgHandle:%s() must be used on an image handle", method);
imgHandle_s* imgHandle = (imgHandle_s*)lua_touserdata(L, 1);
lua_remove(L, 1);
if (loaded) {
ui->LAssert(L, imgHandle->hnd != NULL, "imgHandle:%s(): image handle has no image loaded", method);
}
return imgHandle;
}
static int l_imgHandleGC(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
imgHandle_s* imgHandle = GetImgHandle(L, ui, "__gc", false);
delete imgHandle->hnd;
return 0;
}
SG_LUA_CPP_FUN_BEGIN(imgHandleLoad)
{
ui_main_c* ui = GetUIPtr(L);
ui->LExpect(L, ui->renderer != NULL, "Renderer is not initialised");
imgHandle_s* imgHandle = GetImgHandle(L, ui, "Load", false);
int n = lua_gettop(L);
ui->LExpect(L, n >= 1, "Usage: imgHandle:Load(fileName[, flag1[, flag2...]])");
ui->LExpect(L, lua_isstring(L, 1), "imgHandle:Load() argument 1: expected string, got %s", luaL_typename(L, 1));
auto fileName = std::filesystem::u8path(lua_tostring(L, 1));
if (!fileName.is_absolute() && !ui->scriptWorkDir.empty()) {
fileName = ui->scriptWorkDir / fileName;
}
delete imgHandle->hnd;
int flags = TF_NOMIPMAP;
for (int f = 2; f <= n; f++) {
if (!lua_isstring(L, f)) {
continue;
}
std::string flag = lua_tostring(L, f);
if (flag == "ASYNC") {
flags |= TF_ASYNC;
}
else if (flag == "CLAMP") {
flags |= TF_CLAMP;
}
else if (flag == "MIPMAP") {
flags &= ~TF_NOMIPMAP;
}
else if (flag == "NEAREST") {
flags |= TF_NEAREST;
}
else {
ui->LExpect(L, 0, "imgHandle:Load(): unrecognised flag '%s'", flag.c_str());
}
}
// TODO(LV): should we use u8path throughout here, to support any callers that use paths outside of working directory?
imgHandle->hnd = ui->renderer->RegisterShader(fileName.generic_u8string(), flags);
return 0;
}
SG_LUA_CPP_FUN_END()
static int l_imgHandleUnload(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
imgHandle_s* imgHandle = GetImgHandle(L, ui, "Unload", false);
delete imgHandle->hnd;
imgHandle->hnd = NULL;
return 0;
}
static int l_imgHandleIsValid(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
imgHandle_s* imgHandle = GetImgHandle(L, ui, "IsValid", false);
lua_pushboolean(L, imgHandle->hnd != NULL);
return 1;
}
static int l_imgHandleIsLoading(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
imgHandle_s* imgHandle = GetImgHandle(L, ui, "IsLoading", true);
int width, height;
ui->renderer->GetShaderImageSize(imgHandle->hnd, width, height);
lua_pushboolean(L, width == 0);
return 1;
}
static int l_imgHandleSetLoadingPriority(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
imgHandle_s* imgHandle = GetImgHandle(L, ui, "SetLoadingPriority", true);
int n = lua_gettop(L);
ui->LAssert(L, n >= 1, "Usage: imgHandle:SetLoadingPriority(pri)");
ui->LAssert(L, lua_isnumber(L, 1), "imgHandle:SetLoadingPriority() argument 1: expected number, got %s", luaL_typename(L, 1));
ui->renderer->SetShaderLoadingPriority(imgHandle->hnd, (int)lua_tointeger(L, 1));
return 0;
}
static int l_imgHandleImageSize(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
imgHandle_s* imgHandle = GetImgHandle(L, ui, "ImageSize", true);
int width, height;
ui->renderer->GetShaderImageSize(imgHandle->hnd, width, height);
lua_pushinteger(L, width);
lua_pushinteger(L, height);
return 2;
}
namespace {
int ParseArtFlags(ui_main_c* ui, lua_State* L, int k, int n)
{
int flags = TF_NOMIPMAP;
for (int f = k; f <= n; f++) {
if (!lua_isstring(L, f)) {
continue;
}
const char* flag = lua_tostring(L, f);
if (!strcmp(flag, "CLAMP")) {
flags |= TF_CLAMP;
}
else if (!strcmp(flag, "MIPMAP")) {
flags &= ~TF_NOMIPMAP;
}
else if (!strcmp(flag, "NEAREST")) {
flags |= TF_NEAREST;
}
else {
ui->LExpect(L, 0, "imgHandle:LoadArtRectangle(): unrecognised flag '%s'", flag);
}
}
return flags;
}
r_shaderHnd_c* RegisterShaderFromImage(r_IRenderer& renderer, std::unique_ptr<image_c> img, int flags)
{
return renderer.RegisterShaderFromImage(std::move(img), flags);
}
}
SG_LUA_CPP_FUN_BEGIN(imgHandleLoadArtRectangle)
{
ui_main_c* ui = GetUIPtr(L);
imgHandle_s* imgHandle = GetImgHandle(L, ui, "LoadArtRectangle", false);
const int n = lua_gettop(L);
ui->LExpect(L, n >= 5, "Usage: imgHandle:LoadArtRectangle(art, x1, y1, x2, y2[, flag1[, flag2...]])");
ui_luaReader_c reader(ui, L, "imgHandle::LoadArtRectangle");
reader.ArgCheckNumber(2);
reader.ArgCheckNumber(3);
reader.ArgCheckNumber(4);
reader.ArgCheckNumber(5);
int x1 = (int)lua_tointeger(L, 2);
int y1 = (int)lua_tointeger(L, 3);
int x2 = (int)lua_tointeger(L, 4);
int y2 = (int)lua_tointeger(L, 5);
// Grab the art handle after extracting the parameters so that their error messages have the correct indices.
artHandle_s* artHandle = GetArtHandle(L, ui, "LoadArtRectangle");
if (x1 > x2)
std::swap(x1, x2);
if (y1 > y2)
std::swap(y1, y2);
auto* srcImg = artHandle->img.get();
const auto srcFormat = srcImg->tex.format();
auto extent = srcImg->tex.extent();
const int srcWidth = extent.x;
const int srcHeight = extent.y;
const int comp = (int)component_count(srcFormat);
ui->LExpect(L, x1 >= 0 && x2 <= srcWidth, "imgHandle:LoadArtRectangle(): X range %d to %d outside of the 0 to %d bounds", x1, x2, srcWidth);
ui->LExpect(L, y1 >= 0 && y2 <= srcHeight, "imgHandle:LoadArtRectangle(): Y range %d to %d outside of the 0 to %d bounds", y1, y2, srcHeight);
// Slice rectangle into temporary target image.
auto dstImg = std::make_unique<image_c>(ui->sys->con);
const int dstWidth = x2 - x1;
const int dstHeight = y2 - y1;
const int srcStride = srcWidth * comp;
const int dstStride = dstWidth * comp;
const int dstByteCount = dstHeight * dstStride;
dstImg->tex = gli::texture2d_array(srcFormat, glm::ivec2(dstWidth, dstHeight), 1, 1);
byte* srcPtr = srcImg->tex.data<byte>(0, 0, 0) + y1 * srcStride + x1 * comp;
byte* dstPtr = dstImg->tex.data<byte>(0, 0, 0);
for (int col = 0; col < (int)dstWidth; ++col) {
for (int row = 0; row < (int)dstHeight; ++row) {
memcpy(dstPtr, srcPtr, dstStride);
srcPtr += srcStride;
dstPtr += dstStride;
}
}
const int flags = ParseArtFlags(ui, L, 5, n);
delete imgHandle->hnd;
imgHandle->hnd = RegisterShaderFromImage(*ui->renderer, std::move(dstImg), flags);
return 0;
}
SG_LUA_CPP_FUN_END()
SG_LUA_CPP_FUN_BEGIN(imgHandleLoadArtArcBand)
{
ui_main_c* ui = GetUIPtr(L);
imgHandle_s* imgHandle = GetImgHandle(L, ui, "LoadArtArcBand", false);
const int n = lua_gettop(L);
ui->LExpect(L, n >= 5, "Usage: imgHandle:LoadArtArcBand(art, xC, yC, rMin, rMax[, flag1[, flag2...]])");
ui_luaReader_c reader(ui, L, "imgHandle::LoadArtArcBand");
reader.ArgCheckNumber(2);
reader.ArgCheckNumber(3);
reader.ArgCheckNumber(4);
reader.ArgCheckNumber(5);
const int xC = (int)lua_tointeger(L, 2);
const int yC = (int)lua_tointeger(L, 3);
int rMin = (int)lua_tointeger(L, 4);
int rMax = (int)lua_tointeger(L, 5);
if (rMin > rMax)
std::swap(rMin, rMax);
const int x1 = xC - rMax;
const int y1 = yC - rMax;
// Grab the art handle after extracting the parameters so that their error messages have the correct indices.
artHandle_s* artHandle = GetArtHandle(L, ui, "LoadArtArcBand");
auto* srcImg = artHandle->img.get();
const auto srcFormat = srcImg->tex.format();
const auto srcExtent = srcImg->tex.extent();
const int srcWidth = srcExtent.x;
const int srcHeight = srcExtent.y;
const int comp = (int)component_count(srcFormat);
ui->LExpect(L, xC >= 0 && xC <= srcWidth, "imgHandle:LoadArtArcBand(): X origin %d outside of the 0 to %d bounds", xC, srcWidth);
ui->LExpect(L, yC >= 0 && yC <= srcHeight, "imgHandle:LoadArtArcBand(): Y origin %d outside of the 0 to %d bounds", yC, srcHeight);
ui->LExpect(L, x1 >= 0 && x1 <= srcWidth, "imgHandle:LoadArtArcBand(): X corner %d outside of the 0 to %d bounds", x1, srcWidth);
ui->LExpect(L, y1 >= 0 && y1 <= srcHeight, "imgHandle:LoadArtArcBand(): Y corner %d outside of the 0 to %d bounds", y1, srcHeight);
// Slice rectangle into temporary target image.
auto dstImg = std::make_unique<image_c>(ui->sys->con);
const int dstWidth = xC - x1;
const int dstHeight = yC - y1;
const int srcStride = srcWidth * comp;
const int dstStride = dstWidth * comp;
const int dstByteCount = dstHeight * dstStride;
dstImg->tex = gli::texture2d_array(srcFormat, glm::ivec2(dstWidth, dstHeight), 1, 1);
const byte* srcData = srcImg->tex.data<byte>(0, 0, 0);
byte* dstData = dstImg->tex.data<byte>(0, 0, 0);
memset(dstData, 0x00, dstByteCount);
// Copy all pixels whose center are between the two radii, inclusive.
{
// By doubling all coordinates, we can reference both pixel edges and pixel centers.
// Even numbers are between pixel samples, odd numbers are on pixel samples.
// This makes the distance test math more robust.
// As this is ad-hoc 31.1 bit fixed point math, we should technically shift down the result of
// the multiplications that go into the squares but as the same number of operations occur on both
// sides of the squared equalities, it's fine. Just something to keep in mind for future changes.
const int rMinSq = (rMin * 2) * (rMin * 2), rMaxSq = (rMax * 2) * (rMax * 2);
const int width = dstWidth * 2, height = dstHeight * 2;
for (int row = 1; row < height; row += 2)
{
const int dy = height - row;
// Find the first pixel center that is inside the outer radius
int colLo = -1;
for (int x = 1; x < width; x += 2) {
const int dx = width - x;
const int rSq = dx * dx + dy * dy;
if (rSq <= rMaxSq) {
colLo = x;
break;
}
}
// If no pixel was found to be inside, the row does not contribute.
if (colLo == -1)
continue;
int colHi = width;
// Find the first pixel center that is inside the inner radius
for (int x = colLo; x < width; x += 2) {
const int dx = width - x;
const int rSq = dx * dx + dy * dy;
if (rSq < rMinSq) {
colHi = x;
break;
}
}
// We now have a half-open span of touched pixel centers (or the far border).
// Convert that to regular pixel coordinates and copy to the destination image.
const int xLo = colLo / 2;
const int xHi = colHi / 2;
if (xLo != xHi) {
const int y = row / 2;
const int spanByteSize = (xHi - xLo) * comp;
const int srcRow = y1 + y;
const int dstRow = y;
const int srcCol = x1 + xLo;
const int dstCol = xLo;
const byte* srcPtr = srcData + srcRow * srcStride + srcCol * comp;
byte* dstPtr = dstData + dstRow * dstStride + dstCol * comp;
memcpy(dstPtr, srcPtr, spanByteSize);
}
}
}
const int flags = ParseArtFlags(ui, L, 5, n);
delete imgHandle->hnd;
imgHandle->hnd = RegisterShaderFromImage(*ui->renderer, std::move(dstImg), flags);
return 0;
}
SG_LUA_CPP_FUN_END()
// =========
// Rendering
// =========
static int l_RenderInit(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
int n = lua_gettop(L);
bool dpiAware = false;
for (int i = 1; i <= n; ++i) {
ui->LAssert(L, lua_isstring(L, i), "RenderInit() argument %d: expected string, got %s", i, luaL_typename(L, i));
char const* str = lua_tostring(L, i);
if (strcmp(str, "DPI_AWARE") == 0) {
dpiAware = true;
}
}
r_featureFlag_e features{};
if (dpiAware) {
features = (r_featureFlag_e)(features | F_DPI_AWARE);
}
ui->RenderInit(features);
return 0;
}
static int l_GetScreenSize(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
lua_pushinteger(L, ui->renderer->VirtualScreenWidth());
lua_pushinteger(L, ui->renderer->VirtualScreenHeight());
return 2;
}
static int l_GetScreenScale(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
lua_pushnumber(L, ui->renderer->VirtualScreenScaleFactor());
return 1;
}
static int l_SetClearColor(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
ui->LAssert(L, ui->renderer != NULL, "Renderer is not initialised");
int n = lua_gettop(L);
ui->LAssert(L, n >= 3, "Usage: SetClearColor(red, green, blue[, alpha])");
col4_t color;
for (int i = 1; i <= 3; i++) {
ui->LAssert(L, lua_isnumber(L, i), "SetClearColor() argument %d: expected number, got %s", i, luaL_typename(L, i));
color[i - 1] = (float)lua_tonumber(L, i);
}
if (n >= 4 && !lua_isnil(L, 4)) {
ui->LAssert(L, lua_isnumber(L, 4), "SetClearColor() argument 4: expected number or nil, got %s", luaL_typename(L, 4));
color[3] = (float)lua_tonumber(L, 4);
}
else {
color[3] = 1.0;
}
ui->renderer->SetClearColor(color);
return 0;
}
static int l_SetDrawLayer(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
ui->LAssert(L, ui->renderer != NULL, "Renderer is not initialised");
ui->LAssert(L, ui->renderEnable, "SetDrawLayer() called outside of OnFrame");
int n = lua_gettop(L);
ui->LAssert(L, n >= 1, "Usage: SetDrawLayer({layer|nil}[, subLayer])");
ui->LAssert(L, lua_isnumber(L, 1) || lua_isnil(L, 1), "SetDrawLayer() argument 1: expected number or nil, got %s", luaL_typename(L, 1));
if (n >= 2) {
ui->LAssert(L, lua_isnumber(L, 2), "SetDrawLayer() argument 2: expected number, got %s", luaL_typename(L, 2));
}
if (lua_isnil(L, 1)) {
ui->LAssert(L, n >= 2, "SetDrawLayer(): must provide subLayer if layer is nil");
ui->renderer->SetDrawSubLayer((int)lua_tointeger(L, 2));
}
else if (n >= 2) {
ui->renderer->SetDrawLayer((int)lua_tointeger(L, 1), (int)lua_tointeger(L, 2));
}
else {
ui->renderer->SetDrawLayer((int)lua_tointeger(L, 1));
}
return 0;
}
static int l_GetDrawLayer(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
lua_pushinteger(L, ui->renderer->GetDrawLayer());
return 1;
}
static int l_SetViewport(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
ui->LAssert(L, ui->renderer != NULL, "Renderer is not initialised");
ui->LAssert(L, ui->renderEnable, "SetViewport() called outside of OnFrame");
int n = lua_gettop(L);
if (n) {
ui->LAssert(L, n >= 4, "Usage: SetViewport([x, y, width, height])");
for (int i = 1; i <= 4; i++) {
ui->LAssert(L, lua_isnumber(L, i), "SetViewport() argument %d: expected number, got %s", i, luaL_typename(L, i));
}
ui->renderer->SetViewport((int)lua_tointeger(L, 1), (int)lua_tointeger(L, 2), (int)lua_tointeger(L, 3), (int)lua_tointeger(L, 4));
}
else {
ui->renderer->SetViewport();
}
return 0;
}
static int l_SetBlendMode(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
ui->LAssert(L, ui->renderer != NULL, "Renderer is not initialised");
ui->LAssert(L, ui->renderEnable, "SetViewport() called outside of OnFrame");
int n = lua_gettop(L);
ui->LAssert(L, n >= 1, "Usage: SetBlendMode(mode)");
static const char* modeMap[6] = { "ALPHA", "PREALPHA", "ADDITIVE", NULL };
ui->renderer->SetBlendMode(luaL_checkoption(L, 1, "ALPHA", modeMap));
return 0;
}
static int l_SetDrawColor(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
ui->LAssert(L, ui->renderer != NULL, "Renderer is not initialised");
ui->LAssert(L, ui->renderEnable, "SetDrawColor() called outside of OnFrame");
int n = lua_gettop(L);
ui->LAssert(L, n >= 1, "Usage: SetDrawColor(red, green, blue[, alpha]) or SetDrawColor(escapeStr)");
col4_t color;
if (lua_type(L, 1) == LUA_TSTRING) {
ui->LAssert(L, IsColorEscape(lua_tostring(L, 1)), "SetDrawColor() argument 1: invalid color escape sequence");
ReadColorEscape(lua_tostring(L, 1), color);
color[3] = 1.0;
}
else {
ui->LAssert(L, n >= 3, "Usage: SetDrawColor(red, green, blue[, alpha]) or SetDrawColor(escapeStr)");
for (int i = 1; i <= 3; i++) {
ui->LAssert(L, lua_isnumber(L, i), "SetDrawColor() argument %d: expected number, got %s", i, luaL_typename(L, i));
color[i - 1] = (float)lua_tonumber(L, i);
}
if (n >= 4 && !lua_isnil(L, 4)) {
ui->LAssert(L, lua_isnumber(L, 4), "SetDrawColor() argument 4: expected number or nil, got %s", luaL_typename(L, 4));
color[3] = (float)lua_tonumber(L, 4);
}
else {
color[3] = 1.0;
}
}
ui->renderer->DrawColor(color);
return 0;
}
static int l_DrawImage(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
ui->LAssert(L, ui->renderer != NULL, "Renderer is not initialised");
ui->LAssert(L, ui->renderEnable, "DrawImage() called outside of OnFrame");
int n = lua_gettop(L);
const char* usage = "Usage: DrawImage({imgHandle|nil}, left, top, width, height[, tcLeft, tcTop, tcRight, tcBottom][, stackIdx[, mask]])";
ui->LAssert(L, n >= 5, usage);
ui->LAssert(L, lua_isnil(L, 1) || ui->IsUserData(L, 1, "uiimghandlemeta"), "DrawImage() argument 1: expected image handle or nil, got %s", luaL_typename(L, 1));
r_shaderHnd_c* hnd = NULL;
glm::vec2 xys[2]{}, uvs[2]{};
int stackLayer = 0;
std::optional<int> maskLayer{};
// | n |img| corners | uvs | stack | mask |
// | 5 | X | X | | | |
// | 6 | X | X | | X | |
// | 7 | X | X | | X | X |
// | 9 | X | X | X | | |
// | 10 | X | X | X | X | |
// | 11 | X | X | X | X | X |
enum ArgFlag : uint8_t { AF_IMG = 0x1, AF_XY = 0x2, AF_UV = 0x4, AF_STACK = 0x8, AF_MASK = 0x10 };
ArgFlag af{};
switch (n) {
case 11: af = (ArgFlag)(af | AF_MASK);
case 10: af = (ArgFlag)(af | AF_STACK);
case 9: af = (ArgFlag)(af | AF_IMG | AF_XY | AF_UV); break;
case 7: af = (ArgFlag)(af | AF_MASK);
case 6: af = (ArgFlag)(af | AF_STACK);
case 5: af = (ArgFlag)(af | AF_IMG | AF_XY); break;
default: ui->LAssert(L, false, usage);
}
int k = 1;
if (af & AF_IMG) {
if (!lua_isnil(L, k)) {
imgHandle_s* imgHandle = (imgHandle_s*)lua_touserdata(L, k);
ui->LAssert(L, imgHandle->hnd != NULL, "DrawImage(): image handle has no image loaded");
hnd = imgHandle->hnd;
}
k += 1;
}
if (af & AF_XY) {
for (int i = k; i < k + 4; i++) {
ui->LAssert(L, lua_isnumber(L, i), "DrawImage() argument %d: expected number, got %s", i, luaL_typename(L, i));
const int idx = i - k;
xys[idx/2][idx%2] = (float)lua_tonumber(L, i);
}
k += 4;
}
if (af & AF_UV) {
for (int i = k; i < k + 4; i++) {
ui->LAssert(L, lua_isnumber(L, i), "DrawImage() argument %d: expected number, got %s", i, luaL_typename(L, i));
int idx = i - k;
uvs[idx/2][idx%2] = (float)lua_tonumber(L, i);
}
k += 4;
}
else {
uvs[0] = { 0, 0 };
uvs[1] = { 1, 1 };
}
std::optional<int> maxStackValue;
if (hnd)
maxStackValue = hnd->StackCount();
if (af & AF_STACK) {
ui->LAssert(L, lua_isinteger(L, k), "DrawImage() argument %d: expected integer, got %s", k, luaL_typename(L, k));
const int val = (int)lua_tointeger(L, k);
ui->LAssert(L, val > 0, "DrawImage() argument %d: expected positive integer, got %d", k, val);
if (maxStackValue.has_value())
ui->LAssert(L, val <= *maxStackValue, "DrawImage() argument %d: expected valid stack index <= %d, got %d", k, *maxStackValue, val);
stackLayer = val - 1;
k += 1;
}
if (af & AF_MASK) {
ui->LAssert(L, lua_isnil(L, k) || lua_isinteger(L, k), "DrawImage() argument %d: expected integer or nil, got %s", k, luaL_typename(L, k));
if (lua_isinteger(L, k)) {
const int val = (int)lua_tointeger(L, k);
ui->LAssert(L, val > 0, "DrawImage() argument %d: expected positive integer, got %d", k, val);
if (maxStackValue.has_value())
ui->LAssert(L, val <= *maxStackValue, "DrawImage() argument %d: expected valid stack index <= %d, got %d", k, *maxStackValue, val);
maskLayer = val - 1;
}
k += 1;
}
ui->renderer->DrawImage(hnd, xys[0], xys[1], uvs[0], uvs[1], stackLayer, maskLayer);
return 0;
}
static int l_DrawImageQuad(lua_State* L)
{
ui_main_c* ui = GetUIPtr(L);
ui->LAssert(L, ui->renderer != NULL, "Renderer is not initialised");
ui->LAssert(L, ui->renderEnable, "DrawImageQuad() called outside of OnFrame");
int n = lua_gettop(L);
const char* usage = "Usage: DrawImageQuad({imgHandle|nil}, x1, y1, x2, y2, x3, y3, x4, y4[, s1, t1, s2, t2, s3, t3, s4, t4][, stackIdx[, mask]])";
ui->LAssert(L, n >= 9, usage);
ui->LAssert(L, lua_isnil(L, 1) || ui->IsUserData(L, 1, "uiimghandlemeta"), "DrawImageQuad() argument 1: expected image handle or nil, got %s", luaL_typename(L, 1));
r_shaderHnd_c* hnd = NULL;
glm::vec2 xys[4]{}, uvs[4]{};
int stackLayer = 0;
std::optional<int> maskLayer{};
// | n |img| corners | uvs | stack | mask |
// | 9 | X | X | | | |
// | 10 | X | X | | X | |
// | 11 | X | X | | X | X |
// | 17 | X | X | X | | |
// | 18 | X | X | X | X | |
// | 19 | X | X | X | X | X |
enum ArgFlag : uint8_t { AF_IMG = 0x1, AF_XY = 0x2, AF_UV = 0x4, AF_STACK = 0x8, AF_MASK = 0x10 };
ArgFlag af{};
switch (n) {
case 19: af = (ArgFlag)(af | AF_MASK);
case 18: af = (ArgFlag)(af | AF_STACK);
case 17: af = (ArgFlag)(af | AF_IMG | AF_XY | AF_UV); break;
case 11: af = (ArgFlag)(af | AF_MASK);
case 10: af = (ArgFlag)(af | AF_STACK);
case 9: af = (ArgFlag)(af | AF_IMG | AF_XY); break;
default: ui->LAssert(L, false, usage);
}
int k = 1;
if (af & AF_IMG) {
if (!lua_isnil(L, k)) {
imgHandle_s* imgHandle = (imgHandle_s*)lua_touserdata(L, k);
ui->LAssert(L, imgHandle->hnd != NULL, "DrawImageQuad(): image handle has no image loaded");
hnd = imgHandle->hnd;
}
k += 1;
}
if (af & AF_XY) {
for (int i = k; i < k + 8; i++) {
ui->LAssert(L, lua_isnumber(L, i), "DrawImageQuad() argument %d: expected number, got %s", i, luaL_typename(L, i));
const int idx = i - k;
xys[idx / 2][idx % 2] = (float)lua_tonumber(L, i);
}
k += 8;
}