forked from CelestiaProject/Celestia
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcelx.cpp
More file actions
1683 lines (1425 loc) · 44.2 KB
/
celx.cpp
File metadata and controls
1683 lines (1425 loc) · 44.2 KB
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
// celx.cpp
//
// Copyright (C) 2003-2008, the Celestia Development Team
// Original version by Chris Laurel <claurel@gmail.com>
//
// Lua script extensions for Celestia.
//
// This program 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.
#include <config.h>
#include <cassert>
#include <ctime>
#include <map>
#include <sstream>
#include <utility>
#include <celengine/astro.h>
#include <celengine/asterism.h>
#include <celscript/legacy/cmdparser.h>
#include <celscript/legacy/execution.h>
#include <celengine/timeline.h>
#include <celengine/timelinephase.h>
#include <celutil/debug.h>
#include <celutil/gettext.h>
#include <celestia/celestiacore.h>
#include <celestia/url.h>
#include "celx_internal.h"
#include "celx_misc.h"
#include "celx_vector.h"
#include "celx_rotation.h"
#include "celx_position.h"
#include "celx_frame.h"
#include "celx_phase.h"
#include "celx_object.h"
#include "celx_observer.h"
#include "celx_celestia.h"
#include "celx_gl.h"
#include "celx_category.h"
using namespace Eigen;
using namespace std;
const char* CelxLua::ClassNames[] =
{
"class_celestia",
"class_observer",
"class_object",
"class_vec3",
"class_matrix",
"class_rotation",
"class_position",
"class_frame",
"class_celscript",
"class_font",
"class_image",
"class_texture",
"class_phase",
"class_category"
};
#define CLASS(i) ClassNames[(i)]
// Maximum timeslice a script may run without
// returning control to celestia
static const double MaxTimeslice = 5.0;
// names of callback-functions in Lua:
const char* KbdCallback = "celestia_keyboard_callback";
const char* CleanupCallback = "celestia_cleanup_callback";
const char* EventHandlers = "celestia_event_handlers";
const char* KeyHandler = "key";
const char* TickHandler = "tick";
const char* MouseDownHandler = "mousedown";
const char* MouseUpHandler = "mouseup";
#if LUA_VERSION_NUM < 503
int lua_isinteger(lua_State *L, int index)
{
if (lua_type(L, index) == LUA_TNUMBER)
{
if (lua_tonumber(L, index) == lua_tointeger(L, index))
return 1;
}
return 0;
}
#endif
static void openLuaLibrary(lua_State* l,
const char* name,
lua_CFunction func)
{
#if LUA_VERSION_NUM >= 502
luaL_requiref(l, name, func, 1);
#else
lua_pushcfunction(l, func);
lua_pushstring(l, name);
lua_call(l, 1, 0);
#endif
}
// Push a class name onto the Lua stack
void PushClass(lua_State* l, int id)
{
lua_pushlstring(l, CelxLua::ClassNames[id], strlen(CelxLua::ClassNames[id]));
}
// Set the class (metatable) of the object on top of the stack
void Celx_SetClass(lua_State* l, int id)
{
PushClass(l, id);
lua_rawget(l, LUA_REGISTRYINDEX);
if (lua_type(l, -1) != LUA_TTABLE)
cout << "Metatable for " << CelxLua::ClassNames[id] << " not found!\n";
if (lua_setmetatable(l, -2) == 0)
cout << "Error setting metatable for " << CelxLua::ClassNames[id] << '\n';
}
// Initialize the metatable for a class; sets the appropriate registry
// entries and __index, leaving the metatable on the stack when done.
void Celx_CreateClassMetatable(lua_State* l, int id)
{
lua_newtable(l);
PushClass(l, id);
lua_pushvalue(l, -2);
lua_rawset(l, LUA_REGISTRYINDEX); // registry.name = metatable
lua_pushvalue(l, -1);
PushClass(l, id);
lua_rawset(l, LUA_REGISTRYINDEX); // registry.metatable = name
lua_pushliteral(l, "__index");
lua_pushvalue(l, -2);
lua_rawset(l, -3);
}
// Register a class 'method' in the metatable (assumed to be on top of the stack)
void Celx_RegisterMethod(lua_State* l, const char* name, lua_CFunction fn)
{
lua_pushstring(l, name);
lua_pushvalue(l, -2);
lua_pushcclosure(l, fn, 1);
lua_settable(l, -3);
}
// Verify that an object at location index on the stack is of the
// specified class
bool Celx_istype(lua_State* l, int index, int id)
{
// get registry[metatable]
if (!lua_getmetatable(l, index))
return false;
lua_rawget(l, LUA_REGISTRYINDEX);
if (lua_type(l, -1) != LUA_TSTRING)
{
cout << "Celx_istype failed! Unregistered class.\n";
lua_pop(l, 1);
return false;
}
const char* classname = lua_tostring(l, -1);
lua_pop(l, 1);
return classname != nullptr && strcmp(classname, CelxLua::ClassNames[id]) == 0;
}
// Verify that an object at location index on the stack is of the
// specified class and return pointer to userdata
void* Celx_CheckUserData(lua_State* l, int index, int id)
{
if (Celx_istype(l, index, id))
return lua_touserdata(l, index);
return nullptr;
}
// Return the CelestiaCore object stored in the globals table
CelestiaCore* getAppCore(lua_State* l, FatalErrors fatalErrors)
{
lua_pushstring(l, "celestia-appcore");
lua_gettable(l, LUA_REGISTRYINDEX);
if (!lua_islightuserdata(l, -1))
{
if (fatalErrors == NoErrors)
return nullptr;
lua_pushstring(l, "internal error: invalid appCore");
lua_error(l);
}
CelestiaCore* appCore = static_cast<CelestiaCore*>(lua_touserdata(l, -1));
lua_pop(l, 1);
return appCore;
}
LuaState::LuaState() :
timeout(MaxTimeslice)
{
state = luaL_newstate();
timer = new Timer();
screenshotCount = 0;
}
LuaState::~LuaState()
{
delete timer;
if (state != nullptr)
lua_close(state);
#if 0
if (costate != nullptr)
lua_close(costate);
#endif
}
lua_State* LuaState::getState() const
{
return state;
}
double LuaState::getTime() const
{
return timer->getTime();
}
// Check if the running script has exceeded its allowed timeslice
// and terminate it if it has:
static void checkTimeslice(lua_State* l, lua_Debug* /*ar*/)
{
lua_pushstring(l, "celestia-luastate");
lua_gettable(l, LUA_REGISTRYINDEX);
if (!lua_islightuserdata(l, -1))
{
lua_pushstring(l, "Internal Error: Invalid table entry in checkTimeslice");
lua_error(l);
}
LuaState* luastate = static_cast<LuaState*>(lua_touserdata(l, -1));
if (luastate == nullptr)
{
lua_pushstring(l, "Internal Error: Invalid value in checkTimeslice");
lua_error(l);
return;
}
if (luastate->timesliceExpired())
{
const char* errormsg = "Timeout: script hasn't returned control to celestia (forgot to call wait()?)";
cerr << errormsg << "\n";
lua_pushstring(l, errormsg);
lua_error(l);
}
}
// allow the script to perform cleanup
void LuaState::cleanup()
{
if (ioMode == Asking)
{
// Restore renderflags:
CelestiaCore* appCore = getAppCore(costate, NoErrors);
if (appCore != nullptr)
{
lua_pushstring(state, "celestia-savedrenderflags");
lua_gettable(state, LUA_REGISTRYINDEX);
if (lua_isuserdata(state, -1))
{
uint64_t* savedrenderflags = static_cast<uint64_t*>(lua_touserdata(state, -1));
appCore->getRenderer()->setRenderFlags(*savedrenderflags);
// now delete entry:
lua_pushstring(state, "celestia-savedrenderflags");
lua_pushnil(state);
lua_settable(state, LUA_REGISTRYINDEX);
}
lua_pop(state,1);
}
}
lua_getglobal(costate, CleanupCallback);
if (lua_isnil(costate, -1))
return;
timeout = getTime() + 1.0;
if (lua_pcall(costate, 0, 0, 0) != 0)
cerr << "Error while executing cleanup-callback: " << lua_tostring(costate, -1) << "\n";
}
bool LuaState::createThread()
{
// Initialize the coroutine which wraps the script
if (!(lua_isfunction(state, -1) && !lua_iscfunction(state, -1)))
{
// Should never happen; we manually set up the stack in C++
assert(0);
return false;
}
costate = lua_newthread(state);
if (costate == nullptr)
return false;
lua_sethook(costate, checkTimeslice, LUA_MASKCOUNT, 1000);
lua_pushvalue(state, -2);
lua_xmove(state, costate, 1); // move function from L to NL/
alive = true;
return true;
}
string LuaState::getErrorMessage()
{
if (lua_gettop(state) > 0 && lua_isstring(state, -1))
return lua_tostring(state, -1);
return "";
}
bool LuaState::timesliceExpired()
{
if (timeout < getTime())
{
// timeslice expired, make every instruction (including pcall) fail:
lua_sethook(costate, checkTimeslice, LUA_MASKCOUNT, 1);
return true;
}
return false;
}
static int resumeLuaThread(lua_State *L, lua_State *co, int narg)
{
int status;
//if (!lua_checkstack(co, narg))
// luaL_error(L, "too many arguments to resume");
lua_xmove(L, co, narg);
#if LUA_VERSION_NUM >= 504
int nresults;
status = lua_resume(co, nullptr, narg, &nresults);
#elif LUA_VERSION_NUM >= 502
status = lua_resume(co, nullptr, narg);
#else
status = lua_resume(co, narg);
#endif
if (status == 0 || status == LUA_YIELD)
{
int nres = lua_gettop(co);
//if (!lua_checkstack(L, narg))
// luaL_error(L, "too many results to resume");
lua_xmove(co, L, nres); // move yielded values
return nres;
}
lua_xmove(co, L, 1); // move error message
return -1; // error flag
}
bool LuaState::isAlive() const
{
return alive;
}
struct ReadChunkInfo
{
char* buf;
int bufSize;
istream* in;
};
static const char* readStreamChunk(lua_State* /*unused*/, void* udata, size_t* size)
{
assert(udata != nullptr);
if (udata == nullptr)
return nullptr;
auto* info = reinterpret_cast<ReadChunkInfo*>(udata);
assert(info->buf != nullptr);
assert(info->in != nullptr);
if (!info->in->good())
{
*size = 0;
return nullptr;
}
info->in->read(info->buf, info->bufSize);
streamsize nread = info->in->gcount();
*size = (size_t) nread;
if (nread == 0)
return nullptr;
return info->buf;
}
// Callback for CelestiaCore::charEntered.
// Returns true if keypress has been consumed
bool LuaState::charEntered(const char* c_p)
{
if (ioMode == Asking && getTime() > timeout)
{
int stackTop = lua_gettop(costate);
if (c_p[0] == 'y')
{
openLuaLibrary(costate, LUA_LOADLIBNAME, luaopen_package);
openLuaLibrary(costate, LUA_IOLIBNAME, luaopen_io);
openLuaLibrary(costate, LUA_OSLIBNAME, luaopen_os);
ioMode = IOAllowed;
}
else
{
ioMode = IODenied;
}
CelestiaCore* appCore = getAppCore(costate, NoErrors);
if (appCore == nullptr)
{
cerr << "ERROR: appCore not found\n";
return true;
}
appCore->setTextEnterMode(appCore->getTextEnterMode() & ~CelestiaCore::KbPassToScript);
appCore->showText("", 0, 0, 0, 0);
// Restore renderflags:
lua_pushstring(costate, "celestia-savedrenderflags");
lua_gettable(costate, LUA_REGISTRYINDEX);
if (lua_isuserdata(costate, -1))
{
uint64_t* savedrenderflags = static_cast<uint64_t*>(lua_touserdata(costate, -1));
appCore->getRenderer()->setRenderFlags(*savedrenderflags);
// now delete entry:
lua_pushstring(costate, "celestia-savedrenderflags");
lua_pushnil(costate);
lua_settable(costate, LUA_REGISTRYINDEX);
}
else
{
cerr << "Oops, expected savedrenderflags to be userdata\n";
}
lua_settop(costate,stackTop);
return true;
}
bool result = true;
lua_getglobal(costate, KbdCallback);
lua_pushstring(costate, c_p);
timeout = getTime() + 1.0;
if (lua_pcall(costate, 1, 1, 0) != 0)
{
cerr << "Error while executing keyboard-callback: " << lua_tostring(costate, -1) << "\n";
result = false;
}
else
{
if (lua_isboolean(costate, -1))
{
result = (lua_toboolean(costate, -1) != 0);
}
lua_pop(costate, 1);
}
return result;
}
// Returns true if a handler is registered for the key
bool LuaState::handleKeyEvent(const char* key)
{
CelestiaCore* appCore = getAppCore(costate, NoErrors);
if (appCore == nullptr)
return false;
// get the registered event table
lua_getfield(costate, LUA_REGISTRYINDEX, EventHandlers);
if (!lua_istable(costate, -1))
{
cerr << "Missing event handler table";
lua_pop(costate, 1);
return false;
}
bool handled = false;
lua_getfield(costate, -1, KeyHandler);
if (lua_isfunction(costate, -1))
{
lua_remove(costate, -2); // remove the key event table from the stack
lua_newtable(costate);
lua_pushstring(costate, "char");
lua_pushstring(costate, key); // the default key handler accepts the key name as an argument
lua_settable(costate, -3);
timeout = getTime() + 1.0;
if (lua_pcall(costate, 1, 1, 0) != 0)
{
cerr << "Error while executing keyboard callback: " << lua_tostring(costate, -1) << "\n";
}
else
{
handled = lua_toboolean(costate, -1) == 1 ? true : false;
}
lua_pop(costate, 1); // pop the return value
}
else
{
lua_pop(costate, 2);
}
return handled;
}
// Returns true if a handler is registered for the button event
bool LuaState::handleMouseButtonEvent(float x, float y, int button, bool down)
{
CelestiaCore* appCore = getAppCore(costate, NoErrors);
if (appCore == nullptr)
return false;
// get the registered event table
lua_getfield(costate, LUA_REGISTRYINDEX, EventHandlers);
if (!lua_istable(costate, -1))
{
cerr << "Missing event handler table";
lua_pop(costate, 1);
return false;
}
bool handled = false;
lua_getfield(costate, -1, down ? MouseDownHandler : MouseUpHandler);
if (lua_isfunction(costate, -1))
{
lua_remove(costate, -2); // remove the key event table from the stack
lua_newtable(costate);
lua_pushstring(costate, "button");
lua_pushnumber(costate, button);
lua_settable(costate, -3);
lua_pushstring(costate, "x");
lua_pushnumber(costate, x);
lua_settable(costate, -3);
lua_pushstring(costate, "y");
lua_pushnumber(costate, y);
lua_settable(costate, -3);
timeout = getTime() + 1.0;
if (lua_pcall(costate, 1, 1, 0) != 0)
{
cerr << "Error while executing keyboard callback: " << lua_tostring(costate, -1) << "\n";
}
else
{
handled = lua_toboolean(costate, -1) == 1 ? true : false;
}
lua_pop(costate, 1); // pop the return value
}
else
{
lua_pop(costate, 2);
}
return handled;
}
// Returns true if a handler is registered for the tick event
bool LuaState::handleTickEvent(double dt)
{
if (!costate)
return true;
CelestiaCore* appCore = getAppCore(costate, NoErrors);
if (appCore == nullptr)
return false;
// get the registered event table
lua_getfield(costate, LUA_REGISTRYINDEX, EventHandlers);
if (!lua_istable(costate, -1))
{
cerr << "Missing event handler table";
lua_pop(costate, 1);
return false;
}
bool handled = false;
lua_getfield(costate, -1, TickHandler);
if (lua_isfunction(costate, -1))
{
lua_remove(costate, -2); // remove the key event table from the stack
lua_newtable(costate);
lua_pushstring(costate, "dt");
lua_pushnumber(costate, dt); // the default key handler accepts the key name as an argument
lua_settable(costate, -3);
timeout = getTime() + 1.0;
if (lua_pcall(costate, 1, 1, 0) != 0)
{
cerr << "Error while executing tick callback: " << lua_tostring(costate, -1) << "\n";
}
else
{
handled = lua_toboolean(costate, -1) == 1 ? true : false;
}
lua_pop(costate, 1); // pop the return value
}
else
{
lua_pop(costate, 2);
}
return handled;
}
int LuaState::loadScript(istream& in, const fs::path& streamname)
{
char buf[4096];
ReadChunkInfo info;
info.buf = buf;
info.bufSize = sizeof(buf);
info.in = ∈
if (streamname != "string")
{
lua_pushstring(state, "celestia-scriptpath");
lua_pushstring(state, streamname.string().c_str());
lua_settable(state, LUA_REGISTRYINDEX);
}
#if LUA_VERSION_NUM >= 502
int status = lua_load(state, readStreamChunk, &info,
streamname.string().c_str(), nullptr);
#else
int status = lua_load(state, readStreamChunk, &info,
streamname.string().c_str());
#endif
if (status != 0)
cout << "Error loading script: " << lua_tostring(state, -1) << '\n';
return status;
}
int LuaState::loadScript(const std::string& s)
{
istringstream in(s);
return loadScript(in, "string");
}
// Resume a thread; if the thread completes, the status is set to !alive
int LuaState::resume()
{
assert(costate != nullptr);
if (costate == nullptr)
return 0;
lua_State* co = lua_tothread(state, -1);
//assert(co == costate); // co can be nullptr after error (top stack is errorstring)
if (co != costate)
return 0;
timeout = getTime() + MaxTimeslice;
int nArgs = resumeLuaThread(state, co, 0);
if (nArgs < 0)
{
alive = false;
const char* errorMessage = lua_tostring(state, -1);
if (errorMessage == nullptr)
errorMessage = "Unknown script error";
cout << "Error: " << errorMessage << '\n';
CelestiaCore* appCore = getAppCore(co);
if (appCore != nullptr)
appCore->fatalError(errorMessage);
return 1; // just the error string
}
if (ioMode == Asking)
{
// timeout now is used to first only display warning, and 1s
// later allow response to avoid accidental activation
timeout = getTime() + 1.0;
}
// The thread status is zero if it has terminated normally
if (lua_status(co) == 0)
alive = false;
return nArgs; // arguments from yield
}
// get current linenumber of script and create
// useful error-message
void Celx_DoError(lua_State* l, const char* errorMsg)
{
lua_Debug debug;
if (lua_getstack(l, 1, &debug))
{
if (lua_getinfo(l, "l", &debug))
{
string buf = fmt::sprintf("In line %i: %s", debug.currentline, errorMsg);
lua_pushstring(l, buf.c_str());
lua_error(l);
}
}
lua_pushstring(l, errorMsg);
lua_error(l);
}
bool LuaState::tick(double dt)
{
// Due to the way CelestiaCore::tick is called (at least for KDE),
// this method may be entered a second time when we show the error-alerter
// Workaround: check if we are alive, return true(!) when we aren't anymore
// this way the script isn't deleted after the second enter, but only
// when we return from the first enter. OMG.
// better Solution: defer showing the error-alterter to CelestiaCore, using
// getErrorMessage()
if (!isAlive())
return false;
if (ioMode == Asking)
{
CelestiaCore* appCore = getAppCore(costate, NoErrors);
if (appCore == nullptr)
{
cerr << "ERROR: appCore not found\n";
return true;
}
lua_pushstring(state, "celestia-savedrenderflags");
lua_gettable(state, LUA_REGISTRYINDEX);
if (lua_isnil(state, -1))
{
lua_pushstring(state, "celestia-savedrenderflags");
uint64_t* savedrenderflags = static_cast<uint64_t*>(lua_newuserdata(state, sizeof(int)));
*savedrenderflags = appCore->getRenderer()->getRenderFlags();
lua_settable(state, LUA_REGISTRYINDEX);
appCore->getRenderer()->setRenderFlags(0);
}
// now pop result of gettable
lua_pop(state, 1);
if (getTime() > timeout)
{
appCore->showText(_("WARNING:\n\nThis script requests permission to read/write files\n"
"and execute external programs. Allowing this can be\n"
"dangerous.\n"
"Do you trust the script and want to allow this?\n\n"
"y = yes, ESC = cancel script, any other key = no"),
0, 0,
-15, 5, 5);
appCore->setTextEnterMode(appCore->getTextEnterMode() | CelestiaCore::KbPassToScript);
}
else
{
appCore->showText(_("WARNING:\n\nThis script requests permission to read/write files\n"
"and execute external programs. Allowing this can be\n"
"dangerous.\n"
"Do you trust the script and want to allow this?"),
0, 0,
-15, 5, 5);
appCore->setTextEnterMode(appCore->getTextEnterMode() & ~CelestiaCore::KbPassToScript);
}
return false;
}
if (dt == 0 || scriptAwakenTime > getTime())
return false;
int nArgs = resume();
if (!isAlive()) // The script is complete
return true;
// The script has returned control to us, but it is not completed.
lua_State* state = getState();
// The values on the stack indicate what event will wake up the
// script. For now, we just support wait()
double delay;
if (nArgs == 1 && lua_isnumber(state, -1))
delay = lua_tonumber(state, -1);
else
delay = 0.0;
scriptAwakenTime = getTime() + delay;
// Clean up the stack
lua_pop(state, nArgs);
return false;
}
void LuaState::requestIO()
{
// the script requested IO, set the mode
// so we display the warning during tick
// and can request keyboard. We can't do this now
// because the script is still active and could
// disable keyboard again.
if (ioMode == NoIO)
{
CelestiaCore* appCore = getAppCore(state, AllErrors);
string policy = appCore->getConfig()->scriptSystemAccessPolicy;
if (policy == "allow")
{
openLuaLibrary(costate, LUA_LOADLIBNAME, luaopen_package);
openLuaLibrary(costate, LUA_IOLIBNAME, luaopen_io);
openLuaLibrary(costate, LUA_OSLIBNAME, luaopen_os);
ioMode = IOAllowed;
}
else if (policy == "deny")
{
ioMode = IODenied;
}
else
{
ioMode = Asking;
}
}
}
// Check if the number of arguments on the stack matches
// the allowed range [minArgs, maxArgs]. Cause an error if not.
void Celx_CheckArgs(lua_State* l,
int minArgs, int maxArgs, const char* errorMessage)
{
int argc = lua_gettop(l);
if (argc < minArgs || argc > maxArgs)
{
Celx_DoError(l, errorMessage);
}
}
ObserverFrame::CoordinateSystem parseCoordSys(const string& name)
{
// 'planetographic' is a deprecated name for bodyfixed, but maintained here
// for compatibility with older scripts.
if (compareIgnoringCase(name, "universal") == 0)
return ObserverFrame::Universal;
if (compareIgnoringCase(name, "ecliptic") == 0)
return ObserverFrame::Ecliptical;
if (compareIgnoringCase(name, "equatorial") == 0)
return ObserverFrame::Equatorial;
if (compareIgnoringCase(name, "bodyfixed") == 0)
return ObserverFrame::BodyFixed;
if (compareIgnoringCase(name, "planetographic") == 0)
return ObserverFrame::BodyFixed;
if (compareIgnoringCase(name, "observer") == 0)
return ObserverFrame::ObserverLocal;
if (compareIgnoringCase(name, "lock") == 0)
return ObserverFrame::PhaseLock;
if (compareIgnoringCase(name, "chase") == 0)
return ObserverFrame::Chase;
return ObserverFrame::Universal;
}
// Get a pointer to the LuaState-object from the registry:
LuaState* getLuaStateObject(lua_State* l)
{
int stackSize = lua_gettop(l);
lua_pushstring(l, "celestia-luastate");
lua_gettable(l, LUA_REGISTRYINDEX);
if (!lua_islightuserdata(l, -1))
{
Celx_DoError(l, "Internal Error: Invalid table entry for LuaState-pointer");
return 0;
}
LuaState* luastate_ptr = static_cast<LuaState*>(lua_touserdata(l, -1));
if (luastate_ptr == nullptr)
{
Celx_DoError(l, "Internal Error: Invalid LuaState-pointer");
return 0;
}
lua_settop(l, stackSize);
return luastate_ptr;
}
// Map the observer to its View. Return nullptr if no view exists
// for this observer (anymore).
View* getViewByObserver(CelestiaCore* appCore, Observer* obs)
{
for (const auto view : appCore->views)
if (view->observer == obs)
return view;
return nullptr;
}
// Fill list with all Observers
void getObservers(CelestiaCore* appCore, vector<Observer*>& observerList)
{
for (const auto view : appCore->views)
if (view->type == View::ViewWindow)
observerList.push_back(view->observer);
}
// ==================== Helpers ====================
// safe wrapper for lua_tostring: fatal errors will terminate script by calling
// lua_error with errorMsg.
const char* Celx_SafeGetString(lua_State* l,
int index,
FatalErrors fatalErrors,
const char* errorMsg)
{
if (l == nullptr)
{
cerr << "Error: LuaState invalid in Celx_SafeGetString\n";
return nullptr;
}
int argc = lua_gettop(l);
if (index < 1 || index > argc)
{
if (fatalErrors & WrongArgc)
Celx_DoError(l, errorMsg);
return nullptr;
}
if (!lua_isstring(l, index))
{
if (fatalErrors & WrongType)
Celx_DoError(l, errorMsg);
return nullptr;
}
return lua_tostring(l, index);
}
// safe wrapper for lua_tonumber, c.f. Celx_SafeGetString
// Non-fatal errors will return defaultValue.
lua_Number Celx_SafeGetNumber(lua_State* l, int index, FatalErrors fatalErrors,
const char* errorMsg,
lua_Number defaultValue)
{
if (l == nullptr)
{
cerr << "Error: LuaState invalid in Celx_SafeGetNumber\n";
return 0.0;
}
int argc = lua_gettop(l);
if (index < 1 || index > argc)
{
if (fatalErrors & WrongArgc)
{
Celx_DoError(l, errorMsg);
return 0;
}
return defaultValue;
}
if (!lua_isnumber(l, index))
{
if (fatalErrors & WrongType)
{
Celx_DoError(l, errorMsg);
return 0;
}
return defaultValue;
}
return lua_tonumber(l, index);
}
// Safe wrapper for lua_tobool, c.f. safeGetString
// Non-fatal errors will return defaultValue
bool Celx_SafeGetBoolean(lua_State* l, int index, FatalErrors fatalErrors,
const char* errorMsg,
bool defaultValue)
{
if (l == nullptr)
{
cerr << "Error: LuaState invalid in Celx_SafeGetBoolean\n";
return false;
}
int argc = lua_gettop(l);
if (index < 1 || index > argc)
{
if (fatalErrors & WrongArgc)