Skip to content

Commit a65912f

Browse files
committed
refactor LuaConvertor
rename toObject -> toLua add EntityContextBuilder to prevent millions entityToLua overloads cache the result of blockStateToLua
1 parent 76dd4ed commit a65912f

23 files changed

Lines changed: 270 additions & 251 deletions

src/main/java/de/srendi/advancedperipherals/common/addons/appliedenergistics/AEApi.java

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -406,8 +406,8 @@ public static Map<Object, Object> parseDrive(DriveBlockEntity drive) {
406406
properties.put("totalBytes", totalBytes);
407407
properties.put("cells", driveCells);
408408
properties.put("priority", drive.getPriority());
409-
properties.put("menuIcon", LuaConverter.itemToObject(drive.getMainMenuIcon().getItem()));
410-
properties.put("position", LuaConverter.posToObject(drive.getBlockPos()));
409+
properties.put("menuIcon", LuaConverter.itemToLua(drive.getMainMenuIcon().getItem()));
410+
properties.put("position", LuaConverter.posToLua(drive.getBlockPos()));
411411
properties.put("name", drive.hasCustomName() ? drive.getCustomName().getString() : drive.getDisplayName().getString());
412412

413413
return properties;
@@ -417,7 +417,7 @@ public static Map<Object, Object> parseCell(IBasicCellItem cell, ItemStack cellI
417417
Map<Object, Object> properties = new HashMap<>();
418418
BasicCellInventory cellInventory = BasicCellHandler.INSTANCE.getCellInventory(cellItem, null);
419419

420-
properties.put("item", LuaConverter.itemToObject(cellItem.getItem()));
420+
properties.put("item", LuaConverter.itemToLua(cellItem.getItem()));
421421
properties.put("type", cell.getKeyType().toString());
422422
properties.put("bytes", cell.getBytes(cellItem));
423423
properties.put("bytesPerType", cell.getBytesPerType(cellItem));
@@ -435,7 +435,7 @@ private static Map<String, Object> parseDISKDrive(DISKDrive drive, ItemStack sta
435435
if (cellInventory == null)
436436
return null;
437437

438-
properties.put("item", LuaConverter.itemToObject(stack.getItem()));
438+
properties.put("item", LuaConverter.itemToLua(stack.getItem()));
439439
properties.put("type", drive.getKeyType().toString());
440440
properties.put("bytes", drive.getBytes(stack));
441441
properties.put("bytesPerType", 0);
@@ -447,21 +447,19 @@ private static Map<String, Object> parseDISKDrive(DISKDrive drive, ItemStack sta
447447
}
448448

449449
private static Map<String, Object> parseItemStack(Pair<Long, AEItemKey> stack, @Nullable ICraftingService craftingService) {
450-
Map<String, Object> properties = LuaConverter.itemStackToObject(stack.getRight().getReadOnlyStack());
451-
properties.put("count", stack.getLeft());
450+
Map<String, Object> properties = LuaConverter.itemStackToLua(stack.getRight().getReadOnlyStack(), stack.getLeft());
452451
properties.put("isCraftable", craftingService != null && craftingService.isCraftable(stack.getRight()));
453452
return properties;
454453
}
455454

456455
private static Map<String, Object> parseFluidStack(Pair<Long, AEFluidKey> stack, @Nullable ICraftingService craftingService) {
457-
Map<String, Object> properties = LuaConverter.fluidStackToObject(stack.getRight().toStack(1));
458-
properties.put("count", stack.getLeft());
456+
Map<String, Object> properties = LuaConverter.fluidStackToLua(stack.getRight().toStack(1), stack.getLeft());
459457
properties.put("isCraftable", craftingService != null && craftingService.isCraftable(stack.getRight()));
460458
return properties;
461459
}
462460

463461
private static Map<String, Object> parseChemStack(Pair<Long, MekanismKey> stack, @Nullable ICraftingService craftingService) {
464-
Map<String, Object> properties = LuaConverter.chemicalStackToObject(stack.getRight().withAmount(stack.getLeft()));
462+
Map<String, Object> properties = LuaConverter.chemicalStackToLua(stack.getRight().withAmount(stack.getLeft()));
465463
properties.put("isCraftable", craftingService != null && craftingService.isCraftable(stack.getRight()));
466464
return properties;
467465
}

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/owner/IPeripheralOwner.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,16 @@ default Vec3 getCenterPos() {
5858
return getPos().getCenter();
5959
}
6060

61+
@NotNull
62+
default Vec3 getPhysicsPos() {
63+
Vec3 pos = this.getCenterPos();
64+
return pos;
65+
// if (!APAddons.vs2Loaded) {
66+
// return pos;
67+
// }
68+
// return ValkyrienSkies.transformToWorldPos(getLevel(), getPos(), pos);
69+
}
70+
6171
@NotNull
6272
default Vec3 getDirection() {
6373
Vec3 dir = Vec3.atLowerCornerOf(getFacing().getNormal());

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/BlockReaderPeripheral.java

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,11 @@
77
import de.srendi.advancedperipherals.common.configuration.APConfig;
88
import de.srendi.advancedperipherals.common.util.LuaConverter;
99
import de.srendi.advancedperipherals.lib.peripherals.BasePeripheral;
10+
import net.minecraft.core.BlockPos;
1011
import net.minecraft.core.registries.BuiltInRegistries;
11-
import net.minecraft.world.level.Level;
12-
import net.minecraft.world.level.block.Blocks;
1312
import net.minecraft.world.level.block.entity.BlockEntity;
1413
import net.minecraft.world.level.block.state.BlockState;
15-
import net.minecraft.world.level.block.state.properties.Property;
1614

17-
import java.util.HashMap;
1815
import java.util.Map;
1916

2017
public class BlockReaderPeripheral extends BasePeripheral<BlockEntityPeripheralOwner<BlockReaderEntity>> {
@@ -32,43 +29,43 @@ public boolean isEnabled() {
3229

3330
@LuaFunction(mainThread = true)
3431
public final String getBlockName() {
35-
if (getBlockInFront().is(Blocks.AIR)) return "none";
36-
return BuiltInRegistries.BLOCK.getKey(getBlockInFront().getBlock()).toString();
32+
if (getTargetBlock().isAir()) {
33+
return null;
34+
}
35+
return BuiltInRegistries.BLOCK.getKey(getTargetBlock().getBlock()).toString();
3736
}
3837

3938
@LuaFunction(mainThread = true)
40-
public final Object getBlockData() {
41-
if (getBlockInFront().is(Blocks.AIR))
42-
return null;
43-
Level level = getLevel();
44-
BlockEntity target = level.getBlockEntity(getPos().relative(owner.getFacing()));
45-
if (target == null)
46-
return null;
47-
return NBTUtil.toLua(target.saveWithoutMetadata(level.registryAccess()));
39+
public final Map<String, Object> getBlockState() {
40+
BlockState state = getTargetBlock();
41+
return state.isAir() ? null : LuaConverter.blockStateToLua(state);
4842
}
4943

5044
@LuaFunction(mainThread = true)
51-
public final Object getBlockStates() {
52-
if (getBlockInFront().is(Blocks.AIR))
45+
public final Map<String, Object> getBlockData() {
46+
if (getTargetBlock().isAir()) {
5347
return null;
54-
Map<String, Object> states = new HashMap<>();
55-
BlockState block = getLevel().getBlockState(getPos().relative(owner.getFacing()));
56-
for (Property<?> property : block.getProperties())
57-
states.put(property.getName(), LuaConverter.stateToObject(block.getValue(property)));
58-
59-
return states;
48+
}
49+
BlockEntity target = getLevel().getBlockEntity(getTargetBlockPos());
50+
if (target == null) {
51+
return null;
52+
}
53+
return (Map<String, Object>) NBTUtil.toLua(target.saveWithId(getLevel().registryAccess()));
6054
}
6155

6256
@LuaFunction(mainThread = true)
63-
public final boolean isTileEntity() {
64-
if (getBlockInFront().is(Blocks.AIR))
57+
public final boolean hasBlockEntity() {
58+
if (getTargetBlock().isAir()) {
6559
return false;
60+
}
61+
return getLevel().getBlockEntity(getTargetBlockPos()) != null;
62+
}
6663

67-
BlockEntity target = getLevel().getBlockEntity(getPos().relative(owner.getFacing()));
68-
return target != null;
64+
protected BlockPos getTargetBlockPos() {
65+
return getPos().relative(owner.getFacing());
6966
}
7067

71-
private BlockState getBlockInFront() {
72-
return getLevel().getBlockState(getPos().relative(owner.getFacing()));
68+
private BlockState getTargetBlock() {
69+
return getLevel().getBlockState(getTargetBlockPos());
7370
}
7471
}

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/ColonyPeripheral.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ public final double getHappiness() throws LuaException {
131131
public final Object getLocation() throws LuaException {
132132
IColony colony = getColony();
133133

134-
return LuaConverter.posToObject(colony.getCenter());
134+
return LuaConverter.posToLua(colony.getCenter());
135135
}
136136

137137
@LuaFunction(mainThread = true)
@@ -275,7 +275,7 @@ public final Object getRequests() throws LuaException {
275275
map.put("state", request.getState().toString());
276276
map.put("count", deliverableRequest.getCount());
277277
map.put("minCount", deliverableRequest.getMinimumCount());
278-
map.put("items", request.getDisplayStacks().stream().map(item -> LuaConverter.itemStackToObject(item, getLevel())).toList());
278+
map.put("items", request.getDisplayStacks().stream().map(item -> LuaConverter.itemStackToLua(item)).toList());
279279
map.put("target", request.getRequester().getRequesterDisplayName(requestManager, request).getString());
280280
result.add(map);
281281
});

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/EnvironmentDetectorPeripheral.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,16 @@ public final MethodResult scanEntities(@NotNull IArguments arguments) throws Lua
207207
return context.getRadius() > SCAN_ENTITIES.getMaxCostRadius() ? MethodResult.of(null, "Radius exceeds max value") : null;
208208
}, context -> {
209209
Vec3 pos = this.getPhysicsPos();
210-
AABB box = new AABB(pos, pos);
211-
List<Map<String, Object>> entities = getLevel().getEntities((Entity) null, box.inflate(context.getRadius() + 0.5), entity -> entity instanceof LivingEntity && entity.isAlive()).stream().map(entity -> LuaConverter.completeEntityWithPositionToLua(entity, pos, detailed)).toList();
210+
AABB box = new AABB(pos, pos).inflate(context.getRadius() + 0.5);
211+
LuaConverter.EntityConverter.Context convContext = LuaConverter.entityContextBuilder()
212+
.detailed(detailed)
213+
.position(pos)
214+
.build();
215+
List<Map<String, Object>> entities = getLevel()
216+
.getEntities((Entity) null, box, entity -> entity instanceof LivingEntity && entity.isAlive())
217+
.stream()
218+
.map(entity -> LuaConverter.entityToLua(entity, convContext))
219+
.toList();
212220
return MethodResult.of(entities);
213221
}, null);
214222
}

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/GeoScannerPeripheral.java

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,12 @@
2222
import net.minecraft.resources.ResourceLocation;
2323
import net.minecraft.world.level.ChunkPos;
2424
import net.minecraft.world.level.Level;
25-
import net.minecraft.world.level.block.Block;
2625
import net.minecraft.world.level.block.state.BlockState;
2726
import net.minecraft.world.level.chunk.LevelChunk;
2827
import net.minecraft.world.phys.Vec3;
2928
import net.neoforged.neoforge.common.Tags;
3029
import org.jetbrains.annotations.NotNull;
3130

32-
import java.util.AbstractMap;
3331
import java.util.ArrayList;
3432
import java.util.HashMap;
3533
import java.util.List;
@@ -65,17 +63,10 @@ public GeoScannerPeripheral(IPocketAccess pocket) {
6563
private static List<Map<String, Object>> scan(Level level, Vec3 center, int radius) {
6664
List<Map<String, Object>> result = new ArrayList<>();
6765
ScanUtils.traverseBlocks(level, center, radius, (state, pos) -> {
68-
Map<String, Object> data = new HashMap<>(6 * 2);
66+
Map<String, Object> data = new HashMap<>(LuaConverter.blockStateToLua(state));
6967
data.put("x", pos.x);
7068
data.put("y", pos.y);
7169
data.put("z", pos.z);
72-
73-
Block block = state.getBlock();
74-
ResourceLocation name = BuiltInRegistries.BLOCK.getKey(block);
75-
data.put("name", name == null ? "unknown" : name.toString());
76-
data.put("tags", LuaConverter.getHolderTags(block.builtInRegistryHolder()));
77-
data.put("state", LuaConverter.serializeState(state));
78-
7970
result.add(data);
8071
});
8172

@@ -124,7 +115,7 @@ public final MethodResult chunkAnalyze() throws LuaException {
124115
Map.ofEntries(
125116
data.entrySet()
126117
.stream()
127-
.map((entry) -> new AbstractMap.SimpleImmutableEntry<>(entry.getKey().toString(), entry.getValue()))
118+
.map((entry) -> Map.entry(entry.getKey().toString(), entry.getValue()))
128119
.toArray(Map.Entry[]::new)
129120
)
130121
);

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/InventoryManagerPeripheral.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ public final List<Object> list() throws LuaException {
114114
for (int slot = 0; slot < stacks.size(); slot++) {
115115
ItemStack stack = stacks.get(slot);
116116
if (!stack.isEmpty()) {
117-
items.add(LuaConverter.stackToObjectWithSlot(stack, slot));
117+
items.add(LuaConverter.itemStackToLuaWithSlot(stack, slot));
118118
}
119119
}
120120
return items;
@@ -133,7 +133,7 @@ public final MethodResult listChest(String target) throws LuaException {
133133
List<Object> items = new ArrayList<>();
134134
for (int slot = 0; slot < inventoryTo.getSlots(); slot++) {
135135
if (!inventoryTo.getStackInSlot(slot).isEmpty()) {
136-
items.add(LuaConverter.stackToObjectWithSlot(inventoryTo.getStackInSlot(slot), slot));
136+
items.add(LuaConverter.itemStackToLuaWithSlot(inventoryTo.getStackInSlot(slot), slot));
137137
}
138138
}
139139
return MethodResult.of(items);
@@ -144,7 +144,7 @@ public final List<Object> getArmor() throws LuaException {
144144
List<Object> items = new ArrayList<>();
145145
for (ItemStack stack : getOwnerPlayerOrError().getInventory().armor) {
146146
if (!stack.isEmpty()) {
147-
items.add(LuaConverter.stackToObjectWithSlot(stack, ArmorSlot.getSlotForItem(stack)));
147+
items.add(LuaConverter.itemStackToLuaWithSlot(stack, ArmorSlot.getSlotForItem(stack)));
148148
}
149149
}
150150
return items;
@@ -196,12 +196,12 @@ public final int getHandSlot() throws LuaException {
196196
@LuaFunction(mainThread = true)
197197
public final Map<String, Object> getItemInHand() throws LuaException {
198198
Player player = getOwnerPlayerOrError();
199-
return LuaConverter.stackToObjectWithSlot(player.getMainHandItem(), player.getInventory().selected);
199+
return LuaConverter.itemStackToLuaWithSlot(player.getMainHandItem(), player.getInventory().selected);
200200
}
201201

202202
@LuaFunction(mainThread = true)
203203
public final Map<String, Object> getItemInOffHand() throws LuaException {
204-
return LuaConverter.itemStackToObject(getOwnerPlayerOrError().getOffhandItem());
204+
return LuaConverter.itemStackToLua(getOwnerPlayerOrError().getOffhandItem());
205205
}
206206

207207
private Player getOwnerPlayerOrError() throws LuaException {

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/PlayerDetectorPeripheral.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ private Map<String, Object> getPlayerInfo(ServerPlayer player, int posPrecision)
208208
info.put("health", player.getHealth());
209209
info.put("maxHealth", player.getMaxHealth());
210210
info.put("airSupply", player.getAirSupply());
211-
info.put("respawnPosition", LuaConverter.posToObject(player.getRespawnPosition()));
211+
info.put("respawnPosition", LuaConverter.posToLua(player.getRespawnPosition()));
212212
info.put("respawnDimension", player.getRespawnDimension().location().toString());
213213
info.put("respawnAngle", player.getRespawnAngle());
214214
}

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/SaddlePeripheral.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,13 @@ public MethodResult getRider(IArguments args) throws LuaException {
198198
if (entity == null) {
199199
return MethodResult.of(null, "No entity is riding");
200200
}
201-
Map<String, Object> data = LuaConverter.completeEntityToLua(entity, getPeripheralOwner().getToolInMainHand(), detailed);
201+
Map<String, Object> data = LuaConverter.entityToLua(
202+
entity,
203+
LuaConverter.entityContextBuilder()
204+
.detailed(detailed)
205+
.itemInHand(getPeripheralOwner().getToolInMainHand())
206+
.build()
207+
);
202208
if (data.get("pitch") instanceof Number pitch) {
203209
data.put("pitch", (pitch.floatValue() - owner.getTurtle().getDirection().toYRot() + 360 + 180) % 360 - 180);
204210
}

src/main/java/de/srendi/advancedperipherals/common/addons/computercraft/peripheral/plugins/AutomataEntityHandPlugin.java

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,15 @@
1111
import de.srendi.advancedperipherals.common.util.fakeplayer.APFakePlayer;
1212
import de.srendi.advancedperipherals.lib.peripherals.AutomataCorePeripheral;
1313
import de.srendi.advancedperipherals.lib.peripherals.IPeripheralOperation;
14-
import net.minecraft.core.BlockPos;
1514
import net.minecraft.world.InteractionResult;
1615
import net.minecraft.world.entity.Entity;
1716
import net.minecraft.world.entity.animal.Animal;
1817
import net.minecraft.world.item.ItemStack;
1918
import net.minecraft.world.phys.AABB;
2019
import net.minecraft.world.phys.EntityHitResult;
2120
import net.minecraft.world.phys.HitResult;
21+
import net.minecraft.world.phys.Vec3;
22+
2223
import org.jetbrains.annotations.NotNull;
2324
import org.jetbrains.annotations.Nullable;
2425

@@ -48,7 +49,7 @@ public final MethodResult useOnAnimal(@NotNull IArguments arguments) throws LuaE
4849

4950
boolean sneak = options.optBoolean("sneak").orElse(false);
5051
float yaw = options.optDouble("yaw").orElse(0d).floatValue();
51-
float pitch = options.optDouble( "pitch").orElse(0d).floatValue();
52+
float pitch = options.optDouble("pitch").orElse(0d).floatValue();
5253

5354
return automataCore.withOperation(USE_ON_ANIMAL, context -> {
5455
TurtlePeripheralOwner owner = automataCore.getPeripheralOwner();
@@ -66,32 +67,42 @@ public final MethodResult useOnAnimal(@NotNull IArguments arguments) throws LuaE
6667
public final MethodResult inspectAnimal(@NotNull IArguments arguments) throws LuaException {
6768
LuaTable<?, ?> options = EmptyLuaTable.orEmpty(arguments.optTable(0).orElse(null));
6869

69-
boolean sneak = options.optBoolean("sneak").orElse(false);
7070
float yaw = options.optDouble("yaw").orElse(0d).floatValue();
71-
float pitch = options.optDouble( "pitch").orElse(0d).floatValue();
71+
float pitch = options.optDouble("pitch").orElse(0d).floatValue();
7272

7373
automataCore.addRotationCycle();
7474
TurtlePeripheralOwner owner = automataCore.getPeripheralOwner();
7575
HitResult entityHit = owner.withPlayer(APFakePlayer.wrapActionWithRot(yaw, pitch, p -> p.findHit(false, true, suitableEntity)));
76-
if (entityHit.getType() == HitResult.Type.MISS)
76+
if (entityHit.getType() == HitResult.Type.MISS) {
7777
return MethodResult.of(null, "Nothing found");
78+
}
7879

7980
Entity entity = ((EntityHitResult) entityHit).getEntity();
80-
if (!(entity instanceof Animal animal))
81+
if (!(entity instanceof Animal animal)) {
8182
return MethodResult.of(null, "Well, entity is not animal entity, but how?");
83+
}
8284

83-
return MethodResult.of(LuaConverter.completeEntityToLua(animal, owner.getToolInMainHand(), true));
85+
return MethodResult.of(LuaConverter.entityToLua(animal, LuaConverter.entityContextBuilder().detailed().itemInHand(owner.getToolInMainHand()).build()));
8486
}
8587

8688
@LuaFunction(mainThread = true)
8789
public final MethodResult searchAnimals(IArguments args) throws LuaException {
8890
boolean detailed = args.count() > 0 ? args.getBoolean(0) : false;
8991
automataCore.addRotationCycle();
9092
TurtlePeripheralOwner owner = automataCore.getPeripheralOwner();
91-
BlockPos currentPos = owner.getPos();
92-
AABB box = new AABB(currentPos);
93-
ItemStack itemInHand = owner.getToolInMainHand();
94-
List<Map<String, Object>> entities = owner.getLevel().getEntities((Entity) null, box.inflate(automataCore.getInteractionRadius()), suitableEntity).stream().map(entity -> LuaConverter.completeEntityWithPositionToLua(entity, itemInHand, currentPos, detailed)).toList();
93+
Vec3 currentPos = owner.getPhysicsPos();
94+
AABB box = new AABB(currentPos, currentPos).inflate(automataCore.getInteractionRadius() + 0.5);
95+
LuaConverter.EntityConverter.Context convContext = LuaConverter.entityContextBuilder()
96+
.detailed(detailed)
97+
.itemInHand(owner.getToolInMainHand())
98+
.position(currentPos)
99+
.build();
100+
List<Map<String, Object>> entities = owner
101+
.getLevel()
102+
.getEntities((Entity) null, box, suitableEntity)
103+
.stream()
104+
.map(entity -> LuaConverter.entityToLua(entity, convContext))
105+
.toList();
95106
return MethodResult.of(entities);
96107
}
97108
}

0 commit comments

Comments
 (0)