-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmainfunctions.lua
2367 lines (2015 loc) · 78.9 KB
/
mainfunctions.lua
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
local PopupDialogScreen = require "screens/redux/popupdialog"
local WorldGenScreen = require "screens/worldgenscreen"
local HealthWarningPopup = require "screens/healthwarningpopup"
local Stats = require("stats")
local DebugNodes = CAN_USE_DBUI and require("dbui_no_package/debug_nodes") or nil
local DebugConsole = CAN_USE_DBUI and require("dbui_no_package/debug_console") or nil
require "scheduler"
--require "skinsutils"
local DEBUG_MODE = BRANCH == "dev"
SimTearingDown = false
SimShuttingDown = false
PerformingRestart = false
function SavePersistentString(name, data, encode, callback)
if TheFrontEnd then
TheFrontEnd:ShowSavingIndicator()
local function cb()
TheFrontEnd:HideSavingIndicator()
if callback then
callback()
end
end
TheSim:SetPersistentString(name, data, encode or false, cb)
else
TheSim:SetPersistentString(name, data, encode or false, callback)
end
end
function ErasePersistentString(name, callback)
if TheFrontEnd then
TheFrontEnd:ShowSavingIndicator()
local function cb()
TheFrontEnd:HideSavingIndicator()
if callback then
callback()
end
end
TheSim:ErasePersistentString(name, cb)
else
TheSim:ErasePersistentString(name, callback)
end
end
function Print( msg_verbosity, ... )
if msg_verbosity <= VERBOSITY_LEVEL then
print( ... )
end
end
function SecondsToTimeString( total_seconds )
local minutes = math.floor(total_seconds / 60)
local seconds = math.floor(total_seconds - minutes*60)
if minutes > 0 then
return string.format("%d:%02d", minutes, seconds)
elseif seconds > 9 then
return string.format("%02d", seconds)
else
return string.format("%d", seconds)
end
end
---PREFABS AND ENTITY INSTANTIATION
function ShouldIgnoreResolve( filename, assettype )
if assettype == "INV_IMAGE" then
return true
end
if assettype == "MINIMAP_IMAGE" then
return true
end
if filename:find(".dyn") and assettype == "PKGREF" then
return true
end
if TheNet:IsDedicated() then
if assettype == "SOUNDPACKAGE" then
return true
end
if assettype == "SOUND" then
return true
end
if filename:find(".ogv") then
return true
end
if filename:find(".fev") and assettype == "PKGREF" then
return true
end
if filename:find("fsb") then
return true
end
end
return false
end
local modprefabinitfns = {}
function RegisterPrefabsImpl(prefab, resolve_fn)
--print ("Register " .. tostring(prefab))
-- allow mod-relative asset paths
for i,asset in ipairs(prefab.assets) do
if not ShouldIgnoreResolve(asset.file, asset.type) then
resolve_fn(prefab, asset)
end
end
modprefabinitfns[prefab.name] = ModManager:GetPostInitFns("PrefabPostInit", prefab.name)
Prefabs[prefab.name] = prefab
TheSim:RegisterPrefab(prefab.name, prefab.assets, prefab.deps)
end
local function RegisterPrefabsResolveAssets(prefab, asset)
--print(" - - RegisterPrefabsResolveAssets: " .. asset.file, debugstack())
local resolvedpath = resolvefilepath(asset.file, prefab.force_path_search, prefab.search_asset_first_path)
assert(resolvedpath, "Could not find "..asset.file.." required by "..prefab.name)
TheSim:OnAssetPathResolve(asset.file, resolvedpath)
asset.file = resolvedpath
end
local function VerifyPrefabAssetExistsAsync(prefab, asset)
-- this is being done to prime the HDD's file cache and ensure all the assets exist before going into game
--TheSim:VerifyFileExistsAsync(asset.file)
TheSim:AddBatchVerifyFileExists(asset.file)
end
function RegisterPrefabs(...)
for i, prefab in ipairs({...}) do
RegisterPrefabsImpl(prefab, RegisterPrefabsResolveAssets)
end
end
function RegisterSinglePrefab(prefab)
RegisterPrefabsImpl(prefab, RegisterPrefabsResolveAssets)
end
PREFABDEFINITIONS = {}
function LoadPrefabFile( filename, async_batch_validation, search_asset_first_path )
--not is used as cast to boolean
--this check ensures that both values are not defined, while still allowing both to be undefined.
assert(not async_batch_validation or not search_asset_first_path, "search_asset_first_path and async_batch_validation cannot both be defined")
--print("Loading prefab file "..filename)
local fn, r = loadfile(filename)
assert(fn, "Could not load file ".. filename)
if type(fn) == "string" then
local error_msg = "Error loading file "..filename.."\n"..fn
if DEBUG_MODE then
-- Common error in development when working in a branch (we don't
-- submit updateprefab changes in branches).
print(error_msg)
known_assert(false, "DEV_FAILED_TO_LOAD_PREFAB")
end
assert(false, error_msg)
end
assert( type(fn) == "function", "Prefab file doesn't return a callable chunk: "..filename)
local ret = {fn()}
if ret then
for i,val in ipairs(ret) do
if type(val)=="table" and val.is_a and val:is_a(Prefab) then
val.search_asset_first_path = search_asset_first_path
if async_batch_validation then
RegisterPrefabsImpl(val, VerifyPrefabAssetExistsAsync)
else
RegisterSinglePrefab(val)
end
PREFABDEFINITIONS[val.name] = val
end
end
end
return ret
end
local MOD_FRONTEND_PREFABS = {}
function ModUnloadFrontEndAssets(modname)
if modname == nil then
TheSim:UnloadPrefabs(MOD_FRONTEND_PREFABS)
TheSim:UnregisterPrefabs(MOD_FRONTEND_PREFABS)
MOD_FRONTEND_PREFABS = {}
else
local prefab = {table.removearrayvalue(MOD_FRONTEND_PREFABS, "MODFRONTEND_"..modname)}
if not IsTableEmpty(prefab) then
TheSim:UnloadPrefabs(prefab)
TheSim:UnregisterPrefabs(prefab)
end
end
end
function ModReloadFrontEndAssets(assets, modname)
assert(KnownModIndex:DoesModExistAnyVersion(modname), "modname "..modname.." must refer to a valid mod!")
if assets then
ModUnloadFrontEndAssets(modname)
assets = shallowcopy(assets) --make a copy so that changes to the table in the mod code don't do anything funky
for i, v in ipairs(assets) do
local modroot = MODS_ROOT..modname.."/"
resolvefilepath_soft(v.file, nil, modroot)
end
local prefab = Prefab("MODFRONTEND_"..modname, nil, assets, nil)
table.insert(MOD_FRONTEND_PREFABS, prefab.name)
RegisterSinglePrefab(prefab)
TheSim:LoadPrefabs({prefab.name})
end
end
local MOD_PRELOAD_PREFABS = {}
function ModUnloadPreloadAssets(modname)
if modname == nil then
TheSim:UnloadPrefabs(MOD_PRELOAD_PREFABS)
TheSim:UnregisterPrefabs(MOD_PRELOAD_PREFABS)
MOD_PRELOAD_PREFABS = {}
else
local prefab = {table.removearrayvalue(MOD_PRELOAD_PREFABS, "MODPRELOAD_"..modname)}
if not IsTableEmpty(prefab) then
TheSim:UnloadPrefabs(prefab)
TheSim:UnregisterPrefabs(prefab)
end
end
end
function ModPreloadAssets(assets, modname)
assert(KnownModIndex:DoesModExistAnyVersion(modname), "modname "..modname.." must refer to a valid mod!")
if assets then
ModUnloadPreloadAssets(modname)
assets = shallowcopy(assets) --make a copy so that changes to the table in the mod code don't do anything funky
for i, v in ipairs(assets) do
local modroot = MODS_ROOT..modname.."/"
resolvefilepath_soft(v.file, nil, modroot)
end
local prefab = Prefab("MODPRELOAD_"..modname, nil, assets, nil)
table.insert(MOD_PRELOAD_PREFABS, prefab.name)
RegisterSinglePrefab(prefab)
TheSim:LoadPrefabs({prefab.name})
end
end
function RegisterAchievements(achievements)
for i, achievement in ipairs(achievements) do
--print ("Registering achievement:", achievement.name, achievement.id.steam, achievement.id.psn)
TheGameService:RegisterAchievement(achievement.name, achievement.id.steam, achievement.id.psn)
end
end
function LoadAchievements( filename )
--print("Loading achievement file "..filename)
local fn, r = loadfile(filename)
assert(fn, "Could not load file ".. filename)
if type(fn) == "string" then
assert(false, "Error loading file "..filename.."\n"..fn)
end
assert( type(fn) == "function", "Achievements file doesn't return a callable chunk: "..filename)
local ret = {fn()}
if ret then
for i,val in ipairs(ret) do
if type(val)=="table" then --and val.is_a and val:is_a(Achievements)then
RegisterAchievements(val)
end
end
end
return ret
end
function AwardFrontendAchievement( name )
if IsConsole() then
TheGameService:AwardAchievement(name, nil)
end
end
function AwardPlayerAchievement( name, player )
if IsConsole() then
if player ~= nil and player:HasTag("player") then
TheGameService:AwardAchievement(name, tostring(player.userid))
else
print( "AwardPlayerAchievement Error:", name, "to", tostring(player) )
end
end
end
function NotifyPlayerProgress( name, value, player )
if IsConsole() then
if player ~= nil and player:HasTag("player") then
TheGameService:NotifyProgress(name, value, tostring(player.userid))
else
print( "NotifyPlayerProgress Error:", name, "to", tostring(player) )
end
end
end
function NotifyPlayerPresence( name, level, days, player )
if IsConsole() then
if player ~= nil and player:HasTag("player") then
TheGameService:NotifyPresence(name, level, days, tostring(player.userid))
else
TheGameService:NotifyPresence(name, level, days, nil)
end
end
end
function AwardRadialAchievement( name, pos, radius )
if IsConsole() then
local players = FindPlayersInRange( pos.x, pos.y, pos.z, radius, true )
for k,player in pairs(players) do
AwardPlayerAchievement(name, player)
end
end
end
function SpawnPrefabFromSim(name)
name = string.sub(name, string.find(name, "[^/]*$"))
name = string.lower(name)
local prefab = Prefabs[name]
if prefab == nil then
print( "Can't find prefab " .. tostring(name) )
return -1
end
if prefab then
local inst = prefab.fn(TheSim)
if inst ~= nil then
inst:SetPrefabName(inst.prefab or name)
local modfns = modprefabinitfns[inst.prefab or name]
if modfns ~= nil then
for k,mod in pairs(modfns) do
mod(inst)
end
end
if inst.prefab ~= name then
modfns = modprefabinitfns[name]
if modfns ~= nil then
for k,mod in pairs(modfns) do
mod(inst)
end
end
end
for k,prefabpostinitany in pairs(ModManager:GetPostInitFns("PrefabPostInitAny")) do
prefabpostinitany(inst)
end
if TheWorld then
TheWorld:PushEvent("entity_spawned", inst)
end
return inst.entity:GetGUID()
else
print( "Failed to spawn", name )
return -1
end
end
end
function PrefabExists(name)
return Prefabs[name] ~= nil
end
function SpawnPrefab(name, skin, skin_id, creator)
name = string.sub(name, string.find(name, "[^/]*$"))
if skin and not IsItemId(skin) then
print("Unknown skin", skin)
skin = nil
end
local guid = TheSim:SpawnPrefab(name, skin, skin_id, creator)
return Ents[guid]
end
function ReplacePrefab(original_inst, name, skin, skin_id, creator)
local x,y,z = original_inst.Transform:GetWorldPosition()
local replacement_inst = SpawnPrefab(name, skin, skin_id, creator)
replacement_inst.Transform:SetPosition(x,y,z)
original_inst:Remove()
return replacement_inst
end
local function ResolveSaveRecordPosition(data)
if data.puid ~= nil then
local walkableplatformmanager = TheWorld.components.walkableplatformmanager
if walkableplatformmanager ~= nil then
local platform = walkableplatformmanager:GetPlatformWithUID(data.puid)
if platform ~= nil then
local x, y, z = platform.entity:LocalToWorldSpace(data.rx or 0, data.ry or 0, data.rz or 0)
return x, y, z, platform
end
end
end
return data.x or 0, data.y or 0, data.z or 0
end
function SpawnSaveRecord(saved, newents)
--print(string.format("~~~~~~~~~~~~~~~~~~~~~SpawnSaveRecord [%s, %s, %s]", tostring(saved.id), tostring(saved.prefab), tostring(saved.data)))
local inst = SpawnPrefab(saved.prefab, saved.skinname, saved.skin_id)
if inst then
if saved.alt_skin_ids then
inst.alt_skin_ids = saved.alt_skin_ids
end
local x, y, z, platform = ResolveSaveRecordPosition(saved)
inst.Transform:SetPosition(x, y, z)
if not inst.entity:IsValid() then
--print(string.format("SpawnSaveRecord [%s, %s] FAILED - entity invalid", tostring(saved.id), saved.prefab))
return nil
elseif saved.is_snapshot_save_record then
--V2C: We won't properly attach to platforms when restoring snapshot save records.
-- ie. inst:GetCurrentPlatform() will likely return nil
-- Workaround for passing our platform over to the GetSaveRecord()
inst._snapshot_platform = platform
end
if newents then
--this is kind of weird, but we can't use non-saved ids because they might collide
if saved.id then
newents[saved.id] = {entity=inst, data=saved.data}
else
newents[inst] = {entity=inst, data=saved.data}
end
end
-- Attach scenario. This is a special component that's added based on save data, not prefab setup.
if saved.scenario or (saved.data and saved.data.scenariorunner) then
if inst.components.scenariorunner == nil then
inst:AddComponent("scenariorunner")
end
if saved.scenario then
inst.components.scenariorunner:SetScript(saved.scenario)
end
end
inst:SetPersistData(saved.data, newents)
else
print(string.format("SpawnSaveRecord [%s, %s] FAILED", tostring(saved.id), saved.prefab))
end
return inst
end
function CreateEntity(name)
local ent = TheSim:CreateEntity()
local guid = ent:GetGUID()
local scr = EntityScript(ent)
if name ~= nil then
scr.name = name
end
Ents[guid] = scr
NumEnts = NumEnts + 1
return scr
end
local debug_entity = nil
local debug_table = nil
function OnRemoveEntity(entityguid)
PhysicsCollisionCallbacks[entityguid] = nil
local ent = Ents[entityguid]
if ent then
if debug_entity == ent then
debug_entity = nil
end
BrainManager:OnRemoveEntity(ent)
SGManager:OnRemoveEntity(ent)
ent:KillTasks()
NumEnts = NumEnts - 1
Ents[entityguid] = nil
if UpdatingEnts[entityguid] then
UpdatingEnts[entityguid] = nil
num_updating_ents = num_updating_ents - 1
end
if StaticUpdatingEnts[entityguid] then
StaticUpdatingEnts[entityguid] = nil
end
if WallUpdatingEnts[entityguid] then
WallUpdatingEnts[entityguid] = nil
end
end
end
function RemoveEntity(guid)
local inst = Ents[guid]
if inst then
--certain things(like seamless player swapping) need to delay the despawning on a local client until they have ran their own code.
if inst.delayclientdespawn then
inst.delayclientdespawn_attempted = true
return
end
inst:Remove()
end
end
function PushEntityEvent(guid, event, data)
local inst = Ents[guid]
if inst then
inst:PushEvent(event, data)
end
end
function GetEntityDisplayName(guid)
local inst = Ents[guid]
return inst ~= nil and inst:GetDisplayName() or ""
end
------TIME FUNCTIONS
function GetTickTime()
return TheSim:GetTickTime()
end
local ticktime = GetTickTime()
function GetTime()
return TheSim:GetTick()*ticktime
end
function GetStaticTime()
return TheSim:GetStaticTick()*ticktime
end
function GetTick()
return TheSim:GetTick()
end
function GetStaticTick()
return TheSim:GetStaticTick()
end
function GetTimeReal()
return TheSim:GetRealTime()
end
function GetTimeRealSeconds()
return TheSim:GetRealTime() / 1000
end
---SCRIPTING
local Scripts = {}
function LoadScript(filename)
if not Scripts[filename] then
local scriptfn = loadfile("scripts/" .. filename)
assert(type(scriptfn) == "function", scriptfn)
Scripts[filename] = scriptfn()
end
return Scripts[filename]
end
function RunScript(filename)
local fn = LoadScript(filename)
if fn then
fn()
end
end
function GetEntityString(guid)
local ent = Ents[guid]
if ent then
return ent:GetDebugString()
end
return ""
end
function GetExtendedDebugString()
if debug_entity and debug_entity.brain then
return debug_entity:GetBrainString()
elseif SOUNDDEBUG_ENABLED then
return GetSoundDebugString(), 24
elseif WORLDSTATEDEBUG_ENABLED then
return TheWorld and TheWorld.components.worldstate and TheWorld.components.worldstate:Dump()
end
if TheFrontEnd and TheFrontEnd:GetActiveScreen() then
return "Current screen:" .. TheFrontEnd:GetActiveScreen().name
end
return ""
end
function GetDebugString()
local str = {}
table.insert(str, tostring(scheduler))
if debug_entity then
table.insert(str, "\n-------DEBUG-ENTITY-----------------------\n")
table.insert(str, debug_entity.GetDebugString and debug_entity:GetDebugString() or "<no debug string>")
end
return table.concat(str)
end
function GetDebugEntity()
return debug_entity
end
function SetDebugEntity(inst)
if debug_entity ~= nil and debug_entity:IsValid() then
debug_entity.entity:SetSelected(false)
end
if inst ~= nil and inst:IsValid() then
debug_entity = inst
inst.entity:SetSelected(true)
else
debug_entity = nil
end
end
function GetDebugTable()
return debug_table
end
function SetDebugTable(tbl)
debug_table = tbl
end
function OnEntitySleep(guid)
local inst = Ents[guid]
if inst then
inst:PushEvent("entitysleep")
if inst.OnEntitySleep then
inst:OnEntitySleep()
end
inst:StopBrain()
if inst.sg then
SGManager:Hibernate(inst.sg)
end
if inst.emitter then
EmitterManager:Hibernate(inst.emitter)
end
for k,v in pairs(inst.components) do
if v.OnEntitySleep then
v:OnEntitySleep()
end
end
end
end
function OnEntityWake(guid)
local inst = Ents[guid]
if inst then
inst:PushEvent("entitywake")
if inst.OnEntityWake then
inst:OnEntityWake()
end
--V2C: Note that if this needs to work properly for networked
-- entities on clients, then should use the slower check
-- :HasTag("INLIMBO"). But there should be no networked
-- entities on clients that can go to sleep.
if not inst:IsInLimbo() then
inst:RestartBrain()
if inst.sg then
SGManager:Wake(inst.sg)
end
end
if inst.emitter then
EmitterManager:Wake(inst.emitter)
end
for k,v in pairs(inst.components) do
if v.OnEntityWake then
v:OnEntityWake()
end
end
end
end
function OnPhysicsWake(guid)
local inst = Ents[guid]
if inst then
if inst.OnPhysicsWake then
inst:OnPhysicsWake()
end
for k, v in pairs(inst.components) do
if v.OnPhysicsWake then
v:OnPhysicsWake()
end
end
end
end
function OnPhysicsSleep(guid)
local inst = Ents[guid]
if inst then
if inst.OnPhysicsSleep then
inst:OnPhysicsSleep()
end
for k,v in pairs(inst.components) do
if v.OnPhysicsSleep then
v:OnPhysicsSleep()
end
end
end
end
local Paused = false
local Autopaused = false
local GameAutopaused = false
function OnServerPauseDirty(pause, autopause, gameautopause, source)
--autopause means we are paused but we don't act like it,
--this would be for stuff like autpausing from the map being open.
--gameautopause means we are paused, but we really don't act like it, like not even acknowledge it at all.
--this only occurs when a non dedicated server has all players in the lobby.
--gameautopause has no information text, at the top of the screen, and doesn't push the sound mix that deafens the game.
local WasPaused = Paused or Autopaused or GameAutopaused
local IsPaused = pause or autopause or gameautopause
local WasNormalPaused = (Paused or Autopaused) and not GameAutopaused
local IsNormalPaused = (pause or autopause) and not gameautopause
if WasPaused and not IsPaused then
print("Server Unpaused")
elseif not Paused and pause then
print("Server Paused")
elseif (autopause or gameautopause) and not pause then
print("Server Autopaused")
end
Paused = pause
Autopaused = autopause
GameAutopaused = gameautopause
if not WasNormalPaused and IsNormalPaused then
TheMixer:PushMix("serverpause")
elseif not IsNormalPaused then
TheMixer:DeleteMix("serverpause")
end
if ThePlayer and ThePlayer.HUD then
ThePlayer.HUD:SetServerPaused(pause)
end
if TheFrontEnd then
TheFrontEnd:SetServerPauseText(pause and source or autopause and "autopause" or nil)
end
if TheWorld then
TheWorld:PushEvent("serverpauseddirty", {pause = pause, autopause = autopause, gameautopause = gameautopause, source = source})
end
end
function ReplicateEntity(guid)
local inst = Ents[guid]
local _ThePlayer
if inst.isseamlessswaptarget then
_ThePlayer = ThePlayer
ThePlayer = inst
end
inst:ReplicateEntity()
if _ThePlayer then
ThePlayer = _ThePlayer
end
end
function DisableLoadingProtection(guid)
local player = Ents[guid]
if player then
player:DisableLoadingProtection()
end
end
------------------------------
function PlayNIS(nisname, lines)
local nis = require ("nis/"..nisname)
local inst = CreateEntity()
inst:AddComponent("nis")
inst.components.nis:SetName(nisname)
inst.components.nis:SetInit(nis.init)
inst.components.nis:SetScript(nis.script)
inst.components.nis:SetCancel(nis.cancel)
inst.entity:CallPrefabConstructionComplete()
inst.components.nis:Play(lines)
return inst
end
local paused = false
local simpaused = false
local default_time_scale = 1
function IsPaused()
return paused
end
function IsSimPaused()
return simpaused
end
global("PlayerPauseCheck") -- function not defined when this file included
function SetDefaultTimeScale(scale)
default_time_scale = scale
if not paused then
TheSim:SetTimeScale(default_time_scale)
end
end
---------------------------------------------------------------------
--V2C: We don't use this in DST
function SetSimPause(val)
simpaused = val
end
function SetServerPaused(pause)
-- Ignore if an imgui window is open & has focus
if CAN_USE_DBUI then
if TheFrontEnd:IsImGuiWindowFocused() then
return
end
end
if pause == nil then pause = not TheNet:IsServerPaused(true) end
TheNet:SetServerPaused(pause)
end
local autopausecount = 0
function SetAutopaused(autopause)
autopausecount = autopausecount + (autopause and 1 or -1)
if DEBUG_MODE and autopausecount < 0 or autopausecount > 5 then
print("ERROR: autopausecount is invalid:", autopausecount)
assert(false)
end
DoAutopause()
end
local craftingautopause = false
function SetCraftingAutopaused(autopause)
craftingautopause = autopause
DoAutopause()
end
local consoleautopausecount = 0
function SetConsoleAutopaused(autopause)
consoleautopausecount = consoleautopausecount + (autopause and 1 or -1)
DoAutopause()
end
function DoAutopause()
TheNet:SetAutopaused(
((autopausecount > 0 and Profile:GetAutopauseEnabled())
or (craftingautopause and Profile:GetCraftingAutopauseEnabled())
or (consoleautopausecount > 0 and Profile:GetConsoleAutopauseEnabled())
) and not TheFrontEnd:IsControlsDisabled()
)
end
---------------------------------------------------------------------
--V2C: DST sim pauses via network checks, and will notify LUA here
function OnSimPaused()
--Probably shouldn't do anything here, since sim is now paused
--and most likely anything triggered here won't actually work.
end
function OnSimUnpaused()
if TheWorld ~= nil then
TheWorld:PushEvent("ms_simunpaused")
end
end
---------------------------------------------------------------------
function SetPause(val,reason)
if val ~= paused then
if val then
paused = true
TheMixer:PushMix("pause")
else
paused = false
TheMixer:PopMix("pause")
end
end
if PlayerPauseCheck then -- probably don't need this check
PlayerPauseCheck(val, reason) -- must be done after SetTimeScale
end
end
--- EXTERNALLY SET GAME SETTINGS ---
Settings = {}
function SetInstanceParameters(settings)
if settings ~= "" then
--print("SetInstanceParameters:",settings)
Settings = json.decode(settings)
end
end
Purchases = {}
function SetPurchases(purchases)
if purchases ~= "" then
Purchases = json.decode(purchases)
end
end
local function UpdateWorldGenOverride(overrides, cb, slot, shard)
local Levels = require("map/levels")
local filename = "../worldgenoverride.lua"
local function SetPersistentString(str)
if shard ~= nil then
TheSim:SetPersistentStringInClusterSlot(slot, shard, filename, str, false, cb)
else
TheSim:SetPersistentString(filename, str, false, cb)
end
end
local function GenerateWorldGenOverride(savedata)
local out = {}
table.insert(out, "return {")
table.insert(out, "\toverride_enabled = true,")
local worldgen_preset = savedata.worldgen_preset or savedata.preset
if worldgen_preset and Levels.GetDataForWorldGenID(worldgen_preset) then
table.insert(out, string.format("\tworldgen_preset = %q,", worldgen_preset))
end
local settings_preset = savedata.settings_preset or savedata.preset
if settings_preset and Levels.GetDataForWorldGenID(settings_preset) then
table.insert(out, string.format("\tsettings_preset = %q,", settings_preset))
end
table.insert(out, "\toverrides = {")
for name, value in orderedPairs(savedata.overrides) do
if not name:match('^[_%a][_%w]*$') then
name = string.format("[%q]", name)
end
if type(value) == "string" then
value = string.format("%q", value)
else
value = tostring(value)
end
table.insert(out, string.format("\t\t%s = %s,", name, value))
end
table.insert(out, "\t},")
table.insert(out, "}")
SetPersistentString(table.concat(out, "\n"))
end
local function onload(load_success, str)
if load_success == true then
local success, savedata = RunInSandboxSafe(str)
if success and savedata then
local savefileupgrades = require("savefileupgrades")
savedata = savefileupgrades.utilities.UpgradeWorldgenoverrideFromV1toV2(savedata)
if savedata.override_enabled then
local worldgen_preset = savedata.worldgen_preset or savedata.preset
local worldgen_presetdata = {overrides = {}}
if worldgen_preset then
worldgen_presetdata = Levels.GetDataForWorldGenID(worldgen_preset) or worldgen_presetdata
end
local settings_preset = savedata.settings_preset or savedata.preset
local settings_presetdata = {overrides = {}}
if settings_preset then
settings_presetdata = Levels.GetDataForSettingsID(settings_preset) or settings_presetdata