-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdreamMount_functions.lua
1807 lines (1476 loc) · 64 KB
/
dreamMount_functions.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
-- STL Functions
local Concat = table.concat
local Format = string.format
local Traceback = debug.traceback
local Uppercase = string.upper
-- TES3MP Functions
local AddBodyPartRecord = packetBuilder.AddBodyPartRecord
local AddClothingRecord = packetBuilder.AddClothingRecord
local AddContainerItem = tes3mp.AddContainerItem
local AddContainerRecord = packetBuilder.AddContainerRecord
local AddCreatureRecord = packetBuilder.AddCreatureRecord
local AddItem = inventoryHelper.addItem
local AddObject = tes3mp.AddObject
local AddRecordTypeToPacket = packetBuilder.AddRecordByType
local BuildObjectData = dataTableBuilder.BuildObjectData
local ClearObjectList = tes3mp.ClearObjectList
local ClearRecords = tes3mp.ClearRecords
local ContainsItem = inventoryHelper.containsItem
local CreateObjectAtPlayer = logicHandler.CreateObjectAtPlayer
local DeleteObjectForEveryone = logicHandler.DeleteObjectForEveryone
local EventStatus = customEventHooks.makeEventStatus
local GetActorCell = tes3mp.GetActorCell
local GetActorListSize = tes3mp.GetActorListSize
local GetActorMpNum = tes3mp.GetActorMpNum
local GetActorRefNum = tes3mp.GetActorRefNum
local GetCell = tes3mp.GetCell
local GetInventoryChangesAction = tes3mp.GetInventoryChangesAction
local GetInventoryChangesSize = tes3mp.GetInventoryChangesSize
local GetInventoryItemCount = tes3mp.GetInventoryItemCount
local GetInventoryItemRefId = tes3mp.GetInventoryItemRefId
local GetItemIndex = inventoryHelper.getItemIndex
local GetPosX = tes3mp.GetPosX
local GetPosY = tes3mp.GetPosY
local ListBox = tes3mp.ListBox
local Load = jsonInterface.load
local MessageBox = tes3mp.MessageBox
local ProcessCommand = commandHandler.ProcessCommand
local ReadReceivedActorList = tes3mp.ReadReceivedActorList
local RemoveClosestItem = inventoryHelper.removeClosestItem
local RunConsoleCommandOnObject = logicHandler.RunConsoleCommandOnObject
local RunConsoleCommandOnPlayer = logicHandler.RunConsoleCommandOnPlayer
local Save = jsonInterface.quicksave
local SendBaseInfo = tes3mp.SendBaseInfo
local SendConsoleCommand = tes3mp.SendConsoleCommand
local SendContainer = tes3mp.SendContainer
local SendMessage = tes3mp.SendMessage
local SendObjectActivate = tes3mp.SendObjectActivate
local SendObjectPlace = tes3mp.SendObjectPlace
local SendObjectScale = tes3mp.SendObjectScale
local SendRecordDynamic = tes3mp.SendRecordDynamic
local SetAIForActor = logicHandler.SetAIForActor
local SetContainerItemCharge = tes3mp.SetContainerItemCharge
local SetContainerItemCount = tes3mp.SetContainerItemCount
local SetContainerItemEnchantmentCharge = tes3mp.SetContainerItemEnchantmentCharge
local SetContainerItemRefId = tes3mp.SetContainerItemRefId
local SetContainerItemSoul = tes3mp.SetContainerItemSoul
local SetCurrentMpNum = tes3mp.SetCurrentMpNum
local SetModel = tes3mp.SetModel
local SetObjectActivatingPid = tes3mp.SetObjectActivatingPid
local SetObjectListAction = tes3mp.SetObjectListAction
local SetObjectListCell = tes3mp.SetObjectListCell
local SetObjectListConsoleCommand = tes3mp.SetObjectListConsoleCommand
local SetObjectListPid = tes3mp.SetObjectListPid
local SetObjectMpNum = tes3mp.SetObjectMpNum
local SetObjectPosition = tes3mp.SetObjectPosition
local SetObjectRefId = tes3mp.SetObjectRefId
local SetObjectRefNum = tes3mp.SetObjectRefNum
local SetObjectRotation = tes3mp.SetObjectRotation
local SetObjectScale = tes3mp.SetObjectScale
local SetPlayerAsObject = tes3mp.SetPlayerAsObject
local SetRecordType = tes3mp.SetRecordType
local SlowSave = jsonInterface.save
local TablePrint = tableHelper.print
--TES3MP Globals
local AddToInventory = enumerations.inventory.ADD
local AIFollow = enumerations.ai.FOLLOW
local BarterDialogue = enumerations.dialogueChoice.BARTER
local BodyPartRecord = enumerations.recordType.BODYPART
local ClothingRecord = enumerations.recordType.CLOTHING
local ContainerRecordType = enumerations.recordType.CONTAINER
local ContainerSet = enumerations.container.SET
local CreatureRecordType = enumerations.recordType.CREATURE
local EquipEnums = enumerations.equipment
local FortifyAttribute = enumerations.effects.FORTIFY_ATTRIBUTE
local LoadedCells = LoadedCells
local RecordStores = RecordStores
local RemoveFromInventory = enumerations.inventory.REMOVE
local RestoreFatigue = enumerations.effects.RESTORE_FATIGUE
local Players = Players
local MiscRecordType = enumerations.recordType.MISCELLANEOUS
local SpellRecordType = enumerations.recordType.SPELL
-- Local Constants
local DreamMountStrings = require('custom.dreamMount.dreamMount_strings')
local DreamMountDefaults = require('custom.dreamMount.dreamMount_defaultConfig')
--- Since mwscripts are not reloadable clientside,
--- we won't bother to make them reloadable on the backend either
local MWScripts = require('custom.dreamMount.dreamMount_mwscripts')
local DreamMountAdminRankRequired = 2
local DreamMountsGUIID = 381342
local DreamMountsMountActivateGUIID = 381343
---@enum MountType
local MountTypes = {
Gauntlet = 0,
Shirt = 1,
}
---@enum EquipEnum
local MountSlotMap = {
[MountTypes.Gauntlet] = 'LEFT_GAUNTLET',
[MountTypes.Shirt] = 'SHIRT',
}
-- We don't currently use armor types, but we might later and
-- I don't feel like drawing the enums out again
---@diagnostic disable-next-line: unused-local
local ArmorTypes = {
Helmet = 0,
Cuirass = 1,
LPauldron = 2,
RPauldron = 3,
Greaves = 4,
Boots = 5,
LGauntlet = 6,
RGauntlet = 7,
Shield = 8,
LBracer = 9,
RBracer = 10,
LENGTH = 11,
}
local DefaultKeyName = "Reins"
-- CustomVariables index keys
local DreamMountVarTable = 'dreamMountVars'
local DreamMountEnabledKey = 'isMounted'
local DreamMountPreferredMountKey = 'preferredMount'
local DreamMountPrevItemId = 'previousItemId'
local DreamMountPrevMountTypeKey = 'previousMountType'
local DreamMountPrevSpellId = 'previousSpellId'
local DreamMountPrevAuraId = 'previousAuraId'
local DreamMountSummonRefNumKey = 'summonRefNum'
local DreamMountSummonCellKey = 'summonCellDescription'
local DreamMountSummonWasEnabledKey = 'hadMountSummon'
local DreamMountCurrentSummonsKey = 'summonsTable'
local DreamMountSummonInventoryDataKey = 'dreamMountSummonInventories'
--- Populated during DreamMountFunctions:createKeyRecords
---@type table <string, boolean>
local KeyRecords = {}
---@alias MountIndex integer
local KeyItemTemplate = {
value = 3000,
icon = "c/tx_belt_common01.tga",
model = "c/c_belt_common_1.nif",
weight = 0.0,
}
---@class DreamMountFunctions
---@field mountRefs table <string, string> Stores a map of mount refNums to their owners for the purpose of UI messages
local DreamMountFunctions = {
mountConfig = {},
mountMerchants = {},
mountParts = {},
mountClothing = {},
mountRefs = {},
}
local function mountLog(message)
print(Format(DreamMountStrings.Patterns.LogStr, DreamMountStrings.Log.LogPrefix, message))
end
local function getKeyTemplate(mountData)
local newKey = {}
for k, v in pairs(KeyItemTemplate) do rawset(newKey, k, v) end
for k, v in pairs(mountData.key or {}) do rawset(newKey, k, v) end
if not newKey.name then
rawset(newKey, 'name', Format("%s %s", mountData.name, DefaultKeyName))
end
return newKey
end
local function getFilePath(model)
return Format(DreamMountStrings.Paths.AnimRigPath, model)
end
local function actorPacketUniqueIndex(actorIndex)
return Format("%s-%s", GetActorRefNum(actorIndex), GetActorMpNum(actorIndex))
end
local function round(number)
return math.floor(number + 0.5)
end
local function addOrRemoveItem(addOrRemove, mount, player)
local inventory = player.data.inventory
local hasMountAlready = ContainsItem(inventory, mount)
if addOrRemove == hasMountAlready then return end
(addOrRemove and AddItem or RemoveClosestItem)(inventory, mount, 1)
player:LoadItemChanges ({{ refId = mount, count = 1, }}, (addOrRemove and AddToInventory or RemoveFromInventory))
end
local function enableModelOverrideMount(player, characterData, mountModel)
characterData.modelOverride = getFilePath(mountModel)
player:LoadCharacter()
end
local function canRunMountAdminCommands(player)
return player.data.settings.staffRank >= DreamMountAdminRankRequired
end
local function getMountKeyString(mountData)
return Format("%s_%s", mountData.name, mountData.keyName or DefaultKeyName):lower()
end
local function assertPidProvided(pid)
assert(pid, Format(DreamMountStrings.Err.NoPidProvided, Traceback(3)))
end
local function unauthorizedUserMessage(pid)
assertPidProvided(pid)
SendMessage(pid, DreamMountStrings.UI.UnauthorizedUserMessage, false)
end
---@param player JSONPlayer
--- Uses the TM command to forcefully close any open menus once
--- Then invoke it a second time to restore the HUD
local function CloseMenu(player)
local pid = player.pid
ClearObjectList()
SetObjectListPid(pid)
SetObjectListCell(player.data.location.cell)
SetObjectListConsoleCommand("TM")
SetPlayerAsObject(pid)
AddObject()
for _ = 1, 2 do
table.insert(player.consoleCommandsQueued, "TM")
SendConsoleCommand(false)
end
end
---@param player JSONPlayer
---@return table
local function getPlayerMountVars(player)
assert(player and player:IsLoggedIn(), DreamMountStrings.Err.UnloggedPlayerSummonErr .. Traceback(3))
local customVariables = player.data.customVariables
if not customVariables[DreamMountVarTable] then customVariables[DreamMountVarTable] = {} end
return customVariables[DreamMountVarTable]
end
local function dismountIfMounted(player)
if getPlayerMountVars(player)[DreamMountEnabledKey] then
DreamMountFunctions:toggleMount(player)
end
end
--- Returns whether the player has the necessary key for their mount,
--- Or emits a warning message to them if they do not.
--- NOTE: ContainsItem only works with handlers, since validators won't have taken the inventory changes into account yet
--- So DON'T try to use this on the inventory validators like you were just thinking about doing
---@param player JSONPlayer
---@return true|nil ContainsItem True if the player has the item, nil if the message is emitted due to short circuiting
local function hasMountKey(player)
local mountData = DreamMountFunctions:getMountData(player)
local keyId = getMountKeyString(mountData)
return ContainsItem(player.data.inventory, keyId) or player:Message(DreamMountStrings.UI.MissingMountKey)
end
local function buildSpellEffectString(mountSpellRecordId, mountSpell)
local parts = {
mountSpellRecordId,
':\n----------'
}
for _, spellEffect in ipairs(mountSpell.effects) do
parts[#parts + 1] = '\n'
for k, v in pairs(spellEffect) do
parts[#parts + 1] = Format('%s: %s ', k, v)
end
parts[#parts + 1] = '\n----------'
end
return Concat(parts)
end
local AttributeNames = {
STRENGTH = 0,
INTELLIGENCE = 1,
WILLPOWER = 2,
AGILITY = 3,
SPEED = 4,
ENDURANCE = 5,
PERSONALITY = 6,
LUCK = 7,
}
local Effects = {
FortifyAttribute = function(attributeId, magnitudeMin, magnitudeMax)
assert(attributeId >= 0 and attributeId <= 7, Format(DreamMountStrings.Err.ImpossibleAttributeIDErr, attributeId))
assert(magnitudeMin, DreamMountStrings.Err.InvalidSpellEffectErrorStr .. Traceback(3))
return {
attribute = attributeId,
id = FortifyAttribute,
rangeType = 0,
magnitudeMin = magnitudeMin,
magnitudeMax = magnitudeMax or magnitudeMin,
skill = -1,
}
end,
RestoreFatigue = function(magnitudeMin, magnitudeMax)
assert(magnitudeMin, DreamMountStrings.Err.InvalidSpellEffectErrorStr .. Traceback(3))
return {
id = RestoreFatigue,
rangeType = 0,
magnitudeMin = magnitudeMin,
magnitudeMax = magnitudeMax or magnitudeMin,
skill = -1,
}
end,
}
---@param mountData MountData
---@return string PetAuraId - Record Id of the pet aura
---@return string PetAuraName Human-readable name of the pet aura
local function getPetAuraStrings(mountData)
assert(mountData.name ~= nil and mountData.name ~= '', DreamMountStrings.Err.ImpossibleMountNameErr)
return Format("%s_aura", mountData.name):lower(), Format("%s Aura", mountData.name)
end
local function getMountActiveEffects(inputMountEffects)
local mountEffects = {}
for effectName, effectMagnitude in pairs(inputMountEffects or {}) do
local effectData
local attributeName = AttributeNames[Uppercase(effectName)]
local effectGenerator = Effects[effectName]
if attributeName then
effectData = Effects.FortifyAttribute(attributeName, effectMagnitude)
elseif effectGenerator then
effectData = effectGenerator(effectMagnitude)
else
error(Format("%s is not a supported effect name for mount active effects!", effectName))
end
mountEffects[#mountEffects + 1] = effectData
end
if #mountEffects > 0 then return mountEffects end
end
--- Enforces that either:
--- 1. If mounted, the player cannot remove the mount clothing item from their inventory
--- 2. If mounted or using a summon, removing the relevant key for the mount will unsummon it or disengage the mount as needed
---@param player JSONPlayer
---@param itemChangeIndex integer
---@param keyId string
---@param mountItemId string
---@return true|nil DisableOtherHandlers If true, indicates that EventStatus should return false for this call
local function correctMountStateOnInventory(player, itemChangeIndex, keyId, mountItemId)
local pid = player.pid
local itemId = GetInventoryItemRefId(pid, itemChangeIndex)
if not itemId then return end
if itemId == mountItemId then
CloseMenu(player)
return true
elseif itemId == keyId then
local inventory = player.data.inventory
local itemIndex = GetItemIndex(inventory, keyId)
local countRemoved = GetInventoryItemCount(pid, itemChangeIndex)
local originalCount = (itemIndex ~= nil and inventory[itemIndex].count) or 0
local countRemaining = originalCount - countRemoved
if itemIndex and countRemaining > 0 then return end
player:Message(DreamMountStrings.UI.DroppedMountWhileMounted)
dismountIfMounted(player)
DreamMountFunctions:despawnMountSummon(player)
end
end
function DreamMountFunctions.addMountSpellEffect(effects, spellId, spellName, permanentSpells)
local mountSpell = {
name = spellName,
effects = effects,
subtype = 1,
}
local spellString = buildSpellEffectString(spellId, mountSpell)
permanentSpells[spellId] = mountSpell
mountLog(Format(DreamMountStrings.Log.CreatedSpellRecordStr, spellString))
AddRecordTypeToPacket(spellId, mountSpell, 'spell')
end
function DreamMountFunctions:getMountData(player)
assert(player and player:IsLoggedIn(), Traceback(3))
local preferredMount = getPlayerMountVars(player)[DreamMountPreferredMountKey]
return self.mountConfig[preferredMount]
end
function DreamMountFunctions:despawnBagRef(player)
assert(player, DreamMountStrings.Err.DespawnNoPlayerErr .. Traceback(3))
local containerData = self:getCurrentContainerData(player)
if not containerData or not containerData.cell or not containerData.index then return end
local containerIndex = Concat(containerData.index, '-')
DeleteObjectForEveryone(containerData.cell, containerIndex)
containerData.cell = nil
containerData.index = nil
mountLog(Format(DreamMountStrings.Log.SuccessfulContainerDespawnStr,
self:getContainerRecordId(player),
containerIndex,
player.name))
player:QuicksaveToDrive()
end
function DreamMountFunctions:activateCurrentMountContainer(player)
local pid = player.pid
ClearObjectList()
SetObjectListPid(pid)
SetObjectListCell(GetCell(pid))
local containerData = self:getCurrentContainerData(player)
if not containerData then return end
local splitIndex = containerData.index
SetObjectRefNum(splitIndex[1])
SetObjectMpNum(splitIndex[2])
SetObjectActivatingPid(pid)
AddObject()
SendObjectActivate()
end
function DreamMountFunctions:updateCurrentMountContainer(player)
local containerData = self:getCurrentContainerData(player)
local containerId = self:getContainerRecordId(player)
if not containerData or not containerId then return end
local pid = player.pid
local playerCellId = GetCell(pid)
local playerCell = LoadedCells[playerCellId]
local cellObjectData = playerCell.data.objectData
local containerIndex = Concat(containerData.index, '-')
cellObjectData[containerIndex].inventory = containerData.inventory
ClearObjectList(pid)
SetObjectListPid(pid)
SetObjectListCell(playerCellId)
SetObjectRefNum(containerData.index[1])
SetObjectMpNum(containerData.index[2])
SetObjectRefId(containerId)
for _, item in ipairs(containerData.inventory) do
assert(item.refId and item.refId ~= '', DreamMountStrings.Err.ImpossibleRefidErr .. Traceback(3))
SetContainerItemRefId(item.refId)
SetContainerItemCount(item.count or 1)
SetContainerItemCharge(item.charge or -1)
SetContainerItemEnchantmentCharge(item.enchantmentCharge or -1)
SetContainerItemSoul(item.soul or '')
AddContainerItem()
end
AddObject()
SetObjectListAction(ContainerSet)
SendContainer(false, false)
end
local function toggleSpell(spell, player, spellRecords)
if not spellRecords then spellRecords = RecordStores['spell'].data.permanentRecords end
player:updateSpellbook {
[spell] = false,
}
if spellRecords[spell] then
player:updateSpellbook {
[spell] = true,
}
end
end
--- Destroys the player's summoned pet, if one exists.
--- This method also destroys the associated creature record, since current impl would
--- otherwide be really spammy.
---@param player JSONPlayer
function DreamMountFunctions:despawnMountSummon(player)
assert(player, DreamMountStrings.Err.DespawnNoPlayerErr .. Traceback(3))
local customVariables = getPlayerMountVars(player)
local summonRef = customVariables[DreamMountSummonRefNumKey]
local summonCell = customVariables[DreamMountSummonCellKey]
if not summonRef and not summonCell then return end
local preferredMount = customVariables[DreamMountPreferredMountKey]
local mountData = self.mountConfig[preferredMount]
if not mountData or not preferredMount then return end
local mountName = mountData.name
DeleteObjectForEveryone(summonCell, summonRef)
local petAura = customVariables[DreamMountPrevAuraId]
if petAura then
player:updateSpellbook {
[petAura] = false,
}
end
customVariables[DreamMountPrevAuraId] = nil
customVariables[DreamMountSummonRefNumKey] = nil
customVariables[DreamMountSummonCellKey] = nil
local currentSummons = customVariables[DreamMountCurrentSummonsKey]
if currentSummons and currentSummons[mountName] then
local summonToRemove = currentSummons[mountName]
mountLog(Format(DreamMountStrings.Log.RemovingRecordStr, summonToRemove, player.name))
local creatureRecordStore = RecordStores["creature"]
local creatureRecords = creatureRecordStore.data.permanentRecords
creatureRecords[summonToRemove] = nil
creatureRecordStore:Save()
currentSummons[mountName] = nil
end
player:QuicksaveToDrive()
if self.mountRefs[summonRef] then self.mountRefs[summonRef] = nil end
end
---@class ObjectDataTable
---@field pid PlayerId
---@field refId string Record id of the object to add to the list
---@field refNum number Reference number (generated by the server, probably) of the object to add to the list
---@field mpNum number Plugin origin of the object. Should always be 0?
---@field clear boolean whether or not to clear the object list and assign it to the player on this call
---@param objectDataTable ObjectDataTable
local function addObjectInPlayerCellToObjectList(objectDataTable)
local pid = objectDataTable.pid
if objectDataTable.clear then
ClearObjectList()
SetObjectListPid(pid)
SetObjectListCell(GetCell(pid))
end
SetObjectRefId(objectDataTable.refId)
SetObjectRefNum(objectDataTable.refNum)
SetObjectMpNum(objectDataTable.mpNum)
AddObject()
end
--- Assign creature attributes here instead of as record data
--- Because spells, skills, and attributes can't be set by custom records
local function sendCreatureAttributePacket(attributePacketData)
local Err = DreamMountStrings.Err
local player = attributePacketData.player
local playerPetData = attributePacketData.playerPetData
local petId = attributePacketData.petId
local playerQueuedCommands = player.consoleCommandsQueued
local summonSplitIndex = getPlayerMountVars(player)[DreamMountSummonRefNumKey]:split('-')
assert(summonSplitIndex, Err.MissingSummonRefNumErr)
local summonRefNum = summonSplitIndex[1]
local summonMpNum = summonSplitIndex[2]
---@type ObjectDataTable
local objectData = {
clear = true,
pid = player.pid,
refId = petId,
refNum = summonRefNum,
mpNum = summonMpNum,
}
local playerAttributes = player.data.attributes
for attributeName, attributeValue in pairs(playerPetData.attributes or {}) do
assert(AttributeNames[Uppercase(attributeName)],
Format(Err.ImpossibleAttributeNameErr,
attributeName,
Traceback(3)))
local finalValue = round(playerAttributes[attributeName].base * attributeValue)
local attributeSetter = Format("set%s %s", attributeName, finalValue)
addObjectInPlayerCellToObjectList(objectData)
SetObjectListConsoleCommand(attributeSetter)
playerQueuedCommands[#playerQueuedCommands + 1] = attributeSetter
SendConsoleCommand(true)
end
for _, spellName in ipairs(playerPetData.spells or {}) do
addObjectInPlayerCellToObjectList(objectData)
local addSpellCommand = Format("addspell %s", spellName)
SetObjectListConsoleCommand(addSpellCommand)
playerQueuedCommands[#playerQueuedCommands + 1] = addSpellCommand
SendConsoleCommand(true)
end
end
--- Place the appropriate summon at the player's location,
--- Enabling the follow routine when doing so
---@param player JSONPlayer
---@param summonId string generated recordId for the mount summon
function DreamMountFunctions:spawnMountSummon(player, summonId)
assert(player and player:IsLoggedIn(), DreamMountStrings.Err.UnloggedPlayerSummonErr)
local pid = player.pid
local playerCell = player.data.location.cell
local customVariables = getPlayerMountVars(player)
local summonIndex = CreateObjectAtPlayer(pid, BuildObjectData(summonId), "spawn")
SetAIForActor(LoadedCells[playerCell], summonIndex, AIFollow, pid)
customVariables[DreamMountSummonRefNumKey] = summonIndex
customVariables[DreamMountSummonCellKey] = playerCell
self.mountRefs[summonIndex] = player.name
player:QuicksaveToDrive()
end
--- Remove and if necessary, re-add the relevant mount buff for the player
--- Used when resetting the spell records, or custom variables
local function resetMountSpellForPlayer(player, spellRecords)
local prevMountSpell = getPlayerMountVars(player)[DreamMountPrevSpellId]
if not prevMountSpell then return end
toggleSpell(prevMountSpell, player, spellRecords)
end
local function resetSummonSpellForPlayer(player, mountData, spellRecords)
if not mountData then return end
local prevSummonSpell = getPetAuraStrings(mountData)
toggleSpell(prevSummonSpell, player, spellRecords)
end
--- Resets all DreamMount state for a given player
---@param player JSONPlayer
function DreamMountFunctions:clearCustomVariables(player)
-- De-summon summons
self:despawnMountSummon(player)
-- Dismount if necessary
dismountIfMounted(player)
self:despawnBagRef(player)
player.data.customVariables[DreamMountVarTable] = {}
player:QuicksaveToDrive()
end
local function clearCustomVarsForPlayer(player)
if not player or not player:IsLoggedIn() then return end
DreamMountFunctions:clearCustomVariables(player)
SendMessage(player.pid,
Format(DreamMountStrings.Patterns.SingleVarReset
, DreamMountStrings.UI.ResetVarsString
, player.name)
, false)
end
local function createScriptRecords()
local scriptRecordStore = RecordStores['script']
local scriptRecords = scriptRecordStore.data.permanentRecords
for scriptId, scriptText in pairs(MWScripts) do
scriptRecords[scriptId] = { scriptText = scriptText }
end
scriptRecordStore:Save()
end
local function createPetRecord(petRecordInput)
local Err = DreamMountStrings.Err
local playerPetData = petRecordInput.playerPetData
local mountName = petRecordInput.mountName
local petId = petRecordInput.petId
local player = petRecordInput.player
local playerStats = player.data.stats
assert(playerPetData, Err.CreatePetNoPetDataErr .. Traceback(3))
assert(petId, Err.CreatePetNoIdErr .. Traceback(3))
assert(player, Err.CreatePetNoPlayerErr .. Traceback(3))
assert(mountName, Err.CreatePetNoMountNameErr .. Traceback(3))
local creatureRecordStore = RecordStores["creature"]
local creatureRecords = creatureRecordStore.data.permanentRecords
ClearRecords()
SetRecordType(CreatureRecordType)
local petName = Format("%s's %s", player.name, mountName)
local petLevel = playerPetData.levelPct * playerStats.level
local damagePerLevelPct = playerPetData.damagePerLevelPct
local chopMax = round(playerPetData.damageChop * (1 + (damagePerLevelPct * petLevel)))
local slashMax = round(playerPetData.damageSlash * (1 + (damagePerLevelPct * petLevel)))
local thrustMax = round(playerPetData.damageThrust * (1 + (damagePerLevelPct * petLevel)))
local petRecord = {
name = petName,
baseId = playerPetData.baseId,
health = round(playerPetData.healthPct * playerStats.healthBase),
magicka = round(playerPetData.magickaPct * playerStats.magickaBase),
fatigue = round(playerPetData.fatiguePct * playerStats.fatigueBase),
level = round(petLevel),
damageChop = { min = round(chopMax * playerPetData.chopMinDmgPct), max = chopMax },
damageSlash = { min = round(slashMax * playerPetData.slashMinDmgPct), max = slashMax },
damageThrust = { min = round(thrustMax * playerPetData.thrustMinDmgPct), max = thrustMax },
}
creatureRecords[petId] = petRecord
creatureRecordStore:Save()
AddCreatureRecord(petId, petRecord)
SendRecordDynamic(player.pid, true)
end
local function saveContainerData(containerSaveData)
---@diagnostic disable-next-line: deprecated
local player, containerId, containerIndex, containerCell = unpack(containerSaveData)
local customVariables = player.data.customVariables
if not customVariables[DreamMountSummonInventoryDataKey] then
customVariables[DreamMountSummonInventoryDataKey] = {}
end
local inventoryData = customVariables[DreamMountSummonInventoryDataKey]
if not inventoryData[containerId] then
inventoryData[containerId] = {
inventory = {},
}
end
local containerData = inventoryData[containerId]
containerData.index = containerIndex
containerData.cell = containerCell
player:QuicksaveToDrive()
end
function DreamMountFunctions:getCurrentContainerData(player)
assert(player and player:IsLoggedIn(), Traceback(3))
local customVariables = player.data.customVariables
local mountInventories = customVariables[DreamMountSummonInventoryDataKey]
if not mountInventories then return end
return mountInventories[self:getContainerRecordId(player)]
end
function DreamMountFunctions:mountHasContainerData(player)
local mountData = self:getMountData(player)
if mountData and mountData.containerData then
return true
end
end
function DreamMountFunctions:getContainerRecordId(player)
assert(player and player:IsLoggedIn(), Traceback(3))
local mountName = self:getPlayerMountName(player)
if not mountName then return end
return Format("%s_%s_container", player.name, mountName):lower()
end
function DreamMountFunctions:getPlayerPetName(player)
local mountData = self:getMountData(player)
if not mountData or not mountData.petData then return end
return Format("%s's %s", player.name, mountData.name)
end
function DreamMountFunctions:getPlayerMountName(player)
local mountData = self:getMountData(player)
return mountData and mountData.name
end
function DreamMountFunctions.sendContainerPlacePacket(containerPacket)
---@diagnostic disable-next-line: deprecated
local pid, splitIndex, targetContainer, targetObject = unpack(containerPacket)
ClearObjectList()
SetObjectListPid(pid)
SetObjectListCell(GetCell(pid))
SetObjectRefNum(splitIndex[1])
SetObjectMpNum(splitIndex[2])
SetObjectRefId(targetContainer)
local location = targetObject.location
SetObjectPosition(location.posX, location.posY, location.posZ)
SetObjectRotation(location.rotX, location.rotY, location.rotZ)
SetObjectScale(targetObject.scale)
AddObject()
SendObjectPlace(false)
SendObjectScale(false)
end
function DreamMountFunctions:createContainerServerside(player)
local Err = DreamMountStrings.Err
local targetContainer = self:getContainerRecordId(player)
local pid = player.pid
local cellDescription = GetCell(pid)
local mpNum = WorldInstance:GetCurrentMpNum() + 1
local uniqueIndex = Format("0-%s", mpNum)
local bagSpawnCell = LoadedCells[cellDescription]
assert(bagSpawnCell, Err.ImpossibleUnloadedCellErr .. debug.traceback(3))
bagSpawnCell:InitializeObjectData(uniqueIndex, targetContainer)
local cellData = bagSpawnCell.data
local cellPackets = cellData.packets
local objectData = cellData.objectData
local targetObject = objectData[uniqueIndex]
assert(objectData[uniqueIndex], Err.ImpossibleObjectDataErr .. debug.traceback(3))
targetObject.location = {
posX = GetPosX(pid),
posY = GetPosY(pid),
posZ = -99999,
rotX = 0,
rotY = 0,
rotZ = 0
}
targetObject.scale = 0.0001
targetObject.inventory = {}
for _, packetType in ipairs { 'place', 'scale', 'container' } do
local packetTable = cellPackets[packetType]
packetTable[#packetTable + 1] = uniqueIndex
end
WorldInstance:SetCurrentMpNum(mpNum)
SetCurrentMpNum(mpNum)
local splitIndex = uniqueIndex:split('-')
saveContainerData {
player,
targetContainer,
splitIndex,
cellDescription,
}
return {
pid,
splitIndex,
targetContainer,
targetObject
}
end
function DreamMountFunctions:selectedMountIsPet(player)
return self:getPlayerPetName(player) ~= nil
end
function DreamMountFunctions:activateMountContainer(player)
if not self:mountHasContainerData(player) then
return player:Message(DreamMountStrings.UI.NoContainerDataErr)
end
self:despawnBagRef(player)
self.sendContainerPlacePacket(self:createContainerServerside(player))
self:updateCurrentMountContainer(player)
self:activateCurrentMountContainer(player)
end
function DreamMountFunctions:handleMountActivateMenu(pid, activateMenuChoice)
local Err = DreamMountStrings.Err
activateMenuChoice = tonumber(activateMenuChoice)
local player = Players[pid]
assert(activateMenuChoice, Err.ActivateChoiceFailedToConvertErr)
assert(player and player:IsLoggedIn(), Err.NoContainerForUnloggedPlayerErr)
if activateMenuChoice == 0 then
self:activateMountContainer(player)
elseif activateMenuChoice == 1 then
mountLog(Format(DreamMountStrings.Log.DismissedStr, player.name))
self:despawnMountSummon(player)
self:despawnBagRef(player)
elseif activateMenuChoice == 2 then
local petCellRef = getPlayerMountVars(player)[DreamMountSummonRefNumKey]
local playerCell = player.data.location.cell
assert(petCellRef, Err.ImpossibleActivationErr)
RunConsoleCommandOnObject(pid, "loopgroup idle6 1 2",
playerCell, petCellRef, true)
RunConsoleCommandOnObject(pid, "loopgroup idle2 0 0",
playerCell, petCellRef, true)
elseif activateMenuChoice == 3 then
self:toggleMount(player)
end
end
function DreamMountFunctions:reloadMountMerchants(_, _, cellDescription, objects)
local actorIndex, actor = next(objects)
if actor.dialogueChoiceType ~= BarterDialogue then return end
local expectedKeys = self.mountMerchants[actor.refId]
if not expectedKeys then return end
local Err = DreamMountStrings.Err
local cell = LoadedCells[cellDescription]
assert(cell, Format(Err.NilCellErr, Traceback(3)))
local objectData = cell.data.objectData
local reloadInventory = false
local currentMountKeys = 0
local cellRef = objectData[actorIndex]
local currentInventory = cellRef.inventory
assert(cellRef, Err.MerchantNotInCell .. Traceback(3))
assert(objectData, Format(Err.NilObjectDataErr, Traceback(3)))
assert(currentInventory, Format(Err.NilInventoryErr, Traceback(3)))
for _, object in pairs(currentInventory) do
if KeyRecords[object.refId] then
currentMountKeys = currentMountKeys + object.count
end
end
local keysToAdd = expectedKeys.capacity - currentMountKeys
if keysToAdd < 1 then return end
for _ = 1, keysToAdd do
local mountIndex = math.random(1, #expectedKeys.selection)
local mountData = self.mountConfig[mountIndex]
local keyId = getMountKeyString(mountData)
AddItem(currentInventory, keyId, 1, -1, -1, "")
if not reloadInventory then reloadInventory = true end
end
if not reloadInventory then return end
for playerId, player in pairs(Players) do
if player
and player:IsLoggedIn()
and player.data.location.cell == cellDescription
then
cell:LoadContainers(playerId, objectData, { actor.uniqueIndex })
end
end
end
function DreamMountFunctions:createClothingRecords(firstPid)
local clothingRecords = RecordStores['clothing']
local permanentClothing = clothingRecords.data.permanentRecords
if firstPid then
ClearRecords()
SetRecordType(ClothingRecord)
end
local clothesSaved = 0
for _, clothingData in ipairs(self.mountClothing) do
local newClothingId = clothingData.id
local newClothingName = clothingData.name
local newClothingParts = clothingData.parts
local newClothingType = clothingData.clothingType
local hasValidClothingData = newClothingType
and newClothingId
and newClothingName
and newClothingParts
assert(hasValidClothingData, DreamMountStrings.Err.InvalidClothingDataErr .. Traceback())
local newClothing = {
name = newClothingName,
subtype = newClothingType,