-
Notifications
You must be signed in to change notification settings - Fork 12
/
LuaEngine.cs
1977 lines (1722 loc) · 77.5 KB
/
LuaEngine.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using RogueEssence.Menu;
using RogueEssence.Data;
using RogueEssence.Ground;
using RogueEssence.Dungeon;
using Microsoft.Xna.Framework;
using NLua;
using System.IO;
using System.Collections;
using Newtonsoft.Json;
using System.Text;
using RogueEssence.Dev;
/*
* LuaEngine.cs
* 2017/06/24
* psycommando@gmail.com
* Description: Object managing the lua state, loading of scripts, and initializing the script interface.
*/
namespace RogueEssence.Script
{
/// <summary>
/// Class each components of the lua engine should implement
/// </summary>
public abstract class ILuaEngineComponent
{
/// <summary>
/// Setups any extra functionalities for this object written on the lua side.
/// </summary>
public abstract void SetupLuaFunctions(LuaEngine state);
}
/**************************************************************************************
* LuaEngine
**************************************************************************************/
/// <summary>
/// Manager for the program-wide lua state. Init and de-init block!
/// </summary>
public partial class LuaEngine
{
#region ZONE_EVENTS
/// <summary>
/// The available callbacks a zone's lua script may receive from the engine.
/// </summary>
public enum EZoneCallbacks
{
Init = 0, //When the zone is not yet active and being setup
EnterSegment, //When a segment is being entered
ExitSegment, //When a segment is exited by escape, defeat, completion, etc.
//TODO: move these events to services
Rescued,
Invalid
}
public static readonly string ZoneCurrentScriptSym = "CURZONESCR";
//The last one is optional, and is called before the map script is unloaded, so the script may do any needed cleanup
public static readonly string ZoneCleanupFun = "{0}.Cleanup";
/// <summary>
/// Enumerate the values in the EDungeonFloorCallbacks enum
/// </summary>
/// <returns></returns>
public static IEnumerable<EZoneCallbacks> EnumerateZoneCallbackTypes()
{
for (int ii = (int)EZoneCallbacks.Init; ii < (int)EZoneCallbacks.Invalid; ++ii)
yield return (EZoneCallbacks)ii;
}
/// <summary>
/// Create the name of a map's expected callback function in its script.
/// Each specifc callbacks has its own name and format.
/// </summary>
/// <param name="callbackformat"></param>
/// <param name="mapname"></param>
/// <returns></returns>
public static string MakeZoneScriptCallbackName(string zonename, EZoneCallbacks callback)
{
if (callback < 0 && callback >= EZoneCallbacks.Invalid)
throw new Exception("LuaEngine.MakeZoneScriptCallbackName(): Unknown callback!");
return String.Format("{0}.{1}", zonename, callback.ToString());
}
public static string MakeZoneCallbackDef(string zonename, EZoneCallbacks type)
{
string args = "";
if (type == EZoneCallbacks.Init)
args = "zone";
else if (type == EZoneCallbacks.Rescued)
args = "zone, name, mail";
else if (type == EZoneCallbacks.EnterSegment)
args = "zone, rescuing, segmentID, mapID";
else if (type == EZoneCallbacks.ExitSegment)
args = "zone, result, rescue, segmentID, mapID";
return String.Format("{0}({1})", MakeZoneScriptCallbackName(zonename, type), args);
}
#endregion
#region MAP_EVENTS
/// <summary>
/// The available callbacks a map's lua script may receive from the engine.
/// </summary>
public enum EMapCallbacks
{
Init = 0, //When the map is not yet displayed and being setup
Enter, //When the map is just being displayed an the game fades-in
Exit, //When the map has finished fading out before transition to the next
Update, //When the game script engine ticks
GameSave,
GameLoad,
Invalid
}
//Name for common map callback functions
public static readonly string MapCurrentScriptSym = "CURMAPSCR";
//The last one is optional, and is called before the map script is unloaded, so the script may do any needed cleanup
public static readonly string MapCleanupFun = "{0}.Cleanup";
/// <summary>
/// Utility function for the EMapCallbacks enum. Allows iterating all the enum's values.
/// Meant to be used with a foreach loop
/// </summary>
/// <returns>One of the enum value.</returns>
public static IEnumerable<EMapCallbacks> EnumerateCallbackTypes()
{
for (int ii = (int)EMapCallbacks.Init; ii < (int)EMapCallbacks.Invalid; ++ii)
yield return (EMapCallbacks)ii;
}
/// <summary>
/// Create the name of a map's expected callback function in its script.
/// Each specifc callbacks has its own name and format.
/// </summary>
/// <param name="callbackformat"></param>
/// <param name="mapname"></param>
/// <param name="callback"></param>
/// <returns></returns>
public static string MakeMapScriptCallbackName(string mapname, EMapCallbacks callback)
{
if (callback < 0 && callback >= EMapCallbacks.Invalid)
throw new Exception("LuaEngine.MakeMapScriptCallbackName(): Unknown callback!");
return String.Format("{0}.{1}", mapname, callback.ToString());
}
public static string MakeGroundMapCallbackDef(string mapname, EMapCallbacks type)
{
return String.Format("{0}(map)", MakeMapScriptCallbackName(mapname, type));
}
#endregion
#region DUNGEON_MAP_EVENTS
/// <summary>
/// Possible lua callbacks for a given dungeon floor
/// </summary>
public enum EDungeonMapCallbacks
{
Init = 0, //When the map is not yet displayed and being setup
Enter, //When the map is just being displayed an the game fades-in
Exit, //When the player is leaving a dungeon floor
Invalid,
}
//Name for common map callback functions
public static readonly string DungeonMapCurrentScriptSym = "CURDUNMAPSCR";
//The last one is optional, and is called before the map script is unloaded, so the script may do any needed cleanup
public static readonly string DungeonMapCleanupFun = "{0}.Cleanup";
/// <summary>
/// Enumerate the values in the EDungeonFloorCallbacks enum
/// </summary>
/// <returns></returns>
public static IEnumerable<EDungeonMapCallbacks> EnumerateDungeonFloorCallbackTypes()
{
for (int ii = (int)EDungeonMapCallbacks.Init; ii < (int)EDungeonMapCallbacks.Invalid; ++ii)
yield return (EDungeonMapCallbacks)ii;
}
/// <summary>
/// Returns the name string for a lua callback function for the given dungeon's floor
/// </summary>
/// <param name="zonename"></param>
/// <param name="floornumber"></param>
/// <param name="callback"></param>
/// <returns></returns>
public static string MakeDungeonMapScriptCallbackName(string zonename, int floornumber, EDungeonMapCallbacks callback)
{
return MakeDungeonMapScriptCallbackName(MakeDungeonFloorAssetName(zonename, floornumber), callback);
}
public static string MakeDungeonMapScriptCallbackName(string floorname, EDungeonMapCallbacks callback)
{
if (callback < 0 && callback >= EDungeonMapCallbacks.Invalid)
throw new Exception("LuaEngine.MakeDungeonMapScriptCallbackName(): Unknown callback!");
return String.Format("{0}.{1}", floorname, callback.ToString());
}
public static string MakeDungeonMapCallbackDef(string floorname, EDungeonMapCallbacks type)
{
return String.Format("{0}(map)", MakeDungeonMapScriptCallbackName(floorname, type));
}
/// <summary>
/// Generates an asset name for the given floor in the given dungeon. Mainly used for scripts.
/// </summary>
/// <param name="dungeonname"></param>
/// <param name="floornumber"></param>
/// <returns></returns>
public static string MakeDungeonFloorAssetName(string dungeonname, int floornumber)
{
return String.Format("{0}.floor{1}", dungeonname, floornumber);
}
/// <summary>
/// Return the name string for a lua callback for all the non-overriden dungeon floor events, for a given dungeon.
/// </summary>
/// <param name="dungeonname"></param>
/// <param name="callback"></param>
/// <returns></returns>
public static string MakeDefaultDungeonFloorCallbackName(string dungeonname, EDungeonMapCallbacks callback)
{
if (callback < 0 && callback >= EDungeonMapCallbacks.Invalid)
throw new Exception("LuaEngine.MakeDefaultDungeonFloorCallbackName(): Unknown callback!");
return String.Format("{0}.floordefault.{1}", dungeonname, callback.ToString());
}
#endregion
#region ENTITY_EVENT
/// <summary>
/// Types of events that an entity may have.
/// </summary>
public enum EEntLuaEventTypes
{
Action = 0,
Touch = 1,
Think = 2,
Update = 3,
EntSpawned = 4, //When a spawner spawned an entity
Invalid,
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IEnumerable<EEntLuaEventTypes> IterateLuaEntityEvents()
{
for (int ii = (int)EEntLuaEventTypes.Action; ii < (int)EEntLuaEventTypes.Invalid; ++ii)
yield return (EEntLuaEventTypes)ii;
}
public static string MakeLuaEntityCallbackName(string entname, EEntLuaEventTypes type)
{
if (type < 0 && type >= EEntLuaEventTypes.Invalid)
throw new Exception("LuaEngine.MakeLuaEntityCallbackName(): Invalid Lua entity event type!");
return String.Format("{2}.{0}_{1}", entname, type.ToString(), MapCurrentScriptSym);
}
public static string MakeEntLuaEventDef(string mapname, string entname, EEntLuaEventTypes type)
{
if (type < 0 && type >= EEntLuaEventTypes.Invalid)
throw new Exception("LuaEngine.MakeLuaEntityCallbackName(): Invalid Lua entity event type!");
string callback = String.Format("{2}.{0}_{1}", entname, type.ToString(), mapname);
return String.Format("{0}(obj, activator)", callback);
}
#endregion
#region SERVICES_EVENTS
private static readonly string NameLuaServiceEventNames = "EngineServiceEvents";
private enum EServiceEvents
{
Init = 0,
Deinit,
GraphicsLoad,
GraphicsUnload,
MenuButtonPressed,
NewGame,
LossPenalty,
UpgradeSave,
Restart,
Update,
MusicChange,
GroundEntityInteract,
DungeonModeBegin,
DungeonModeEnd,
DungeonMapInit,
DungeonFloorEnter,
DungeonFloorExit,
ZoneInit,
DungeonSegmentStart,
DungeonSegmentEnd,
GroundModeBegin,
GroundModeEnd,
GroundMapInit,
GroundMapEnter,
GroundMapExit,
//Keep last
_NBEvents
};
private IEnumerator<EServiceEvents> IterateServiceEvents()
{
for (int cntev = 0; cntev < (int)EServiceEvents._NBEvents; ++cntev)
yield return (EServiceEvents)cntev;
}
#endregion
#region MAIN_SCRIPTS
const string SCRIPT_MAIN = "main.lua";
const string SCRIPT_COMMON = "common.lua";
const string SCRIPT_VARS = "scriptvars.lua";
const string SCRIPT_EVENT = "event.lua";
const string INCLUDE_EVENT = "include.lua";
/// <summary>
/// Assemble the path to the specified script
/// </summary>
/// <param name="script">Script to make the path for</param>
/// <returns>The path to the script file.</returns>
private string PathToScript(string script)
{
return PathMod.QuestPath(String.Format("{0}{1}", SCRIPT_PATH, script));
}
#endregion
//Paths
public const string MAP_SCRIPT_PATTERN = "ground.{0}";
public const string MAP_SCRIPT_DIR = SCRIPT_PATH + "ground/";
public const string MAP_SCRIPT_ENTRY_POINT = "init"; //filename of the map's main script file that the engine will run when the map is loaded (by default lua package entrypoints are init.lua)
public const string DUNGEON_MAP_SCRIPT_PATTERN = "map.{0}";
public const string DUNGEON_MAP_SCRIPT_DIR = SCRIPT_PATH + "map/";
public const string DUNGEON_MAP_SCRIPT_ENTRY_POINT = "init";
public const string ZONE_SCRIPT_PATTERN = "zone.{0}";
public const string ZONE_SCRIPT_DIR = SCRIPT_PATH + "zone/";
public const string ZONE_SCRIPT_ENTRY_POINT = "init"; //filename of the zone's main script file that the engine will run when the zone is loaded (by default lua package entrypoints are init.lua)
//Global lua symbol names
public const string SCRIPT_VARS_NAME = "SV"; //Name of the table of script variables that gets loaded and saved with the game
//Lua State
public const string SCRIPT_PATH = DataManager.DATA_PATH + "Script/"; //Base script engine scripts path
public const string SCRIPT_CPATH = DataManager.DATA_PATH + "Script/bin/"; //Base script engine libraries, for so and dlls
private ScriptServices m_scrsvc;
private ScriptSound m_scriptsound;
private ScriptGround m_scriptground;
private ScriptGame m_scriptgame;
private ScriptUI m_scriptUI;
private ScriptDungeon m_scriptdungeon;
private ScriptStrings m_scriptstr;
private ScriptTask m_scripttask;
private ScriptAI m_scriptai;
private ScriptXML m_scriptxml;
//Engine time
private TimeSpan m_nextUpdate;
private GameTime m_curtime = new GameTime();
//Properties
public Lua LuaState { get; set; }
public GameTime Curtime { get { return m_curtime; } set { m_curtime = value; } }
public bool Breaking { get; private set; }
//Pre-compiled internal lua functions
private LuaFunction m_MkCoIter; //Instantiate a lua coroutine iterator function/state, for the ScriptEvent class mainly.
private LuaFunction m_UnpackParamsAndRun;
//==============================================================================
// LuaEngine Initialization code
//==============================================================================
private static LuaEngine instance;
public static void InitInstance()
{
instance = new LuaEngine();
}
public static LuaEngine Instance { get { return instance; } }
/// <summary>
/// Constructor private, since we don't want to instantiate this more than once! Otherwise bad things will happen.
/// </summary>
private LuaEngine()
{
Reset();
}
public static void InitScriptFolders(string baseFolder)
{
Directory.CreateDirectory(Path.Join(baseFolder, SCRIPT_PATH));
Directory.CreateDirectory(Path.Join(baseFolder, MAP_SCRIPT_DIR));
Directory.CreateDirectory(Path.Join(baseFolder, DUNGEON_MAP_SCRIPT_DIR));
Directory.CreateDirectory(Path.Join(baseFolder, ZONE_SCRIPT_DIR));
}
/// <summary>
/// Handles importing the various .NET namespaces used in the project to lua.
/// It uses reflection to do so.
/// </summary>
private void ImportDotNet()
{
DiagManager.Instance.LogInfo("[SE]:Importing .NET packages..");
LuaState.LoadCLRPackage();
LuaState.DoFile(PathToScript(INCLUDE_EVENT));
}
/// <summary>
/// Clean the lua state
/// Must call init methods manually again!!
/// </summary>
public void Reset()
{
if (LuaState != null)
LuaState.Close();
//init lua
LuaState = new Lua();
//LuaState.UseTraceback = true;
LuaState.State.Encoding = Encoding.UTF8;
m_nextUpdate = new TimeSpan(-1);
DiagManager.Instance.LogInfo(String.Format("[SE]:Initialized {0}", LuaState["_VERSION"] as string));
ImportDotNet();
m_scriptstr = new ScriptStrings();
//Disable the import command, we could also rewrite it to only allow importing some specific things!
//LuaState.DoString("import = function() end");
//!#FIXME: disable import again
//Instantiate components
m_nextUpdate = new TimeSpan(0);
m_scrsvc = new ScriptServices(this);
m_scriptsound = new ScriptSound();
m_scriptgame = new ScriptGame();
m_scriptground = new ScriptGround();
m_scriptUI = new ScriptUI();
m_scriptdungeon = new ScriptDungeon();
m_scripttask = new ScriptTask();
m_scriptai = new ScriptAI();
m_scriptxml = new ScriptXML();
//Expose symbols
ExposeInterface();
SetupGlobals();
CacheMainScripts();
DiagManager.Instance.LogInfo("[SE]: **- Lua engine ready! -**");
}
public void BreakScripts()
{
Breaking = true;
}
public void SceneOver()
{
Breaking = false;
}
/// <summary>
/// Calling this sends the OnInit event to the script engine.
/// Use this if you just reset the script state, and want to force it to do its initialization.
/// </summary>
public void ReInit()
{
Breaking = true;
DiagManager.Instance.LogInfo("[SE]:Re-initializing scripts!");
DiagManager.Instance.LogInfo("[SE]:Loading last serialized script variables!");
if (DataManager.Instance.Save != null)
LoadSavedData(DataManager.Instance.Save);
if (ZoneManager.Instance != null)
{
ZoneManager.Instance.LuaEngineReload();
if (ZoneManager.Instance.CurrentZone != null)
{
if (GameManager.Instance.CurrentScene == GroundScene.Instance || GameManager.Instance.CurrentScene == DungeonScene.Instance)
GameManager.Instance.SceneOutcome = ReInitZone();
else if (GameManager.Instance.CurrentScene == GroundEditScene.Instance || GameManager.Instance.CurrentScene == DungeonEditScene.Instance)
ReInitZoneEditor();
}
}
}
public IEnumerator<YieldInstruction> ReInitZone()
{
yield return CoroutineManager.Instance.StartCoroutine(ZoneManager.Instance.CurrentZone.OnInit());
if (ZoneManager.Instance.CurrentGround != null)
{
OnGroundModeBegin();
yield return CoroutineManager.Instance.StartCoroutine(ZoneManager.Instance.CurrentGround.OnInit());
}
else if (ZoneManager.Instance.CurrentMap != null)
{
OnDungeonModeBegin();
yield return CoroutineManager.Instance.StartCoroutine(ZoneManager.Instance.CurrentMap.OnInit());
}
}
public void ReInitZoneEditor()
{
if (ZoneManager.Instance.CurrentGround != null)
{
ZoneManager.Instance.CurrentGround.OnEditorInit();
}
else if (ZoneManager.Instance.CurrentMap != null)
{
ZoneManager.Instance.CurrentMap.OnEditorInit();
}
}
/// <summary>
/// Set lua package paths to the ones in the game's files.
/// </summary>
private void SetLuaPaths()
{
DiagManager.Instance.LogInfo("[SE]:Setting up lua paths..");
//windows-specific: set the encoding to code page 1252, just for this block
//This is because the filesystem uses cp1252, and if the search paths arent passed in with cp1252 encoding,
//then searching for lua includes will fail when paths contain unicode letters.
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
LuaState.State.Encoding = Encoding.GetEncoding(1252);
//Add the current script directory to the lua searchpath for loading modules!
string buildPath = (string)(LuaState["package.path"]);
foreach (string pathMod in PathMod.FallbackPaths(SCRIPT_PATH))
{
buildPath += ";" + pathMod + "lib/?.lua";
buildPath += ";" + pathMod + "?.lua";
buildPath += ";" + pathMod + "?/init.lua";
}
LuaState["package.path"] = buildPath;
//Add lua binary path. No mods
string cpath = LuaState["package.cpath"] + ";" + Path.GetFullPath(PathMod.NoMod(SCRIPT_CPATH));
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
cpath += "?.dll";
else
cpath += "?.so";
LuaState["package.cpath"] = cpath;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
LuaState.State.Encoding = Encoding.UTF8;
}
/// <summary>
/// Expose the list of available service callbacks names to Lua. It should make it easier for script devs to get a list of them to fiddle with.
/// </summary>
private void FillServiceEventsTable()
{
LuaTable availables = RunString("return {}").First() as LuaTable;
LuaFunction fnAddToTable = RunString("return function(tbl, name, item) tbl[name] = item end").First() as LuaFunction;
var svcev = IterateServiceEvents();
while (svcev.MoveNext())
fnAddToTable.Call(availables, svcev.Current.ToString(), svcev.Current.ToString());
LuaState[NameLuaServiceEventNames] = availables;
}
/// <summary>
/// Add all the required global variables to the lua environment!
/// </summary>
private void SetupGlobals()
{
DiagManager.Instance.LogInfo("[SE]:Setting up lua globals..");
SetLuaPaths();
//Setup some global vars
//LuaState["_SCRIPT_PATH"] = Path.GetFullPath(PathMod.QuestPath(SCRIPT_PATH)); //Share with the script engine the path to the root of the script files
RunString(ZoneCurrentScriptSym + " = nil");
RunString(MapCurrentScriptSym + " = nil");
RunString(DungeonMapCurrentScriptSym + " = nil");
//Make empty script variable table
LuaState.NewTable(SCRIPT_VARS_NAME);
LuaState[SCRIPT_VARS_NAME + ".__ALL_SET"] = "OK"; //This is just a debug variable, to make sure the table isn't overwritten at runtime by something else, and help track down issues linked to that.
//Add the list of available Callbacknames
FillServiceEventsTable();
RunString("require 'CLRPackage'");
RunString(@"
__GetLevel = function()
local curground = RogueEssence.Dungeon.ZoneManager.Instance.CurrentGround
local curmap = RogueEssence.Dungeon.ZoneManager.Instance.CurrentMap
if curground then
return curground
elseif curmap then
return curmap
end
return nil
end
", "__GetLevel function init");
//Setup lookup functions
//Character lookup
RunString(@"
function CH(charname)
local curlvl = __GetLevel()
if curlvl then
return curlvl:GetChar(charname)
end
return nil
end
", "CH function init");
//Object lookup
RunString(@"
OBJ = function(name)
if _ZONE.CurrentGround then
return _ZONE.CurrentGround:GetObj(name)
elseif _ZONE.CurrentMap then
assert(false, 'OBJ(' .. name .. '): unimplemented on dungeon maps!!!!')
end
return nil
end
", "OBJ function init");
//Marker lookup
RunString(@"
MRKR = function(name)
if _ZONE.CurrentGround then
return _ZONE.CurrentGround:GetMarker(name)
elseif _ZONE.CurrentMap then
assert(false, 'MRKR(' .. name .. '): unimplemented on dungeon maps!!!!')
end
return nil
end
", "OBJ function init");
//Character localized name
RunString(@"
CHName = function(name)
if _ZONE.CurrentGround then
local ch = _ZONE.CurrentGround:GetChar(name)
if ch then
return ch:GetDisplayName()
end
elseif _ZONE.CurrentMap then
assert(false, 'CHName(' .. name .. '): unimplemented on dungeon maps!!!!')
end
return nil
end
", "CHName function init");
//This returns a MonsterID
RunString(@"
IDX = function(id, ...)
local param = {...}
local form = param[0]
local skin = param[1]
local gender= param[2]
if not form then form = 0 end
if not skin then skin = 0 end
if not gender then gender = Gender.Male end
return MonsterID(id, form, skin, gender)
end
", "IDX function init");
//LTBL is a wrapper to access the LuaTable that some entiies have
RunString(@"
function LTBL(entity)
if not entity then return nil end
if not entity.LuaData then return nil end
return entity.LuaData
end
",
"LTBL");
//Function to lookup a NPC spawner by name on the current level
RunString(@"
SPWN = function(spawnername)
local curlvl = __GetLevel()
if curlvl then
return curlvl:GetSpanwer(spawnername)
end
return nil
end
", "SPWN function init");
//Expose the lua system
LuaState["LUA_ENGINE"] = this;
}
/// <summary>
/// Call this on map changes to ensure that the script engine has access to those .NET globals!
/// </summary>
private void ExposeInterface()
{
DiagManager.Instance.LogInfo("[SE]:Exposing game engine components instances..");
//Expose directly parts of the engine
LuaState[ScriptServices.SInterfaceInstanceName] = m_scrsvc;
LuaState["_GROUND"] = GroundScene.Instance;
LuaState["_DUNGEON"] = DungeonScene.Instance;
LuaState["_ZONE"] = ZoneManager.Instance;
LuaState["_GAME"] = GameManager.Instance;
LuaState["_DATA"] = DataManager.Instance;
LuaState["_MENU"] = MenuManager.Instance;
LuaState["_DIAG"] = DiagManager.Instance;
DiagManager.Instance.LogInfo("[SE]:Exposing script interface..");
//Expose script interface objects
LuaState["GROUND"] = m_scriptground;
LuaState["DUNGEON"] = m_scriptdungeon;
LuaState["GAME"] = m_scriptgame;
m_scriptgame.SetupLuaFunctions(this); //Need to do this at this very moment.
LuaState["SOUND"] = m_scriptsound;
LuaState["UI"] = m_scriptUI;
LuaState["STRINGS"] = m_scriptstr;
LuaState["TASK"] = m_scripttask;
LuaState["AI"] = m_scriptai;
LuaState["XML"] = m_scriptxml;
}
public void UpdateZoneInstance()
{
LuaState["_ZONE"] = ZoneManager.Instance;
}
private void SetupLuaFunctions()
{
//Add the function to make iterators on coroutines
m_MkCoIter = RunString(
@"return function(fun,...)
local arguments = {...}
local co = coroutine.create(function() xpcall( fun, PrintStack, table.unpack(arguments)) end)
return function () -- iterator
local code, res = coroutine.resume(co)
if code == false then --This means there was an error in there
assert(false,'Error running coroutine ' .. tostring(fun) .. '! :\n' .. PrintStack(res))
end
return res
end
end",
"MakeCoroutineIterator").First() as LuaFunction;
m_UnpackParamsAndRun = RunString(
@"return function(fun, params)
local size = params.Length
local transittbl = {}
print('Length == ' .. tostring(params.Length))
local i = 0
while i < size do
table.insert(transittbl, params[i])
i = i + 1
end
return fun(table.unpack(transittbl))
end",
"UnpackParamsAndRun").First() as LuaFunction;
}
/// <summary>
/// Preload the script files we expect to be there!
/// </summary>
private void CacheMainScripts()
{
DiagManager.Instance.LogInfo("[SE]:Caching scripts..");
m_scrsvc.SetupLuaFunctions(this);
//Cache default script variables
LuaState.DoFile(PathToScript(SCRIPT_VARS));
//Cache common lib
LuaState.LoadFile(PathToScript(SCRIPT_COMMON));
//load events
LuaState.DoFile(PathToScript(SCRIPT_EVENT));
//Install misc lua functions each interfaces needs
DiagManager.Instance.LogInfo("[SE]:Installing game interface functions..");
SetupLuaFunctions();
//m_scrco.SetupLuaFunctions(this);
m_scriptstr.SetupLuaFunctions(this);
m_scriptsound.SetupLuaFunctions(this);
m_scriptground.SetupLuaFunctions(this);
m_scriptUI.SetupLuaFunctions(this);
m_scriptdungeon.SetupLuaFunctions(this);
m_scripttask.SetupLuaFunctions(this);
m_scriptai.SetupLuaFunctions(this);
m_scriptxml.SetupLuaFunctions(this);
//If script vars aren't initialized in the save, do it now!
//DiagManager.Instance.LogInfo("[SE]:Checking if we need to initialize the script variables saved state..");
//if (DataManager.Instance != null && DataManager.Instance.Save != null && String.IsNullOrEmpty(DataManager.Instance.Save.ScriptVars))
// SaveData(DataManager.Instance.Save);
//Run main script
DiagManager.Instance.LogInfo(String.Format("[SE]:Running {0} script..", SCRIPT_MAIN));
LuaState.DoFile(PathToScript(SCRIPT_MAIN));
}
/// <summary>
/// Use this to un-serialize the script variables and load them.
/// </summary>
public void LoadSavedData(GameProgress loaded)
{
//Do stuff when resuming from a save!
DiagManager.Instance.LogInfo("LuaEngine.LoadSavedData()..");
if ( loaded == null || loaded.ScriptVars == null)
{
LuaState.DoFile(PathToScript(SCRIPT_VARS));
}
else
{
LuaTable tbl = LoadLuaTable(loaded.ScriptVars);
LuaState[SCRIPT_VARS_NAME] = tbl;
}
if (loaded != null)
{
loaded.ActiveTeam.LoadLua();
}
//Tell the script we've just resumed a save!
m_scrsvc.Publish("LoadSavedData");
}
/// <summary>
/// Use this to serialize the script variables and place the serialized data into the current GameProgress.
/// </summary>
public void SaveData(GameProgress save)
{
//First tell the script we're gonna save
m_scrsvc.Publish("SaveData");
//Save script engine stuff here!
DiagManager.Instance.LogInfo("LuaEngine.SaveData()..");
LuaTable tbl = LuaState.GetTable(SCRIPT_VARS_NAME);
save.ScriptVars = SaveLuaTable(tbl);
save.ActiveTeam.SaveLua();
}
/// <summary>
/// Creates a deep-copy conversion of the input lua table to a dictionary of objects.
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public LuaTableContainer SaveLuaTable(LuaTable table)
{
Dictionary<object, object> dict = LuaState.GetTableDict(table);
List<object[]> tbl_list = new List<object[]>();
foreach (object key in dict.Keys)
{
object val = dict[key];
if (val is LuaTable)
{
LuaTableContainer subDict = SaveLuaTable(val as LuaTable);
tbl_list.Add(new object[] { key, subDict });
}
else
tbl_list.Add(new object[] { key, val });
}
return new LuaTableContainer(tbl_list);
}
public LuaTable LoadLuaTable(LuaTableContainer dict)
{
if (dict == null)
return null;
LuaTable tbl = LuaEngine.Instance.RunString("return {}").First() as LuaTable;
LuaFunction addfn = LuaEngine.Instance.RunString("return function(tbl, key, itm) tbl[key] = itm end").First() as LuaFunction;
foreach (object[] entry in dict.Table)
{
object key = entry[0];
object val = entry[1];
if (val is LuaTableContainer)
val = LoadLuaTable((LuaTableContainer)val);
addfn.Call(tbl, key, val);
}
return tbl;
}
/// <summary>
/// Dumps the specified lua table to a string, for serialization!
/// </summary>
/// <param name="tbl">lua table itself</param>
/// <returns>A string representation of the lua table.Returns null if failed!</returns>
public string SerializeLuaTable(LuaTable tbl)
{
object[] result = CallLuaFunctions("Serpent.dump", tbl);
if (result != null && result[0] != null)
return result[0] as string;
else
return null;
}
/// <summary>
/// Deserialize a lua table that was dumped to a string using the SerializeLuaTable method.
/// </summary>
/// <param name="serializedtbl"></param>
/// <returns></returns>
public LuaTable DeserializedLuaTable(string serializedtbl)
{
//Load returns a boolean and the result. The boolean is true if it succeeded.
object[] result = CallLuaFunctions("Serpent.load", serializedtbl).ToArray();
if ((bool)result[0])
return result[1] as LuaTable;
else
return null;
}
/// <summary>
/// Struct used for defining an entry to be imported by the script engine.
/// </summary>
private struct ImportEntry
{
String m_Assembly;
String m_Namespace;
public ImportEntry(String asm, String nspace)
{
m_Assembly = asm;
m_Namespace = nspace;
}
public bool hasAssembly()
{
return (m_Assembly!= null && m_Assembly.Length > 0) &&
(m_Namespace != null && m_Namespace.Length > 0);
}
public string Namespace { get { return m_Namespace;} set { m_Namespace = value;} }
public string Assembly { get { return m_Assembly; } set { m_Assembly = value; } }
}
/// <summary>
/// Instantiate a lua module's Class table using its metatable's "__call" definition
/// </summary>
/// <param name="classpath"></param>
/// <param name="args"></param>
/// <returns></returns>
public LuaTable InstantiateLuaModule(string modulepath, params object[] args)
{
try
{
LuaTable luaclass = RunString(String.Format("return require '{0}'", modulepath)).First() as LuaTable;
//LuaTable tbl = LuaState.GetTable(classpath);
if (luaclass != null)
{
//LuaFunction DoInstantiate = RunString("return function(srcclass, ...) return srcclass(...) end").First() as LuaFunction;
//LuaFunction fn = luaclass["__call"] as LuaFunction;
//if (fn != null)
// return fn.Call(args).First() as LuaTable;
//if(DoInstantiate != null)
//{
return m_UnpackParamsAndRun.Call(luaclass, args).First() as LuaTable;
//}
}
}
catch (Exception ex)
{
DiagManager.Instance.LogInfo(String.Format("LuaEngine.InstantiateLuaClass(): Error instantiating class \"{0}\"!\n{1}", modulepath, ex.Message));
}
return null;
}
/// <summary>
/// Allow calling a lua function of a lua table/object with the specified parameters, and returns the result.
/// </summary>
/// <param name="objname">Path of the lua object instance whose method we'll call.</param>
/// <param name="funname">Name of the method of the lua object instance to call.</param>
/// <param name="args">Parameters to pass the method (excluding "self")</param>
/// <returns>Returns the array of objects that the lua interpreter returns after executing the method.</returns>
public object[] CallLuaMemberFun(string objname, string funname, params object[] args)
{