-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathEntityValue.java
1694 lines (1553 loc) · 72.4 KB
/
EntityValue.java
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
package carpet.script.value;
import carpet.fakes.EntityInterface;
import carpet.fakes.ItemEntityInterface;
import carpet.fakes.LivingEntityInterface;
import carpet.fakes.MobEntityInterface;
import carpet.fakes.ServerPlayerEntityInterface;
import carpet.fakes.ServerPlayerInteractionManagerInterface;
import carpet.helpers.Tracer;
import carpet.network.ServerNetworkHandler;
import carpet.patches.EntityPlayerMPFake;
import carpet.script.CarpetContext;
import carpet.script.CarpetScriptServer;
import carpet.script.EntityEventsGroup;
import carpet.script.argument.Vector3Argument;
import carpet.script.exception.InternalExpressionException;
import carpet.script.utils.InputValidator;
import com.google.common.collect.Sets;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.selector.EntitySelector;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.StringTag;
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket;
import net.minecraft.network.protocol.game.ClientboundSetExperiencePacket;
import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket;
import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.Tag;
import net.minecraft.tags.TagKey;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.AgeableMob;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.entity.MobType;
import net.minecraft.world.entity.PathfinderMob;
import net.minecraft.world.entity.Pose;
import net.minecraft.world.entity.ai.Brain;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeMap;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.entity.ai.goal.MoveTowardsRestrictionGoal;
import net.minecraft.world.entity.ai.memory.ExpirableValue;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.Projectile;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.pathfinder.Path;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static carpet.script.value.NBTSerializableValue.nameFromRegistryId;
import static carpet.utils.MobAI.genericJump;
// TODO: decide whether copy(entity) should duplicate entity in the world.
public class EntityValue extends Value
{
private Entity entity;
public EntityValue(Entity e)
{
entity = e;
}
public static Value of(Entity e)
{
if (e == null) return Value.NULL;
return new EntityValue(e);
}
private static final Map<String, EntitySelector> selectorCache = new HashMap<>();
public static Collection<? extends Entity > getEntitiesFromSelector(CommandSourceStack source, String selector)
{
try
{
EntitySelector entitySelector = selectorCache.get(selector);
if (entitySelector != null)
{
return entitySelector.findEntities(source.withMaximumPermission(4));
}
entitySelector = new EntitySelectorParser(new StringReader(selector), true).parse();
selectorCache.put(selector, entitySelector);
return entitySelector.findEntities(source.withMaximumPermission(4));
}
catch (CommandSyntaxException e)
{
throw new InternalExpressionException("Cannot select entities from "+selector);
}
}
public Entity getEntity()
{
if (entity instanceof ServerPlayer && ((ServerPlayerEntityInterface)entity).isInvalidEntityObject())
{
ServerPlayer newPlayer = entity.getServer().getPlayerList().getPlayer(entity.getUUID());
if (newPlayer != null) entity = newPlayer;
}
return entity;
}
public static ServerPlayer getPlayerByValue(MinecraftServer server, Value value)
{
ServerPlayer player = null;
if (value instanceof EntityValue)
{
Entity e = ((EntityValue) value).getEntity();
if (e instanceof ServerPlayer)
{
player = (ServerPlayer) e;
}
}
else if (value.isNull())
{
return null;
}
else
{
String playerName = value.getString();
player = server.getPlayerList().getPlayerByName(playerName);
}
return player;
}
public static String getPlayerNameByValue(Value value)
{
String playerName = null;
if (value instanceof EntityValue)
{
Entity e = ((EntityValue) value).getEntity();
if (e instanceof ServerPlayer)
{
playerName = e.getScoreboardName();
}
}
else if (value.isNull())
{
return null;
}
else
{
playerName = value.getString();
}
return playerName;
}
@Override
public String getString()
{
return getEntity().getName().getString();
}
@Override
public boolean getBoolean()
{
return true;
}
@Override
public boolean equals(Object v)
{
if (v instanceof EntityValue)
{
return getEntity().getId()==((EntityValue) v).getEntity().getId();
}
return super.equals((Value)v);
}
@Override
public Value in(Value v)
{
if (v instanceof ListValue)
{
List<Value> values = ((ListValue) v).getItems();
String what = values.get(0).getString();
Value arg = null;
if (values.size() == 2)
{
arg = values.get(1);
}
else if (values.size() > 2)
{
arg = ListValue.wrap(values.subList(1,values.size()));
}
return this.get(what, arg);
}
String what = v.getString();
return this.get(what, null);
}
@Override
public String getTypeString()
{
return "entity";
}
@Override
public int hashCode()
{
return getEntity().hashCode();
}
public static final EntityTypeTest<Entity, ?> ANY = EntityTypeTest.forClass(Entity.class);
public static EntityClassDescriptor getEntityDescriptor(String who, MinecraftServer server)
{
EntityClassDescriptor eDesc = EntityClassDescriptor.byName.get(who);
if (eDesc == null)
{
boolean positive = true;
if (who.startsWith("!"))
{
positive = false;
who = who.substring(1);
}
String booWho = who;
HolderSet.Named<EntityType<?>> eTagValue = server.registryAccess().registryOrThrow(Registry.ENTITY_TYPE_REGISTRY)
.getTag(TagKey.create(Registry.ENTITY_TYPE_REGISTRY, InputValidator.identifierOf(who)))
.orElseThrow( () -> new InternalExpressionException(booWho+" is not a valid entity descriptor"));
Set<EntityType<?>> eTag = eTagValue.stream().map(Holder::value).collect(Collectors.toUnmodifiableSet());
if (positive)
{
if (eTag.size() == 1)
{
EntityType<?> type = eTag.iterator().next();
return new EntityClassDescriptor(type, Entity::isAlive, eTag.stream());
}
else
{
return new EntityClassDescriptor(ANY, e -> eTag.contains(e.getType()) && e.isAlive(), eTag.stream());
}
}
else
{
return new EntityClassDescriptor(ANY, e -> !eTag.contains(e.getType()) && e.isAlive(), Registry.ENTITY_TYPE.stream().filter(et -> !eTag.contains(et)));
}
}
return eDesc;
//TODO add more here like search by tags, or type
//if (who.startsWith('tag:'))
}
public static class EntityClassDescriptor
{
public EntityTypeTest<Entity, ? extends Entity> directType; // interface of EntityType
public Predicate<? super Entity> filteringPredicate;
public List<EntityType<? extends Entity>> typeList;
public Value listValue;
EntityClassDescriptor(EntityType<?> type, Predicate<? super Entity> predicate, List<EntityType<?>> types)
{
directType = type;
filteringPredicate = predicate;
typeList = types;
listValue = (types==null)?Value.NULL:ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(Registry.ENTITY_TYPE.getKey(et)))).collect(Collectors.toList()));
}
EntityClassDescriptor( EntityTypeTest<Entity, ?> type, Predicate<? super Entity> predicate, List<EntityType<?>> types)
{
directType = type;
filteringPredicate = predicate;
typeList = types;
listValue = (types==null)?Value.NULL:ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(Registry.ENTITY_TYPE.getKey(et)))).collect(Collectors.toList()));
}
EntityClassDescriptor(EntityType<?> type, Predicate<? super Entity> predicate, Stream<EntityType<?>> types)
{
this(type, predicate, types.collect(Collectors.toList()));
}
EntityClassDescriptor(EntityTypeTest<Entity, ?> type, Predicate<? super Entity> predicate, Stream<EntityType<?>> types)
{
this(type, predicate, types.collect(Collectors.toList()));
}
public final static Map<String, EntityClassDescriptor> byName = new HashMap<String, EntityClassDescriptor>() {{
List<EntityType<?>> allTypes = Registry.ENTITY_TYPE.stream().collect(Collectors.toList());
// nonliving types
Set<EntityType<?>> projectiles = Sets.newHashSet(
EntityType.ARROW, EntityType.DRAGON_FIREBALL, EntityType.FIREWORK_ROCKET,
EntityType.FIREBALL, EntityType.LLAMA_SPIT, EntityType.SMALL_FIREBALL,
EntityType.SNOWBALL, EntityType.SPECTRAL_ARROW, EntityType.EGG,
EntityType.ENDER_PEARL, EntityType.EXPERIENCE_BOTTLE, EntityType.POTION,
EntityType.TRIDENT, EntityType.WITHER_SKULL, EntityType.FISHING_BOBBER, EntityType.SHULKER_BULLET
);
Set<EntityType<?>> deads = Sets.newHashSet(
EntityType.AREA_EFFECT_CLOUD, EntityType.MARKER, EntityType.BOAT, EntityType.END_CRYSTAL,
EntityType.EVOKER_FANGS, EntityType.EXPERIENCE_ORB, EntityType.EYE_OF_ENDER,
EntityType.FALLING_BLOCK, EntityType.ITEM, EntityType.ITEM_FRAME, EntityType.GLOW_ITEM_FRAME,
EntityType.LEASH_KNOT, EntityType.LIGHTNING_BOLT, EntityType.PAINTING,
EntityType.TNT, EntityType.ARMOR_STAND
);
Set<EntityType<?>> minecarts = Sets.newHashSet(
EntityType.MINECART, EntityType.CHEST_MINECART, EntityType.COMMAND_BLOCK_MINECART,
EntityType.FURNACE_MINECART, EntityType.HOPPER_MINECART,
EntityType.SPAWNER_MINECART, EntityType.TNT_MINECART
);
// living mob groups - non-defeault
Set<EntityType<?>> undeads = Sets.newHashSet(
EntityType.STRAY, EntityType.SKELETON, EntityType.WITHER_SKELETON,
EntityType.ZOMBIE, EntityType.DROWNED, EntityType.ZOMBIE_VILLAGER,
EntityType.ZOMBIE_HORSE, EntityType.SKELETON_HORSE, EntityType.PHANTOM,
EntityType.WITHER, EntityType.ZOGLIN, EntityType.HUSK, EntityType.ZOMBIFIED_PIGLIN
);
Set<EntityType<?>> arthropods = Sets.newHashSet(
EntityType.BEE, EntityType.ENDERMITE, EntityType.SILVERFISH, EntityType.SPIDER,
EntityType.CAVE_SPIDER
);
Set<EntityType<?>> aquatique = Sets.newHashSet(
EntityType.GUARDIAN, EntityType.TURTLE, EntityType.COD, EntityType.DOLPHIN, EntityType.PUFFERFISH,
EntityType.SALMON, EntityType.SQUID, EntityType.TROPICAL_FISH
);
Set<EntityType<?>> illagers = Sets.newHashSet(
EntityType.PILLAGER, EntityType.ILLUSIONER, EntityType.VINDICATOR, EntityType.EVOKER,
EntityType.RAVAGER, EntityType.WITCH
);
Set<EntityType<?>> living = allTypes.stream().filter(et ->
!deads.contains(et) && !projectiles.contains(et) && !minecarts.contains(et)
).collect(Collectors.toSet());
Set<EntityType<?>> regular = allTypes.stream().filter(et ->
living.contains(et) && !undeads.contains(et) && !arthropods.contains(et) && !aquatique.contains(et) && !illagers.contains(et)
).collect(Collectors.toSet());
put("*", new EntityClassDescriptor(ANY, e -> true, allTypes) );
put("valid", new EntityClassDescriptor(ANY, net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes));
put("!valid", new EntityClassDescriptor(ANY, e -> !e.isAlive(), allTypes));
put("living", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes.stream().filter(living::contains)));
put("!living", new EntityClassDescriptor(ANY, (e) -> (!(e instanceof LivingEntity) && e.isAlive()), allTypes.stream().filter(et -> !living.contains(et))));
put("projectile", new EntityClassDescriptor(EntityTypeTest.forClass(Projectile.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes.stream().filter(projectiles::contains)));
put("!projectile", new EntityClassDescriptor(ANY, (e) -> (!(e instanceof Projectile) && e.isAlive()), allTypes.stream().filter(et -> !projectiles.contains(et) && !living.contains(et))));
put("minecarts", new EntityClassDescriptor(EntityTypeTest.forClass(AbstractMinecart.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes.stream().filter(minecarts::contains)));
put("!minecarts", new EntityClassDescriptor(ANY, (e) -> (!(e instanceof AbstractMinecart) && e.isAlive()), allTypes.stream().filter(et -> !minecarts.contains(et) && !living.contains(et))));
// combat groups
put("arthropod", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.ARTHROPOD && e.isAlive()), allTypes.stream().filter(arthropods::contains)));
put("!arthropod", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.ARTHROPOD && e.isAlive()), allTypes.stream().filter(et -> !arthropods.contains(et) && living.contains(et))));
put("undead", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.UNDEAD && e.isAlive()), allTypes.stream().filter(undeads::contains)));
put("!undead", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.UNDEAD && e.isAlive()), allTypes.stream().filter(et -> !undeads.contains(et) && living.contains(et))));
put("aquatic", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.WATER && e.isAlive()), allTypes.stream().filter(aquatique::contains)));
put("!aquatic", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.WATER && e.isAlive()), allTypes.stream().filter(et -> !aquatique.contains(et) && living.contains(et))));
put("illager", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.ILLAGER && e.isAlive()), allTypes.stream().filter(illagers::contains)));
put("!illager", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.ILLAGER && e.isAlive()), allTypes.stream().filter(et -> !illagers.contains(et) && living.contains(et))));
put("regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(regular::contains)));
put("!regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(et -> !regular.contains(et) && living.contains(et))));
for (ResourceLocation typeId : Registry.ENTITY_TYPE.keySet())
{
EntityType<?> type = Registry.ENTITY_TYPE.get(typeId);
String mobType = ValueConversions.simplify(typeId);
put( mobType, new EntityClassDescriptor(type, net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, Stream.of(type)));
put("!"+mobType, new EntityClassDescriptor(ANY, (e) -> e.getType() != type && e.isAlive(), allTypes.stream().filter(et -> et != type)));
}
for (MobCategory catId : MobCategory.values())
{
String catStr = catId.getName();
put( catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() == catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() == catId)));
put("!"+catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() != catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() != catId)));
}
}};
}
public Value get(String what, Value arg)
{
if (!(featureAccessors.containsKey(what)))
throw new InternalExpressionException("Unknown entity feature: "+what);
try
{
return featureAccessors.get(what).apply(getEntity(), arg);
}
catch (NullPointerException npe)
{
throw new InternalExpressionException("Cannot fetch '"+what+"' with these arguments");
}
}
private static final Map<String, EquipmentSlot> inventorySlots = Map.of(
"mainhand", EquipmentSlot.MAINHAND,
"offhand", EquipmentSlot.OFFHAND,
"head", EquipmentSlot.HEAD,
"chest", EquipmentSlot.CHEST,
"legs", EquipmentSlot.LEGS,
"feet", EquipmentSlot.FEET
);
private static final Map<String, BiFunction<Entity, Value, Value>> featureAccessors = new HashMap<String, BiFunction<Entity, Value, Value>>() {{
//put("test", (e, a) -> a == null ? Value.NULL : new StringValue(a.getString()));
put("removed", (entity, arg) -> BooleanValue.of(entity.isRemoved()));
put("uuid",(e, a) -> new StringValue(e.getStringUUID()));
put("id",(e, a) -> new NumericValue(e.getId()));
put("pos", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ())));
put("location", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()), new NumericValue(e.getYRot()), new NumericValue(e.getXRot())));
put("x", (e, a) -> new NumericValue(e.getX()));
put("y", (e, a) -> new NumericValue(e.getY()));
put("z", (e, a) -> new NumericValue(e.getZ()));
put("motion", (e, a) ->
{
Vec3 velocity = e.getDeltaMovement();
return ListValue.of(new NumericValue(velocity.x), new NumericValue(velocity.y), new NumericValue(velocity.z));
});
put("motion_x", (e, a) -> new NumericValue(e.getDeltaMovement().x));
put("motion_y", (e, a) -> new NumericValue(e.getDeltaMovement().y));
put("motion_z", (e, a) -> new NumericValue(e.getDeltaMovement().z));
put("on_ground", (e, a) -> BooleanValue.of(e.isOnGround()));
put("name", (e, a) -> new StringValue(e.getName().getString()));
put("display_name", (e, a) -> new FormattedTextValue(e.getDisplayName()));
put("command_name", (e, a) -> new StringValue(e.getScoreboardName()));
put("custom_name", (e, a) -> e.hasCustomName()?new StringValue(e.getCustomName().getString()):Value.NULL);
put("type", (e, a) -> new StringValue(nameFromRegistryId(Registry.ENTITY_TYPE.getKey(e.getType()))));
put("is_riding", (e, a) -> BooleanValue.of(e.isPassenger()));
put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle()));
put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new).collect(Collectors.toList())));
put("mount", (e, a) -> (e.getVehicle()!=null)?new EntityValue(e.getVehicle()):Value.NULL);
put("unmountable", (e, a) -> BooleanValue.of(((EntityInterface)e).isPermanentVehicle()));
// deprecated
put("tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new).collect(Collectors.toList())));
put("scoreboard_tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new).collect(Collectors.toList())));
put("entity_tags", (e, a) -> {
EntityType<?> type = e.getType();
return ListValue.wrap(e.getServer().registryAccess().registryOrThrow(Registry.ENTITY_TYPE_REGISTRY).getTags().filter(entry -> entry.getSecond().stream().anyMatch(h -> h.value()==type)).map(entry -> ValueConversions.of(entry.getFirst())).collect(Collectors.toList()));
});
// deprecated
put("has_tag", (e, a) -> BooleanValue.of(e.getTags().contains(a.getString())));
put("has_scoreboard_tag", (e, a) -> BooleanValue.of(e.getTags().contains(a.getString())));
put("has_entity_tag", (e, a) -> {
Optional<HolderSet.Named<EntityType<?>>> tag = e.getServer().registryAccess().registryOrThrow(Registry.ENTITY_TYPE_REGISTRY).getTag(TagKey.create(Registry.ENTITY_TYPE_REGISTRY, InputValidator.identifierOf(a.getString())));
if (tag.isEmpty()) return Value.NULL;
//Tag<EntityType<?>> tag = e.getServer().getTags().getOrEmpty(Registry.ENTITY_TYPE_REGISTRY).getTag(InputValidator.identifierOf(a.getString()));
//if (tag == null) return Value.NULL;
//return BooleanValue.of(e.getType().is(tag));
EntityType<?> type = e.getType();
return BooleanValue.of(tag.get().stream().anyMatch(h -> h.value() == type));
});
put("yaw", (e, a)-> new NumericValue(e.getYRot()));
put("head_yaw", (e, a)-> {
if (e instanceof LivingEntity)
{
return new NumericValue(e.getYHeadRot());
}
return Value.NULL;
});
put("body_yaw", (e, a)-> {
if (e instanceof LivingEntity)
{
return new NumericValue(((LivingEntity) e).yBodyRot);
}
return Value.NULL;
});
put("pitch", (e, a)-> new NumericValue(e.getXRot()));
put("look", (e, a) -> {
Vec3 look = e.getLookAngle();
return ListValue.of(new NumericValue(look.x),new NumericValue(look.y),new NumericValue(look.z));
});
put("is_burning", (e, a) -> BooleanValue.of(e.isOnFire()));
put("fire", (e, a) -> new NumericValue(e.getRemainingFireTicks()));
put("is_freezing", (e, a) -> BooleanValue.of(e.isFullyFrozen()));
put("frost", (e, a) -> new NumericValue(e.getTicksFrozen()));
put("silent", (e, a)-> BooleanValue.of(e.isSilent()));
put("gravity", (e, a) -> BooleanValue.of(!e.isNoGravity()));
put("immune_to_fire", (e, a) -> BooleanValue.of(e.fireImmune()));
put("immune_to_frost", (e, a) -> BooleanValue.of(!e.canFreeze()));
put("invulnerable", (e, a) -> BooleanValue.of(e.isInvulnerable()));
put("dimension", (e, a) -> new StringValue(nameFromRegistryId(e.level.dimension().location()))); // getDimId
put("height", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).height));
put("width", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).width));
put("eye_height", (e, a) -> new NumericValue(e.getEyeHeight()));
put("age", (e, a) -> new NumericValue(e.tickCount));
put("breeding_age", (e, a) -> e instanceof AgeableMob?new NumericValue(((AgeableMob) e).getAge()):Value.NULL);
put("despawn_timer", (e, a) -> e instanceof LivingEntity?new NumericValue(((LivingEntity) e).getNoActionTime()):Value.NULL);
put("item", (e, a) -> (e instanceof ItemEntity)?ValueConversions.of(((ItemEntity) e).getItem()):Value.NULL);
put("count", (e, a) -> (e instanceof ItemEntity)?new NumericValue(((ItemEntity) e).getItem().getCount()):Value.NULL);
put("pickup_delay", (e, a) -> (e instanceof ItemEntity)?new NumericValue(((ItemEntityInterface) e).getPickupDelayCM()):Value.NULL);
put("portal_cooldown", (e , a) ->new NumericValue(((EntityInterface)e).getPortalTimer()));
put("portal_timer", (e , a) ->new NumericValue(((EntityInterface)e).getPublicNetherPortalCooldown()));
// ItemEntity -> despawn timer via ssGetAge
put("is_baby", (e, a) -> (e instanceof LivingEntity)?BooleanValue.of(((LivingEntity) e).isBaby()):Value.NULL);
put("target", (e, a) -> {
if (e instanceof Mob)
{
LivingEntity target = ((Mob) e).getTarget(); // there is also getAttacking in living....
if (target != null)
{
return new EntityValue(target);
}
}
return Value.NULL;
});
put("home", (e, a) -> {
if (e instanceof Mob)
{
return (((Mob) e).getRestrictRadius () > 0)?new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((PathfinderMob) e).getRestrictCenter()):Value.FALSE;
}
return Value.NULL;
});
put("spawn_point", (e, a) -> {
if (e instanceof ServerPlayer spe)
{
if (spe.getRespawnPosition() == null) return Value.FALSE;
return ListValue.of(
ValueConversions.of(spe.getRespawnPosition()),
ValueConversions.of(spe.getRespawnDimension()),
new NumericValue(spe.getRespawnAngle()),
BooleanValue.of(spe.isRespawnForced())
);
}
return Value.NULL;
});
put("pose", (e, a) -> new StringValue(e.getPose().name().toLowerCase(Locale.ROOT)));
put("sneaking", (e, a) -> e.isShiftKeyDown()?Value.TRUE:Value.FALSE);
put("sprinting", (e, a) -> e.isSprinting()?Value.TRUE:Value.FALSE);
put("swimming", (e, a) -> e.isSwimming()?Value.TRUE:Value.FALSE);
put("swinging", (e, a) -> {
if (e instanceof LivingEntity) return BooleanValue.of(((LivingEntity) e).swinging);
return Value.NULL;
});
put("air", (e, a) -> new NumericValue(e.getAirSupply()));
put("language", (e, a)->{
if(!(e instanceof ServerPlayer))
return NULL;
String lang = ((ServerPlayerEntityInterface) e).getLanguage();
return StringValue.of(lang);
});
put("persistence", (e, a) -> {
if (e instanceof Mob) return BooleanValue.of(((Mob) e).isPersistenceRequired());
return Value.NULL;
});
put("hunger", (e, a) -> {
if(e instanceof Player) return new NumericValue(((Player) e).getFoodData().getFoodLevel());
return Value.NULL;
});
put("saturation", (e, a) -> {
if(e instanceof Player) return new NumericValue(((Player) e).getFoodData().getSaturationLevel());
return Value.NULL;
});
put("exhaustion",(e, a)->{
if(e instanceof Player) return new NumericValue(((Player) e).getFoodData().getExhaustionLevel());
return Value.NULL;
});
put("absorption",(e, a)->{
if(e instanceof Player) return new NumericValue(((Player) e).getAbsorptionAmount());
return Value.NULL;
});
put("xp",(e, a)->{
if(e instanceof Player) return new NumericValue(((Player) e).totalExperience);
return Value.NULL;
});
put("xp_level", (e, a)->{
if(e instanceof Player) return new NumericValue(((Player) e).experienceLevel);
return Value.NULL;
});
put("xp_progress", (e, a)->{
if(e instanceof Player) return new NumericValue(((Player) e).experienceProgress);
return Value.NULL;
});
put("score", (e, a)->{
if(e instanceof Player) return new NumericValue(((Player) e).getScore());
return Value.NULL;
});
put("jumping", (e, a) -> {
if (e instanceof LivingEntity)
{
return ((LivingEntityInterface) e).isJumpingCM()?Value.TRUE:Value.FALSE;
}
return Value.NULL;
});
put("gamemode", (e, a) -> {
if (e instanceof ServerPlayer)
{
return new StringValue(((ServerPlayer) e).gameMode.getGameModeForPlayer().getName());
}
return Value.NULL;
});
put("path", (e, a) -> {
if (e instanceof Mob)
{
Path path = ((Mob)e).getNavigation().getPath();
if (path == null) return Value.NULL;
return ValueConversions.fromPath((ServerLevel)e.getCommandSenderWorld(), path);
}
return Value.NULL;
});
put("brain", (e, a) -> {
String module = a.getString();
MemoryModuleType<?> moduleType = Registry.MEMORY_MODULE_TYPE.get(InputValidator.identifierOf(module));
if (moduleType == MemoryModuleType.DUMMY) return Value.NULL;
if (e instanceof LivingEntity livingEntity)
{
Brain<?> brain = livingEntity.getBrain();
Map<MemoryModuleType<?>, Optional<? extends ExpirableValue<?>>> memories = brain.getMemories();
Optional<? extends ExpirableValue<?>> optmemory = memories.get(moduleType);
if (optmemory==null || !optmemory.isPresent()) return Value.NULL;
ExpirableValue<?> memory = optmemory.get();
return ValueConversions.fromTimedMemory(e, memory.getTimeToLive(), memory.getValue());
}
return Value.NULL;
});
put("gamemode_id", (e, a) -> {
if (e instanceof ServerPlayer)
{
return new NumericValue(((ServerPlayer) e).gameMode.getGameModeForPlayer().getId());
}
return Value.NULL;
});
put("permission_level", (e, a) -> {
if (e instanceof ServerPlayer spe)
{
for (int i=4; i>=0; i--)
{
if (spe.hasPermissions(i))
return new NumericValue(i);
}
return new NumericValue(0);
}
return Value.NULL;
});
put("player_type", (e, a) -> {
if (e instanceof Player p)
{
if (e instanceof EntityPlayerMPFake) return new StringValue(((EntityPlayerMPFake) e).isAShadow?"shadow":"fake");
MinecraftServer server = p.getCommandSenderWorld().getServer();
if (server.isDedicatedServer()) return new StringValue("multiplayer");
boolean runningLan = server.isPublished();
if (!runningLan) return new StringValue("singleplayer");
boolean isowner = server.isSingleplayerOwner(p.getGameProfile());
if (isowner) return new StringValue("lan_host");
return new StringValue("lan player");
// realms?
}
return Value.NULL;
});
put("client_brand", (e, a) -> {
if (e instanceof ServerPlayer)
{
return StringValue.of(ServerNetworkHandler.getPlayerStatus((ServerPlayer) e));
}
return Value.NULL;
});
put("team", (e, a) -> e.getTeam()==null?Value.NULL:new StringValue(e.getTeam().getName()));
put("ping", (e, a) -> {
if (e instanceof ServerPlayer)
{
ServerPlayer spe = (ServerPlayer) e;
return new NumericValue(spe.latency);
}
return Value.NULL;
});
//spectating_entity
// isGlowing
put("effect", (e, a) ->
{
if (!(e instanceof LivingEntity))
{
return Value.NULL;
}
if (a == null)
{
List<Value> effects = new ArrayList<>();
for (MobEffectInstance p : ((LivingEntity) e).getActiveEffects())
{
effects.add(ListValue.of(
new StringValue(p.getDescriptionId().replaceFirst("^effect\\.minecraft\\.", "")),
new NumericValue(p.getAmplifier()),
new NumericValue(p.getDuration())
));
}
return ListValue.wrap(effects);
}
String effectName = a.getString();
MobEffect potion = Registry.MOB_EFFECT.get(InputValidator.identifierOf(effectName));
if (potion == null)
throw new InternalExpressionException("No such an effect: "+effectName);
if (!((LivingEntity) e).hasEffect(potion))
return Value.NULL;
MobEffectInstance pe = ((LivingEntity) e).getEffect(potion);
return ListValue.of( new NumericValue(pe.getAmplifier()), new NumericValue(pe.getDuration()) );
});
put("health", (e, a) ->
{
if (e instanceof LivingEntity)
{
return new NumericValue(((LivingEntity) e).getHealth());
}
//if (e instanceof ItemEntity)
//{
// e.h consider making item health public
//}
return Value.NULL;
});
put("may_fly", (e, a) -> {
if (e instanceof ServerPlayer player) {
return BooleanValue.of(player.getAbilities().mayfly);
}
return Value.NULL;
});
put("flying", (e, v) -> {
if (e instanceof ServerPlayer player) {
return BooleanValue.of(player.getAbilities().flying);
}
return Value.NULL;
});
put("may_build", (e, v) -> {
if (e instanceof ServerPlayer player) {
return BooleanValue.of(player.getAbilities().mayBuild);
}
return Value.NULL;
});
put("insta_build", (e, v) -> {
if (e instanceof ServerPlayer player) {
return BooleanValue.of(player.getAbilities().instabuild);
}
return Value.NULL;
});
put("fly_speed", (e, v) -> {
if (e instanceof ServerPlayer player) {
return NumericValue.of(player.getAbilities().getFlyingSpeed());
}
return Value.NULL;
});
put("walk_speed", (e, v) -> {
if (e instanceof ServerPlayer player) {
return NumericValue.of(player.getAbilities().getWalkingSpeed());
}
return Value.NULL;
});
put("holds", (e, a) -> {
EquipmentSlot where = EquipmentSlot.MAINHAND;
if (a != null)
where = inventorySlots.get(a.getString());
if (where == null)
throw new InternalExpressionException("Unknown inventory slot: "+a.getString());
if (e instanceof LivingEntity)
return ValueConversions.of(((LivingEntity)e).getItemBySlot(where));
return Value.NULL;
});
put("selected_slot", (e, a) -> {
if (e instanceof Player)
return new NumericValue(((Player) e).getInventory().selected); //getInventory
return Value.NULL;
});
put("active_block", (e, a) -> {
if (e instanceof ServerPlayer)
{
ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayer) e).gameMode);
BlockPos pos = manager.getCurrentBreakingBlock();
if (pos == null) return Value.NULL;
return new BlockValue(null, (ServerLevel) e.level, pos);
}
return Value.NULL;
});
put("breaking_progress", (e, a) -> {
if (e instanceof ServerPlayer)
{
ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayer) e).gameMode);
int progress = manager.getCurrentBlockBreakingProgress();
if (progress < 0) return Value.NULL;
return new NumericValue(progress);
}
return Value.NULL;
});
put("facing", (e, a) -> {
int index = 0;
if (a != null)
index = (6+(int)NumericValue.asNumber(a).getLong())%6;
if (index < 0 || index > 5)
throw new InternalExpressionException("Facing order should be between -6 and 5");
return new StringValue(Direction.orderedByNearest(e)[index].getSerializedName());
});
put("trace", (e, a) ->
{
float reach = 4.5f;
boolean entities = true;
boolean liquids = false;
boolean blocks = true;
boolean exact = false;
if (a!=null)
{
if (!(a instanceof ListValue))
{
reach = (float) NumericValue.asNumber(a).getDouble();
}
else
{
List<Value> args = ((ListValue) a).getItems();
if (args.size()==0)
throw new InternalExpressionException("'trace' needs more arguments");
reach = (float) NumericValue.asNumber(args.get(0)).getDouble();
if (args.size() > 1)
{
entities = false;
blocks = false;
for (int i = 1; i < args.size(); i++)
{
String what = args.get(i).getString();
if (what.equalsIgnoreCase("entities"))
entities = true;
else if (what.equalsIgnoreCase("blocks"))
blocks = true;
else if (what.equalsIgnoreCase("liquids"))
liquids = true;
else if (what.equalsIgnoreCase("exact"))
exact = true;
else throw new InternalExpressionException("Incorrect tracing: "+what);
}
}
}
}
else if (e instanceof ServerPlayer && ((ServerPlayer) e).gameMode.isCreative())
{
reach = 5.0f;
}
HitResult hitres;
if (entities && !blocks)
hitres = Tracer.rayTraceEntities(e, 1, reach, reach*reach);
else if (entities)
hitres = Tracer.rayTrace(e, 1, reach, liquids);
else
hitres = Tracer.rayTraceBlocks(e, 1, reach, liquids);
if (hitres == null) return Value.NULL;
if (exact && hitres.getType() != HitResult.Type.MISS) return ValueConversions.of(hitres.getLocation());
switch (hitres.getType())
{
case MISS: return Value.NULL;
case BLOCK: return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((BlockHitResult)hitres).getBlockPos() );
case ENTITY: return new EntityValue(((EntityHitResult)hitres).getEntity());
}
return Value.NULL;
});
put("attribute", (e, a) ->{
if (!(e instanceof LivingEntity)) return Value.NULL;
LivingEntity el = (LivingEntity)e;
if (a == null)
{
AttributeMap container = el.getAttributes();
return MapValue.wrap(Registry.ATTRIBUTE.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(Registry.ATTRIBUTE.getKey(aa)), aa -> NumericValue.of(container.getValue(aa)))));
}
ResourceLocation id = InputValidator.identifierOf(a.getString());
Attribute attrib = Registry.ATTRIBUTE.getOptional(id).orElseThrow(
() -> new InternalExpressionException("Unknown attribute: "+a.getString())
);
if (!el.getAttributes().hasAttribute(attrib)) return Value.NULL;
return NumericValue.of(el.getAttributeValue(attrib));
});
put("nbt",(e, a) -> {
CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag()));
if (a==null)
return new NBTSerializableValue(nbttagcompound);
return new NBTSerializableValue(nbttagcompound).get(a);
});
put("category",(e,a)->{return new StringValue(e.getType().getCategory().toString().toLowerCase(Locale.ROOT));});
}};
public void set(String what, Value toWhat)
{
if (!(featureModifiers.containsKey(what)))
throw new InternalExpressionException("Unknown entity action: " + what);
try
{
featureModifiers.get(what).accept(getEntity(), toWhat);
}
catch (NullPointerException npe)
{
throw new InternalExpressionException("'modify' for '"+what+"' expects a value");
}
catch (IndexOutOfBoundsException ind)
{
throw new InternalExpressionException("Wrong number of arguments for `modify` option: "+what);
}
}
private static void updatePosition(Entity e, double x, double y, double z, float yaw, float pitch)
{
if (
!Double.isFinite(x) || Double.isNaN(x) ||
!Double.isFinite(y) || Double.isNaN(y) ||
!Double.isFinite(z) || Double.isNaN(z) ||
!Float.isFinite(yaw) || Float.isNaN(yaw) ||
!Float.isFinite(pitch) || Float.isNaN(pitch)
)
return;
if (e instanceof ServerPlayer)
{
// this forces position but doesn't angles for some reason. Need both in the API in the future.
EnumSet<ClientboundPlayerPositionPacket.RelativeArgument> set = EnumSet.noneOf(ClientboundPlayerPositionPacket.RelativeArgument.class);
set.add(ClientboundPlayerPositionPacket.RelativeArgument.X_ROT);
set.add(ClientboundPlayerPositionPacket.RelativeArgument.Y_ROT);
((ServerPlayer)e).connection.teleport(x, y, z, yaw, pitch, set );
}
else
{
e.moveTo(x, y, z, yaw, pitch);
// we were sending to players for not-living entites, that were untracked. Living entities should be tracked.
//((ServerWorld) e.getEntityWorld()).getChunkManager().sendToNearbyPlayers(e, new EntityS2CPacket.(e));
if (e instanceof LivingEntity le)
{
le.yBodyRotO = le.yRotO = yaw;
le.yHeadRotO = le.yHeadRot = yaw;
// seems universal for:
//e.setHeadYaw(yaw);
//e.setYaw(yaw);
}
else
{
((ServerLevel) e.getCommandSenderWorld()).getChunkSource().broadcastAndSend(e, new ClientboundTeleportEntityPacket(e));
}
}
}