Repository navigation
Expand file tree
/
Copy pathshield.lua
More file actions
1156 lines (1069 loc) · 47.6 KB
/
Copy pathshield.lua
File metadata and controls
1156 lines (1069 loc) · 47.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Shield usage tracking.
--
-- Cuberite has no dedicated shield hook. Shields go through the generic item-use
-- path in cClientHandle::HandleRightClick (the ItemUseable branch):
-- CallHookPlayerUsingItem -> ItemHandler::OnItemUse -> CallHookPlayerUsedItem
-- All three happen in the SAME tick, on the tick the client pressed right-click.
-- HOOK_PLAYER_USING_ITEM is the "shield raised" signal, and HOOK_PLAYER_SHOOTING
-- is the "shield released" signal (it fires both when a bow is shot AND when a
-- raised shield is lowered). There is no per-tick firing.
--
-- A single IsUsingShield flag is used: the player has only one shield state,
-- and shield behavior is independent of which hand holds it. Vanilla raises the
-- main-hand shield first if both hands hold shields.
--
-- Bucket items produce MULTIPLE USING_ITEM/USED_ITEM events per right-click
-- (some targeting the clicked block, some targeting air at (-1,255,-1)). Each
-- event is resolved independently: when the reported coords are an air use,
-- GetTargetedBlock re-traces the player's eye ray to recover the real targeted
-- block, so the consumed/not-consumed decision is reliable per-event and no
-- cross-event batching is needed.
---Thrown items that unconditionally consume the right-click and so never raise
---the shield when held in the main hand.
---
---Note that E_ITEM_FIRE_CHARGE is NOT here: the engine routes it through the same
---cItemLighterHandler as flint and steel (it lights a fire on a block face), it is
---not thrown. E_ITEM_LINGERING_POTION IS here: cItemPotionHandler throws it just
---like a splash potion.
local ProjectileItems =
{
[E_ITEM_SNOWBALL] = true,
[E_ITEM_EGG] = true,
[E_ITEM_ENDER_PEARL] = true,
[E_ITEM_EYE_OF_ENDER] = true,
[E_ITEM_SPLASH_POTION] = true,
[E_ITEM_LINGERING_POTION] = true,
[E_ITEM_BOTTLE_O_ENCHANTING] = true,
}
---All boat variants. Same logic as the empty bucket: consumed only against a
---fluid (they are placed on water).
local BoatItems =
{
[E_ITEM_BOAT] = true,
[E_ITEM_SPRUCE_BOAT] = true,
[E_ITEM_BIRCH_BOAT] = true,
[E_ITEM_JUNGLE_BOAT] = true,
[E_ITEM_ACACIA_BOAT] = true,
[E_ITEM_DARK_OAK_BOAT] = true,
}
---All minecart variants. Consumed only when placed on a rail.
local MinecartItems =
{
[E_ITEM_MINECART] = true,
[E_ITEM_CHEST_MINECART] = true,
[E_ITEM_FURNACE_MINECART] = true,
[E_ITEM_MINECART_WITH_TNT] = true,
[E_ITEM_MINECART_WITH_HOPPER] = true,
}
---All hoe variants. Consumed when tilling grass / dirt into farmland.
local HoeItems =
{
[E_ITEM_WOODEN_HOE] = true,
[E_ITEM_STONE_HOE] = true,
[E_ITEM_IRON_HOE] = true,
[E_ITEM_GOLD_HOE] = true,
[E_ITEM_DIAMOND_HOE] = true,
}
---All shovel variants. Consumed when flattening grass / dirt into grass path.
local ShovelItems =
{
[E_ITEM_WOODEN_SHOVEL] = true,
[E_ITEM_STONE_SHOVEL] = true,
[E_ITEM_IRON_SHOVEL] = true,
[E_ITEM_GOLD_SHOVEL] = true,
[E_ITEM_DIAMOND_SHOVEL] = true,
}
---Helmet items (including leather cap). Equipped in the helmet slot.
local HelmetItems =
{
[E_ITEM_LEATHER_CAP] = true,
[E_ITEM_GOLD_HELMET] = true,
[E_ITEM_CHAIN_HELMET] = true,
[E_ITEM_IRON_HELMET] = true,
[E_ITEM_DIAMOND_HELMET] = true,
}
---Chestplate items (including elytra). Equipped in the chestplate slot.
local ChestplateItems =
{
[E_ITEM_LEATHER_TUNIC] = true,
[E_ITEM_GOLD_CHESTPLATE] = true,
[E_ITEM_CHAIN_CHESTPLATE] = true,
[E_ITEM_IRON_CHESTPLATE] = true,
[E_ITEM_DIAMOND_CHESTPLATE] = true,
[E_ITEM_ELYTRA] = true,
}
---Leggings items. Equipped in the leggings slot.
local LeggingsItems =
{
[E_ITEM_LEATHER_PANTS] = true,
[E_ITEM_GOLD_LEGGINGS] = true,
[E_ITEM_CHAIN_LEGGINGS] = true,
[E_ITEM_IRON_LEGGINGS] = true,
[E_ITEM_DIAMOND_LEGGINGS] = true,
}
---Boots items. Equipped in the boots slot.
local BootsItems =
{
[E_ITEM_LEATHER_BOOTS] = true,
[E_ITEM_GOLD_BOOTS] = true,
[E_ITEM_CHAIN_BOOTS] = true,
[E_ITEM_IRON_BOOTS] = true,
[E_ITEM_DIAMOND_BOOTS] = true,
}
---All food items. In Cuberite, food (cItemFoodHandler descendants, which
---override IsFood() to true) cannot be used at all in creative mode --
---HandleUseItem returns early before StartEating / HOOK_PLAYER_USING_ITEM,
---so these never reach us in creative. In survival they are consumed only
---when the player is hungry (not satiated).
---
---Golden apple and chorus fruit are EXCLUDED from this table: Cuberite's
---HandleUseItem special-cases them so they bypass the creative/satiated
---guard and are still eaten in creative mode (see SpecialFoodItems).
local FoodItems =
{
[E_ITEM_RED_APPLE] = true,
[E_ITEM_BREAD] = true,
[E_ITEM_RAW_PORKCHOP] = true,
[E_ITEM_COOKED_PORKCHOP] = true,
[E_ITEM_RAW_FISH] = true,
[E_ITEM_COOKED_FISH] = true,
[E_ITEM_RAW_BEEF] = true,
[E_ITEM_STEAK] = true,
[E_ITEM_RAW_CHICKEN] = true,
[E_ITEM_COOKED_CHICKEN] = true,
[E_ITEM_ROTTEN_FLESH] = true,
[E_ITEM_RAW_MUTTON] = true,
[E_ITEM_COOKED_MUTTON] = true,
[E_ITEM_RAW_RABBIT] = true,
[E_ITEM_COOKED_RABBIT] = true,
[E_ITEM_RABBIT_STEW] = true,
[E_ITEM_BEETROOT] = true,
[E_ITEM_BEETROOT_SOUP] = true,
[E_ITEM_CARROT] = true,
[E_ITEM_BAKED_POTATO] = true,
[E_ITEM_POISONOUS_POTATO] = true,
[E_ITEM_PUMPKIN_PIE] = true,
[E_ITEM_MELON_SLICE] = true,
[E_ITEM_SPIDER_EYE] = true,
[E_ITEM_COOKIE] = true,
-- Added after cross-checking src/Items/ItemHandler.cpp: these three are food
-- handlers in the engine (cItemSoupHandler / cItemSimpleFoodHandler /
-- cItemFoodSeedsHandler) and were missing from this table.
[E_ITEM_MUSHROOM_SOUP] = true,
[E_ITEM_GOLDEN_CARROT] = true,
[E_ITEM_POTATO] = true,
}
---Special food items (golden apple, chorus fruit). Cuberite's HandleUseItem
---special-cases these so they bypass the creative-mode / satiated guard that
---blocks normal food -- they are still eaten in creative mode. The client,
---however, does not play the eating animation in creative, so it treats the
---right-click as empty and would raise the shield. Since the server actually
---processes the eat (effects applied, chorus fruit teleports), the right-click
---IS consumed and the shield should NOT rise.
local SpecialFoodItems =
{
[E_ITEM_GOLDEN_APPLE] = true,
[E_ITEM_CHORUS_FRUIT] = true,
}
---Drinkable items (milk, potion). Unlike food, these are NOT blocked in
---creative mode -- Cuberite routes them through IsDrinkable() rather than
---IsFood(), so HandleUseItem does not apply the creative/satiated guard.
---They are always consumed (the right-click is used up), even though the
---item itself may not be removed from the inventory in creative.
local DrinkableItems =
{
[E_ITEM_MILK] = true,
[E_ITEM_POTION] = true,
}
---Whether the given block type is a rail (any variant).
---@param BlockType number
---@return boolean
local function IsRail(BlockType)
return BlockType == E_BLOCK_RAIL
or BlockType == E_BLOCK_POWERED_RAIL
or BlockType == E_BLOCK_DETECTOR_RAIL
or BlockType == E_BLOCK_ACTIVATOR_RAIL
end
---Whether the given block type is a fluid (water / lava, flowing or still).
---@param BlockType number
---@return boolean
local function IsFluid(BlockType)
return BlockType == E_BLOCK_WATER
or BlockType == E_BLOCK_STATIONARY_WATER
or BlockType == E_BLOCK_LAVA
or BlockType == E_BLOCK_STATIONARY_LAVA
end
---Whether the given block type is a non-fluid, non-air solid surface.
---@param BlockType number
---@return boolean
local function IsSolidSurface(BlockType)
return BlockType ~= E_BLOCK_AIR and not IsFluid(BlockType)
end
---The player's default block interaction reach: the maximum line-segment
---distance from the eye to the intersection with a block's outline box.
---This is the segment length from eye to hit point, NOT the distance to the
---block's nearest point.
local PLAYER_REACH = 4.5
---Determine the block the given player is currently interacting with (the
---block their crosshair is aiming at).
---
---Casts a ray from the player's eye along the look direction and returns the
---first non-air block the ray passes through within MaxDistance. If no
---non-air block is hit within MaxDistance, returns E_BLOCK_AIR.
---
---Implementation notes:
--- * cLineBlockTracer:Trace does a DDA traversal that visits blocks in
--- near-to-far order (by ray-wall-crossing coefficient 0 -> 1) and only
--- reports blocks the segment [Start, End] actually passes through. So
--- the first non-air block reported IS the targeted block, and End
--- (= EyePos + Look * MaxDistance) already enforces the distance limit --
--- no manual distance / intersection check is needed.
--- * We cannot use cLineBlockTracer:FirstSolidHitTrace because it uses
--- cBlockInfo::IsSolid(), which treats fluids (water / lava) as
--- non-solid and skips them. Bucket scooping needs to target fluids,
--- so we use Trace with a custom "first non-air" callback instead.
--- * Cuberite's Lua API does not expose the actual block outline boxes
--- (cBlockHandler's collision/outline box interfaces are not exported),
--- so the DDA's full-cube traversal is the best approximation available.
--- For non-full blocks (stairs, slabs, fences, etc.) this is more lenient
--- than vanilla (a ray grazing their air portion still counts as a hit).
--- For this plugin's use case -- deciding whether a right-click with a
--- bucket / flint-and-steel / firework hit a block -- this is sufficient.
---@param Player cPlayer
---@param MaxDistance number? max interaction distance (segment length), defaults to PLAYER_REACH (4.5)
---@return BLOCKTYPE BlockType block type (E_BLOCK_AIR if none)
---@return Vector3i|nil BlockPos block coords (nil if none)
local function GetTargetedBlock(Player, MaxDistance)
MaxDistance = MaxDistance or PLAYER_REACH
local World = Player:GetWorld()
local EyePos = Player:GetEyePosition()
local Look = Player:GetLookVector()
Look:Normalize()
local End = EyePos + Look * MaxDistance
local Result = { BlockType = E_BLOCK_AIR, BlockPos = nil }
local Callbacks =
{
OnNextBlock = function(BlockPos, BlockType, BlockMeta, EntryFace)
if BlockType == E_BLOCK_AIR then
return false -- Air: keep tracing
end
-- First non-air block: the DDA only reports blocks the segment
-- [EyePos, End] passes through, so this is the targeted block.
Result.BlockType = BlockType
Result.BlockPos = BlockPos
return true -- Hit, stop tracing
end,
}
cLineBlockTracer:Trace(World, Callbacks, EyePos, End)
return Result.BlockType, Result.BlockPos
end
---Whether a single USING_ITEM event indicates the main-hand item was consumed.
---
---The event's reported block coords can be (-1,255,-1) ("air use") even when
---the player is actually aiming at a block -- the client sometimes targets air
---for the secondary events of a single right-click. The caller resolves this
---by passing the real targeted block's type: for air-use events it comes from
---GetTargetedBlock (a server-side eye-ray trace), for normal events it comes
---from World:GetBlock at the reported coords. The per-event decision is then
---reliable on its own and no cross-event batching is needed.
---@param Player cPlayer
---@param Type number item type at the time of the event
---@param BlockType number block type the player is actually aiming at
--- (E_BLOCK_AIR if nothing is in reach; for air-use events this is the
--- GetTargetedBlock result, for normal events it is World:GetBlock at the
--- reported coords)
---@return boolean consumed, boolean definitive (definitive=false => caller still raises shield if not consumed)
local function EvaluateEvent(Player, Type, BlockType)
if ProjectileItems[Type] then
return true, true
end
if Type == E_ITEM_FISHING_ROD then
return true, true
end
if Type == E_ITEM_BOW then
return Player:IsGameModeCreative() or Player:GetInventory():HasItems(cItem(E_ITEM_ARROW)), true
end
-- BlockType == E_BLOCK_AIR means the player is aiming at nothing within
-- reach (either a real air use, or an air-use event whose eye-ray trace
-- also found nothing). All block-dependent items below are not consumed
-- in that case.
local IsAir = (BlockType == E_BLOCK_AIR)
-- The `Consumed` property for bucket interaction events is not precise. We do not actually rely on it though.
if Type == E_ITEM_WATER_BUCKET or Type == E_ITEM_LAVA_BUCKET then
-- Placing fluid: consumed iff the player's reach contains a solid
-- block to pour onto. This is NOT the same as "the first non-air
-- block is solid" -- the player may be aiming through a fluid (e.g.
-- water covering a stone floor) and still place the fluid on the
-- solid block beneath. Use FirstSolidHitTrace, which skips fluids
-- (cBlockInfo::IsSolid returns false for water / lava) and reports
-- the first solid block within reach, if any.
local EyePos = Player:GetEyePosition()
local Look = Player:GetLookVector()
Look:Normalize()
local End = EyePos + Look * PLAYER_REACH
local HasSolid = cLineBlockTracer:FirstSolidHitTrace(Player:GetWorld(), EyePos, End)
return HasSolid, true
end
if Type == E_ITEM_BUCKET then
-- Scooping: consumed only against a fluid.
if IsAir then
return false, true
end
return IsFluid(BlockType), true
end
if BoatItems[Type] then
-- Boats: same logic as the empty bucket -- placed on a fluid.
if IsAir then
return false, true
end
return IsFluid(BlockType), true
end
if MinecartItems[Type] then
-- Minecarts: consumed only when placed on a rail; definitive either way.
if IsAir then
return false, true
end
return IsRail(BlockType), true
end
if HoeItems[Type] or ShovelItems[Type] then
-- Hoe / shovel: consumed only against grass / dirt; definitive either way.
if IsAir then
return false, true
end
return BlockType == E_BLOCK_GRASS or BlockType == E_BLOCK_DIRT, true
end
if HelmetItems[Type] then
-- Helmet: consumed only if the helmet slot is empty; definitive.
return Player:GetEquippedHelmet():IsEmpty(), true
end
if ChestplateItems[Type] then
-- Chestplate / elytra: consumed only if the chestplate slot is empty.
return Player:GetEquippedChestplate():IsEmpty(), true
end
if LeggingsItems[Type] then
-- Leggings: consumed only if the leggings slot is empty.
return Player:GetEquippedLeggings():IsEmpty(), true
end
if BootsItems[Type] then
-- Boots: consumed only if the boots slot is empty.
return Player:GetEquippedBoots():IsEmpty(), true
end
if FoodItems[Type] then
-- Food: in creative mode Cuberite blocks use entirely (HandleUseItem
-- returns before HOOK_PLAYER_USING_ITEM), so this branch is only
-- reached in survival / adventure. There, food is consumed only when
-- the player is hungry (not satiated).
return not Player:IsSatiated(), true
end
if SpecialFoodItems[Type] then
-- Golden apple / chorus fruit: Cuberite special-cases these so they
-- are eaten even in creative mode (effects applied, chorus fruit
-- teleports). The right-click is always consumed, so the shield must
-- not rise -- even though the client plays no eat animation in
-- creative and would otherwise treat this as an empty right-click.
return true, true
end
if DrinkableItems[Type] then
-- Drinkables (milk, potion): usable in all gamemodes, the right-click
-- is always consumed.
return true, true
end
if Type == E_ITEM_EMPTY_MAP then
-- cItemEmptyMapHandler::OnItemUse ignores the clicked block and face
-- entirely: it creates a new map -- cMapManager::CreateMap is called from
-- here and nowhere else -- and replaces the item with the filled map. The
-- right-click is therefore consumed whatever the player aims at, air
-- included. Not modelling this made the offhand shield rise on every
-- empty-map use.
return true, true
end
if Type == E_ITEM_SPAWN_EGG then
-- Spawn egg: consumed iff it actually spawns a mob, i.e. the player is
-- aiming at a non-air block (solid or fluid). Aiming at nothing within
-- reach does NOT consume the egg.
if IsAir then
return false, true
end
return true, true
end
-- Flint-and-steel and fire charge share cItemLighterHandler: both only act on a
-- real block face (a_ClickedBlockFace < 0 does nothing), so an air use is never
-- consumed. Neither is thrown (that is dispenser behaviour), so unlike the vanilla
-- inventory they must NOT be treated as projectiles.
if Type == E_ITEM_FLINT_AND_STEEL or Type == E_ITEM_FIRE_CHARGE then
if IsAir then
return false, true
end
return IsSolidSurface(BlockType), true
end
if Type == E_ITEM_FIREWORK_ROCKET then
if Player:IsElytraFlying() then
return true, true
end
if IsAir then
return false, true
end
return IsSolidSurface(BlockType), true
end
if Type == E_ITEM_GLASS_BOTTLE then
-- cItemBottleHandler: fills only from a water source the eye ray reaches.
-- (The engine traces up to 5 blocks and insists on a source block; the
-- trace handed in here is the first non-air block within player reach, so
-- this is the closest approximation available to Lua.)
if IsAir then
return false, true
end
return (BlockType == E_BLOCK_WATER) or (BlockType == E_BLOCK_STATIONARY_WATER), true
end
if Type == E_ITEM_END_CRYSTAL then
-- cItemEndCrystalHandler: places only on obsidian or bedrock.
if IsAir then
return false, true
end
return (BlockType == E_BLOCK_OBSIDIAN) or (BlockType == E_BLOCK_BEDROCK), true
end
return false, true
end
---Whether the item is a shield.
---@param ItemType number
---@return boolean
local function IsShield(ItemType)
return ItemType == E_ITEM_SHIELD
end
---Find the shield the player is currently holding (main or off hand), together
---with the slot it came from, so a modified item can be written back.
---
---Returned as an owned COPY: the main-hand getter hands out a live `const cItem`
---reference and the off-hand one a by-value copy, so copying normalises both for
---StoreShield. It is required anyway for members declared in ManualBindings.cpp
---(m_LoreTable), which reject the `const cItem` view via CheckParamSelf("cItem").
---@param Player cPlayer
---@return cItem|nil
---@return boolean IsOffhand true when the shield sits in the off hand slot
local function GetHeldShield(Player)
local Main = Player:GetEquippedItem()
if Main and IsShield(Main.m_ItemType) then
return cItem(Main), false
end
local Off = Player:GetOffHandEquipedItem()
if Off and IsShield(Off.m_ItemType) then
return cItem(Off), true
end
return nil, false
end
---Raise the shield (only on the false -> true transition).
---@param Player cPlayer
local function RaiseShield(Player)
local State = GetPlayerState(Player)
if not State.IsUsingShield then
State.IsUsingShield = true
DebugLog("Player " .. Player:GetName() .. " used a shield!")
end
end
---Lower the shield (only on the true -> false transition).
---@param Player cPlayer
local function ReleaseShield(Player)
local State = GetPlayerState(Player)
if State.IsUsingShield then
State.IsUsingShield = false
DebugLog("Player " .. Player:GetName() .. " released a shield!")
end
end
---Sound event played when a shield blocks an attack. Cuberite sends the name to
---the client as-is (protocol "Named Sound Effect"), which resolves it against its
---own sound registry, so the vanilla 1.9+ name is used.
local SHIELD_BLOCK_SOUND = "item.shield.block"
---Play the shield block sound at the player's position.
---
---Uses the vector overload: both are bound and take volume before pitch, but the
---X / Y / Z form is deprecated and logs a deprecation warning (with a full stack
---trace) on every single call.
---@param Player cPlayer
local function PlayShieldBlockSound(Player)
Player:GetWorld():BroadcastSoundEffect(
SHIELD_BLOCK_SOUND,
Player:GetPosition(),
1.0, -- volume
1.0 -- pitch
)
end
---Maximum durability of a shield (the vanilla value).
local SHIELD_DURABILITY_MAX = 336
---Remaining durability lives in the shield's damage field: cItem::GetMaxDamage() has
---no E_ITEM_SHIELD case, so the engine never reads or writes m_ItemDamage for a
---shield, and the client draws its own durability bar from it.
---@param Item cItem
---@return number
local function GetShieldDurability(Item)
return math.max(0, math.min(SHIELD_DURABILITY_MAX, SHIELD_DURABILITY_MAX - (Item.m_ItemDamage or 0)))
end
---Record the remaining durability in the shield's damage field.
---@param Item cItem
---@param Remaining number
local function SetShieldDurability(Item, Remaining)
Item.m_ItemDamage = SHIELD_DURABILITY_MAX - Remaining
end
---Shields saved by the pre-m_ItemDamage build carry the counter as the lore line
---"Durability: <left>/336"; fold it into the damage field and drop that line.
---@param Item cItem
local function MigrateLegacyDurability(Item)
local Lore = Item.m_LoreTable
for Index = #(Lore or {}), 1, -1 do
local Left = Lore[Index]:match("^Durability: (%d+)/")
if Left then
Item.m_ItemDamage = SHIELD_DURABILITY_MAX - Left
table.remove(Lore, Index)
Item.m_LoreTable = Lore
end
end
end
---Store a (possibly modified) shield back into the slot it was read from.
---@param Player cPlayer
---@param Item cItem cItem() clears the slot
---@param IsOffhand boolean
local function StoreShield(Player, Item, IsOffhand)
local Inventory = Player:GetInventory()
if IsOffhand then
Inventory:SetShieldSlot(Item)
else
Inventory:SetEquippedItem(Item)
end
end
---Wear the raised shield down by the given amount of durability.
---
---Cuberite has no native shield durability, so the remaining durability is stored
---in the item's damage field (see GetShieldDurability). The amount follows vanilla's
---damageShield(): only hits of 3+
---damage wear a shield, for 1 + floor(damage) points. Unbreaking negates each point
---with a chance of 1 / (level + 1) (like ItemStack#attemptDamageItem), creative
---players do not wear items, and the shield is removed once the counter runs out.
---@param Player cPlayer
---@param Loss number durability points vanilla would subtract
local function WearShield(Player, Loss)
if Player:IsGameModeCreative() then
return
end
local Shield, IsOffhand = GetHeldShield(Player)
if not Shield then
return
end
MigrateLegacyDurability(Shield)
local Unbreaking = Shield.m_Enchantments:GetLevel(cEnchantments.enchUnbreaking)
local Applied = 0
for _ = 1, Loss do
-- Each point is skipped with a chance of 1 / (level + 1).
if (Unbreaking <= 0) or (math.random() * (Unbreaking + 1) >= 1) then
Applied = Applied + 1
end
end
if Applied <= 0 then
return
end
local Remaining = GetShieldDurability(Shield) - Applied
if Remaining > 0 then
SetShieldDurability(Shield, Remaining)
StoreShield(Player, Shield, IsOffhand)
return
end
LOG("Player " .. Player:GetName() .. " shield broke!")
ReleaseShield(Player)
StoreShield(Player, cItem(), IsOffhand)
end
-- ============================================================================
-- Consumption probe (debug only): cross-check EvaluateEvent against reality
-- ============================================================================
--
-- EvaluateEvent models cItemHandler::OnItemUse by hand and the test suite checks
-- it against a mock -- one model validating another. HOOK_PLAYER_USED_ITEM is the
-- one independent signal available: it fires right after OnItemUse ran, so
-- comparing the main-hand slot across the two hooks shows whether the handler
-- touched the item at all.
--
-- Only the "slot changed" direction is trustworthy -- it means the click was
-- almost certainly consumed. "Slot unchanged" proves nothing, because creative
-- mode skips consumption entirely and Unbreaking can negate the durability loss.
-- The probe therefore never drives behaviour: it only reports disagreements, which
-- is how the model gets real-world feedback. Full reasoning, including the two
-- majority-case counterexamples, in docs/shield-consumption-oracle.md.
-- Enabled by [Debug] EnableDebugLog.
---Stable identity of an inventory slot's contents, for cross-hook comparison.
---@param Item cItem|nil
---@return string
local function ItemSignature(Item)
if (Item == nil) or Item:IsEmpty() then
return "empty"
end
return Item.m_ItemType .. "/" .. Item.m_ItemCount .. "/" .. Item.m_ItemDamage
end
---Snapshot the main-hand slot and EvaluateEvent's verdict for the USED_ITEM hook.
---Called from CheckUseShieldOnUsingItem; a no-op unless debug logging is on.
---@param Player cPlayer
---@param Item cItem|nil
---@param Type number
---@param BlockType number
---@param Consumed boolean
local function RecordConsumptionProbe(Player, Item, Type, BlockType, Consumed)
if not DebugLogging then
return
end
local Unbreaking = 0
if (Item ~= nil) and (Item.m_Enchantments ~= nil) then
Unbreaking = Item.m_Enchantments:GetLevel(cEnchantments.enchUnbreaking)
end
GetPlayerState(Player).ConsumptionProbe =
{
Signature = ItemSignature(Item),
Consumed = Consumed,
Type = Type,
BlockType = BlockType,
Creative = Player:IsGameModeCreative(),
Unbreaking = Unbreaking,
}
end
-- HOOK_PLAYER_USED_ITEM: fires right after cItemHandler::OnItemUse has run. Compare
-- the main-hand slot with the snapshot taken in HOOK_PLAYER_USING_ITEM and report
-- any disagreement with EvaluateEvent's verdict (see the section comment above).
-- Information only: it never changes shield behaviour.
---@param Player cPlayer
---@param BlockX number
---@param BlockY number
---@param BlockZ number
---@param BlockFace number
---@param CursorX number
---@param CursorY number
---@param CursorZ number
---@return boolean|nil
function ProbeItemConsumptionOnItemUsed(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
local State = GetPlayerState(Player)
local Probe = State.ConsumptionProbe
if Probe == nil then
return
end
State.ConsumptionProbe = nil
local After = ItemSignature(Player:GetEquippedItem())
local Observed = (After ~= Probe.Signature)
if Observed == Probe.Consumed then
return -- model and observation agree: stay quiet
end
local Why
if not Probe.Consumed then
-- EvaluateEvent predicted "not consumed" but the slot moved: an unrelated
-- inventory sync in the same tick, or a real modelling error.
Why = "SUSPICIOUS (unexpected slot change)"
elseif Probe.Creative then
Why = "explained (creative skips consumption)"
elseif Probe.Unbreaking > 0 then
Why = "explained (Unbreaking can negate the durability loss)"
else
Why = "SUSPICIOUS (survival, no Unbreaking, slot unchanged)"
end
DebugLog("consumption-probe: " .. Why ..
"; player=" .. Player:GetName() ..
" item=" .. Probe.Type ..
" block=" .. Probe.BlockType ..
" creative=" .. tostring(Probe.Creative) ..
" unbreaking=" .. Probe.Unbreaking ..
" EvaluateEvent=" .. tostring(Probe.Consumed) ..
" observed=" .. tostring(Observed) ..
" before=" .. Probe.Signature .. " after=" .. After)
end
-- HOOK_PLAYER_USING_ITEM: the "shield raised" signal, fired on the tick the
-- client pressed right-click. For each event we decide immediately whether
-- the main-hand item was consumed (using GetTargetedBlock as the air-use
-- fallback for the real targeted block); if it was not consumed, the offhand
-- shield raises. No cross-event batching is needed.
---@param Player cPlayer
---@param BlockX number
---@param BlockY number
---@param BlockZ number
---@param BlockFace number
---@param CursorX number
---@param CursorY number
---@param CursorZ number
---@return boolean|nil true to cancel the item use, nil/false otherwise
function CheckUseShieldOnUsingItem(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
local Item = Player:GetEquippedItem()
local ItemOffhand = Player:GetOffHandEquipedItem()
-- Both slots can come back nil (no item in hand), so the trace must not assume
-- the userdata exists -- a plain nil dereference here aborts the whole hook.
DebugLog("Player " .. Player:GetName() .. " using item " .. (Item and Item.m_ItemType or -1)
.. " and " .. (ItemOffhand and ItemOffhand.m_ItemType or -1)
.. " at block " .. BlockX .. "," .. BlockY .. "," .. BlockZ
.. " cursor " .. CursorX .. "," .. CursorY .. "," .. CursorZ)
-- Trace the block the player is currently aiming at (independent of the
-- event's reported block coords, which can be (-1,255,-1) for air uses).
local TargetType, TargetPos = GetTargetedBlock(Player)
if TargetPos then
DebugLog("Player " .. Player:GetName() .. " targeting block " .. TargetType ..
" at " .. TargetPos.x .. "," .. TargetPos.y .. "," .. TargetPos.z)
else
DebugLog("Player " .. Player:GetName() .. " targeting block AIR (nothing in reach)")
end
if Item and IsShield(Item.m_ItemType) then
-- Main hand is a shield: it always raises (shields are not blacklisted).
RaiseShield(Player)
return
end
if not (ItemOffhand and IsShield(ItemOffhand.m_ItemType)) then
return
end
-- Offhand shield: depends on whether the main-hand item is consumed.
if not Item or Item:IsEmpty() then
RaiseShield(Player)
return
end
local Type = Item.m_ItemType
-- Resolve the block type the player is actually aiming at. For normal
-- events this is World:GetBlock at the reported coords; for air-use events
-- (coords == -1,255,-1) we reuse the GetTargetedBlock trace above. This
-- fetches the block type exactly once per event.
local IsAirUse = (BlockX == -1 and BlockY == 255 and BlockZ == -1)
local BlockType
if IsAirUse then
BlockType = TargetType -- from GetTargetedBlock above (E_BLOCK_AIR if none)
else
BlockType = Player:GetWorld():GetBlock(Vector3i(BlockX, BlockY, BlockZ))
end
local Consumed, Definitive = EvaluateEvent(Player, Type, BlockType)
-- With GetTargetedBlock as the air-use fallback, every event is now
-- definitive: the consumed/not-consumed decision is made per-event from
-- the real targeted block, so no cross-event batching is needed.
if not Consumed then
RaiseShield(Player)
end
RecordConsumptionProbe(Player, Item, Type, BlockType, Consumed)
DebugLog("Player " .. Player:GetName() .. " using item " .. Type ..
" consumed=" .. tostring(Consumed) ..
" definitive=" .. tostring(Definitive) ..
" blockType=" .. BlockType)
end
---Length of the most recent world tick, in seconds. HOOK_WORLD_TICK's TimeDelta
---is the same value the engine feeds the projectile physics as its dt, so it lets
---the projectile hook reproduce the engine's per-tick collision test exactly.
local LastTickSeconds = 0.05
-- HOOK_WORLD_TICK: drop a raised-shield state whose shield has left both hands
-- (see the safety net in the handler below). Shield durability is applied by
-- CheckUseShieldOnTakeDamage itself, where it is stored in the shield's damage
-- field, so there is nothing left to defer to a tick.
---@param World cWorld
---@param TimeDelta number milliseconds since the last tick
---@param LastTickDurationMSec number
function CheckUseShieldOnTick(World, TimeDelta, LastTickDurationMSec)
if TimeDelta and (TimeDelta > 0) then
LastTickSeconds = TimeDelta / 1000
end
World:ForEachPlayer(
---@param Player cPlayer
function(Player)
local State = GetPlayerState(Player)
-- A probe snapshot left over from an earlier tick means
-- HOOK_PLAYER_USED_ITEM never fired (another plugin cancelled the
-- use), so drop it rather than compare against a stale slot.
if DebugLogging then
State.ConsumptionProbe = nil
end
-- Safety net: a raised shield must never outlive the shield itself.
-- HOOK_PLAYER_TOSSING_ITEM only fires for the Q-drop and the window
-- outside-click, and on the Q path it fires BEFORE TossEquippedItem(),
-- so GetEquippedItem() still returns the shield at that moment and the
-- TOSS handler cannot tell that the raised shield is being dropped.
-- The drop key, closing a window with a dragged item and every other
-- way of losing the shield fire no hook at all. Without this check the
-- flag stayed true forever and CheckUseShieldOnTakeDamage kept
-- negating frontal damage with no shield in hand (observed: 20 -> 20 HP
-- after the shield was dropped).
if State.IsUsingShield and (GetHeldShield(Player) == nil) then
DebugLog("Player " .. Player:GetName() .. " no longer holds a shield; lowering the raised shield state")
ReleaseShield(Player)
end
end
)
end
-- HOOK_PLAYER_SHOOTING: the "shield released" signal. Fires both when a bow is
-- shot and when a raised shield is lowered (same SHOOT status packet), so this
-- is the reliable release event.
---@param Player cPlayer
---@return boolean|nil true to cancel the shot, nil/false otherwise
function CheckUseShieldOnShooting(Player)
ReleaseShield(Player)
end
-- HOOK_PLAYER_TOSSING_ITEM: dropping the held item. Only release if the dropped
-- item was the shield currently being held up, or if neither hand holds a
-- shield anymore (the shield got moved away). Dropping a normal item does NOT
-- release the shield.
---@param Player cPlayer
---@return boolean|nil true to cancel the toss, nil/false otherwise
function CheckUseShieldOnTossingItem(Player)
local Item = Player:GetEquippedItem()
local ItemOffhand = Player:GetOffHandEquipedItem()
local MainIsShield = Item and IsShield(Item.m_ItemType)
local OffIsShield = ItemOffhand and IsShield(ItemOffhand.m_ItemType)
-- If the player just dropped their raised shield, or no shield remains in
-- either hand, lower the state. Otherwise keep it (e.g. tossed a sword
-- while blocking with an offhand shield).
if not MainIsShield and not OffIsShield then
ReleaseShield(Player)
end
end
-- HOOK_PLAYER_RIGHT_CLICK: fires at the very start of both HandleRightClick
-- (right-click a block, BlockFace >= 0) and HandleUseItem (right-click air,
-- BlockFace == BLOCK_FACE_NONE), BEFORE Cuberite's food/item-use dispatch.
--
-- This is the ONLY hook that fires for two cases where HOOK_PLAYER_USING_ITEM
-- never fires, but the client still plays a right-click animation and would
-- raise an offhand shield:
-- (1) Empty main hand -- nothing to use, server does nothing, but the
-- client swings the arm.
-- (2) Creative mode holding normal food -- Cuberite's HandleUseItem blocks
-- food use in creative (IsFood() && IsGameModeCreative() -> return)
-- before StartEating / HOOK_PLAYER_USING_ITEM, so the server does
-- nothing, but the client (which doesn't know about the server-side
-- block) plays no eat animation and treats it as an empty right-click.
-- In both cases the right-click is NOT consumed by any item, so the offhand
-- shield SHOULD raise. We do this here.
--
-- We only handle the right-click-air case (BlockFace == BLOCK_FACE_NONE).
-- Right-clicking a block may be consumed by the block (chest, lever, etc.),
-- which is a real use of the right-click and should NOT raise the shield;
-- HOOK_PLAYER_RIGHT_CLICK fires before we can tell whether the block is
-- usable, so we conservatively skip it.
---@param Player cPlayer
---@param BlockX number
---@param BlockY number
---@param BlockZ number
---@param BlockFace number
---@param CursorX number
---@param CursorY number
---@param CursorZ number
---@return nil this handler never cancels the right-click
function CheckUseShieldOnRightClick(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
local ItemOffhand = Player:GetOffHandEquipedItem()
local OffhandHasShield = ItemOffhand and IsShield(ItemOffhand.m_ItemType)
-- Only the right-click-air case (HandleUseItem) needs shield raising.
-- HandleUseItem passes BLOCK_FACE_NONE and the sentinel block coords.
if BlockFace == BLOCK_FACE_NONE then
local Item = Player:GetEquippedItem()
local MainEmpty = (not Item) or Item:IsEmpty()
-- Normal food the engine refuses to eat (creative mode OR a satiated player,
-- see HandleUseItem): it returns before StartEating, so the right-click is not
-- consumed and the client plays no eating animation -- it raises the offhand
-- shield exactly like an empty main hand. Golden apple / chorus fruit are NOT
-- in FoodItems: the engine exempts them from that guard, so they are eaten and
-- the right-click IS consumed.
local MainIsUnusableFood = Item and FoodItems[Item.m_ItemType]
and (Player:IsGameModeCreative() or Player:IsSatiated())
if OffhandHasShield and (MainEmpty or MainIsUnusableFood) then
-- Right-click not consumed by any item: raise the offhand shield.
RaiseShield(Player)
DebugLog("Player " .. Player:GetName() .. " raised shield via right-click (main "
.. (MainEmpty and "empty" or "unusable food") .. ")")
end
end
end
-- ============================================================================
-- Shield blocking mechanics
-- ============================================================================
---Damage types that CAN be blocked by a shield (in <= 1.12.2).
local BlockableDamageTypes =
{
[dtAttack] = true, -- Melee (mob melee, player melee)
-- Arrows, tridents, snowballs, eggs, shulker bullets, fireballs, llama spit,
-- wither skulls:
[dtRangedAttack] = true,
[dtExplosion] = true, -- Creeper, ghast fireball, end crystal, bed, respawn anchor, TNT
}
---Whether the attack comes from the player's front (within the shield's
---horizontal 180-degree arc). Uses the relative position of the attacker
---when available; falls back to the knockback vector direction for attacks
---without an attacker (e.g. explosions).
---@param Player cPlayer
---@param Attacker cEntity|nil the attacking entity (mob or projectile), or nil
---@param Knockback Vector3d|nil the TDI.Knockback vector, used when Attacker is nil
---@return boolean
local function IsAttackFromFront(Player, Attacker, Knockback)
local ToAttacker
if Attacker then
-- Vector from player to attacker (horizontal only).
ToAttacker = Vector3d(
Attacker:GetPosX() - Player:GetPosX(),
0,
Attacker:GetPosZ() - Player:GetPosZ()
)
elseif Knockback then
-- Knockback points from attacker toward receiver. Reverse it to get
-- the direction from receiver toward attacker.
ToAttacker = Vector3d(-Knockback.x, 0, -Knockback.z)
else
return false
end
if ToAttacker:SqrLength() < 1e-6 then
return true -- Attacker is essentially on top of the player; block it.
end
-- Player's look vector (horizontal only).
local Look = Vector3d(Player:GetLookVector())
Look.y = 0
if Look:SqrLength() < 1e-6 then
return false
end
ToAttacker:Normalize()
Look:Normalize()
-- Dot > 0 means the attacker is in front (angle < 90 degrees).
return (ToAttacker:Dot(Look) > 0)
end
-- HOOK_TAKE_DAMAGE: implement shield blocking. When a player with a raised
-- shield is attacked from the front by a blockable damage type, the damage is
-- negated, knockback is reduced, and the shield takes durability damage.
---@param Receiver cEntity the entity taking damage
---@param TDI TakeDamageInfo the damage info, modifiable
---@return boolean true to cancel the damage
function CheckUseShieldOnTakeDamage(Receiver, TDI)
-- Only players can use shields.
if not Receiver:IsPlayer() then
return false
end
local Player = Receiver
local State = GetPlayerState(Player)
-- Log the damage event for debugging.
local AttackerPos = "nil"
if TDI.Attacker then