too
if (toolClasses.contains(ToolClasses.HARD_HAMMER)) {
return onHardHammerClick(playerIn, hand, gridSideHit, hitResult);
}
+ if (toolClasses.contains(ToolClasses.WIRE_CUTTER)) {
+ return onWireCutterClick(playerIn, hand, gridSideHit, hitResult);
+ }
return false;
}
@@ -657,6 +682,16 @@ public boolean onHardHammerClick(EntityPlayer playerIn, EnumHand hand, EnumFacin
return true;
}
+ /**
+ * Called when player clicks a wire cutter on specific side of this meta tile entity
+ *
+ * @return true if something happened, so the tool will get damaged and animation will be played
+ */
+ public boolean onWireCutterClick(EntityPlayer playerIn, EnumHand hand, EnumFacing facing,
+ CuboidRayTraceResult hitResult) {
+ return false;
+ }
+
public void onLeftClick(EntityPlayer player, EnumFacing facing, CuboidRayTraceResult hitResult) {}
/**
@@ -915,13 +950,14 @@ public void getDrops(@NotNull List<@NotNull ItemStack> dropsList, @Nullable Enti
public final ItemStack getPickItem(CuboidRayTraceResult result, EntityPlayer player) {
IndexedCuboid6 hitCuboid = result.cuboid6;
+ final boolean isCreativePickBlock = player.isCreative() && TooltipHelper.isCtrlDown();
if (hitCuboid.data instanceof CoverRayTracer.CoverSideData coverSideData) {
Cover cover = getCoverAtSide(coverSideData.side);
- return cover == null ? ItemStack.EMPTY : cover.getPickItem();
+ return cover == null || isCreativePickBlock ? ItemStack.EMPTY : cover.getPickItem();
} else if (hitCuboid.data == null || hitCuboid.data instanceof CoverRayTracer.PrimaryBoxData) {
// data is null -> MetaTileEntity hull hit
Cover cover = getCoverAtSide(result.sideHit);
- if (cover != null) {
+ if (cover != null && !isCreativePickBlock) {
return cover.getPickItem();
}
return getPickItem(player);
@@ -1003,7 +1039,10 @@ public void receiveInitialSyncData(@NotNull PacketBuffer buf) {
MTETrait trait = mteTraitByNetworkId.get(traitNetworkId);
if (trait == null) {
GTLog.logger.warn("Could not find MTETrait for id: {} at position {}.", traitNetworkId, getPos());
- } else trait.receiveInitialData(buf);
+ } else {
+ trait.receiveInitialSyncData(buf);
+ ISyncedTileEntity.checkInitialData(buf, trait);
+ }
}
CoverSaveHandler.receiveInitialSyncData(buf, this);
this.muffled = buf.readBoolean();
@@ -1036,10 +1075,14 @@ public void receiveCustomData(int dataId, @NotNull PacketBuffer buf) {
scheduleRenderUpdate();
} else if (dataId == SYNC_MTE_TRAITS) {
int traitNetworkId = buf.readVarInt();
+ int internalId = buf.readVarInt();
MTETrait trait = mteTraitByNetworkId.get(traitNetworkId);
if (trait == null) {
GTLog.logger.warn("Could not find MTETrait for id: {} at position {}.", traitNetworkId, getPos());
- } else trait.receiveCustomData(buf.readVarInt(), buf);
+ } else {
+ trait.receiveCustomData(internalId, buf);
+ ISyncedTileEntity.checkCustomData(internalId, buf, trait);
+ }
} else if (dataId == COVER_ATTACHED_MTE) {
CoverSaveHandler.readCoverPlacement(buf, this);
} else if (dataId == COVER_REMOVED_MTE) {
@@ -1055,6 +1098,7 @@ public void receiveCustomData(int dataId, @NotNull PacketBuffer buf) {
int internalId = buf.readVarInt();
if (cover != null) {
cover.readCustomData(internalId, buf);
+ ISyncedTileEntity.checkCustomData(internalId, buf, cover);
}
} else if (dataId == UPDATE_SOUND_MUFFLED) {
this.muffled = buf.readBoolean();
@@ -1289,6 +1333,10 @@ public NBTTagCompound writeToNBT(NBTTagCompound data) {
CoverSaveHandler.writeCoverNBT(data, this);
data.setBoolean(TAG_KEY_MUFFLED, muffled);
+
+ if (owner != null)
+ data.setUniqueId("Owner", owner);
+
return data;
}
@@ -1314,6 +1362,9 @@ public void readFromNBT(NBTTagCompound data) {
CoverSaveHandler.readCoverNBT(data, this, covers::put);
this.muffled = data.getBoolean(TAG_KEY_MUFFLED);
+
+ if (data.hasKey("Owner"))
+ this.owner = data.getUniqueId("Owner");
}
@Override
@@ -1342,12 +1393,28 @@ public int getItemStackLimit(ItemStack stack) {
}
/**
- * Called whenever a MetaTileEntity is placed in world by {@link Block#onBlockPlacedBy}
+ * Called whenever a MetaTileEntity is placed in world by {@link Block#onBlockPlacedBy},
+ * gives the MetaTileEntity an Owner by UUID
*
* If placing an MTE with methods such as {@link World#setBlockState(BlockPos, IBlockState)},
* this should be manually called immediately afterwards
*/
- public void onPlacement() {}
+ public void onPlacement(@Nullable EntityLivingBase placer) {
+ if (placer instanceof EntityPlayer player) {
+ this.owner = player.getUniqueID();
+ }
+ }
+
+ /**
+ * Called whenever a MetaTileEntity is placed in world by {@link Block#onBlockPlacedBy},
+ * gives the MetaTileEntity an Owner of Null
+ *
+ * If placing an MTE with methods such as {@link World#setBlockState(BlockPos, IBlockState)},
+ * this should be manually called immediately afterwards
+ */
+ public final void onPlacement() {
+ onPlacement(null);
+ }
/**
* Called from breakBlock right before meta tile entity destruction
@@ -1447,6 +1514,11 @@ public boolean getWitherProof() {
return false;
}
+ @Nullable
+ public UUID getOwner() {
+ return owner;
+ }
+
public final void toggleMuffled() {
muffled = !muffled;
if (!getWorld().isRemote) {
@@ -1605,4 +1677,45 @@ public AENetworkProxy getProxy() {
@Method(modid = Mods.Names.APPLIED_ENERGISTICS2)
public void gridChanged() {}
+
+ /**
+ * Add MTE to a creative tab. Ensure that the creative tab has been registered via
+ * {@link gregtech.api.block.machines.MachineItemBlock#addCreativeTab(CreativeTabs)
+ * MachineItemBlock#addCreativeTab(CreativeTabs)} beforehand.
+ */
+ public void addAdditionalCreativeTabs(CreativeTabs creativeTab) {
+ Preconditions.checkNotNull(creativeTab, "creativeTab");
+ if (creativeTabs.contains(creativeTab)) {
+ GTLog.logger.error("{} is already in the creative tab {}.", this, creativeTab.tabLabel,
+ new IllegalArgumentException());
+ return;
+ }
+
+ creativeTabs.add(creativeTab);
+ }
+
+ public void removeFromCreativeTab(CreativeTabs creativeTab) {
+ Preconditions.checkNotNull(creativeTab, "creativeTab");
+ if (creativeTab == CreativeTabs.SEARCH) {
+ GTLog.logger.error("Cannot remove MTEs from the creative search tab.",
+ new IllegalArgumentException());
+ return;
+ }
+ if (creativeTab == GTCreativeTabs.TAB_GREGTECH_MACHINES &&
+ metaTileEntityId.getNamespace().equals(GTValues.MODID)) {
+ GTLog.logger.error("Cannot remove GT MTEs from the GT machines tab.", new IllegalArgumentException());
+ return;
+ }
+ if (!creativeTabs.contains(creativeTab)) {
+ GTLog.logger.error("{} is not in the creative tab {}.", this, creativeTab.tabLabel,
+ new IllegalArgumentException());
+ return;
+ }
+
+ creativeTabs.remove(creativeTab);
+ }
+
+ public Set getCreativeTabs() {
+ return Collections.unmodifiableSet(creativeTabs);
+ }
}
diff --git a/src/main/java/gregtech/api/metatileentity/MetaTileEntityHolder.java b/src/main/java/gregtech/api/metatileentity/MetaTileEntityHolder.java
index b0bd546db51..6884f33ac38 100644
--- a/src/main/java/gregtech/api/metatileentity/MetaTileEntityHolder.java
+++ b/src/main/java/gregtech/api/metatileentity/MetaTileEntityHolder.java
@@ -89,9 +89,12 @@ public MetaTileEntity getMetaTileEntity() {
* Also can use certain data to preinit the block before data is synced
*/
@Override
- public MetaTileEntity setMetaTileEntity(MetaTileEntity sampleMetaTileEntity) {
+ public MetaTileEntity setMetaTileEntity(@NotNull MetaTileEntity sampleMetaTileEntity,
+ @Nullable NBTTagCompound tagCompound) {
Preconditions.checkNotNull(sampleMetaTileEntity, "metaTileEntity");
setRawMetaTileEntity(sampleMetaTileEntity.createMetaTileEntity(this));
+ if (tagCompound != null && !tagCompound.isEmpty())
+ getMetaTileEntity().readFromNBT(tagCompound);
if (hasWorld() && !getWorld().isRemote) {
updateBlockOpacity();
writeCustomData(INITIALIZE_MTE, buffer -> {
@@ -395,7 +398,7 @@ public void onChunkUnload() {
public boolean shouldRefresh(@NotNull World world, @NotNull BlockPos pos, IBlockState oldState,
IBlockState newState) {
return oldState.getBlock() != newState.getBlock(); // MetaTileEntityHolder should never refresh (until block
- // changes)
+ // changes)
}
@Override
diff --git a/src/main/java/gregtech/api/metatileentity/SyncedTileEntityBase.java b/src/main/java/gregtech/api/metatileentity/SyncedTileEntityBase.java
index 4e29fe09328..9b42003a0dc 100644
--- a/src/main/java/gregtech/api/metatileentity/SyncedTileEntityBase.java
+++ b/src/main/java/gregtech/api/metatileentity/SyncedTileEntityBase.java
@@ -4,7 +4,6 @@
import gregtech.api.metatileentity.interfaces.IGregTechTileEntity;
import gregtech.api.metatileentity.interfaces.ISyncedTileEntity;
import gregtech.api.network.PacketDataList;
-import gregtech.api.util.GTLog;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTBase;
@@ -80,20 +79,13 @@ public final void onDataPacket(@NotNull NetworkManager net, @NotNull SPacketUpda
NBTTagCompound entryTag = (NBTTagCompound) entryBase;
for (String discriminatorKey : entryTag.getKeySet()) {
ByteBuf backedBuffer = Unpooled.copiedBuffer(entryTag.getByteArray(discriminatorKey));
- receiveCustomData(Integer.parseInt(discriminatorKey), new PacketBuffer(backedBuffer));
- if (backedBuffer.readableBytes() != 0) {
- String className = null;
- if (this instanceof IGregTechTileEntity gtte) {
- MetaTileEntity mte = gtte.getMetaTileEntity();
- if (mte != null) className = mte.getClass().getName();
- }
- if (className == null) {
- className = this.getClass().getName();
- }
- GTLog.logger.error(
- "Class {} failed to finish reading receiveCustomData with discriminator {} and {} bytes remaining",
- className, discriminatorKey, backedBuffer.readableBytes());
- }
+ int dataId = Integer.parseInt(discriminatorKey);
+ receiveCustomData(dataId, new PacketBuffer(backedBuffer));
+
+ MetaTileEntity mte = null;
+ if (this instanceof IGregTechTileEntity gtte)
+ mte = gtte.getMetaTileEntity();
+ ISyncedTileEntity.checkCustomData(dataId, backedBuffer, mte == null ? this : mte);
}
}
}
@@ -114,18 +106,10 @@ public final void handleUpdateTag(@NotNull NBTTagCompound tag) {
byte[] updateData = tag.getByteArray("d");
ByteBuf backedBuffer = Unpooled.copiedBuffer(updateData);
receiveInitialSyncData(new PacketBuffer(backedBuffer));
- if (backedBuffer.readableBytes() != 0) {
- String className = null;
- if (this instanceof IGregTechTileEntity gtte) {
- MetaTileEntity mte = gtte.getMetaTileEntity();
- if (mte != null) className = mte.getClass().getName();
- }
- if (className == null) {
- className = this.getClass().getName();
- }
- GTLog.logger.error("Class {} failed to finish reading initialSyncData with {} bytes remaining",
- className, backedBuffer.readableBytes());
- }
+ MetaTileEntity mte = null;
+ if (this instanceof IGregTechTileEntity gtte)
+ mte = gtte.getMetaTileEntity();
+ ISyncedTileEntity.checkInitialData(backedBuffer, mte == null ? this : mte);
}
}
diff --git a/src/main/java/gregtech/api/metatileentity/TieredMetaTileEntity.java b/src/main/java/gregtech/api/metatileentity/TieredMetaTileEntity.java
index 0c03b3bc794..3cf30dd6480 100644
--- a/src/main/java/gregtech/api/metatileentity/TieredMetaTileEntity.java
+++ b/src/main/java/gregtech/api/metatileentity/TieredMetaTileEntity.java
@@ -7,13 +7,9 @@
import gregtech.api.util.GTUtility;
import gregtech.client.renderer.texture.Textures;
import gregtech.client.renderer.texture.cube.SimpleSidedCubeRenderer;
-import gregtech.common.ConfigHolder;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
-import net.minecraft.client.resources.I18n;
-import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
-import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@@ -23,10 +19,6 @@
import codechicken.lib.vec.Matrix4;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.util.List;
public abstract class TieredMetaTileEntity extends MetaTileEntity
implements IEnergyChangeListener, ITieredMetaTileEntity {
@@ -57,14 +49,6 @@ protected SimpleSidedCubeRenderer getBaseRenderer() {
return Textures.VOLTAGE_CASINGS[tier];
}
- @Override
- public void addInformation(ItemStack stack, @Nullable World player, @NotNull List tooltip,
- boolean advanced) {
- super.addInformation(stack, player, tooltip, advanced);
- if (ConfigHolder.machines.doTerrainExplosion && getIsWeatherOrTerrainResistant())
- tooltip.add(I18n.format("gregtech.universal.tooltip.terrain_resist"));
- }
-
@Override
@SideOnly(Side.CLIENT)
public Pair getParticleTexture() {
diff --git a/src/main/java/gregtech/api/metatileentity/interfaces/IGregTechTileEntity.java b/src/main/java/gregtech/api/metatileentity/interfaces/IGregTechTileEntity.java
index 43446101414..df7ae0563fe 100644
--- a/src/main/java/gregtech/api/metatileentity/interfaces/IGregTechTileEntity.java
+++ b/src/main/java/gregtech/api/metatileentity/interfaces/IGregTechTileEntity.java
@@ -3,6 +3,11 @@
import gregtech.api.gui.IUIHolder;
import gregtech.api.metatileentity.MetaTileEntity;
+import net.minecraft.nbt.NBTTagCompound;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
/**
* A simple compound Interface for all my TileEntities.
*
@@ -13,7 +18,11 @@ public interface IGregTechTileEntity extends IHasWorldObjectAndCoords, INeighbor
MetaTileEntity getMetaTileEntity();
- MetaTileEntity setMetaTileEntity(MetaTileEntity metaTileEntity);
+ default MetaTileEntity setMetaTileEntity(MetaTileEntity metaTileEntity) {
+ return setMetaTileEntity(metaTileEntity, null);
+ }
+
+ MetaTileEntity setMetaTileEntity(@NotNull MetaTileEntity metaTileEntity, @Nullable NBTTagCompound tagCompound);
long getOffsetTimer(); // todo might not keep this one
diff --git a/src/main/java/gregtech/api/metatileentity/interfaces/ISyncedTileEntity.java b/src/main/java/gregtech/api/metatileentity/interfaces/ISyncedTileEntity.java
index f08beb475b9..97bff58419b 100644
--- a/src/main/java/gregtech/api/metatileentity/interfaces/ISyncedTileEntity.java
+++ b/src/main/java/gregtech/api/metatileentity/interfaces/ISyncedTileEntity.java
@@ -1,7 +1,15 @@
package gregtech.api.metatileentity.interfaces;
+import gregtech.api.capability.GregtechDataCodes;
+import gregtech.api.cover.Cover;
+import gregtech.api.cover.CoverableView;
+import gregtech.api.util.GTLog;
+
import net.minecraft.network.PacketBuffer;
+import net.minecraft.tileentity.TileEntity;
+import net.minecraft.util.math.BlockPos;
+import io.netty.buffer.ByteBuf;
import org.jetbrains.annotations.NotNull;
import java.util.function.Consumer;
@@ -11,6 +19,8 @@
*/
public interface ISyncedTileEntity {
+ Consumer NO_OP = buf -> {};
+
/**
* Used to sync data from Server -> Client.
* Called during initial loading of the chunk or when many blocks change at once.
@@ -23,7 +33,7 @@ public interface ISyncedTileEntity {
*
* This method is called Server-Side.
*
- * Equivalent to {@link net.minecraft.tileentity.TileEntity#getUpdateTag}.
+ * Equivalent to {@link TileEntity#getUpdateTag}.
*
* @param buf the buffer to write data to
*/
@@ -41,7 +51,7 @@ public interface ISyncedTileEntity {
*
* This method is called Client-Side.
*
- * Equivalent to {@link net.minecraft.tileentity.TileEntity#handleUpdateTag}.
+ * Equivalent to {@link TileEntity#handleUpdateTag}.
*
* @param buf the buffer to read data from
*/
@@ -60,14 +70,35 @@ public interface ISyncedTileEntity {
*
* This method is called Server-Side.
*
- * Equivalent to {@link net.minecraft.tileentity.TileEntity#getUpdatePacket}
+ * Equivalent to {@link TileEntity#getUpdatePacket}
*
* @param discriminator the discriminator determining the packet sent.
* @param dataWriter a consumer which writes packet data to a buffer.
- * @see gregtech.api.capability.GregtechDataCodes
+ * @see GregtechDataCodes
*/
void writeCustomData(int discriminator, @NotNull Consumer<@NotNull PacketBuffer> dataWriter);
+ /**
+ * Used to send an empty anonymous Server -> Client packet.
+ *
+ * Data is received in {@link #receiveCustomData(int, PacketBuffer)};
+ *
+ * Typically used to signal to the client that a rendering update is needed
+ * when sending a server-side state update.
+ *
+ * Should be called manually.
+ *
+ * This method is called Server-Side.
+ *
+ * Equivalent to {@link TileEntity#getUpdatePacket}
+ *
+ * @param discriminator the discriminator determining the packet sent.
+ * @see GregtechDataCodes
+ */
+ default void writeCustomData(int discriminator) {
+ writeCustomData(discriminator, NO_OP);
+ }
+
/**
* Used to receive an anonymous Server -> Client packet.
* Called when receiving a packet for the location this TileEntity is currently in.
@@ -80,11 +111,51 @@ public interface ISyncedTileEntity {
*
* This method is called Client-Side.
*
- * Equivalent to {@link net.minecraft.tileentity.TileEntity#onDataPacket}
+ * Equivalent to {@link TileEntity#onDataPacket}
*
* @param discriminator the discriminator determining the packet sent.
* @param buf the buffer containing the packet data.
- * @see gregtech.api.capability.GregtechDataCodes
+ * @see GregtechDataCodes
*/
void receiveCustomData(int discriminator, @NotNull PacketBuffer buf);
+
+ static void checkCustomData(int discriminator, @NotNull ByteBuf buf, Object obj) {
+ if (buf.readableBytes() == 0) return;
+
+ GTLog.logger.error(
+ "Class {} failed to finish reading receiveCustomData with discriminator {} and {} bytes remaining",
+ stringify(obj), GregtechDataCodes.getNameFor(discriminator), buf.readableBytes());
+
+ buf.clear(); // clear to prevent further logging
+ }
+
+ static void checkInitialData(@NotNull ByteBuf buf, Object obj) {
+ if (buf.readableBytes() == 0) return;
+
+ GTLog.logger.error("Class {} failed to finish reading initialSyncData with {} bytes remaining",
+ stringify(obj), buf.readableBytes());
+
+ buf.clear(); // clear to prevent further logging
+ }
+
+ static String stringify(Object obj) {
+ StringBuilder builder = new StringBuilder(obj.getClass().getSimpleName());
+
+ BlockPos pos = null;
+ if (obj instanceof TileEntity tileEntity) {
+ pos = tileEntity.getPos(); // TE pos
+ } else if (obj instanceof CoverableView view) {
+ pos = view.getPos(); // MTE pos
+ } else if (obj instanceof Cover cover) {
+ pos = cover.getPos(); // Cover pos and side
+ builder.append("[side=").append(cover.getAttachedSide()).append("]");
+ }
+
+ if (pos != null) builder.append(" @ {")
+ .append(pos.getX()).append("X, ")
+ .append(pos.getY()).append("Y, ")
+ .append(pos.getZ()).append("Z}");
+
+ return builder.toString();
+ }
}
diff --git a/src/main/java/gregtech/api/metatileentity/multiblock/FuelMultiblockController.java b/src/main/java/gregtech/api/metatileentity/multiblock/FuelMultiblockController.java
index faad3421dc1..790a150ec0c 100644
--- a/src/main/java/gregtech/api/metatileentity/multiblock/FuelMultiblockController.java
+++ b/src/main/java/gregtech/api/metatileentity/multiblock/FuelMultiblockController.java
@@ -34,7 +34,10 @@ public FuelMultiblockController(ResourceLocation metaTileEntityId, RecipeMap>
@Override
protected void initializeAbilities() {
super.initializeAbilities();
- this.energyContainer = new EnergyContainerList(getAbilities(MultiblockAbility.OUTPUT_ENERGY));
+ List outputEnergy = new ArrayList<>(getAbilities(MultiblockAbility.OUTPUT_ENERGY));
+ outputEnergy.addAll(getAbilities(MultiblockAbility.SUBSTATION_OUTPUT_ENERGY));
+ outputEnergy.addAll(getAbilities(MultiblockAbility.OUTPUT_LASER));
+ this.energyContainer = new EnergyContainerList(outputEnergy);
}
@Override
diff --git a/src/main/java/gregtech/api/metatileentity/multiblock/MultiMapMultiblockController.java b/src/main/java/gregtech/api/metatileentity/multiblock/MultiMapMultiblockController.java
index 53d204a0d2b..f80337e10c8 100644
--- a/src/main/java/gregtech/api/metatileentity/multiblock/MultiMapMultiblockController.java
+++ b/src/main/java/gregtech/api/metatileentity/multiblock/MultiMapMultiblockController.java
@@ -59,7 +59,6 @@ public boolean onScrewdriverClick(EntityPlayer playerIn, EnumHand hand, EnumFaci
index = (recipeMapIndex + 1) % recipeMaps.length;
setRecipeMapIndex(index);
- this.recipeMapWorkable.forceRecipeRecheck();
} else {
playerIn.sendStatusMessage(
new TextComponentTranslation("gregtech.multiblock.multiple_recipemaps.switch_message"), true);
@@ -79,6 +78,7 @@ public void setRecipeMapIndex(int index) {
this.recipeMapIndex = index;
if (!getWorld().isRemote) {
writeCustomData(GregtechDataCodes.RECIPE_MAP_INDEX, buf -> buf.writeByte(index));
+ recipeMapWorkable.forceRecipeRecheck();
markDirty();
}
}
diff --git a/src/main/java/gregtech/api/metatileentity/multiblock/MultiblockControllerBase.java b/src/main/java/gregtech/api/metatileentity/multiblock/MultiblockControllerBase.java
index 7f8ff37dba1..ff3848b1557 100644
--- a/src/main/java/gregtech/api/metatileentity/multiblock/MultiblockControllerBase.java
+++ b/src/main/java/gregtech/api/metatileentity/multiblock/MultiblockControllerBase.java
@@ -30,6 +30,7 @@
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.I18n;
+import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
@@ -91,8 +92,8 @@ public MultiblockControllerBase(ResourceLocation metaTileEntityId) {
}
@Override
- public void onPlacement() {
- super.onPlacement();
+ public void onPlacement(EntityLivingBase placer) {
+ super.onPlacement(placer);
reinitializeStructurePattern();
}
diff --git a/src/main/java/gregtech/api/metatileentity/multiblock/MultiblockDisplayText.java b/src/main/java/gregtech/api/metatileentity/multiblock/MultiblockDisplayText.java
index 8cacd124e56..9127d5ca68c 100644
--- a/src/main/java/gregtech/api/metatileentity/multiblock/MultiblockDisplayText.java
+++ b/src/main/java/gregtech/api/metatileentity/multiblock/MultiblockDisplayText.java
@@ -93,7 +93,7 @@ public Builder addEnergyUsageLine(IEnergyContainer energyContainer) {
String energyFormatted = TextFormattingUtil.formatNumbers(maxVoltage);
// wrap in text component to keep it from being formatted
ITextComponent voltageName = new TextComponentString(
- GTValues.VNF[GTUtility.getFloorTierByVoltage(maxVoltage)]);
+ GTValues.VOCNF[GTUtility.getFloorTierByVoltage(maxVoltage)]);
ITextComponent bodyText = TextComponentUtil.translationWithColor(
TextFormatting.GRAY,
@@ -138,7 +138,7 @@ public Builder addEnergyUsageExactLine(long energyUsage) {
String energyFormatted = TextFormattingUtil.formatNumbers(energyUsage);
// wrap in text component to keep it from being formatted
ITextComponent voltageName = new TextComponentString(
- GTValues.VNF[GTUtility.getTierByVoltage(energyUsage)]);
+ GTValues.VOCNF[GTUtility.getOCTierByVoltage(energyUsage)]);
textList.add(TextComponentUtil.translationWithColor(
TextFormatting.GRAY,
@@ -159,7 +159,7 @@ public Builder addEnergyProductionLine(long maxVoltage, long recipeEUt) {
String energyFormatted = TextFormattingUtil.formatNumbers(maxVoltage);
// wrap in text component to keep it from being formatted
ITextComponent voltageName = new TextComponentString(
- GTValues.VNF[GTUtility.getFloorTierByVoltage(maxVoltage)]);
+ GTValues.VOCNF[GTUtility.getFloorTierByVoltage(maxVoltage)]);
textList.add(TextComponentUtil.translationWithColor(
TextFormatting.GRAY,
@@ -182,7 +182,7 @@ public Builder addEnergyProductionAmpsLine(long maxVoltage, int amperage) {
String energyFormatted = TextFormattingUtil.formatNumbers(maxVoltage);
// wrap in text component to keep it from being formatted
ITextComponent voltageName = new TextComponentString(
- GTValues.VNF[GTUtility.getFloorTierByVoltage(maxVoltage)]);
+ GTValues.VOCNF[GTUtility.getFloorTierByVoltage(maxVoltage)]);
textList.add(TextComponentUtil.translationWithColor(
TextFormatting.GRAY,
diff --git a/src/main/java/gregtech/api/metatileentity/multiblock/RecipeMapMultiblockController.java b/src/main/java/gregtech/api/metatileentity/multiblock/RecipeMapMultiblockController.java
index d90c9b548db..4949074c91a 100644
--- a/src/main/java/gregtech/api/metatileentity/multiblock/RecipeMapMultiblockController.java
+++ b/src/main/java/gregtech/api/metatileentity/multiblock/RecipeMapMultiblockController.java
@@ -124,7 +124,11 @@ protected void initializeAbilities() {
this.outputInventory = new ItemHandlerList(getAbilities(MultiblockAbility.EXPORT_ITEMS));
this.outputFluidInventory = new FluidTankList(allowSameFluidFillForOutputs(),
getAbilities(MultiblockAbility.EXPORT_FLUIDS));
- this.energyContainer = new EnergyContainerList(getAbilities(MultiblockAbility.INPUT_ENERGY));
+
+ List inputEnergy = new ArrayList<>(getAbilities(MultiblockAbility.INPUT_ENERGY));
+ inputEnergy.addAll(getAbilities(MultiblockAbility.SUBSTATION_INPUT_ENERGY));
+ inputEnergy.addAll(getAbilities(MultiblockAbility.INPUT_LASER));
+ this.energyContainer = new EnergyContainerList(inputEnergy);
}
private void resetTileAbilities() {
diff --git a/src/main/java/gregtech/api/mui/GTGuiTextures.java b/src/main/java/gregtech/api/mui/GTGuiTextures.java
index f17affee609..b92acd290b0 100644
--- a/src/main/java/gregtech/api/mui/GTGuiTextures.java
+++ b/src/main/java/gregtech/api/mui/GTGuiTextures.java
@@ -2,6 +2,8 @@
import gregtech.api.GTValues;
+import com.cleanroommc.modularui.api.drawable.IDrawable;
+import com.cleanroommc.modularui.api.drawable.IKey;
import com.cleanroommc.modularui.drawable.UITexture;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
@@ -167,6 +169,7 @@ public static class IDs {
public static final UITexture[] BUTTON_MATCH_ALL = slice("textures/gui/widget/ore_filter/button_match_all.png",
16, 32, 16, 16, true);
+ public static final UITexture BUTTON_LOCK = fullImage("textures/gui/widget/button_lock.png");
public static final UITexture OREDICT_ERROR = fullImage("textures/gui/widget/ore_filter/error.png");
public static final UITexture OREDICT_INFO = fullImage("textures/gui/widget/ore_filter/info.png");
@@ -176,6 +179,9 @@ public static class IDs {
public static final UITexture OREDICT_WAITING = fullImage("textures/gui/widget/ore_filter/waiting.png");
public static final UITexture OREDICT_WARN = fullImage("textures/gui/widget/ore_filter/warn.png");
+ public static final IDrawable PLUS = IKey.str("+").asIcon().marginLeft(1);
+ public static final IDrawable MINUS = IKey.str("-").asIcon().marginLeft(1);
+
public static final UITexture[] MANUAL_IO_OVERLAY_IN = slice("textures/gui/overlay/manual_io_overlay_in.png",
18, 18 * 3, 18, 18, true);
public static final UITexture[] MANUAL_IO_OVERLAY_OUT = slice("textures/gui/overlay/manual_io_overlay_out.png",
@@ -206,6 +212,8 @@ public static class IDs {
"textures/gui/widget/button_public_private.png",
18, 36, 18, 18, true);
+ public static final UITexture MENU_OVERLAY = fullImage("textures/gui/overlay/menu_overlay.png");
+
// todo bronze/steel/primitive fluid slots?
// SLOT OVERLAYS
@@ -351,6 +359,8 @@ public static class IDs {
public static final UITexture BUTTON_CROSS = fullImage("textures/gui/widget/button_cross.png");
public static final UITexture BUTTON_REDSTONE_ON = fullImage("textures/gui/widget/button_redstone_on.png");
public static final UITexture BUTTON_REDSTONE_OFF = fullImage("textures/gui/widget/button_redstone_off.png");
+ public static final UITexture BUTTON_THROTTLE_PLUS = fullImage("textures/gui/widget/button_throttle_plus.png");
+ public static final UITexture BUTTON_THROTTLE_MINUS = fullImage("textures/gui/widget/button_throttle_minus.png");
// PROGRESS BARS
public static final UITexture PROGRESS_BAR_ARC_FURNACE = progressBar(
diff --git a/src/main/java/gregtech/api/mui/GTGuiTheme.java b/src/main/java/gregtech/api/mui/GTGuiTheme.java
index fce37223e96..4a6c2c2d4dd 100644
--- a/src/main/java/gregtech/api/mui/GTGuiTheme.java
+++ b/src/main/java/gregtech/api/mui/GTGuiTheme.java
@@ -9,7 +9,7 @@
import com.cleanroommc.modularui.api.ITheme;
import com.cleanroommc.modularui.api.IThemeApi;
import com.cleanroommc.modularui.drawable.UITexture;
-import com.cleanroommc.modularui.screen.Tooltip;
+import com.cleanroommc.modularui.screen.RichTooltip;
import com.cleanroommc.modularui.theme.ReloadThemeEvent;
import com.cleanroommc.modularui.utils.JsonBuilder;
import org.jetbrains.annotations.Nullable;
@@ -108,7 +108,7 @@ public static void onReloadThemes(ReloadThemeEvent.Pre event) {
public static Builder templateBuilder(String themeId) {
Builder builder = new Builder(themeId);
builder.openCloseAnimation(0);
- builder.tooltipPos(Tooltip.Pos.NEXT_TO_MOUSE);
+ builder.tooltipPos(RichTooltip.Pos.NEXT_TO_MOUSE);
builder.smoothProgressBar(true);
return builder;
}
@@ -163,7 +163,7 @@ public Builder smoothProgressBar(boolean smoothBar) {
}
/** Set the tooltip pos for this theme. Overrides global cfg. */
- public Builder tooltipPos(Tooltip.Pos tooltipPos) {
+ public Builder tooltipPos(RichTooltip.Pos tooltipPos) {
theme.elementBuilder.add(b -> b.add("tooltipPos", tooltipPos.name()));
return this;
}
@@ -229,7 +229,9 @@ public Builder button(String buttonId, String hoverId, int textColor, boolean te
.add("background", new JsonBuilder()
.add("type", "texture")
.add("id", buttonId))
- .add("hoverBackground", hoverId)
+ .add("hoverBackground", new JsonBuilder()
+ .add("type", "texture")
+ .add("id", hoverId))
.add("textColor", textColor)
.add("textShadow", textShadow)));
return this;
diff --git a/src/main/java/gregtech/api/mui/GTGuis.java b/src/main/java/gregtech/api/mui/GTGuis.java
index b5599dd9cfd..9f9989b2601 100644
--- a/src/main/java/gregtech/api/mui/GTGuis.java
+++ b/src/main/java/gregtech/api/mui/GTGuis.java
@@ -18,6 +18,8 @@
public class GTGuis {
+ public static final int DEFAULT_WIDTH = 176, DEFAULT_HIEGHT = 166;
+
@ApiStatus.Internal
public static void registerFactories() {
GuiManager.registerFactory(MetaTileEntityGuiFactory.INSTANCE);
@@ -38,9 +40,35 @@ public static ModularPanel createPanel(Cover cover, int width, int height) {
}
public static ModularPanel createPanel(ItemStack stack, int width, int height) {
- MetaItem>.MetaValueItem valueItem = ((MetaItem>) stack.getItem()).getItem(stack);
- if (valueItem == null) throw new IllegalArgumentException("Item must be a meta item!");
- return createPanel(valueItem.unlocalizedName, width, height);
+ String locale;
+ if (stack.getItem() instanceof MetaItem>metaItem) {
+ var valueItem = metaItem.getItem(stack);
+ if (valueItem == null) throw new IllegalArgumentException("Item must be a meta item!");
+ locale = valueItem.unlocalizedName;
+ } else {
+ locale = stack.getTranslationKey();
+ }
+ return createPanel(locale, width, height);
+ }
+
+ public static ModularPanel createPanel(String name) {
+ return ModularPanel.defaultPanel(name, DEFAULT_WIDTH, DEFAULT_HIEGHT);
+ }
+
+ public static ModularPanel defaultPanel(MetaTileEntity mte) {
+ return createPanel(mte.metaTileEntityId.getPath());
+ }
+
+ public static ModularPanel defaultPanel(Cover cover) {
+ return createPanel(cover.getDefinition().getResourceLocation().getPath());
+ }
+
+ public static ModularPanel defaultPanel(ItemStack stack) {
+ return createPanel(stack, DEFAULT_WIDTH, DEFAULT_HIEGHT);
+ }
+
+ public static ModularPanel defaultPanel(MetaItem>.MetaValueItem valueItem) {
+ return createPanel(valueItem.unlocalizedName);
}
public static ModularPanel createPopupPanel(String name, int width, int height) {
@@ -52,6 +80,15 @@ public static ModularPanel createPopupPanel(String name, int width, int height,
return new PopupPanel(name, width, height, disableBelow, closeOnOutsideClick);
}
+ public static ModularPanel defaultPopupPanel(String name) {
+ return defaultPopupPanel(name, false, false);
+ }
+
+ public static ModularPanel defaultPopupPanel(String name, boolean disableBelow,
+ boolean closeOnOutsideClick) {
+ return new PopupPanel(name, DEFAULT_WIDTH, DEFAULT_HIEGHT, disableBelow, closeOnOutsideClick);
+ }
+
private static class PopupPanel extends ModularPanel {
private final boolean disableBelow;
@@ -62,7 +99,14 @@ public PopupPanel(@NotNull String name, int width, int height, boolean disableBe
super(name);
size(width, height).align(Alignment.Center);
background(GTGuiTextures.BACKGROUND_POPUP);
- child(ButtonWidget.panelCloseButton().top(5).right(5));
+ child(ButtonWidget.panelCloseButton().top(5).right(5)
+ .onMousePressed(mouseButton -> {
+ if (mouseButton == 0 || mouseButton == 1) {
+ this.closeIfOpen(true);
+ return true;
+ }
+ return false;
+ }));
this.disableBelow = disableBelow;
this.closeOnOutsideClick = closeOnOutsideClick;
}
diff --git a/src/main/java/gregtech/api/mui/StateOverlay.java b/src/main/java/gregtech/api/mui/StateOverlay.java
new file mode 100644
index 00000000000..fefdc7fc477
--- /dev/null
+++ b/src/main/java/gregtech/api/mui/StateOverlay.java
@@ -0,0 +1,22 @@
+package gregtech.api.mui;
+
+import com.cleanroommc.modularui.api.drawable.IDrawable;
+import com.cleanroommc.modularui.widgets.ToggleButton;
+
+import java.util.function.Consumer;
+
+public interface StateOverlay {
+
+ StateOverlay overlay(boolean selected, IDrawable... overlay);
+
+ StateOverlay hoverOverlay(boolean selected, IDrawable... overlay);
+
+ static ToggleButton cast(ToggleButton button, Consumer function) {
+ function.accept((StateOverlay) button);
+ return button;
+ }
+
+ static ToggleButton create(Consumer function) {
+ return cast(new ToggleButton(), function);
+ }
+}
diff --git a/src/main/java/gregtech/api/mui/UnboxFix.java b/src/main/java/gregtech/api/mui/UnboxFix.java
new file mode 100644
index 00000000000..48f1bda2f20
--- /dev/null
+++ b/src/main/java/gregtech/api/mui/UnboxFix.java
@@ -0,0 +1,8 @@
+package gregtech.api.mui;
+
+public interface UnboxFix {
+
+ void gregTech$useDefaultTextColor(boolean b);
+
+ void gregTech$useDefaultShadow(boolean b);
+}
diff --git a/src/main/java/gregtech/api/mui/sync/FixedFluidSlotSH.java b/src/main/java/gregtech/api/mui/sync/FixedFluidSlotSH.java
deleted file mode 100644
index bf3c6c581d7..00000000000
--- a/src/main/java/gregtech/api/mui/sync/FixedFluidSlotSH.java
+++ /dev/null
@@ -1,150 +0,0 @@
-package gregtech.api.mui.sync;
-
-import gregtech.common.covers.filter.readers.SimpleFluidFilterReader;
-
-import net.minecraft.entity.player.EntityPlayer;
-import net.minecraft.item.ItemStack;
-import net.minecraft.network.PacketBuffer;
-import net.minecraftforge.fluids.FluidStack;
-import net.minecraftforge.fluids.IFluidTank;
-import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
-import net.minecraftforge.fluids.capability.IFluidHandlerItem;
-
-import com.cleanroommc.modularui.utils.MouseData;
-import com.cleanroommc.modularui.value.sync.FluidSlotSyncHandler;
-import org.jetbrains.annotations.Nullable;
-
-public class FixedFluidSlotSH extends FluidSlotSyncHandler {
-
- @Nullable
- private FluidStack lastStoredPhantomFluid;
-
- public FixedFluidSlotSH(IFluidTank fluidTank) {
- super(fluidTank);
- if (this.updateCacheFromSource(true) && fluidTank.getFluid() != null) {
- this.lastStoredPhantomFluid = fluidTank.getFluid().copy();
- }
- }
-
- @Override
- public void readOnServer(int id, PacketBuffer buf) {
- super.readOnServer(id, buf);
- if (id == 0) {
- var fluid = getFluidTank().getFluid();
- if (this.lastStoredPhantomFluid == null && fluid != null ||
- (this.lastStoredPhantomFluid != null && !this.lastStoredPhantomFluid.isFluidEqual(fluid))) {
- this.lastStoredPhantomFluid = fluid;
- }
- }
- }
-
- @Override
- public void setValue(@Nullable FluidStack value, boolean setSource, boolean sync) {
- super.setValue(value, setSource, sync);
- if (setSource) {
- this.getFluidTank().drain(Integer.MAX_VALUE, true);
- if (!isFluidEmpty(value)) {
- this.getFluidTank().fill(value.copy(), true);
- }
- }
- }
-
- @Override
- public void tryClickPhantom(MouseData mouseData) {
- EntityPlayer player = getSyncManager().getPlayer();
- ItemStack currentStack = player.inventory.getItemStack();
- FluidStack currentFluid = this.getFluidTank().getFluid();
- IFluidHandlerItem fluidHandlerItem = currentStack
- .getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null);
-
- if (mouseData.mouseButton == 0) {
- if (currentStack.isEmpty() || fluidHandlerItem == null) {
- if (this.canDrainSlot()) {
- this.getFluidTank().drain(mouseData.shift ? Integer.MAX_VALUE : 1000, true);
- }
- } else {
- FluidStack cellFluid = fluidHandlerItem.drain(Integer.MAX_VALUE, false);
- if ((this.controlsAmount() || currentFluid == null) && cellFluid != null) {
- if (this.canFillSlot()) {
- if (!this.controlsAmount()) {
- cellFluid.amount = 1;
- }
- if (this.getFluidTank().fill(cellFluid, true) > 0) {
- this.lastStoredPhantomFluid = cellFluid.copy();
- }
- }
- } else {
- if (this.canDrainSlot()) {
- this.getFluidTank().drain(mouseData.shift ? Integer.MAX_VALUE : 1000, true);
- }
- }
- }
- } else if (mouseData.mouseButton == 1) {
- if (this.canFillSlot()) {
- if (currentFluid != null) {
- if (this.controlsAmount()) {
- FluidStack toFill = currentFluid.copy();
- toFill.amount = 1000;
- this.getFluidTank().fill(toFill, true);
- }
- } else if (this.lastStoredPhantomFluid != null) {
- FluidStack toFill = this.lastStoredPhantomFluid.copy();
- toFill.amount = this.controlsAmount() ? 1 : toFill.amount;
- this.getFluidTank().fill(toFill, true);
- }
- }
- } else if (mouseData.mouseButton == 2 && currentFluid != null && this.canDrainSlot()) {
- this.getFluidTank().drain(mouseData.shift ? Integer.MAX_VALUE : 1000, true);
- }
- this.setValue(this.getFluidTank().getFluid(), false, true);
- }
-
- @Override
- public void tryScrollPhantom(MouseData mouseData) {
- FluidStack currentFluid = this.getFluidTank().getFluid();
- int amount = mouseData.mouseButton;
- if (!this.controlsAmount()) {
- var fluid = getFluidTank().getFluid();
- int newAmt = amount == 1 ? 1 : 0;
- if (fluid != null && fluid.amount != newAmt) {
- fluid.amount = newAmt;
- setValue(fluid, true, true);
- return;
- }
- }
- if (mouseData.shift) {
- amount *= 10;
- }
- if (mouseData.ctrl) {
- amount *= 100;
- }
- if (mouseData.alt) {
- amount *= 1000;
- }
- if (currentFluid == null) {
- if (amount > 0 && this.lastStoredPhantomFluid != null) {
- FluidStack toFill = this.lastStoredPhantomFluid.copy();
- toFill.amount = this.controlsAmount() ? amount : 1;
- this.getFluidTank().fill(toFill, true);
- }
- this.setValue(this.getFluidTank().getFluid(), false, true);
- return;
- }
- if (amount > 0) {
- FluidStack toFill = currentFluid.copy();
- toFill.amount = amount;
- this.getFluidTank().fill(toFill, true);
- } else if (amount < 0) {
- this.getFluidTank().drain(-amount, true);
- }
- this.setValue(this.getFluidTank().getFluid(), false, true);
- }
-
- @Override
- public boolean controlsAmount() {
- if (getFluidTank() instanceof SimpleFluidFilterReader.WritableFluidTank writableFluidTank) {
- return writableFluidTank.showAmount();
- }
- return super.controlsAmount();
- }
-}
diff --git a/src/main/java/gregtech/api/mui/sync/GTFluidSyncHandler.java b/src/main/java/gregtech/api/mui/sync/GTFluidSyncHandler.java
new file mode 100644
index 00000000000..1886be86d31
--- /dev/null
+++ b/src/main/java/gregtech/api/mui/sync/GTFluidSyncHandler.java
@@ -0,0 +1,494 @@
+package gregtech.api.mui.sync;
+
+import gregtech.api.util.GTUtility;
+import gregtech.common.covers.filter.readers.SimpleFluidFilterReader;
+
+import net.minecraft.entity.item.EntityItem;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.ItemStack;
+import net.minecraft.network.PacketBuffer;
+import net.minecraft.util.SoundCategory;
+import net.minecraft.util.SoundEvent;
+import net.minecraftforge.fluids.FluidStack;
+import net.minecraftforge.fluids.FluidTank;
+import net.minecraftforge.fluids.FluidUtil;
+import net.minecraftforge.fluids.IFluidTank;
+import net.minecraftforge.fluids.capability.IFluidHandlerItem;
+
+import com.cleanroommc.modularui.network.NetworkUtils;
+import com.cleanroommc.modularui.utils.BooleanConsumer;
+import com.cleanroommc.modularui.utils.MouseData;
+import com.cleanroommc.modularui.value.sync.SyncHandler;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.function.BooleanSupplier;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+public class GTFluidSyncHandler extends SyncHandler {
+
+ public static final int TRY_CLICK_CONTAINER = 1;
+ public static final int UPDATE_TANK = 2;
+ public static final int UPDATE_AMOUNT = 3;
+ public static final int PHANTOM_SCROLL = 4;
+ public static final int LOCK_FLUID = 5;
+
+ private final IFluidTank tank;
+ private Consumer jeiHandler;
+ private BooleanConsumer lockHandler;
+ private Supplier lockedFluid;
+ private FluidStack lastFluid;
+ private FluidStack phantomFluid;
+ private boolean canDrainSlot = true;
+ private boolean canFillSlot = true;
+ private boolean phantom;
+ private BooleanSupplier showAmount = () -> true;
+
+ public GTFluidSyncHandler(IFluidTank tank) {
+ this.tank = tank;
+ }
+
+ @Override
+ public void detectAndSendChanges(boolean init) {
+ var current = getFluid();
+ if (current == null && lastFluid == null) return;
+ if (current == null || lastFluid == null || lastFluid.getFluid() != current.getFluid()) {
+ lastFluid = current == null ? null : current.copy();
+ syncToClient(UPDATE_TANK, buffer -> NetworkUtils.writeFluidStack(buffer, current));
+ } else if (current.amount != lastFluid.amount) {
+ lastFluid.amount = current.amount;
+ syncToClient(UPDATE_AMOUNT, buffer -> buffer.writeInt(current.amount));
+ }
+ }
+
+ public void lockFluid(FluidStack stack, boolean sync) {
+ if (!canLockFluid()) return;
+ this.jeiHandler.accept(stack);
+ if (sync) sync(LOCK_FLUID, buffer -> {
+ buffer.writeBoolean(stack != null);
+ NetworkUtils.writeFluidStack(buffer, stack);
+ });
+ }
+
+ public void lockFluid(boolean locked, boolean sync) {
+ this.lockHandler.accept(locked);
+ if (sync) sync(LOCK_FLUID, buffer -> {
+ buffer.writeBoolean(locked);
+ NetworkUtils.writeFluidStack(buffer, null);
+ });
+ }
+
+ public GTFluidSyncHandler handleLocking(Supplier lockedFluid, Consumer jeiHandler,
+ BooleanConsumer lockHandler) {
+ this.lockedFluid = lockedFluid;
+ this.jeiHandler = jeiHandler;
+ this.lockHandler = lockHandler;
+ return this;
+ }
+
+ public FluidStack getFluid() {
+ return this.tank.getFluid();
+ }
+
+ public void setFluid(FluidStack fluid) {
+ if (tank instanceof FluidTank fluidTank) {
+ fluidTank.setFluid(fluid);
+ } else {
+ tank.drain(Integer.MAX_VALUE, true);
+ tank.fill(fluid, true);
+ }
+ if (!isPhantom() || fluid == null) return;
+ if (this.phantomFluid == null || this.phantomFluid.getFluid() != fluid.getFluid()) {
+ this.phantomFluid = fluid;
+ }
+ }
+
+ public void setAmount(int amount) {
+ if (this.tank instanceof SimpleFluidFilterReader.WritableFluidTank writableFluidTank) {
+ writableFluidTank.setFluidAmount(amount);
+ return;
+ }
+ FluidStack stack = getFluid();
+ if (stack == null) return;
+ stack.amount = amount;
+ }
+
+ public int getCapacity() {
+ return this.tank.getCapacity();
+ }
+
+ public GTFluidSyncHandler accessibility(boolean canDrain, boolean canFill) {
+ this.canDrainSlot = canDrain;
+ this.canFillSlot = canFill;
+ return this;
+ }
+
+ public boolean canDrainSlot() {
+ return this.canDrainSlot;
+ }
+
+ public boolean canFillSlot() {
+ return this.canFillSlot;
+ }
+
+ public GTFluidSyncHandler phantom(boolean phantom) {
+ this.phantom = phantom;
+ if (phantom && this.tank.getFluid() != null)
+ this.phantomFluid = this.tank.getFluid().copy();
+ return this;
+ }
+
+ public boolean isPhantom() {
+ return phantom;
+ }
+
+ public GTFluidSyncHandler showAmount(boolean showAmount) {
+ this.showAmount = () -> showAmount;
+ return this;
+ }
+
+ public GTFluidSyncHandler showAmount(BooleanSupplier showAmount) {
+ this.showAmount = showAmount;
+ return this;
+ }
+
+ public boolean showAmount() {
+ if (!isPhantom() && phantomFluid != null)
+ return false;
+ return this.showAmount.getAsBoolean();
+ }
+
+ public @NotNull String getFormattedFluidAmount() {
+ var tankFluid = this.tank.getFluid();
+ return String.format("%,d", tankFluid == null ? 0 : tankFluid.amount);
+ }
+
+ public @Nullable String getFluidLocalizedName() {
+ var tankFluid = this.tank.getFluid();
+ if (tankFluid == null && canLockFluid())
+ tankFluid = this.lockedFluid.get();
+
+ return tankFluid == null ? null : tankFluid.getLocalizedName();
+ }
+
+ @Override
+ public void readOnClient(int id, PacketBuffer buf) {
+ switch (id) {
+ case TRY_CLICK_CONTAINER -> replaceCursorItemStack(NetworkUtils.readItemStack(buf));
+ case UPDATE_TANK -> setFluid(NetworkUtils.readFluidStack(buf));
+ case UPDATE_AMOUNT -> setAmount(buf.readInt());
+ case LOCK_FLUID -> lockFluid(NetworkUtils.readFluidStack(buf), false);
+ }
+ }
+
+ public void handlePhantomScroll(MouseData data) {
+ syncToServer(PHANTOM_SCROLL, data::writeToPacket);
+ }
+
+ public void handleClick(MouseData data) {
+ syncToServer(TRY_CLICK_CONTAINER, data::writeToPacket);
+ }
+
+ @Override
+ public void readOnServer(int id, PacketBuffer buf) {
+ if (id == TRY_CLICK_CONTAINER) {
+ var data = MouseData.readPacket(buf);
+ if (isPhantom()) {
+ tryClickPhantom(data);
+ } else {
+ var stack = tryClickContainer(data.mouseButton == 0);
+ if (!stack.isEmpty())
+ syncToClient(TRY_CLICK_CONTAINER, buffer -> NetworkUtils.writeItemStack(buffer, stack));
+ }
+ } else if (id == UPDATE_TANK) {
+ var fluid = NetworkUtils.readFluidStack(buf);
+ setFluid(fluid);
+ } else if (id == PHANTOM_SCROLL) {
+ tryScrollPhantom(MouseData.readPacket(buf));
+ } else if (id == LOCK_FLUID) {
+ boolean locked = buf.readBoolean();
+ var fluidStack = NetworkUtils.readFluidStack(buf);
+ if (fluidStack == null) {
+ this.lockHandler.accept(locked);
+ } else {
+ this.jeiHandler.accept(fluidStack);
+ }
+ }
+ }
+
+ public void tryClickPhantom(MouseData data) {
+ EntityPlayer player = getSyncManager().getPlayer();
+ ItemStack currentStack = player.inventory.getItemStack();
+ FluidStack currentFluid = this.tank.getFluid();
+ if (currentStack.getCount() > 1) currentStack = GTUtility.copy(1, currentStack);
+ var fluidHandlerItem = FluidUtil.getFluidHandler(currentStack);
+
+ switch (data.mouseButton) {
+ case 0 -> {
+ if (currentStack.isEmpty() || fluidHandlerItem == null) {
+ if (this.canDrainSlot()) {
+ this.tank.drain(data.shift ? Integer.MAX_VALUE : 1000, true);
+ }
+ } else {
+ FluidStack cellFluid = fluidHandlerItem.drain(Integer.MAX_VALUE, false);
+ if ((this.showAmount.getAsBoolean() || currentFluid == null) && cellFluid != null) {
+ if (this.canFillSlot()) {
+ if (!this.showAmount.getAsBoolean()) {
+ cellFluid.amount = 1;
+ }
+ if (this.tank.fill(cellFluid, true) > 0) {
+ this.phantomFluid = cellFluid.copy();
+ }
+ }
+ } else {
+ if (this.canDrainSlot()) {
+ this.tank.drain(data.shift ? Integer.MAX_VALUE : 1000, true);
+ }
+ }
+ }
+ }
+ case 1 -> {
+ if (this.canFillSlot()) {
+ if (currentFluid != null) {
+ if (this.showAmount.getAsBoolean()) {
+ FluidStack toFill = currentFluid.copy();
+ toFill.amount = 1000;
+ this.tank.fill(toFill, true);
+ }
+ } else if (this.phantomFluid != null) {
+ FluidStack toFill = this.phantomFluid.copy();
+ toFill.amount = this.showAmount.getAsBoolean() ? 1 : toFill.amount;
+ this.tank.fill(toFill, true);
+ }
+ }
+ }
+ case 2 -> {
+ if (currentFluid != null && canDrainSlot())
+ this.tank.drain(data.shift ? Integer.MAX_VALUE : 1000, true);
+ }
+ }
+ }
+
+ public void tryScrollPhantom(MouseData mouseData) {
+ FluidStack currentFluid = this.tank.getFluid();
+ int amount = mouseData.mouseButton;
+ if (!this.showAmount()) {
+ int newAmt = amount == 1 ? 1 : 0;
+ if (newAmt == 0) {
+ setFluid(null);
+ } else if (currentFluid != null && currentFluid.amount != newAmt) {
+ setAmount(newAmt);
+ }
+ return;
+ }
+ if (mouseData.shift) {
+ amount *= 10;
+ }
+ if (mouseData.ctrl) {
+ amount *= 100;
+ }
+ if (mouseData.alt) {
+ amount *= 1000;
+ }
+ if (currentFluid == null) {
+ if (amount > 0 && this.phantomFluid != null) {
+ FluidStack toFill = this.phantomFluid.copy();
+ toFill.amount = this.showAmount() ? amount : 1;
+ this.tank.fill(toFill, true);
+ }
+ return;
+ }
+ if (amount > 0) {
+ FluidStack toFill = currentFluid.copy();
+ toFill.amount = amount;
+ this.tank.fill(toFill, true);
+ } else if (amount < 0) {
+ this.tank.drain(-amount, true);
+ }
+ }
+
+ public ItemStack tryClickContainer(boolean tryFillAll) {
+ ItemStack playerHeldStack = getSyncManager().getCursorItem();
+ if (playerHeldStack.isEmpty())
+ return ItemStack.EMPTY;
+
+ ItemStack useStack = GTUtility.copy(1, playerHeldStack);
+ var fluidHandlerItem = FluidUtil.getFluidHandler(useStack);
+ if (fluidHandlerItem == null) return ItemStack.EMPTY;
+
+ FluidStack tankFluid = tank.getFluid();
+ FluidStack heldFluid = fluidHandlerItem.drain(Integer.MAX_VALUE, false);
+
+ // nothing to do, return
+ if (tankFluid == null && heldFluid == null)
+ return ItemStack.EMPTY;
+
+ ItemStack returnable = ItemStack.EMPTY;
+
+ // tank is empty, try to fill tank
+ if (canFillSlot && tankFluid == null) {
+ returnable = fillTankFromStack(fluidHandlerItem, heldFluid, tryFillAll);
+
+ // hand is empty, try to drain tank
+ } else if (canDrainSlot && heldFluid == null) {
+ returnable = drainTankIntoStack(fluidHandlerItem, tankFluid, tryFillAll);
+
+ // neither is empty but tank is not full, try to fill tank
+ } else if (canFillSlot && tank.getFluidAmount() < tank.getCapacity() && heldFluid != null) {
+ returnable = fillTankFromStack(fluidHandlerItem, heldFluid, tryFillAll);
+ }
+
+ syncToClient(UPDATE_TANK, buffer -> NetworkUtils.writeFluidStack(buffer, tank.getFluid()));
+
+ return returnable;
+ }
+
+ private ItemStack fillTankFromStack(IFluidHandlerItem fluidHandler, @NotNull FluidStack heldFluid,
+ boolean tryFillAll) {
+ ItemStack heldItem = getSyncManager().getCursorItem();
+ if (heldItem.isEmpty()) return ItemStack.EMPTY;
+
+ FluidStack currentFluid = tank.getFluid();
+ // Fluid type does not match
+ if (currentFluid != null && !currentFluid.isFluidEqual(heldFluid)) return ItemStack.EMPTY;
+
+ int freeSpace = tank.getCapacity() - tank.getFluidAmount();
+ if (freeSpace <= 0) return ItemStack.EMPTY;
+
+ ItemStack itemStackEmptied = ItemStack.EMPTY;
+ int fluidAmountTaken = 0;
+
+ FluidStack drained = fluidHandler.drain(freeSpace, true);
+ if (drained != null && drained.amount > 0) {
+ itemStackEmptied = fluidHandler.getContainer();
+ fluidAmountTaken = drained.amount;
+ }
+ if (itemStackEmptied == ItemStack.EMPTY) {
+ return ItemStack.EMPTY;
+ }
+
+ // find out how many fills we can do
+ // same round down behavior as drain
+ int additional = tryFillAll ? Math.min(freeSpace / fluidAmountTaken, heldItem.getCount()) : 1;
+ FluidStack copiedFluidStack = heldFluid.copy();
+ copiedFluidStack.amount = fluidAmountTaken * additional;
+ tank.fill(copiedFluidStack, true);
+
+ itemStackEmptied.setCount(additional);
+ replaceCursorItemStack(itemStackEmptied);
+ playSound(heldFluid, true);
+ return itemStackEmptied;
+ }
+
+ private ItemStack drainTankIntoStack(IFluidHandlerItem fluidHandler, FluidStack tankFluid, boolean tryFillAll) {
+ ItemStack heldItem = getSyncManager().getCursorItem();
+ if (heldItem.isEmpty()) return ItemStack.EMPTY;
+
+ ItemStack fluidContainer = ItemStack.EMPTY;
+ int filled = fluidHandler.fill(tankFluid, false);
+ int stored = tankFluid.amount;
+ if (filled > 0) {
+ fluidHandler.fill(tankFluid, true);
+ tank.drain(filled, true);
+ fluidContainer = fluidHandler.getContainer();
+ if (tryFillAll) {
+ // Determine how many more items we can fill. One item is already filled.
+ // Integer division means it will round down, so it will only fill equivalent fluid amounts.
+ // For example:
+ // Click with 3 cells, with 2500L of fluid in the tank.
+ // 2 cells will be filled, and 500L will be left behind in the tank.
+ int additional = Math.min(heldItem.getCount(), stored / filled) - 1;
+ tank.drain(filled * additional, true);
+ fluidContainer.grow(additional);
+ }
+ replaceCursorItemStack(fluidContainer);
+ playSound(tankFluid, false);
+ }
+ return fluidContainer;
+ }
+
+ /**
+ * Replace the ItemStack on the player's cursor with the passed stack. Use to replace empty cells with filled, or
+ * filled cells with empty. If it is not fully emptied/filled, it will place the new items into the player inventory
+ * instead, and shrink the held stack by the appropriate amount.
+ */
+ private void replaceCursorItemStack(ItemStack resultStack) {
+ int resultStackSize = resultStack.getMaxStackSize();
+ ItemStack playerStack = getSyncManager().getCursorItem();
+
+ if (!getSyncManager().isClient())
+ syncToClient(TRY_CLICK_CONTAINER, buffer -> NetworkUtils.writeItemStack(buffer, resultStack));
+
+ while (resultStack.getCount() > resultStackSize) {
+ playerStack.shrink(resultStackSize);
+ addItemToPlayerInventory(resultStack.splitStack(resultStackSize));
+ }
+ if (playerStack.getCount() == resultStack.getCount()) {
+ // every item on the cursor is mutated, so leave it there
+ getSyncManager().setCursorItem(resultStack);
+ } else {
+ // some items not mutated. Mutated items go into the inventory/world.
+ playerStack.shrink(resultStack.getCount());
+ getSyncManager().setCursorItem(playerStack);
+ addItemToPlayerInventory(resultStack);
+ }
+ }
+
+ /** Place an item into the player's inventory, or drop it in-world as an item entity if it cannot fit. */
+ private void addItemToPlayerInventory(ItemStack stack) {
+ if (stack == null) return;
+ var player = getSyncManager().getPlayer();
+
+ if (!player.inventory.addItemStackToInventory(stack) && !player.world.isRemote) {
+ EntityItem dropItem = player.entityDropItem(stack, 0);
+ if (dropItem != null) dropItem.setPickupDelay(0);
+ }
+ }
+
+ /**
+ * Play the appropriate fluid interaction sound for the fluid.
+ * Must be called on server to work correctly
+ **/
+ private void playSound(FluidStack fluid, boolean fill) {
+ if (fluid == null) return;
+ SoundEvent soundEvent;
+ if (fill) {
+ soundEvent = fluid.getFluid().getFillSound(fluid);
+ } else {
+ soundEvent = fluid.getFluid().getEmptySound(fluid);
+ }
+ EntityPlayer player = getSyncManager().getPlayer();
+ player.world.playSound(null, player.posX, player.posY + 0.5, player.posZ,
+ soundEvent, SoundCategory.PLAYERS, 1.0F, 1.0F);
+ }
+
+ public FluidStack getPhantomFluid() {
+ return isPhantom() ? phantomFluid : null;
+ }
+
+ public FluidStack getLockedFluid() {
+ return !isPhantom() && canLockFluid() ? lockedFluid.get() : null;
+ }
+
+ public boolean canLockFluid() {
+ return jeiHandler != null && lockHandler != null && lockedFluid != null;
+ }
+
+ public void toggleLockFluid() {
+ var cursorItem = getSyncManager().getCursorItem();
+ if (getLockedFluid() == null) {
+ if (cursorItem.isEmpty()) return;
+ if (cursorItem.getCount() > 1) cursorItem = GTUtility.copy(1, cursorItem);
+
+ var fluidHandler = FluidUtil.getFluidHandler(cursorItem);
+ if (fluidHandler == null) return;
+
+ var fluidStack = fluidHandler.getTankProperties()[0].getContents();
+ if (fluidStack == null) return;
+ lockFluid(fluidStack.copy(), true);
+ } else if (cursorItem.isEmpty()) {
+ lockFluid(null, true);
+ }
+ }
+}
diff --git a/src/main/java/gregtech/api/mui/widget/GhostCircuitSlotWidget.java b/src/main/java/gregtech/api/mui/widget/GhostCircuitSlotWidget.java
index 448740e7147..991f65e7d05 100644
--- a/src/main/java/gregtech/api/mui/widget/GhostCircuitSlotWidget.java
+++ b/src/main/java/gregtech/api/mui/widget/GhostCircuitSlotWidget.java
@@ -6,17 +6,16 @@
import gregtech.api.recipes.ingredients.IntCircuitIngredient;
import gregtech.client.utils.TooltipHelper;
-import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
-import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.items.IItemHandler;
import com.cleanroommc.modularui.api.IPanelHandler;
import com.cleanroommc.modularui.api.drawable.IKey;
import com.cleanroommc.modularui.api.widget.IWidget;
+import com.cleanroommc.modularui.api.widget.Interactable;
import com.cleanroommc.modularui.drawable.ItemDrawable;
import com.cleanroommc.modularui.screen.ModularScreen;
-import com.cleanroommc.modularui.screen.Tooltip;
+import com.cleanroommc.modularui.screen.RichTooltip;
import com.cleanroommc.modularui.utils.MouseData;
import com.cleanroommc.modularui.value.sync.ItemSlotSH;
import com.cleanroommc.modularui.widgets.ButtonWidget;
@@ -27,7 +26,6 @@
import java.io.IOException;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
public class GhostCircuitSlotWidget extends ItemSlot {
@@ -35,6 +33,7 @@ public class GhostCircuitSlotWidget extends ItemSlot {
private static final int SYNC_CIRCUIT_INDEX = 10;
public GhostCircuitSlotWidget() {
+ super();
tooltipBuilder(this::getCircuitSlotTooltip);
}
@@ -56,7 +55,7 @@ public boolean onMouseScroll(ModularScreen.UpOrDown scrollDirection, int amount)
if (isSelectorPanelOpen()) return true;
MouseData mouseData = MouseData.create(scrollDirection.modifier);
getSyncHandler().syncToServer(3, mouseData::writeToPacket);
- return false;
+ return true;
}
@Override
@@ -67,21 +66,15 @@ public ItemSlot slot(ModularSlot slot) {
return this;
}
- @Override
- protected List getItemTooltip(ItemStack stack) {
- // we don't want the item tooltip
- return Collections.emptyList();
- }
-
- protected void getCircuitSlotTooltip(@NotNull Tooltip tooltip) {
+ protected void getCircuitSlotTooltip(@NotNull RichTooltip tooltip) {
String configString;
int value = getSyncHandler().getGhostCircuitHandler().getCircuitValue();
if (value == GhostCircuitItemStackHandler.NO_CONFIG) {
- configString = new TextComponentTranslation("gregtech.gui.configurator_slot.no_value").getFormattedText();
+ configString = IKey.lang("gregtech.gui.configurator_slot.no_value").get();
} else {
configString = String.valueOf(value);
}
-
+ tooltip.clearText();
tooltip.addLine(IKey.lang("gregtech.gui.configurator_slot.tooltip", configString));
}
@@ -105,37 +98,38 @@ private boolean isSelectorPanelOpen() {
private void createSelectorPanel() {
ItemDrawable circuitPreview = new ItemDrawable(getSyncHandler().getSlot().getStack());
- List> options = new ArrayList<>();
- for (int i = 0; i < 4; i++) {
- options.add(new ArrayList<>());
- for (int j = 0; j < 9; j++) {
- int index = i * 9 + j;
- if (index > 32) break;
- options.get(i).add(new ButtonWidget<>()
- .size(18)
- .background(GTGuiTextures.SLOT, new ItemDrawable(
- IntCircuitIngredient.getIntegratedCircuit(index)).asIcon())
- .disableHoverBackground()
- .onMousePressed(mouseButton -> {
- getSyncHandler().syncToServer(SYNC_CIRCUIT_INDEX, buf -> buf.writeShort(index));
- circuitPreview.setItem(IntCircuitIngredient.getIntegratedCircuit(index));
- return true;
- }));
+ IPanelHandler.simple(getPanel(), (mainPanel, player) -> {
+ var panel = GTGuis.createPopupPanel("circuit_selector", 176, 120);
+ List> options = new ArrayList<>();
+ for (int i = 0; i < 4; i++) {
+ options.add(new ArrayList<>());
+ for (int j = 0; j < 9; j++) {
+ int index = i * 9 + j;
+ if (index > 32) break;
+ options.get(i).add(new ButtonWidget<>()
+ .size(18)
+ .background(GTGuiTextures.SLOT, new ItemDrawable(
+ IntCircuitIngredient.getIntegratedCircuit(index)).asIcon())
+ .disableHoverBackground()
+ .onMousePressed(mouseButton -> {
+ getSyncHandler().syncToServer(SYNC_CIRCUIT_INDEX, buf -> buf.writeShort(index));
+ circuitPreview.setItem(IntCircuitIngredient.getIntegratedCircuit(index));
+ if (Interactable.hasShiftDown()) panel.animateClose();
+ return true;
+ }));
+ }
}
- }
-
- IPanelHandler.simple(getPanel(), (mainPanel, player) -> GTGuis.createPopupPanel("circuit_selector", 176, 120)
- .child(IKey.lang("metaitem.circuit.integrated.gui").asWidget().pos(5, 5))
- .child(circuitPreview.asIcon().size(16).asWidget()
- .size(18)
- .top(19).alignX(0.5f)
- .background(GTGuiTextures.SLOT, GTGuiTextures.INT_CIRCUIT_OVERLAY))
- .child(new Grid()
- .left(7).right(7).top(41).height(4 * 18)
- .matrix(options)
- .minColWidth(18).minRowHeight(18)
- .minElementMargin(0, 0)))
- .openPanel();
+ return panel.child(IKey.lang("metaitem.circuit.integrated.gui").asWidget().pos(5, 5))
+ .child(circuitPreview.asIcon().size(16).asWidget()
+ .size(18)
+ .top(19).alignX(0.5f)
+ .background(GTGuiTextures.SLOT, GTGuiTextures.INT_CIRCUIT_OVERLAY))
+ .child(new Grid()
+ .left(7).right(7).top(41).height(4 * 18)
+ .matrix(options)
+ .minColWidth(18).minRowHeight(18)
+ .minElementMargin(0, 0));
+ }, true).openPanel();
}
private static class GhostCircuitSyncHandler extends ItemSlotSH {
diff --git a/src/main/java/gregtech/api/pattern/BlockPattern.java b/src/main/java/gregtech/api/pattern/BlockPattern.java
index 98fde0d5a9d..8479368a3db 100644
--- a/src/main/java/gregtech/api/pattern/BlockPattern.java
+++ b/src/main/java/gregtech/api/pattern/BlockPattern.java
@@ -390,7 +390,7 @@ public void autoBuild(EntityPlayer player, MultiblockControllerBase controllerBa
MetaTileEntity sampleMetaTileEntity = registry.getObjectById(found.getItemDamage());
if (sampleMetaTileEntity != null) {
MetaTileEntity metaTileEntity = igtte.setMetaTileEntity(sampleMetaTileEntity);
- metaTileEntity.onPlacement();
+ metaTileEntity.onPlacement(player);
blocks.put(pos, metaTileEntity);
if (found.getTagCompound() != null) {
metaTileEntity.initFromItemStackData(found.getTagCompound());
diff --git a/src/main/java/gregtech/api/pipenet/tile/TileEntityPipeBase.java b/src/main/java/gregtech/api/pipenet/tile/TileEntityPipeBase.java
index 7d4fc9015ef..3756849a3e7 100644
--- a/src/main/java/gregtech/api/pipenet/tile/TileEntityPipeBase.java
+++ b/src/main/java/gregtech/api/pipenet/tile/TileEntityPipeBase.java
@@ -67,7 +67,7 @@ public void transferDataFrom(IPipeTile tileEntity) {
if (tileEntity instanceof SyncedTileEntityBase pipeBase) {
addPacketsFrom(pipeBase);
}
- coverableImplementation.transferDataTo(tileEntity.getCoverableImplementation());
+ tileEntity.getCoverableImplementation().transferDataTo(coverableImplementation);
setFrameMaterial(tileEntity.getFrameMaterial());
}
diff --git a/src/main/java/gregtech/api/recipes/Recipe.java b/src/main/java/gregtech/api/recipes/Recipe.java
index 923c463e0c4..ff495651ac5 100644
--- a/src/main/java/gregtech/api/recipes/Recipe.java
+++ b/src/main/java/gregtech/api/recipes/Recipe.java
@@ -8,9 +8,9 @@
import gregtech.api.recipes.chance.output.impl.ChancedFluidOutput;
import gregtech.api.recipes.chance.output.impl.ChancedItemOutput;
import gregtech.api.recipes.ingredients.GTRecipeInput;
-import gregtech.api.recipes.recipeproperties.EmptyRecipePropertyStorage;
-import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage;
-import gregtech.api.recipes.recipeproperties.RecipeProperty;
+import gregtech.api.recipes.properties.RecipeProperty;
+import gregtech.api.recipes.properties.RecipePropertyStorage;
+import gregtech.api.recipes.properties.RecipePropertyStorageImpl;
import gregtech.api.util.GTUtility;
import gregtech.api.util.ItemStackHashStrategy;
import gregtech.integration.groovy.GroovyScriptModule;
@@ -26,15 +26,15 @@
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
-import java.util.Map;
-import java.util.Set;
/**
* Class that represent machine recipe.
@@ -99,7 +99,7 @@ public static int getMaxChancedValue() {
// TODO YEET
private final boolean isCTRecipe;
private final boolean groovyRecipe;
- private final IRecipePropertyStorage recipePropertyStorage;
+ private final RecipePropertyStorage recipePropertyStorage;
private final int hashCode;
@@ -113,10 +113,9 @@ public Recipe(@NotNull List inputs,
long EUt,
boolean hidden,
boolean isCTRecipe,
- IRecipePropertyStorage recipePropertyStorage,
+ @NotNull RecipePropertyStorage recipePropertyStorage,
@NotNull GTRecipeCategory recipeCategory) {
- this.recipePropertyStorage = recipePropertyStorage == null ? EmptyRecipePropertyStorage.INSTANCE :
- recipePropertyStorage;
+ this.recipePropertyStorage = recipePropertyStorage;
this.inputs = GTRecipeInputCache.deduplicateInputs(inputs);
if (outputs.isEmpty()) {
this.outputs = Collections.emptyList();
@@ -742,40 +741,26 @@ public GTRecipeCategory getRecipeCategory() {
///////////////////////////////////////////////////////////
// Property Helper Methods //
///////////////////////////////////////////////////////////
- public T getProperty(RecipeProperty property, T defaultValue) {
- return recipePropertyStorage.getRecipePropertyValue(property, defaultValue);
- }
-
- public Object getPropertyRaw(String key) {
- return recipePropertyStorage.getRawRecipePropertyValue(key);
- }
-
- public Set, Object>> getPropertyValues() {
- return recipePropertyStorage.getRecipeProperties();
- }
-
- public Set getPropertyKeys() {
- return recipePropertyStorage.getRecipePropertyKeys();
- }
-
- public Set> getPropertyTypes() {
- return recipePropertyStorage.getPropertyTypes();
- }
- public boolean hasProperty(RecipeProperty> property) {
- return recipePropertyStorage.hasRecipeProperty(property);
- }
-
- public int getPropertyCount() {
- return recipePropertyStorage.getSize();
+ /**
+ * @see RecipePropertyStorageImpl#get(RecipeProperty, Object)
+ */
+ @Contract("_, !null -> !null")
+ public @Nullable T getProperty(@NotNull RecipeProperty property, @Nullable T defaultValue) {
+ return recipePropertyStorage.get(property, defaultValue);
}
- public int getUnhiddenPropertyCount() {
- return (int) recipePropertyStorage.getRecipeProperties().stream()
- .filter((property) -> !property.getKey().isHidden()).count();
+ /**
+ * @see RecipePropertyStorageImpl#contains(RecipeProperty)
+ */
+ public boolean hasProperty(@NotNull RecipeProperty> property) {
+ return recipePropertyStorage.contains(property);
}
- public IRecipePropertyStorage getRecipePropertyStorage() {
+ /**
+ * @return the property storage
+ */
+ public @NotNull RecipePropertyStorage propertyStorage() {
return recipePropertyStorage;
}
}
diff --git a/src/main/java/gregtech/api/recipes/RecipeBuilder.java b/src/main/java/gregtech/api/recipes/RecipeBuilder.java
index b57b8c25db4..d7d8884daa7 100644
--- a/src/main/java/gregtech/api/recipes/RecipeBuilder.java
+++ b/src/main/java/gregtech/api/recipes/RecipeBuilder.java
@@ -16,11 +16,11 @@
import gregtech.api.recipes.ingredients.IntCircuitIngredient;
import gregtech.api.recipes.ingredients.nbtmatch.NBTCondition;
import gregtech.api.recipes.ingredients.nbtmatch.NBTMatcher;
-import gregtech.api.recipes.recipeproperties.CleanroomProperty;
-import gregtech.api.recipes.recipeproperties.DimensionProperty;
-import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage;
-import gregtech.api.recipes.recipeproperties.RecipeProperty;
-import gregtech.api.recipes.recipeproperties.RecipePropertyStorage;
+import gregtech.api.recipes.properties.RecipeProperty;
+import gregtech.api.recipes.properties.RecipePropertyStorage;
+import gregtech.api.recipes.properties.RecipePropertyStorageImpl;
+import gregtech.api.recipes.properties.impl.CleanroomProperty;
+import gregtech.api.recipes.properties.impl.DimensionProperty;
import gregtech.api.unification.OreDictUnifier;
import gregtech.api.unification.material.Material;
import gregtech.api.unification.ore.OrePrefix;
@@ -35,6 +35,7 @@
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
+import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.Optional;
@@ -44,7 +45,7 @@
import com.cleanroommc.groovyscript.helper.ingredient.OreDictIngredient;
import crafttweaker.CraftTweakerAPI;
import it.unimi.dsi.fastutil.ints.IntList;
-import it.unimi.dsi.fastutil.ints.IntLists;
+import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.MustBeInvokedByOverriders;
@@ -54,6 +55,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -84,9 +86,12 @@ public class RecipeBuilder> {
protected boolean isCTRecipe = false;
protected int parallel = 0;
protected EnumValidationResult recipeStatus = EnumValidationResult.VALID;
- protected @Nullable IRecipePropertyStorage recipePropertyStorage = null;
+ protected RecipePropertyStorage recipePropertyStorage = RecipePropertyStorage.EMPTY;
protected boolean recipePropertyStorageErrored = false;
+ protected boolean ignoreAllBuildActions = false;
+ protected Map> ignoredBuildActions;
+
protected RecipeBuilder() {
this.inputs = new ArrayList<>();
this.outputs = new ArrayList<>();
@@ -108,10 +113,7 @@ public RecipeBuilder(Recipe recipe, RecipeMap recipeMap) {
this.EUt = recipe.getEUt();
this.hidden = recipe.isHidden();
this.category = recipe.getRecipeCategory();
- this.recipePropertyStorage = recipe.getRecipePropertyStorage().copy();
- if (this.recipePropertyStorage != null) {
- this.recipePropertyStorage.freeze(false);
- }
+ this.recipePropertyStorage = recipe.propertyStorage().copy();
}
@SuppressWarnings("CopyConstructorMissesField")
@@ -129,18 +131,17 @@ protected RecipeBuilder(RecipeBuilder recipeBuilder) {
this.EUt = recipeBuilder.EUt;
this.hidden = recipeBuilder.hidden;
this.category = recipeBuilder.category;
- this.recipePropertyStorage = recipeBuilder.recipePropertyStorage == null ? null :
- recipeBuilder.recipePropertyStorage.copy();
- if (this.recipePropertyStorage != null) {
- this.recipePropertyStorage = this.recipePropertyStorage.copy();
+ this.recipePropertyStorage = recipeBuilder.recipePropertyStorage.copy();
+ this.ignoreAllBuildActions = recipeBuilder.ignoreAllBuildActions;
+ if (recipeBuilder.ignoredBuildActions != null) {
+ this.ignoredBuildActions = new Object2ObjectOpenHashMap<>(recipeBuilder.ignoredBuildActions);
}
}
public R cleanroom(@Nullable CleanroomType cleanroom) {
- if (!ConfigHolder.machines.enableCleanroom) {
- return (R) this;
+ if (ConfigHolder.machines.enableCleanroom && cleanroom != null) {
+ this.applyProperty(CleanroomProperty.getInstance(), cleanroom);
}
- this.applyProperty(CleanroomProperty.getInstance(), cleanroom);
return (R) this;
}
@@ -150,7 +151,7 @@ public R dimension(int dimensionID) {
public R dimension(int dimensionID, boolean toBlackList) {
DimensionProperty.DimensionPropertyList dimensionIDs = getCompleteDimensionIDs();
- if (dimensionIDs == DimensionProperty.DimensionPropertyList.EMPTY_LIST) {
+ if (dimensionIDs == null) {
dimensionIDs = new DimensionProperty.DimensionPropertyList();
this.applyProperty(DimensionProperty.getInstance(), dimensionIDs);
}
@@ -158,29 +159,26 @@ public R dimension(int dimensionID, boolean toBlackList) {
return (R) this;
}
- public DimensionProperty.DimensionPropertyList getCompleteDimensionIDs() {
- return this.recipePropertyStorage == null ? DimensionProperty.DimensionPropertyList.EMPTY_LIST :
- this.recipePropertyStorage.getRecipePropertyValue(DimensionProperty.getInstance(),
- DimensionProperty.DimensionPropertyList.EMPTY_LIST);
+ public @Nullable DimensionProperty.DimensionPropertyList getCompleteDimensionIDs() {
+ return this.recipePropertyStorage.get(DimensionProperty.getInstance(), null);
}
- public IntList getDimensionIDs() {
- return this.recipePropertyStorage == null ? IntLists.EMPTY_LIST :
- this.recipePropertyStorage.getRecipePropertyValue(DimensionProperty.getInstance(),
- DimensionProperty.DimensionPropertyList.EMPTY_LIST).whiteListDimensions;
+ public @NotNull IntList getDimensionIDs() {
+ return this.recipePropertyStorage.get(DimensionProperty.getInstance(),
+ DimensionProperty.DimensionPropertyList.EMPTY_LIST).whiteListDimensions;
}
- public IntList getBlockedDimensionIDs() {
- return this.recipePropertyStorage == null ? IntLists.EMPTY_LIST :
- this.recipePropertyStorage.getRecipePropertyValue(DimensionProperty.getInstance(),
- DimensionProperty.DimensionPropertyList.EMPTY_LIST).whiteListDimensions;
+ public @NotNull IntList getBlockedDimensionIDs() {
+ return this.recipePropertyStorage.get(DimensionProperty.getInstance(),
+ DimensionProperty.DimensionPropertyList.EMPTY_LIST).blackListDimensions;
}
- public boolean applyProperty(@NotNull String key, @Nullable Object value) {
+ @MustBeInvokedByOverriders
+ public boolean applyPropertyCT(@NotNull String key, @NotNull Object value) {
if (key.equals(DimensionProperty.KEY)) {
if (value instanceof DimensionProperty.DimensionPropertyList list) {
DimensionProperty.DimensionPropertyList dimensionIDs = getCompleteDimensionIDs();
- if (dimensionIDs == DimensionProperty.DimensionPropertyList.EMPTY_LIST) {
+ if (dimensionIDs == null) {
dimensionIDs = new DimensionProperty.DimensionPropertyList();
this.applyProperty(DimensionProperty.getInstance(), dimensionIDs);
}
@@ -201,22 +199,16 @@ public boolean applyProperty(@NotNull String key, @Nullable Object value) {
return false;
}
- public boolean applyProperty(@NotNull RecipeProperty> property, @Nullable Object value) {
- if (value == null) {
- if (this.recipePropertyStorage != null) {
- return this.recipePropertyStorage.remove(property);
- }
- } else {
- if (this.recipePropertyStorage == null) {
- this.recipePropertyStorage = new RecipePropertyStorage();
- }
- boolean stored = this.recipePropertyStorage.store(property, value);
- if (!stored) {
- this.recipePropertyStorageErrored = true;
- }
- return stored;
+ public final boolean applyProperty(@NotNull RecipeProperty> property, @NotNull Object value) {
+ if (this.recipePropertyStorage == RecipePropertyStorage.EMPTY) {
+ this.recipePropertyStorage = new RecipePropertyStorageImpl();
}
- return true;
+
+ boolean stored = this.recipePropertyStorage.store(property, value);
+ if (!stored) {
+ this.recipePropertyStorageErrored = true;
+ }
+ return stored;
}
public R input(GTRecipeInput input) {
@@ -791,8 +783,8 @@ public void chancedOutputsMultiply(Recipe chancedOutputsFrom, int numberOfOperat
*/
public R append(Recipe recipe, int multiplier, boolean multiplyDuration) {
- for (Map.Entry, Object> property : recipe.getPropertyValues()) {
- this.applyProperty(property.getKey().getKey(), property.getValue());
+ for (Map.Entry, Object> property : recipe.propertyStorage().entrySet()) {
+ this.applyPropertyCT(property.getKey().getKey(), property.getValue());
}
// Create holders for the various parts of the new multiplied Recipe
@@ -836,7 +828,7 @@ protected static void multiplyInputsAndOutputs(List newRecipeInpu
if (ri.isNonConsumable()) {
newRecipeInputs.add(ri);
} else {
- newRecipeInputs.add(ri.withAmount(ri.getAmount() * numberOfOperations));
+ newRecipeInputs.add(ri.copyWithAmount(ri.getAmount() * numberOfOperations));
}
});
@@ -844,7 +836,7 @@ protected static void multiplyInputsAndOutputs(List newRecipeInpu
if (fi.isNonConsumable()) {
newFluidInputs.add(fi);
} else {
- newFluidInputs.add(fi.withAmount(fi.getAmount() * numberOfOperations));
+ newFluidInputs.add(fi.copyWithAmount(fi.getAmount() * numberOfOperations));
}
});
@@ -905,12 +897,34 @@ public R copy() {
return (R) new RecipeBuilder<>(this);
}
- protected EnumValidationResult finalizeAndValidate() {
- return recipePropertyStorageErrored ? EnumValidationResult.INVALID : validate();
+ /**
+ * Only use if you absolutely don't want the recipe to be run through any build actions.
+ * Instead, you should blacklist specific actions with {@link #ignoreBuildAction(ResourceLocation)}
+ */
+ public R ignoreAllBuildActions() {
+ this.ignoreAllBuildActions = true;
+ return (R) this;
+ }
+
+ public R ignoreBuildAction(ResourceLocation buildActionName) {
+ if (ignoredBuildActions == null) {
+ ignoredBuildActions = new Object2ObjectOpenHashMap<>();
+ } else if (!recipeMap.getBuildActions().containsKey(buildActionName)) {
+ GTLog.logger.error("Recipe map {} does not contain build action {}!", recipeMap, buildActionName,
+ new Throwable());
+ return (R) this;
+ } else if (ignoredBuildActions.containsKey(buildActionName)) {
+ return (R) this;
+ }
+
+ ignoredBuildActions.put(buildActionName, recipeMap.getBuildActions().get(buildActionName));
+
+ return (R) this;
}
public ValidationResult build() {
- return ValidationResult.newResult(finalizeAndValidate(), new Recipe(inputs, outputs,
+ EnumValidationResult result = recipePropertyStorageErrored ? EnumValidationResult.INVALID : validate();
+ return ValidationResult.newResult(result, new Recipe(inputs, outputs,
new ChancedOutputList<>(this.chancedOutputLogic, chancedOutputs),
fluidInputs, fluidOutputs,
new ChancedOutputList<>(this.chancedFluidOutputLogic, chancedFluidOutputs),
@@ -956,9 +970,6 @@ protected EnumValidationResult validate() {
if (recipeStatus == EnumValidationResult.INVALID) {
GTLog.logger.error("Invalid recipe, read the errors above: {}", this);
}
- if (recipePropertyStorage != null) {
- recipePropertyStorage.freeze(true);
- }
return recipeStatus;
}
@@ -1009,8 +1020,14 @@ protected R invalidateOnBuildAction() {
*/
@MustBeInvokedByOverriders
public void buildAndRegister() {
- for (RecipeBuildAction action : recipeMap.getBuildActions()) {
- action.accept((R) this);
+ if (!ignoreAllBuildActions) {
+ for (Map.Entry> buildAction : recipeMap.getBuildActions()
+ .entrySet()) {
+ if (ignoredBuildActions != null && ignoredBuildActions.containsKey(buildAction.getKey())) {
+ continue;
+ }
+ buildAction.getValue().accept((R) this);
+ }
}
ValidationResult validationResult = build();
recipeMap.addRecipe(validationResult);
@@ -1067,10 +1084,29 @@ public int getDuration() {
return duration;
}
- @Nullable
- public CleanroomType getCleanroom() {
- return this.recipePropertyStorage == null ? null :
- this.recipePropertyStorage.getRecipePropertyValue(CleanroomProperty.getInstance(), null);
+ public @Nullable CleanroomType getCleanroom() {
+ return this.recipePropertyStorage.get(CleanroomProperty.getInstance(), null);
+ }
+
+ public boolean ignoresAllBuildActions() {
+ return ignoreAllBuildActions;
+ }
+
+ /**
+ * Get all ignored build actions for the recipe map.
+ *
+ * @return A map of ignored build actions.
+ */
+ public @NotNull Map> getIgnoredBuildActions() {
+ if (ignoreAllBuildActions) {
+ return recipeMap.getBuildActions();
+ }
+
+ if (ignoredBuildActions == null) {
+ return Collections.emptyMap();
+ }
+
+ return ignoredBuildActions;
}
@Override
@@ -1090,6 +1126,8 @@ public String toString() {
.append("dimensions", getDimensionIDs().toString())
.append("dimensions_blocked", getBlockedDimensionIDs().toString())
.append("recipeStatus", recipeStatus)
+ .append("ignoresBuildActions", ignoresAllBuildActions())
+ .append("ignoredBuildActions", getIgnoredBuildActions())
.toString();
}
}
diff --git a/src/main/java/gregtech/api/recipes/RecipeMap.java b/src/main/java/gregtech/api/recipes/RecipeMap.java
index df5ae2d7d2e..a2c2ef7b1f4 100644
--- a/src/main/java/gregtech/api/recipes/RecipeMap.java
+++ b/src/main/java/gregtech/api/recipes/RecipeMap.java
@@ -347,8 +347,8 @@ protected void onRecipeBuild(@NotNull Map
* @return the build actions for this RecipeMap's default RecipeBuilder
*/
@ApiStatus.Internal
- protected @UnmodifiableView @NotNull Collection<@NotNull RecipeBuildAction> getBuildActions() {
- return this.recipeBuildActions.values();
+ protected @UnmodifiableView @NotNull Map> getBuildActions() {
+ return this.recipeBuildActions;
}
public RecipeMap allowEmptyOutput() {
diff --git a/src/main/java/gregtech/api/recipes/builders/AssemblyLineRecipeBuilder.java b/src/main/java/gregtech/api/recipes/builders/AssemblyLineRecipeBuilder.java
index 40a23a261ff..dc711dd0a0a 100644
--- a/src/main/java/gregtech/api/recipes/builders/AssemblyLineRecipeBuilder.java
+++ b/src/main/java/gregtech/api/recipes/builders/AssemblyLineRecipeBuilder.java
@@ -4,8 +4,8 @@
import gregtech.api.recipes.Recipe;
import gregtech.api.recipes.RecipeBuilder;
import gregtech.api.recipes.RecipeMap;
-import gregtech.api.recipes.recipeproperties.ResearchProperty;
-import gregtech.api.recipes.recipeproperties.ResearchPropertyData;
+import gregtech.api.recipes.properties.impl.ResearchProperty;
+import gregtech.api.recipes.properties.impl.ResearchPropertyData;
import gregtech.api.util.AssemblyLineManager;
import gregtech.api.util.EnumValidationResult;
import gregtech.api.util.GTLog;
@@ -14,7 +14,6 @@
import net.minecraft.item.ItemStack;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
@@ -45,14 +44,15 @@ public AssemblyLineRecipeBuilder copy() {
}
@Override
- public boolean applyProperty(@NotNull String key, @Nullable Object value) {
+ public boolean applyPropertyCT(@NotNull String key, @NotNull Object value) {
if (key.equals(ResearchProperty.KEY)) {
if (value instanceof ItemStack itemStack) {
scannerResearch(itemStack);
return true;
}
+ return false;
}
- return super.applyProperty(key, value);
+ return super.applyPropertyCT(key, value);
}
private boolean applyResearchProperty(ResearchPropertyData.ResearchEntry researchEntry) {
@@ -70,15 +70,13 @@ private boolean applyResearchProperty(ResearchPropertyData.ResearchEntry researc
return false;
}
- if (recipePropertyStorage != null && recipePropertyStorage.hasRecipeProperty(ResearchProperty.getInstance())) {
- ResearchPropertyData property = recipePropertyStorage.getRecipePropertyValue(ResearchProperty.getInstance(),
- null);
- if (property == null) throw new IllegalStateException("Property storage has a null property");
+ ResearchPropertyData property = recipePropertyStorage.get(ResearchProperty.getInstance(), null);
+ if (property != null) {
property.add(researchEntry);
return true;
}
- ResearchPropertyData property = new ResearchPropertyData();
+ property = new ResearchPropertyData();
if (applyProperty(ResearchProperty.getInstance(), property)) {
property.add(researchEntry);
return true;
diff --git a/src/main/java/gregtech/api/recipes/builders/BlastRecipeBuilder.java b/src/main/java/gregtech/api/recipes/builders/BlastRecipeBuilder.java
index 8aa2bd236cc..c5bf92c5e16 100644
--- a/src/main/java/gregtech/api/recipes/builders/BlastRecipeBuilder.java
+++ b/src/main/java/gregtech/api/recipes/builders/BlastRecipeBuilder.java
@@ -3,7 +3,7 @@
import gregtech.api.recipes.Recipe;
import gregtech.api.recipes.RecipeBuilder;
import gregtech.api.recipes.RecipeMap;
-import gregtech.api.recipes.recipeproperties.TemperatureProperty;
+import gregtech.api.recipes.properties.impl.TemperatureProperty;
import gregtech.api.util.EnumValidationResult;
import gregtech.api.util.GTLog;
@@ -28,12 +28,12 @@ public BlastRecipeBuilder copy() {
}
@Override
- public boolean applyProperty(@NotNull String key, Object value) {
+ public boolean applyPropertyCT(@NotNull String key, @NotNull Object value) {
if (key.equals(TemperatureProperty.KEY)) {
this.blastFurnaceTemp(((Number) value).intValue());
return true;
}
- return super.applyProperty(key, value);
+ return super.applyPropertyCT(key, value);
}
public BlastRecipeBuilder blastFurnaceTemp(int blastFurnaceTemp) {
@@ -47,8 +47,7 @@ public BlastRecipeBuilder blastFurnaceTemp(int blastFurnaceTemp) {
}
public int getBlastFurnaceTemp() {
- return this.recipePropertyStorage == null ? 0 :
- this.recipePropertyStorage.getRecipePropertyValue(TemperatureProperty.getInstance(), 0);
+ return this.recipePropertyStorage.get(TemperatureProperty.getInstance(), 0);
}
@Override
diff --git a/src/main/java/gregtech/api/recipes/builders/ComputationRecipeBuilder.java b/src/main/java/gregtech/api/recipes/builders/ComputationRecipeBuilder.java
index 2da0309972a..1d6c49a75d8 100644
--- a/src/main/java/gregtech/api/recipes/builders/ComputationRecipeBuilder.java
+++ b/src/main/java/gregtech/api/recipes/builders/ComputationRecipeBuilder.java
@@ -3,8 +3,8 @@
import gregtech.api.recipes.Recipe;
import gregtech.api.recipes.RecipeBuilder;
import gregtech.api.recipes.RecipeMap;
-import gregtech.api.recipes.recipeproperties.ComputationProperty;
-import gregtech.api.recipes.recipeproperties.TotalComputationProperty;
+import gregtech.api.recipes.properties.impl.ComputationProperty;
+import gregtech.api.recipes.properties.impl.TotalComputationProperty;
import gregtech.api.util.EnumValidationResult;
import gregtech.api.util.GTLog;
@@ -28,7 +28,7 @@ public ComputationRecipeBuilder copy() {
}
@Override
- public boolean applyProperty(@NotNull String key, Object value) {
+ public boolean applyPropertyCT(@NotNull String key, @NotNull Object value) {
if (key.equals(ComputationProperty.KEY)) {
this.CWUt(((Number) value).intValue());
return true;
@@ -37,7 +37,7 @@ public boolean applyProperty(@NotNull String key, Object value) {
this.totalCWU(((Number) value).intValue());
return true;
}
- return super.applyProperty(key, value);
+ return super.applyPropertyCT(key, value);
}
public ComputationRecipeBuilder CWUt(int cwut) {
diff --git a/src/main/java/gregtech/api/recipes/builders/FusionRecipeBuilder.java b/src/main/java/gregtech/api/recipes/builders/FusionRecipeBuilder.java
index a6f56e1420a..91622a9950c 100644
--- a/src/main/java/gregtech/api/recipes/builders/FusionRecipeBuilder.java
+++ b/src/main/java/gregtech/api/recipes/builders/FusionRecipeBuilder.java
@@ -3,7 +3,7 @@
import gregtech.api.recipes.Recipe;
import gregtech.api.recipes.RecipeBuilder;
import gregtech.api.recipes.RecipeMap;
-import gregtech.api.recipes.recipeproperties.FusionEUToStartProperty;
+import gregtech.api.recipes.properties.impl.FusionEUToStartProperty;
import gregtech.api.util.EnumValidationResult;
import gregtech.api.util.GTLog;
@@ -28,12 +28,12 @@ public FusionRecipeBuilder copy() {
}
@Override
- public boolean applyProperty(@NotNull String key, Object value) {
+ public boolean applyPropertyCT(@NotNull String key, @NotNull Object value) {
if (key.equals(FusionEUToStartProperty.KEY)) {
this.EUToStart(((Number) value).longValue());
return true;
}
- return super.applyProperty(key, value);
+ return super.applyPropertyCT(key, value);
}
public FusionRecipeBuilder EUToStart(long EUToStart) {
@@ -46,8 +46,7 @@ public FusionRecipeBuilder EUToStart(long EUToStart) {
}
public long getEUToStart() {
- return this.recipePropertyStorage == null ? 0L :
- this.recipePropertyStorage.getRecipePropertyValue(FusionEUToStartProperty.getInstance(), 0L);
+ return this.recipePropertyStorage.get(FusionEUToStartProperty.getInstance(), 0L);
}
@Override
diff --git a/src/main/java/gregtech/api/recipes/builders/ImplosionRecipeBuilder.java b/src/main/java/gregtech/api/recipes/builders/ImplosionRecipeBuilder.java
index 3ada0e83415..ce078b9751b 100644
--- a/src/main/java/gregtech/api/recipes/builders/ImplosionRecipeBuilder.java
+++ b/src/main/java/gregtech/api/recipes/builders/ImplosionRecipeBuilder.java
@@ -4,10 +4,9 @@
import gregtech.api.recipes.RecipeBuilder;
import gregtech.api.recipes.RecipeMap;
import gregtech.api.recipes.ingredients.GTRecipeItemInput;
-import gregtech.api.recipes.recipeproperties.ImplosionExplosiveProperty;
+import gregtech.api.recipes.properties.impl.ImplosionExplosiveProperty;
import gregtech.api.util.EnumValidationResult;
import gregtech.api.util.GTLog;
-import gregtech.api.util.ValidationResult;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
@@ -34,61 +33,52 @@ public ImplosionRecipeBuilder copy() {
}
@Override
- public boolean applyProperty(@NotNull String key, Object value) {
+ public boolean applyPropertyCT(@NotNull String key, @NotNull Object value) {
if (key.equals(ImplosionExplosiveProperty.KEY)) {
- if (value instanceof ItemStack) {
- this.applyProperty(ImplosionExplosiveProperty.getInstance(), value);
- } else {
- this.applyProperty(ImplosionExplosiveProperty.getInstance(), new ItemStack(Blocks.TNT, (int) value));
+ if (value instanceof ItemStack stack) {
+ return this.applyProperty(ImplosionExplosiveProperty.getInstance(), stack);
+ } else if (value instanceof Number number) {
+ return this.applyProperty(ImplosionExplosiveProperty.getInstance(), number.intValue());
}
- return true;
+ return false;
}
- return super.applyProperty(key, value);
+ return super.applyPropertyCT(key, value);
}
@ZenMethod
- public ImplosionRecipeBuilder explosivesAmount(int explosivesAmount) {
- if (1 > explosivesAmount || explosivesAmount > 64) {
- GTLog.logger.error("Amount of explosives should be from 1 to 64 inclusive", new Throwable());
- recipeStatus = EnumValidationResult.INVALID;
- }
- this.applyProperty(ImplosionExplosiveProperty.getInstance(), new ItemStack(Blocks.TNT, explosivesAmount));
- return this;
+ public ImplosionRecipeBuilder explosives(int amount) {
+ return explosives(new ItemStack(Blocks.TNT, amount));
}
@ZenMethod
- public ImplosionRecipeBuilder explosivesType(ItemStack explosivesType) {
- if (1 > explosivesType.getCount() || explosivesType.getCount() > 64) {
+ public ImplosionRecipeBuilder explosives(@NotNull ItemStack explosive) {
+ if (explosive.isEmpty()) {
+ GTLog.logger.error("Cannot use empty explosives", new Throwable());
+ this.recipeStatus = EnumValidationResult.INVALID;
+ return this;
+ }
+
+ int count = explosive.getCount();
+ if (count < 1 || count > 64) {
GTLog.logger.error("Amount of explosives should be from 1 to 64 inclusive", new Throwable());
recipeStatus = EnumValidationResult.INVALID;
+ return this;
}
- this.applyProperty(ImplosionExplosiveProperty.getInstance(), explosivesType);
- return this;
- }
-
- public ItemStack getExplosivesType() {
- if (this.recipePropertyStorage == null) {
- return ItemStack.EMPTY;
+ if (this.applyProperty(ImplosionExplosiveProperty.getInstance(), explosive)) {
+ this.inputs.add(new GTRecipeItemInput(explosive));
}
- return this.recipePropertyStorage.getRecipePropertyValue(ImplosionExplosiveProperty.getInstance(),
- ItemStack.EMPTY);
+ return this;
}
- public ValidationResult build() {
- ItemStack explosivesType = getExplosivesType();
- if (!explosivesType.isEmpty()) {
- this.inputs.add(new GTRecipeItemInput(explosivesType));
- } else {
- this.recipePropertyStorageErrored = true;
- }
- return super.build();
+ public @NotNull ItemStack getExplosives() {
+ return this.recipePropertyStorage.get(ImplosionExplosiveProperty.getInstance(), ItemStack.EMPTY);
}
@Override
public String toString() {
return new ToStringBuilder(this)
.appendSuper(super.toString())
- .append(ImplosionExplosiveProperty.getInstance().getKey(), getExplosivesType())
+ .append(ImplosionExplosiveProperty.getInstance().getKey(), getExplosives())
.toString();
}
}
diff --git a/src/main/java/gregtech/api/recipes/builders/PrimitiveRecipeBuilder.java b/src/main/java/gregtech/api/recipes/builders/PrimitiveRecipeBuilder.java
index 858a94d1177..ec0e8cf2202 100644
--- a/src/main/java/gregtech/api/recipes/builders/PrimitiveRecipeBuilder.java
+++ b/src/main/java/gregtech/api/recipes/builders/PrimitiveRecipeBuilder.java
@@ -3,7 +3,7 @@
import gregtech.api.recipes.Recipe;
import gregtech.api.recipes.RecipeBuilder;
import gregtech.api.recipes.RecipeMap;
-import gregtech.api.recipes.recipeproperties.PrimitiveProperty;
+import gregtech.api.recipes.properties.impl.PrimitiveProperty;
import gregtech.api.util.ValidationResult;
public class PrimitiveRecipeBuilder extends RecipeBuilder {
diff --git a/src/main/java/gregtech/api/recipes/machines/RecipeMapAssemblyLine.java b/src/main/java/gregtech/api/recipes/machines/RecipeMapAssemblyLine.java
index 5c23b88f6a2..d1d8301a3c7 100644
--- a/src/main/java/gregtech/api/recipes/machines/RecipeMapAssemblyLine.java
+++ b/src/main/java/gregtech/api/recipes/machines/RecipeMapAssemblyLine.java
@@ -3,8 +3,8 @@
import gregtech.api.recipes.Recipe;
import gregtech.api.recipes.RecipeBuilder;
import gregtech.api.recipes.RecipeMap;
-import gregtech.api.recipes.recipeproperties.ResearchProperty;
-import gregtech.api.recipes.recipeproperties.ResearchPropertyData;
+import gregtech.api.recipes.properties.impl.ResearchProperty;
+import gregtech.api.recipes.properties.impl.ResearchPropertyData;
import gregtech.api.recipes.ui.RecipeMapUIFunction;
import gregtech.core.sound.GTSoundEvents;
@@ -32,15 +32,11 @@ public RecipeMapAssemblyLine(@NotNull String unlocalizedName, @NotNull R default
@Override
public boolean compileRecipe(Recipe recipe) {
if (!super.compileRecipe(recipe)) return false;
- if (recipe.hasProperty(ResearchProperty.getInstance())) {
- ResearchPropertyData data = recipe.getProperty(ResearchProperty.getInstance(), null);
- if (data != null) {
- for (ResearchPropertyData.ResearchEntry entry : data) {
- addDataStickEntry(entry.getResearchId(), recipe);
- }
- return true;
+ ResearchPropertyData data = recipe.getProperty(ResearchProperty.getInstance(), null);
+ if (data != null) {
+ for (ResearchPropertyData.ResearchEntry entry : data) {
+ addDataStickEntry(entry.researchId(), recipe);
}
- return false;
}
return true;
}
@@ -48,15 +44,11 @@ public boolean compileRecipe(Recipe recipe) {
@Override
public boolean removeRecipe(@NotNull Recipe recipe) {
if (!super.removeRecipe(recipe)) return false;
- if (recipe.hasProperty(ResearchProperty.getInstance())) {
- ResearchPropertyData data = recipe.getProperty(ResearchProperty.getInstance(), null);
- if (data != null) {
- for (ResearchPropertyData.ResearchEntry entry : data) {
- removeDataStickEntry(entry.getResearchId(), recipe);
- }
- return true;
+ ResearchPropertyData data = recipe.getProperty(ResearchProperty.getInstance(), null);
+ if (data != null) {
+ for (ResearchPropertyData.ResearchEntry entry : data) {
+ removeDataStickEntry(entry.researchId(), recipe);
}
- return false;
}
return true;
}
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/RecipeProperty.java b/src/main/java/gregtech/api/recipes/properties/RecipeProperty.java
similarity index 62%
rename from src/main/java/gregtech/api/recipes/recipeproperties/RecipeProperty.java
rename to src/main/java/gregtech/api/recipes/properties/RecipeProperty.java
index 9dde81bb195..bb54c07603f 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/RecipeProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/RecipeProperty.java
@@ -1,11 +1,13 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties;
import net.minecraft.client.Minecraft;
+import net.minecraft.nbt.NBTBase;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
+import org.jetbrains.annotations.NotNull;
+
import java.util.List;
-import java.util.Objects;
public abstract class RecipeProperty {
@@ -17,6 +19,18 @@ protected RecipeProperty(String key, Class type) {
this.type = type;
}
+ /**
+ * @param value the value to serialize
+ * @return the serialized form of the value
+ */
+ public abstract @NotNull NBTBase serialize(@NotNull Object value);
+
+ /**
+ * @param nbt the nbt to deserialize
+ * @return the deserialized property value
+ */
+ public abstract @NotNull Object deserialize(@NotNull NBTBase nbt);
+
@SideOnly(Side.CLIENT)
public abstract void drawInfo(Minecraft minecraft, int x, int y, int color, Object value);
@@ -28,19 +42,15 @@ public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value,
@SideOnly(Side.CLIENT)
public void getTooltipStrings(List tooltip, int mouseX, int mouseY, Object value) {}
- public int getInfoHeight(Object value) {
+ public int getInfoHeight(@NotNull Object value) {
return 10; // GTRecipeWrapper#LINE_HEIGHT
}
- public boolean isOfType(Class> otherType) {
- return this.type == otherType;
- }
-
- public String getKey() {
+ public final @NotNull String getKey() {
return key;
}
- public T castValue(Object value) {
+ protected final T castValue(@NotNull Object value) {
return this.type.cast(value);
}
@@ -75,15 +85,20 @@ public boolean hideDuration() {
}
@Override
- public boolean equals(Object o) {
+ public final boolean equals(Object o) {
if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- RecipeProperty> that = (RecipeProperty>) o;
- return Objects.equals(type, that.type) && Objects.equals(key, that.key);
+ if (!(o instanceof RecipeProperty>that)) return false;
+
+ return type.equals(that.type) && getKey().equals(that.getKey());
+ }
+
+ @Override
+ public final int hashCode() {
+ return 31 * type.hashCode() + getKey().hashCode();
}
@Override
- public int hashCode() {
- return Objects.hash(type, key);
+ public String toString() {
+ return "RecipeProperty{" + "key='" + key + "'}";
}
}
diff --git a/src/main/java/gregtech/api/recipes/properties/RecipePropertyRegistry.java b/src/main/java/gregtech/api/recipes/properties/RecipePropertyRegistry.java
new file mode 100644
index 00000000000..13defc9f723
--- /dev/null
+++ b/src/main/java/gregtech/api/recipes/properties/RecipePropertyRegistry.java
@@ -0,0 +1,29 @@
+package gregtech.api.recipes.properties;
+
+import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap;
+import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.Map;
+
+public final class RecipePropertyRegistry {
+
+ private final Map> map = new Object2ReferenceOpenHashMap<>();
+
+ /**
+ * @param key the RecipeProperty's key
+ * @param property the property's instance
+ */
+ public void register(@NotNull String key, @NotNull RecipeProperty> property) {
+ if (map.containsKey(key)) {
+ throw new IllegalArgumentException("RecipeProperty is already registered: " + key);
+ }
+ map.put(key, property);
+ }
+
+ @ApiStatus.Internal
+ public @Nullable RecipeProperty> get(@NotNull String key) {
+ return map.get(key);
+ }
+}
diff --git a/src/main/java/gregtech/api/recipes/properties/RecipePropertyStorage.java b/src/main/java/gregtech/api/recipes/properties/RecipePropertyStorage.java
new file mode 100644
index 00000000000..790143293dd
--- /dev/null
+++ b/src/main/java/gregtech/api/recipes/properties/RecipePropertyStorage.java
@@ -0,0 +1,119 @@
+package gregtech.api.recipes.properties;
+
+import gregtech.api.util.GTLog;
+
+import net.minecraft.nbt.NBTTagCompound;
+
+import org.jetbrains.annotations.Contract;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.UnmodifiableView;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+
+public interface RecipePropertyStorage {
+
+ /**
+ * @param recipeProperty the property to store
+ * @param value the value to store
+ * @return if the store succeeds
+ */
+ boolean store(@NotNull RecipeProperty> recipeProperty, @NotNull Object value);
+
+ /**
+ * @return a copy of this property storage
+ */
+ @NotNull
+ RecipePropertyStorage copy();
+
+ /**
+ * @return number of stored properties
+ */
+ int size();
+
+ /**
+ * @return all stored properties and values
+ */
+ @NotNull
+ Set, Object>> entrySet();
+
+ /**
+ * @param recipeProperty the property to retrieve
+ * @param defaultValue default value if the property is not found
+ * @param the type of returned value
+ * @return value associated with the provided recipeProperty, otherwise the default
+ */
+ @Contract("_, !null -> !null")
+ @Nullable T get(@NotNull RecipeProperty recipeProperty, @Nullable T defaultValue);
+
+ /**
+ * @param recipeProperty the property to check
+ * @return if the property is in this storage
+ */
+ boolean contains(@NotNull RecipeProperty> recipeProperty);
+
+ /**
+ * @return the recipe property values
+ */
+ @UnmodifiableView
+ @NotNull
+ Set<@NotNull RecipeProperty>> values();
+
+ @NotNull
+ NBTTagCompound serializeNBT();
+
+ void deserializeNBT(@NotNull NBTTagCompound nbt);
+
+ RecipePropertyStorage EMPTY = new RecipePropertyStorage() {
+
+ @Override
+ public boolean store(@NotNull RecipeProperty> recipeProperty, @NotNull Object value) {
+ throw new UnsupportedOperationException("empty");
+ }
+
+ @Override
+ public @NotNull RecipePropertyStorage copy() {
+ return this;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public @NotNull Set, Object>> entrySet() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public @Nullable T get(@NotNull RecipeProperty recipeProperty, @Nullable T defaultValue) {
+ return defaultValue;
+ }
+
+ @Override
+ public boolean contains(@NotNull RecipeProperty> recipeProperty) {
+ return false;
+ }
+
+ @Override
+ public @UnmodifiableView @NotNull Set<@NotNull RecipeProperty>> values() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public @NotNull NBTTagCompound serializeNBT() {
+ return new NBTTagCompound();
+ }
+
+ @Override
+ public void deserializeNBT(@NotNull NBTTagCompound nbt) {
+ if (!nbt.isEmpty()) {
+ GTLog.logger.warn("Tried to deserialize non-empty tag in RecipePropertyStorage.EMPTY: {}", nbt,
+ new Throwable());
+ }
+ }
+ };
+}
diff --git a/src/main/java/gregtech/api/recipes/properties/RecipePropertyStorageImpl.java b/src/main/java/gregtech/api/recipes/properties/RecipePropertyStorageImpl.java
new file mode 100644
index 00000000000..ffc7ea21227
--- /dev/null
+++ b/src/main/java/gregtech/api/recipes/properties/RecipePropertyStorageImpl.java
@@ -0,0 +1,111 @@
+package gregtech.api.recipes.properties;
+
+import gregtech.api.GregTechAPI;
+import gregtech.api.util.GTLog;
+
+import net.minecraft.nbt.NBTTagCompound;
+
+import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
+import org.jetbrains.annotations.Contract;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.UnmodifiableView;
+
+import java.util.Map;
+import java.util.Set;
+
+public final class RecipePropertyStorageImpl implements RecipePropertyStorage {
+
+ private final Map, Object> map;
+
+ public RecipePropertyStorageImpl() {
+ this(new Object2ObjectArrayMap<>(1));
+ }
+
+ private RecipePropertyStorageImpl(@NotNull Map, Object> map) {
+ this.map = map;
+ }
+
+ @Override
+ public boolean store(@NotNull RecipeProperty> recipeProperty, @NotNull Object value) {
+ String key = recipeProperty.getKey();
+ if (map.containsKey(recipeProperty)) {
+ GTLog.logger.warn("Duplicate recipe property added: {} -> {}", key, value, new Throwable());
+ return false;
+ }
+
+ try {
+ recipeProperty.castValue(value);
+ } catch (ClassCastException e) {
+ GTLog.logger.error("Provided incorrect value for RecipeProperty with key {}", key, e);
+ return false;
+ }
+
+ map.put(recipeProperty, value);
+ return true;
+ }
+
+ @Override
+ public @NotNull RecipePropertyStorage copy() {
+ return new RecipePropertyStorageImpl(new Object2ObjectArrayMap<>(this.map));
+ }
+
+ @Override
+ public int size() {
+ return map.size();
+ }
+
+ @Override
+ public @NotNull Set, Object>> entrySet() {
+ return this.map.entrySet();
+ }
+
+ @Override
+ @Contract("_, !null -> !null")
+ public @Nullable T get(@NotNull RecipeProperty recipeProperty, @Nullable T defaultValue) {
+ var value = map.get(recipeProperty);
+ if (value == null) {
+ return defaultValue;
+ }
+
+ return recipeProperty.castValue(value);
+ }
+
+ @Override
+ public boolean contains(@NotNull RecipeProperty> recipeProperty) {
+ return map.containsKey(recipeProperty);
+ }
+
+ @Override
+ @UnmodifiableView
+ public @NotNull Set<@NotNull RecipeProperty>> values() {
+ return map.keySet();
+ }
+
+ @Override
+ public @NotNull String toString() {
+ return "RecipePropertyStorage{" + map + '}';
+ }
+
+ @Override
+ public @NotNull NBTTagCompound serializeNBT() {
+ NBTTagCompound tag = new NBTTagCompound();
+ for (var entry : map.entrySet()) {
+ var property = entry.getKey();
+ tag.setTag(property.getKey(), property.serialize(entry.getValue()));
+ }
+ return tag;
+ }
+
+ @Override
+ public void deserializeNBT(@NotNull NBTTagCompound nbt) {
+ for (var entry : nbt.tagMap.entrySet()) {
+ var property = GregTechAPI.RECIPE_PROPERTIES.get(entry.getKey());
+ if (property == null) {
+ GTLog.logger.warn("Failed to read property with key {}", entry.getKey());
+ continue;
+ }
+ map.put(property, property.deserialize(entry.getValue()));
+ }
+ }
+}
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/CleanroomProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/CleanroomProperty.java
similarity index 63%
rename from src/main/java/gregtech/api/recipes/recipeproperties/CleanroomProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/CleanroomProperty.java
index e048ffa5626..5329b868c04 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/CleanroomProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/CleanroomProperty.java
@@ -1,15 +1,21 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+import gregtech.api.GregTechAPI;
import gregtech.api.metatileentity.multiblock.CleanroomType;
+import gregtech.api.recipes.properties.RecipeProperty;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagString;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.jetbrains.annotations.NotNull;
-public class CleanroomProperty extends RecipeProperty {
+import java.util.Objects;
+
+public final class CleanroomProperty extends RecipeProperty {
public static final String KEY = "cleanroom";
@@ -22,24 +28,27 @@ private CleanroomProperty() {
public static CleanroomProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new CleanroomProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
@Override
- @SideOnly(Side.CLIENT)
- public void drawInfo(@NotNull Minecraft minecraft, int x, int y, int color, Object value) {
- CleanroomType type = castValue(value);
- if (type == null) return;
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ return new NBTTagString(castValue(value).getName());
+ }
- minecraft.fontRenderer.drawString(I18n.format("gregtech.recipe.cleanroom", getName(type)), x, y, color);
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ return Objects.requireNonNull(CleanroomType.getByName(((NBTTagString) nbt).getString()));
}
@Override
- public int getInfoHeight(Object value) {
+ @SideOnly(Side.CLIENT)
+ public void drawInfo(@NotNull Minecraft minecraft, int x, int y, int color, Object value) {
CleanroomType type = castValue(value);
- if (type == null) return 0;
- return super.getInfoHeight(value);
+
+ minecraft.fontRenderer.drawString(I18n.format("gregtech.recipe.cleanroom", getName(type)), x, y, color);
}
@NotNull
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/ComputationProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/ComputationProperty.java
similarity index 53%
rename from src/main/java/gregtech/api/recipes/recipeproperties/ComputationProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/ComputationProperty.java
index 5f2de1b653b..f57a6ed2ea7 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/ComputationProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/ComputationProperty.java
@@ -1,27 +1,45 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+
+import gregtech.api.GregTechAPI;
+import gregtech.api.recipes.properties.RecipeProperty;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagInt;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
-public class ComputationProperty extends RecipeProperty {
+import org.jetbrains.annotations.NotNull;
+
+public final class ComputationProperty extends RecipeProperty {
public static final String KEY = "computation_per_tick";
private static ComputationProperty INSTANCE;
- protected ComputationProperty() {
+ private ComputationProperty() {
super(KEY, Integer.class);
}
public static ComputationProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new ComputationProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
+ @Override
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ return new NBTTagInt(castValue(value));
+ }
+
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ return ((NBTTagInt) nbt).getInt();
+ }
+
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value) {
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/DimensionProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/DimensionProperty.java
similarity index 63%
rename from src/main/java/gregtech/api/recipes/recipeproperties/DimensionProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/DimensionProperty.java
index 3795db18aa1..721300af5d4 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/DimensionProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/DimensionProperty.java
@@ -1,17 +1,22 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+import gregtech.api.GregTechAPI;
+import gregtech.api.recipes.properties.RecipeProperty;
import gregtech.api.worldgen.config.WorldGenRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
+import org.jetbrains.annotations.NotNull;
-public class DimensionProperty extends RecipeProperty {
+public final class DimensionProperty extends RecipeProperty {
public static final String KEY = "dimension";
@@ -22,11 +27,36 @@ private DimensionProperty() {
}
public static DimensionProperty getInstance() {
- if (INSTANCE == null)
+ if (INSTANCE == null) {
INSTANCE = new DimensionProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
+ }
return INSTANCE;
}
+ @Override
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ DimensionPropertyList list = castValue(value);
+ NBTTagCompound tag = new NBTTagCompound();
+ tag.setIntArray("whiteListDimensions", list.whiteListDimensions.toArray(new int[0]));
+ tag.setIntArray("blackListDimensions", list.blackListDimensions.toArray(new int[0]));
+ return tag;
+ }
+
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ NBTTagCompound tag = (NBTTagCompound) nbt;
+ DimensionPropertyList list = new DimensionPropertyList();
+ for (int i : tag.getIntArray("whiteListDimensions")) {
+ list.add(i, false);
+ }
+
+ for (int i : tag.getIntArray("blackListDimensions")) {
+ list.add(i, true);
+ }
+ return tag;
+ }
+
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value) {
@@ -62,8 +92,8 @@ public static class DimensionPropertyList {
public static DimensionPropertyList EMPTY_LIST = new DimensionPropertyList();
- public IntList whiteListDimensions = new IntArrayList();
- public IntList blackListDimensions = new IntArrayList();
+ public final IntList whiteListDimensions = new IntArrayList();
+ public final IntList blackListDimensions = new IntArrayList();
public void add(int key, boolean toBlacklist) {
if (toBlacklist) {
@@ -75,16 +105,13 @@ public void add(int key, boolean toBlacklist) {
}
}
- public void merge(DimensionPropertyList list) {
+ public void merge(@NotNull DimensionPropertyList list) {
this.whiteListDimensions.addAll(list.whiteListDimensions);
this.blackListDimensions.addAll(list.blackListDimensions);
}
public boolean checkDimension(int dim) {
- boolean valid = true;
- if (this.blackListDimensions.size() > 0) valid = !this.blackListDimensions.contains(dim);
- if (this.whiteListDimensions.size() > 0) valid = this.whiteListDimensions.contains(dim);
- return valid;
+ return !blackListDimensions.contains(dim) && whiteListDimensions.contains(dim);
}
}
}
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/FusionEUToStartProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/FusionEUToStartProperty.java
similarity index 74%
rename from src/main/java/gregtech/api/recipes/recipeproperties/FusionEUToStartProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/FusionEUToStartProperty.java
index 758480a4816..13446abe8d1 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/FusionEUToStartProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/FusionEUToStartProperty.java
@@ -1,19 +1,24 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+import gregtech.api.GregTechAPI;
+import gregtech.api.recipes.properties.RecipeProperty;
import gregtech.api.util.TextFormattingUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagLong;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
+import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.TreeMap;
-public class FusionEUToStartProperty extends RecipeProperty {
+public final class FusionEUToStartProperty extends RecipeProperty {
public static final String KEY = "eu_to_start";
@@ -21,18 +26,29 @@ public class FusionEUToStartProperty extends RecipeProperty {
private static FusionEUToStartProperty INSTANCE;
- protected FusionEUToStartProperty() {
+ private FusionEUToStartProperty() {
super(KEY, Long.class);
}
public static FusionEUToStartProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new FusionEUToStartProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
+ @Override
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ return new NBTTagLong(castValue(value));
+ }
+
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ return ((NBTTagLong) nbt).getLong();
+ }
+
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value) {
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/ImplosionExplosiveProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/ImplosionExplosiveProperty.java
similarity index 55%
rename from src/main/java/gregtech/api/recipes/recipeproperties/ImplosionExplosiveProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/ImplosionExplosiveProperty.java
index fd88401041b..915fc5aa4e3 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/ImplosionExplosiveProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/ImplosionExplosiveProperty.java
@@ -1,12 +1,19 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+
+import gregtech.api.GregTechAPI;
+import gregtech.api.recipes.properties.RecipeProperty;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
-public class ImplosionExplosiveProperty extends RecipeProperty {
+import org.jetbrains.annotations.NotNull;
+
+public final class ImplosionExplosiveProperty extends RecipeProperty {
public static final String KEY = "explosives";
@@ -19,16 +26,27 @@ private ImplosionExplosiveProperty() {
public static ImplosionExplosiveProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new ImplosionExplosiveProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
+ @Override
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ return castValue(value).serializeNBT();
+ }
+
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ return new ItemStack((NBTTagCompound) nbt);
+ }
+
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value) {
minecraft.fontRenderer.drawString(I18n.format("gregtech.recipe.explosive",
- ((ItemStack) value).getDisplayName()), x, y, color);
+ castValue(value).getDisplayName()), x, y, color);
}
@Override
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/PrimitiveProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/PrimitiveProperty.java
similarity index 55%
rename from src/main/java/gregtech/api/recipes/recipeproperties/PrimitiveProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/PrimitiveProperty.java
index 908127d3573..22b49f00bb8 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/PrimitiveProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/PrimitiveProperty.java
@@ -1,13 +1,20 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+
+import gregtech.api.GregTechAPI;
+import gregtech.api.recipes.properties.RecipeProperty;
import net.minecraft.client.Minecraft;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagByte;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
+import org.jetbrains.annotations.NotNull;
+
/**
* Simple Marker Property to tell JEI to not display Total EU and EU/t.
*/
-public class PrimitiveProperty extends RecipeProperty {
+public final class PrimitiveProperty extends RecipeProperty {
public static final String KEY = "primitive_property";
private static PrimitiveProperty INSTANCE;
@@ -19,16 +26,27 @@ private PrimitiveProperty() {
public static PrimitiveProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new PrimitiveProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
+ @Override
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ return new NBTTagByte((byte) (castValue(value) ? 1 : 0));
+ }
+
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ return ((NBTTagByte) nbt).getByte() == 1;
+ }
+
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value) {}
@Override
- public int getInfoHeight(Object value) {
+ public int getInfoHeight(@NotNull Object value) {
return 0;
}
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/ResearchProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/ResearchProperty.java
similarity index 50%
rename from src/main/java/gregtech/api/recipes/recipeproperties/ResearchProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/ResearchProperty.java
index ec4d6ab105e..15b538fa5d6 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/ResearchProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/ResearchProperty.java
@@ -1,7 +1,12 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+
+import gregtech.api.GregTechAPI;
+import gregtech.api.recipes.properties.RecipeProperty;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@@ -21,10 +26,31 @@ private ResearchProperty() {
public static ResearchProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new ResearchProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
+ @Override
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ NBTTagList list = new NBTTagList();
+ for (var entry : castValue(value)) {
+ list.appendTag(entry.serializeNBT());
+ }
+ return list;
+ }
+
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ NBTTagList list = (NBTTagList) nbt;
+ ResearchPropertyData data = new ResearchPropertyData();
+ for (int i = 0; i < list.tagCount(); i++) {
+ data.add(ResearchPropertyData.ResearchEntry.deserializeFromNBT(list.getCompoundTagAt(i)));
+ }
+
+ return data;
+ }
+
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(@NotNull Minecraft minecraft, int x, int y, int color, Object value) {
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/ResearchPropertyData.java b/src/main/java/gregtech/api/recipes/properties/impl/ResearchPropertyData.java
similarity index 66%
rename from src/main/java/gregtech/api/recipes/recipeproperties/ResearchPropertyData.java
rename to src/main/java/gregtech/api/recipes/properties/impl/ResearchPropertyData.java
index 4b199221d6c..95a5159aac0 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/ResearchPropertyData.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/ResearchPropertyData.java
@@ -1,6 +1,7 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
import org.jetbrains.annotations.NotNull;
@@ -12,8 +13,6 @@ public final class ResearchPropertyData implements Iterable entries = new ArrayList<>();
- public ResearchPropertyData() {}
-
/**
* @param entry the entry to add
*/
@@ -46,14 +45,23 @@ public ResearchEntry(@NotNull String researchId, @NotNull ItemStack dataItem) {
this.dataItem = dataItem;
}
- @NotNull
- public String getResearchId() {
+ public @NotNull String researchId() {
return researchId;
}
- @NotNull
- public ItemStack getDataItem() {
+ public @NotNull ItemStack dataItem() {
return dataItem;
}
+
+ public @NotNull NBTTagCompound serializeNBT() {
+ NBTTagCompound tag = new NBTTagCompound();
+ tag.setString("researchId", researchId);
+ tag.setTag("dataItem", dataItem.serializeNBT());
+ return tag;
+ }
+
+ public static @NotNull ResearchEntry deserializeFromNBT(@NotNull NBTTagCompound tag) {
+ return new ResearchEntry(tag.getString("researchId"), new ItemStack(tag.getCompoundTag("dataItem")));
+ }
}
}
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/ScanProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/ScanProperty.java
similarity index 56%
rename from src/main/java/gregtech/api/recipes/recipeproperties/ScanProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/ScanProperty.java
index 8018561a710..4e80ca61c20 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/ScanProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/ScanProperty.java
@@ -1,13 +1,18 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+
+import gregtech.api.GregTechAPI;
+import gregtech.api.recipes.properties.RecipeProperty;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagByte;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.jetbrains.annotations.NotNull;
-public class ScanProperty extends RecipeProperty {
+public final class ScanProperty extends RecipeProperty {
public static final String KEY = "scan";
@@ -21,10 +26,21 @@ private ScanProperty() {
public static ScanProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new ScanProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
+ @Override
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ return new NBTTagByte((byte) (castValue(value) ? 1 : 0));
+ }
+
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ return ((NBTTagByte) nbt).getByte() == 1;
+ }
+
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value) {
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/TemperatureProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/TemperatureProperty.java
similarity index 79%
rename from src/main/java/gregtech/api/recipes/recipeproperties/TemperatureProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/TemperatureProperty.java
index c9c1681d9ae..3764158baed 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/TemperatureProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/TemperatureProperty.java
@@ -1,9 +1,13 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+import gregtech.api.GregTechAPI;
+import gregtech.api.recipes.properties.RecipeProperty;
import gregtech.api.unification.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagInt;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@@ -13,7 +17,7 @@
import java.util.Map;
import java.util.TreeMap;
-public class TemperatureProperty extends RecipeProperty {
+public final class TemperatureProperty extends RecipeProperty {
public static final String KEY = "temperature";
@@ -28,10 +32,21 @@ private TemperatureProperty() {
public static TemperatureProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new TemperatureProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
+ @Override
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ return new NBTTagInt(castValue(value));
+ }
+
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ return ((NBTTagInt) nbt).getInt();
+ }
+
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value) {
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/TotalComputationProperty.java b/src/main/java/gregtech/api/recipes/properties/impl/TotalComputationProperty.java
similarity index 56%
rename from src/main/java/gregtech/api/recipes/recipeproperties/TotalComputationProperty.java
rename to src/main/java/gregtech/api/recipes/properties/impl/TotalComputationProperty.java
index a6247be32c4..0704e44cb46 100644
--- a/src/main/java/gregtech/api/recipes/recipeproperties/TotalComputationProperty.java
+++ b/src/main/java/gregtech/api/recipes/properties/impl/TotalComputationProperty.java
@@ -1,27 +1,45 @@
-package gregtech.api.recipes.recipeproperties;
+package gregtech.api.recipes.properties.impl;
+
+import gregtech.api.GregTechAPI;
+import gregtech.api.recipes.properties.RecipeProperty;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagInt;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
-public class TotalComputationProperty extends RecipeProperty {
+import org.jetbrains.annotations.NotNull;
+
+public final class TotalComputationProperty extends RecipeProperty {
public static final String KEY = "total_computation";
private static TotalComputationProperty INSTANCE;
- protected TotalComputationProperty() {
+ private TotalComputationProperty() {
super(KEY, Integer.class);
}
public static TotalComputationProperty getInstance() {
if (INSTANCE == null) {
INSTANCE = new TotalComputationProperty();
+ GregTechAPI.RECIPE_PROPERTIES.register(KEY, INSTANCE);
}
return INSTANCE;
}
+ @Override
+ public @NotNull NBTBase serialize(@NotNull Object value) {
+ return new NBTTagInt(castValue(value));
+ }
+
+ @Override
+ public @NotNull Object deserialize(@NotNull NBTBase nbt) {
+ return ((NBTTagInt) nbt).getInt();
+ }
+
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value) {
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/DefaultProperty.java b/src/main/java/gregtech/api/recipes/recipeproperties/DefaultProperty.java
deleted file mode 100644
index 1579297b2cd..00000000000
--- a/src/main/java/gregtech/api/recipes/recipeproperties/DefaultProperty.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package gregtech.api.recipes.recipeproperties;
-
-import net.minecraft.client.Minecraft;
-import net.minecraft.client.resources.I18n;
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-public class DefaultProperty extends RecipeProperty {
-
- public DefaultProperty(String key, Class type) {
- super(key, type);
- }
-
- @SideOnly(Side.CLIENT)
- public void drawInfo(Minecraft minecraft, int x, int y, int color, Object value) {
- minecraft.fontRenderer.drawString(I18n.format("gregtech.recipe." + getKey(),
- castValue(value)), x, y, color);
- }
-}
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/EmptyRecipePropertyStorage.java b/src/main/java/gregtech/api/recipes/recipeproperties/EmptyRecipePropertyStorage.java
deleted file mode 100644
index 89f6bb201d6..00000000000
--- a/src/main/java/gregtech/api/recipes/recipeproperties/EmptyRecipePropertyStorage.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package gregtech.api.recipes.recipeproperties;
-
-import java.util.Collections;
-import java.util.Map;
-import java.util.Set;
-
-public final class EmptyRecipePropertyStorage implements IRecipePropertyStorage {
-
- public static final EmptyRecipePropertyStorage INSTANCE = new EmptyRecipePropertyStorage();
-
- private EmptyRecipePropertyStorage() {}
-
- @Override
- public boolean store(RecipeProperty> recipeProperty, Object value) {
- return false;
- }
-
- @Override
- public boolean remove(RecipeProperty> recipeProperty) {
- return false;
- }
-
- @Override
- public void freeze(boolean frozen) {}
-
- @Override
- public IRecipePropertyStorage copy() {
- return null; // Fresh for RecipeBuilder to handle
- }
-
- @Override
- public int getSize() {
- return 0;
- }
-
- @Override
- public Set, Object>> getRecipeProperties() {
- return Collections.emptySet();
- }
-
- @Override
- public T getRecipePropertyValue(RecipeProperty recipeProperty, T defaultValue) {
- return defaultValue;
- }
-
- @Override
- public boolean hasRecipeProperty(RecipeProperty> recipeProperty) {
- return false;
- }
-
- @Override
- public Set getRecipePropertyKeys() {
- return Collections.emptySet();
- }
-
- @Override
- public Set> getPropertyTypes() {
- return Collections.emptySet();
- }
-
- @Override
- public Object getRawRecipePropertyValue(String key) {
- return null;
- }
-}
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/IRecipePropertyStorage.java b/src/main/java/gregtech/api/recipes/recipeproperties/IRecipePropertyStorage.java
deleted file mode 100644
index 9781e2484ce..00000000000
--- a/src/main/java/gregtech/api/recipes/recipeproperties/IRecipePropertyStorage.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package gregtech.api.recipes.recipeproperties;
-
-import java.util.Map;
-import java.util.Set;
-
-public interface IRecipePropertyStorage {
-
- /**
- * Stores new {@link RecipeProperty} with value
- *
- * @param recipeProperty {@link RecipeProperty}
- * @param value value
- * @return {@code true} if store succeeds; otherwise {@code false}
- */
- boolean store(RecipeProperty> recipeProperty, Object value);
-
- boolean remove(RecipeProperty> recipeProperty);
-
- void freeze(boolean frozen);
-
- IRecipePropertyStorage copy();
-
- /**
- * Provides information how many {@link RecipeProperty} are stored
- *
- * @return number of stored {@link RecipeProperty}
- */
- int getSize();
-
- /**
- * Provides all stored {@link RecipeProperty}
- *
- * @return all stored {@link RecipeProperty} and values
- */
- Set, Object>> getRecipeProperties();
-
- /**
- * Provides casted value for one specific {@link RecipeProperty} if is stored or defaultValue
- *
- * @param recipeProperty {@link RecipeProperty}
- * @param defaultValue Default value if recipeProperty is not found
- * @param Type of returned value
- * @return value tied with provided recipeProperty on success; otherwise defaultValue
- */
- T getRecipePropertyValue(RecipeProperty recipeProperty, T defaultValue);
-
- boolean hasRecipeProperty(RecipeProperty> recipeProperty);
-
- Set getRecipePropertyKeys();
-
- Set> getPropertyTypes();
-
- /**
- * Provides un-casted value for one specific {@link RecipeProperty} searched by key
- *
- * @param key Key of stored {@link RecipeProperty}
- * @return {@link Object} value on success; otherwise {@code null}
- */
- Object getRawRecipePropertyValue(String key);
-}
diff --git a/src/main/java/gregtech/api/recipes/recipeproperties/RecipePropertyStorage.java b/src/main/java/gregtech/api/recipes/recipeproperties/RecipePropertyStorage.java
deleted file mode 100644
index cf38c40ef3e..00000000000
--- a/src/main/java/gregtech/api/recipes/recipeproperties/RecipePropertyStorage.java
+++ /dev/null
@@ -1,134 +0,0 @@
-package gregtech.api.recipes.recipeproperties;
-
-import gregtech.api.util.GTLog;
-
-import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
-
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-public class RecipePropertyStorage implements IRecipePropertyStorage {
-
- private final Map, Object> recipeProperties;
-
- private boolean frozen = false;
-
- public RecipePropertyStorage() {
- recipeProperties = new Object2ObjectArrayMap<>(1);
- }
-
- private RecipePropertyStorage(Map, Object> recipeProperties) {
- this();
- this.recipeProperties.putAll(recipeProperties);
- }
-
- @Override
- public boolean store(RecipeProperty> recipeProperty, Object value) {
- boolean success = true;
- String key = recipeProperty.getKey();
- if (frozen) {
- GTLog.logger.warn("Unable to add RecipeProperty with key {} as the storage is frozen", key);
- success = false;
- }
- for (RecipeProperty> existingRecipeProperty : recipeProperties.keySet()) {
- if (existingRecipeProperty.getKey().equals(key)) {
- GTLog.logger.warn("Unable to add RecipeProperty with key {} as it already exists", key);
- success = false;
- }
- }
-
- if (value == null) {
- GTLog.logger.warn("Provided value is null for RecipeProperty with key {}", key);
- success = false;
- }
-
- try {
- recipeProperty.castValue(value);
- } catch (ClassCastException e) {
- GTLog.logger.warn("Provided incorrect value for RecipeProperty with key {}", key, e);
- success = false;
- }
-
- if (success) {
- recipeProperties.put(recipeProperty, value);
- } else {
- GTLog.logger.warn("RecipePropertyStorage error found", new Throwable());
- }
-
- return success;
- }
-
- @Override
- public boolean remove(RecipeProperty> recipeProperty) {
- return this.recipeProperties.remove(recipeProperty) != null;
- }
-
- @Override
- public void freeze(boolean frozen) {
- this.frozen = frozen;
- }
-
- @Override
- public IRecipePropertyStorage copy() {
- return new RecipePropertyStorage(this.recipeProperties);
- }
-
- @Override
- public int getSize() {
- return recipeProperties.size();
- }
-
- @Override
- public Set, Object>> getRecipeProperties() {
- return this.recipeProperties.entrySet();
- }
-
- @Override
- public T getRecipePropertyValue(RecipeProperty recipeProperty, T defaultValue) {
- Object value = recipeProperties.get(recipeProperty);
-
- if (value == null) {
- return defaultValue;
- }
-
- return recipeProperty.castValue(value);
- }
-
- public boolean hasRecipeProperty(RecipeProperty> recipeProperty) {
- return recipeProperties.containsKey(recipeProperty);
- }
-
- @Override
- public Set getRecipePropertyKeys() {
- HashSet keys = new HashSet<>();
-
- recipeProperties.keySet().forEach(recipeProperty -> keys.add(recipeProperty.getKey()));
-
- return keys;
- }
-
- @Override
- public Set> getPropertyTypes() {
- return recipeProperties.keySet();
- }
-
- @Override
- public Object getRawRecipePropertyValue(String key) {
- RecipeProperty> recipeProperty = getRecipePropertyValue(key);
- if (recipeProperty != null) {
- return recipeProperties.get(recipeProperty);
- }
-
- return null;
- }
-
- private RecipeProperty> getRecipePropertyValue(String key) {
- for (RecipeProperty> recipeProperty : recipeProperties.keySet()) {
- if (recipeProperty.getKey().equals(key))
- return recipeProperty;
- }
-
- return null;
- }
-}
diff --git a/src/main/java/gregtech/api/recipes/ui/RecipeMapUI.java b/src/main/java/gregtech/api/recipes/ui/RecipeMapUI.java
index a85fd546cae..a6d66d3e62e 100644
--- a/src/main/java/gregtech/api/recipes/ui/RecipeMapUI.java
+++ b/src/main/java/gregtech/api/recipes/ui/RecipeMapUI.java
@@ -283,8 +283,10 @@ public int getPropertyHeightShift() {
int maxPropertyCount = 0;
if (shouldShiftWidgets()) {
for (Recipe recipe : recipeMap.getRecipeList()) {
- if (recipe.getPropertyCount() > maxPropertyCount)
- maxPropertyCount = recipe.getPropertyCount();
+ int count = recipe.propertyStorage().size();
+ if (count > maxPropertyCount) {
+ maxPropertyCount = count;
+ }
}
}
return maxPropertyCount * 10; // GTRecipeWrapper#LINE_HEIGHT
diff --git a/src/main/java/gregtech/api/terminal/TerminalRegistry.java b/src/main/java/gregtech/api/terminal/TerminalRegistry.java
deleted file mode 100644
index e842eb0c7a9..00000000000
--- a/src/main/java/gregtech/api/terminal/TerminalRegistry.java
+++ /dev/null
@@ -1,347 +0,0 @@
-package gregtech.api.terminal;
-
-import gregtech.api.GTValues;
-import gregtech.api.terminal.app.AbstractApplication;
-import gregtech.api.terminal.hardware.Hardware;
-import gregtech.api.util.FileUtility;
-import gregtech.api.util.GTLog;
-import gregtech.api.util.Mods;
-import gregtech.common.ConfigHolder;
-import gregtech.common.items.MetaItems;
-import gregtech.common.terminal.app.VirtualTankApp;
-import gregtech.common.terminal.app.appstore.AppStoreApp;
-import gregtech.common.terminal.app.batterymanager.BatteryManagerApp;
-import gregtech.common.terminal.app.capeselector.CapeSelectorApp;
-import gregtech.common.terminal.app.console.ConsoleApp;
-import gregtech.common.terminal.app.game.maze.MazeApp;
-import gregtech.common.terminal.app.game.minesweeper.MinesweeperApp;
-import gregtech.common.terminal.app.game.pong.PongApp;
-import gregtech.common.terminal.app.guide.ItemGuideApp;
-import gregtech.common.terminal.app.guide.MultiBlockGuideApp;
-import gregtech.common.terminal.app.guide.SimpleMachineGuideApp;
-import gregtech.common.terminal.app.guide.TutorialGuideApp;
-import gregtech.common.terminal.app.guideeditor.GuideEditorApp;
-import gregtech.common.terminal.app.hardwaremanager.HardwareManagerApp;
-import gregtech.common.terminal.app.multiblockhelper.MultiBlockPreviewARApp;
-import gregtech.common.terminal.app.prospector.ProspectorApp;
-import gregtech.common.terminal.app.prospector.ProspectorMode;
-import gregtech.common.terminal.app.recipechart.RecipeChartApp;
-import gregtech.common.terminal.app.settings.SettingsApp;
-import gregtech.common.terminal.app.teleport.TeleportApp;
-import gregtech.common.terminal.app.worldprospector.WorldProspectorARApp;
-import gregtech.common.terminal.hardware.BatteryHardware;
-import gregtech.common.terminal.hardware.DeviceHardware;
-
-import net.minecraft.client.Minecraft;
-import net.minecraft.client.resources.IResourceManager;
-import net.minecraft.client.resources.SimpleReloadableResourceManager;
-import net.minecraft.init.Items;
-import net.minecraft.item.ItemStack;
-import net.minecraftforge.fml.common.FMLCommonHandler;
-import net.minecraftforge.fml.common.Loader;
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-import org.jetbrains.annotations.NotNull;
-
-import java.io.File;
-import java.util.*;
-import java.util.stream.Collectors;
-
-public class TerminalRegistry {
-
- public static final Map APP_REGISTER = new LinkedHashMap<>();
- public static final Map HW_REGISTER = new LinkedHashMap<>();
- public static final Map[]> APP_HW_DEMAND = new HashMap<>();
- public static final Map[]> APP_UPGRADE_CONDITIONS = new HashMap<>();
- public static final List DEFAULT_APPS = new ArrayList<>();
- @SideOnly(Side.CLIENT)
- public static File TERMINAL_PATH;
-
- static {
- if (FMLCommonHandler.instance().getSide().isClient()) {
- TERMINAL_PATH = new File(Loader.instance().getConfigDir(), ConfigHolder.client.terminalRootPath);
- }
- }
-
- public static void init() {
- // register hardware
- registerHardware(new BatteryHardware());
- int deviceSize = DeviceHardware.DEVICE.values().length;
- for (int i = 1; i < deviceSize; i++) {
- registerHardware(new DeviceHardware(i));
- }
- // register applications
- AppRegistryBuilder.create(new SimpleMachineGuideApp()).defaultApp().build();
- AppRegistryBuilder.create(new MultiBlockGuideApp()).defaultApp().build();
- AppRegistryBuilder.create(new ItemGuideApp()).defaultApp().build();
- AppRegistryBuilder.create(new TutorialGuideApp()).defaultApp().build();
- AppRegistryBuilder.create(new GuideEditorApp()).defaultApp().build();
- AppRegistryBuilder.create(new SettingsApp()).defaultApp().build();
- AppRegistryBuilder.create(new CapeSelectorApp()).defaultApp().build();
-
- AppRegistryBuilder.create(new TeleportApp())
- .battery(GTValues.ZPM, 10000)
- .device(DeviceHardware.DEVICE.FIELD_GENERATOR_UV)
- .build();
-
- AppRegistryBuilder.create(new PongApp())
- .battery(GTValues.LV, 75)
- .build();
- AppRegistryBuilder.create(new MazeApp())
- .battery(GTValues.LV, 150)
- .build();
- AppRegistryBuilder.create(new MinesweeperApp())
- .battery(GTValues.LV, 150)
- .build();
-
- AppRegistryBuilder.create(new ProspectorApp(ProspectorMode.ORE))
- .battery(0, GTValues.LV, 640)
- .battery(1, GTValues.LV, 640)
- .battery(2, GTValues.MV, 1000)
- .battery(3, GTValues.HV, 1500)
- .battery(4, GTValues.HV, 1500)
- .upgrade(0, MetaItems.SENSOR_LV.getStackForm(1))
- .upgrade(1, MetaItems.SENSOR_HV.getStackForm(1))
- .upgrade(2, MetaItems.SENSOR_EV.getStackForm(1))
- .upgrade(3, MetaItems.SENSOR_IV.getStackForm(1))
- .upgrade(4, MetaItems.SENSOR_LuV.getStackForm(1))
- .device(0, DeviceHardware.DEVICE.PROSPECTOR_LV)
- .device(1, DeviceHardware.DEVICE.PROSPECTOR_LV)
- .device(2, DeviceHardware.DEVICE.PROSPECTOR_LV)
- .device(3, DeviceHardware.DEVICE.PROSPECTOR_HV)
- .device(4, DeviceHardware.DEVICE.PROSPECTOR_HV)
- .build();
-
- AppRegistryBuilder.create(new ProspectorApp(ProspectorMode.FLUID))
- .battery(0, GTValues.MV, 1000)
- .battery(1, GTValues.MV, 1000)
- .battery(2, GTValues.HV, 1500)
- .battery(3, GTValues.HV, 1500)
- .battery(4, GTValues.HV, 1500)
- .upgrade(0, MetaItems.SENSOR_HV.getStackForm(1))
- .upgrade(1, MetaItems.SENSOR_HV.getStackForm(3))
- .upgrade(2, MetaItems.SENSOR_EV.getStackForm(1))
- .upgrade(3, MetaItems.SENSOR_IV.getStackForm(1))
- .upgrade(4, MetaItems.SENSOR_LuV.getStackForm(1))
- .device(DeviceHardware.DEVICE.PROSPECTOR_HV)
- .build();
- AppRegistryBuilder.create(new MultiBlockPreviewARApp())
- .battery(GTValues.LV, 128)
- .device(DeviceHardware.DEVICE.CAMERA)
- .upgrade(1, MetaItems.EMITTER_HV.getStackForm(4), MetaItems.WORKSTATION_EV.getStackForm(2))
- .defaultApp()
- .build();
- if (Mods.JustEnoughItems.isModLoaded()) {
- AppRegistryBuilder.create(new RecipeChartApp())
- .battery(GTValues.LV, 160)
- .upgrade(0, new ItemStack(Items.PAPER, 32))
- .upgrade(1, new ItemStack(Items.PAPER, 64))
- .upgrade(2, MetaItems.RANDOM_ACCESS_MEMORY.getStackForm(16))
- .upgrade(3, MetaItems.RANDOM_ACCESS_MEMORY.getStackForm(32))
- .build();
- }
- AppRegistryBuilder.create(new ConsoleApp())
- .battery(GTValues.LV, 500)
- .device(DeviceHardware.DEVICE.WIRELESS)
- .build();
- AppRegistryBuilder.create(new BatteryManagerApp()).defaultApp()
- .battery(GTValues.ULV, 0)
- .build();
- AppRegistryBuilder.create(new HardwareManagerApp()).defaultApp().build();
- AppRegistryBuilder.create(new AppStoreApp()).defaultApp().build();
- AppRegistryBuilder.create(new WorldProspectorARApp())
- .battery(GTValues.LV, 320)
- .upgrade(0, MetaItems.EMITTER_LV.getStackForm(2))
- .upgrade(1, MetaItems.EMITTER_MV.getStackForm(2))
- .upgrade(2, MetaItems.EMITTER_HV.getStackForm(2))
- .device(DeviceHardware.DEVICE.CAMERA)
- .build();
- AppRegistryBuilder.create(new VirtualTankApp())
- .battery(GTValues.MV, 500)
- .device(DeviceHardware.DEVICE.WIRELESS)
- .build();
- }
-
- @SideOnly(Side.CLIENT)
- public static void initTerminalFiles() {
- ((SimpleReloadableResourceManager) Minecraft.getMinecraft().getResourceManager())
- .registerReloadListener(TerminalRegistry::onResourceManagerReload);
- }
-
- @SideOnly(Side.CLIENT)
- public static void onResourceManagerReload(IResourceManager resourceManager) {
- FileUtility.extractJarFiles(String.format("/assets/%s/%s", GTValues.MODID, "terminal"), TERMINAL_PATH, false);
- }
-
- public static void registerApp(AbstractApplication application) {
- String name = application.getRegistryName();
- if (APP_REGISTER.containsKey(name)) {
- GTLog.logger.warn("Duplicate APP registry names exist: {}", name);
- return;
- }
- APP_REGISTER.put(name, application);
- }
-
- public static void registerHardware(Hardware hardware) {
- String name = hardware.getRegistryName();
- if (APP_REGISTER.containsKey(name)) {
- GTLog.logger.warn("Duplicate APP registry names exist: {}", name);
- return;
- }
- HW_REGISTER.put(name, hardware);
- }
-
- public static void registerHardwareDemand(String name, boolean isDefaultApp, @NotNull List[] hardware,
- @NotNull List[] upgrade) {
- if (name != null && APP_REGISTER.containsKey(name)) {
- if (isDefaultApp) {
- DEFAULT_APPS.add(name);
- }
- APP_HW_DEMAND.put(name, hardware);
- APP_UPGRADE_CONDITIONS.put(name, upgrade);
- } else {
- GTLog.logger.error("Not found the app {}", name);
- }
- }
-
- public static List getDefaultApps() {
- return DEFAULT_APPS.stream().map(APP_REGISTER::get).collect(Collectors.toList());
- }
-
- public static Collection getAllApps() {
- return APP_REGISTER.values();
- }
-
- public static AbstractApplication getApplication(String name) {
- return APP_REGISTER.get(name);
- }
-
- public static Collection getAllHardware() {
- return HW_REGISTER.values();
- }
-
- public static Hardware getHardware(String name) {
- return HW_REGISTER.get(name);
- }
-
- public static List getAppHardwareDemand(String name, int tier) {
- return APP_HW_DEMAND.get(name)[tier] != null ? APP_HW_DEMAND.get(name)[tier] : Collections.emptyList();
- }
-
- public static List getAppHardwareUpgradeConditions(String name, int tier) {
- return APP_UPGRADE_CONDITIONS.get(name)[tier] != null ? APP_UPGRADE_CONDITIONS.get(name)[tier] :
- Collections.emptyList();
- }
-
- private static class AppRegistryBuilder {
-
- AbstractApplication app;
- boolean isDefaultApp;
- BatteryHardware[] battery;
- List[] hardware;
- List[] upgrade;
-
- public static AppRegistryBuilder create(AbstractApplication app) {
- AppRegistryBuilder builder = new AppRegistryBuilder();
- builder.app = app;
- builder.battery = new BatteryHardware[app.getMaxTier() + 1];
- builder.hardware = new List[app.getMaxTier() + 1];
- builder.upgrade = new List[app.getMaxTier() + 1];
- return builder;
- }
-
- public AppRegistryBuilder defaultApp() {
- this.isDefaultApp = true;
- return this;
- }
-
- public AppRegistryBuilder battery(int batteryTier, long cost) {
- BatteryHardware hw = new BatteryHardware.BatteryDemand(batteryTier, cost);
- for (int i = 0; i <= app.getMaxTier(); i++) {
- battery[i] = hw;
- }
- return this;
- }
-
- public AppRegistryBuilder battery(int tier, int batteryTier, long cost) {
- if (tier < battery.length) {
- battery[tier] = new BatteryHardware.BatteryDemand(batteryTier, cost);
- }
- return this;
- }
-
- public AppRegistryBuilder device(DeviceHardware.DEVICE... device) {
- Hardware[] hw = Arrays.stream(device).map(DeviceHardware.DeviceDemand::new).toArray(Hardware[]::new);
- for (int i = 0; i <= app.getMaxTier(); i++) {
- this.hardware(i, hw);
- }
- return this;
- }
-
- public AppRegistryBuilder device(int tier, DeviceHardware.DEVICE... device) {
- this.hardware(tier, Arrays.stream(device).map(DeviceHardware.DeviceDemand::new).toArray(Hardware[]::new));
- return this;
- }
-
- public AppRegistryBuilder hardware(Hardware... hardware) {
- for (int i = 0; i <= app.getMaxTier(); i++) {
- this.hardware(i, hardware);
- }
- return this;
- }
-
- public AppRegistryBuilder hardware(int tier, Hardware... hardware) {
- if (tier < this.hardware.length) {
- this.hardware[tier] = new LinkedList<>();
- for (Hardware hw : hardware) {
- this.hardware[tier].add(hw);
- }
- }
- return this;
- }
-
- public AppRegistryBuilder appendHardware(int tier, Hardware... hardware) {
- if (tier < this.hardware.length) {
- if (this.hardware[tier] == null) {
- this.hardware[tier] = new LinkedList<>();
- }
- for (Hardware hw : hardware) {
- this.hardware[tier].add(hw);
- }
- }
- return this;
- }
-
- public AppRegistryBuilder upgrade(ItemStack... upgrade) {
- ItemStack[] up = Arrays.stream(upgrade).toArray(ItemStack[]::new);
- for (int i = 0; i <= app.getMaxTier(); i++) {
- this.upgrade(i, up);
- }
- return this;
- }
-
- public AppRegistryBuilder upgrade(int tier, ItemStack... upgrade) {
- if (tier < this.upgrade.length) {
- this.upgrade[tier] = new LinkedList<>();
- for (ItemStack up : upgrade) {
- this.upgrade[tier].add(up);
- }
- }
- return this;
- }
-
- public void build() {
- TerminalRegistry.registerApp(app);
- for (int i = 0; i < hardware.length; i++) {
- if (battery[i] != null) {
- if (hardware[i] == null) {
- hardware[i] = new LinkedList<>();
- }
- hardware[i].add(battery[i]);
- }
- }
- TerminalRegistry.registerHardwareDemand(app.getRegistryName(), isDefaultApp, hardware, upgrade);
- }
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/app/ARApplication.java b/src/main/java/gregtech/api/terminal/app/ARApplication.java
deleted file mode 100644
index c5bd9a4e564..00000000000
--- a/src/main/java/gregtech/api/terminal/app/ARApplication.java
+++ /dev/null
@@ -1,104 +0,0 @@
-package gregtech.api.terminal.app;
-
-import gregtech.api.terminal.os.SystemCall;
-import gregtech.common.items.behaviors.TerminalBehaviour;
-
-import net.minecraft.entity.player.EntityPlayer;
-import net.minecraft.item.ItemStack;
-import net.minecraftforge.client.event.RenderWorldLastEvent;
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-/**
- * Created with IntelliJ IDEA.
- *
- * @Author: KilaBash
- * @Date: 2021/09/13
- * @Description: Application for AR.
- * When AR is running, {@link #tickAR(EntityPlayer)} and {@link #drawARScreen(RenderWorldLastEvent)} will
- * be called when you hold the terminal in one of your hands.
- * Therefore, at most one AR app is active on the terminal at any one time. And when you open the terminal
- * GUI it automatically closes the currently running AR.
- * You have access to the app's NBT of the handheld terminal when the AR is active, to load configs, init
- * and so on.
- * Don't try to write NBT, you should always be aware that the AR is running on the client side.
- * if you really want to do something on the server side when AR is running, plz send packets. Because
- * it's always running on the client side!!!!!!!!!!
- * (If you need data from NBT, dont forget to write nbt when closeApp {@link #closeApp()})
- */
-public abstract class ARApplication extends AbstractApplication {
-
- protected ItemStack heldStack;
-
- public ARApplication(String name) {
- super(name);
- }
-
- @Override
- public int getAppTier() {
- if (nbt != null) {
- if (os != null) {
- return super.getAppTier();
- } else if (TerminalBehaviour.isCreative(heldStack)) {
- return getMaxTier();
- }
- return Math.min(nbt.getInteger("_tier"), getMaxTier());
- }
- return 0;
- }
-
- @SideOnly(Side.CLIENT)
- public final void setAROpened(ItemStack heldStack) {
- this.heldStack = heldStack;
- this.nbt = heldStack.getOrCreateSubCompound("terminal").getCompoundTag(getRegistryName());
- }
-
- @Override
- public AbstractApplication initApp() {
- openAR();
- return this;
- }
-
- /**
- * open Camera for this AR and shutdown.
- * then, this AR will be in active and running on the client side.
- * It is best to call it on both sides.
- */
- protected final void openAR() {
- os.tabletNBT.setString("_ar", getRegistryName());
- if (isClient) {
- SystemCall.SHUT_DOWN.call(getOs(), true);
- }
- }
-
- /**
- * this will be fired every time you first switch selected slot to the held terminal.
- */
- @SideOnly(Side.CLIENT)
- public void onAROpened() {}
-
- /**
- * this will be fired when switch the current slot (terminal) to other slots or open this terminal.
- */
- @SideOnly(Side.CLIENT)
- public void onARClosed() {
- nbt = null;
- heldStack = null;
- }
-
- /**
- * Be careful! do not try to use non-static field or call a non-static function here.
- * This method is called with the registered instance.
- * {@link gregtech.api.terminal.TerminalRegistry#registerApp(AbstractApplication)}
- */
- @SideOnly(Side.CLIENT)
- public void tickAR(EntityPlayer player) {}
-
- /**
- * Be careful! do not try to use non-static field or call a non-static function here.
- * This method is called with the registered instance.
- * {@link gregtech.api.terminal.TerminalRegistry#registerApp(AbstractApplication)}
- */
- @SideOnly(Side.CLIENT)
- public abstract void drawARScreen(RenderWorldLastEvent event);
-}
diff --git a/src/main/java/gregtech/api/terminal/app/AbstractApplication.java b/src/main/java/gregtech/api/terminal/app/AbstractApplication.java
deleted file mode 100644
index 30f5878f829..00000000000
--- a/src/main/java/gregtech/api/terminal/app/AbstractApplication.java
+++ /dev/null
@@ -1,268 +0,0 @@
-package gregtech.api.terminal.app;
-
-import gregtech.api.gui.INativeWidget;
-import gregtech.api.gui.resources.IGuiTexture;
-import gregtech.api.gui.resources.ResourceHelper;
-import gregtech.api.gui.resources.TextureArea;
-import gregtech.api.terminal.TerminalRegistry;
-import gregtech.api.terminal.gui.widgets.AnimaWidgetGroup;
-import gregtech.api.terminal.os.TerminalOSWidget;
-import gregtech.api.terminal.os.menu.IMenuComponent;
-import gregtech.api.util.GTLog;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-import gregtech.common.items.behaviors.TerminalBehaviour;
-
-import net.minecraft.client.resources.I18n;
-import net.minecraft.entity.player.EntityPlayer;
-import net.minecraft.nbt.CompressedStreamTools;
-import net.minecraft.nbt.NBTTagCompound;
-import net.minecraft.network.PacketBuffer;
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.function.Consumer;
-import java.util.regex.Pattern;
-
-public abstract class AbstractApplication extends AnimaWidgetGroup {
-
- private static final Pattern NEW_LINE_PATTERN = Pattern.compile("\\\\n");
-
- protected final String name;
- protected TerminalOSWidget os;
- protected boolean isClient;
- protected NBTTagCompound nbt;
-
- public AbstractApplication(String name) {
- super(Position.ORIGIN, new Size(TerminalOSWidget.DEFAULT_WIDTH, TerminalOSWidget.DEFAULT_HEIGHT));
- this.name = name;
- }
-
- public AbstractApplication setOs(TerminalOSWidget os) {
- this.os = os;
- return this;
- }
-
- public boolean canOpenMenuOnEdge() {
- return true;
- }
-
- /**
- * App theme color
- */
- public int getThemeColor() {
- return name.hashCode() | 0xff000000;
- }
-
- /**
- * App Name
- */
- public String getRegistryName() {
- return name;
- }
-
- public String getUnlocalizedName() {
- return "gregtech.terminal.app_name." + name;
- }
-
- /**
- * App Icon
- */
- public IGuiTexture getIcon() {
- return TextureArea.fullImage("textures/gui/terminal/" + name + "/icon.png");
- }
-
- /**
- * App Description
- */
- @SideOnly(Side.CLIENT)
- public String getDescription() {
- if (I18n.hasKey("terminal." + getRegistryName() + ".description")) {
- return NEW_LINE_PATTERN.matcher(I18n.format("terminal." + getRegistryName() + ".description"))
- .replaceAll("\n");
- }
- return I18n.format("terminal.app_name.description");
- }
-
- /**
- * App Profile
- */
- @SideOnly(Side.CLIENT)
- public IGuiTexture getProfile() {
- if (ResourceHelper.isResourceExist("textures/gui/terminal/" + name + "/profile.png")) {
- return TextureArea.fullImage("textures/gui/terminal/" + name + "/profile.png");
- }
- return getIcon();
- }
-
- /**
- * App Banner
- */
- @SideOnly(Side.CLIENT)
- public IGuiTexture getBanner() {
- if (ResourceHelper.isResourceExist("textures/gui/terminal/" + name + "/banner.png")) {
- return TextureArea.fullImage("textures/gui/terminal/" + name + "/banner.png");
- }
- return null;
- }
-
- /**
- * App Information for each tier
- */
- @SideOnly(Side.CLIENT)
- public String getTierInformation(int tier) {
- if (I18n.hasKey("terminal." + name + ".tier." + tier)) {
- return I18n.format("terminal." + name + ".tier." + tier);
- }
- return I18n.format("terminal.app_name.tier", tier);
- }
-
- /**
- * Will be called when try to open this app. you should return an instance here.
- * Due to INative's poor synchronization, do not add the INativeWidget {@link INativeWidget} here.
- * Instead, It's probably best not to initialize your app here. initialize should in initApp {@link #initApp()}
- */
- public AbstractApplication createAppInstance(TerminalOSWidget os, boolean isClient, NBTTagCompound nbt) {
- try {
- AbstractApplication app = this.getClass().newInstance();
- app.isClient = isClient;
- app.nbt = nbt;
- return app;
- } catch (InstantiationException | IllegalAccessException e) {
- GTLog.logger.error("Error while create default app. {}", this.getClass(), e);
- }
- return null;
- }
-
- /**
- * init app here. you have access to os, isClient, nbt.
- */
- public AbstractApplication initApp() {
- return this;
- }
-
- /**
- * you should store the persistent data for both side here.
- *
- * @return nbt data. if its a clientSideApp and the nbt not null, this nbt should be synced to the server side.
- */
- public NBTTagCompound closeApp() {
- return null;
- }
-
- /**
- * Whether the app can run in the background when minimized.
- */
- public boolean isBackgroundApp() {
- return false;
- }
-
- /**
- * If it is a client side app, will block all action packets sent from client.
- * If the app doesn't require server execution, it better be a client side app.
- * For details about data synchronization, see {@link #closeApp()}
- */
- public boolean isClientSideApp() {
- return false;
- }
-
- public TerminalOSWidget getOs() {
- return os;
- }
-
- /**
- * Add components to menu bar.
- *
- * @see IMenuComponent
- */
- public List getMenuComponents() {
- return Collections.emptyList();
- }
-
- /**
- * Whether the player can open this app.
- */
- public boolean canPlayerUse(EntityPlayer player) {
- return true;
- }
-
- /**
- * App Current Tier. Creative Terminal(return max tier)
- */
- public int getAppTier() {
- if (nbt != null) {
- if (TerminalBehaviour.isCreative(getOs().itemStack)) {
- return getMaxTier();
- }
- return Math.min(nbt.getInteger("_tier"), getMaxTier());
- }
- return 0;
- }
-
- /**
- * App Max Tier
- */
- public int getMaxTier() {
- return 0;
- }
-
- @Override
- protected void writeClientAction(int id, Consumer packetBufferWriter) {
- if (!isClientSideApp()) {
- super.writeClientAction(id, packetBufferWriter);
- }
- }
-
- /**
- * read NBT from the local config folder.
- */
- protected void loadLocalConfig(Consumer reader) {
- if (isClient && reader != null) {
- NBTTagCompound nbt = null;
- try {
- nbt = CompressedStreamTools.read(
- new File(TerminalRegistry.TERMINAL_PATH, String.format("config/%S.nbt", getRegistryName())));
- } catch (IOException e) {
- GTLog.logger.error("error while loading local nbt for {}", getRegistryName(), e);
- }
- if (nbt == null) {
- nbt = new NBTTagCompound();
- }
- reader.accept(nbt);
- }
- }
-
- /**
- * Write NBT to the local config folder.
- */
- protected void saveLocalConfig(Consumer writer) {
- if (isClient && writer != null) {
- NBTTagCompound nbt = new NBTTagCompound();
- try {
- writer.accept(nbt);
- if (!nbt.isEmpty()) {
- CompressedStreamTools.safeWrite(nbt, new File(TerminalRegistry.TERMINAL_PATH,
- String.format("config/%S.nbt", getRegistryName())));
- }
- } catch (IOException e) {
- GTLog.logger.error("error while saving local nbt for {}", getRegistryName(), e);
- }
- }
- }
-
- /**
- * Fired when you open this app or terminal's size updated. (maximize)
- */
- public void onOSSizeUpdate(int width, int height) {
- setSelfPosition(
- Position.ORIGIN.add(new Position((width - getSize().width) / 2, (height - getSize().height) / 2)));
- }
-
- public boolean canLaunchConcurrently(AbstractApplication application) {
- return true;
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/gui/CustomTabListRenderer.java b/src/main/java/gregtech/api/terminal/gui/CustomTabListRenderer.java
deleted file mode 100644
index c3cf0733e93..00000000000
--- a/src/main/java/gregtech/api/terminal/gui/CustomTabListRenderer.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package gregtech.api.terminal.gui;
-
-import gregtech.api.gui.ModularUI;
-import gregtech.api.gui.resources.IGuiTexture;
-import gregtech.api.gui.widgets.tab.ITabInfo;
-import gregtech.api.gui.widgets.tab.TabListRenderer;
-import gregtech.api.util.Position;
-
-import net.minecraft.client.renderer.GlStateManager;
-
-import java.util.List;
-
-public class CustomTabListRenderer extends TabListRenderer {
-
- private final IGuiTexture unSelected;
- private final IGuiTexture selected;
- private final int width;
- private final int height;
-
- public CustomTabListRenderer(IGuiTexture unSelected, IGuiTexture selected, int width, int height) {
- this.unSelected = unSelected;
- this.selected = selected;
- this.width = width;
- this.height = height;
- }
-
- @Override
- public void renderTabs(ModularUI gui, Position offset, List tabInfos, int guiWidth, int guiHeight,
- int selectedTabIndex) {
- int y = offset.y - height;
- GlStateManager.color(gui.getRColorForOverlay(), gui.getGColorForOverlay(), gui.getBColorForOverlay(), 1.0F);
- for (int i = 0; i < tabInfos.size(); i++) {
- int x = offset.x + i * width;
- if (selectedTabIndex == i && selected != null) {
- tabInfos.get(i).renderTab(selected, x, y, width, height, true);
- GlStateManager.color(gui.getRColorForOverlay(), gui.getGColorForOverlay(), gui.getBColorForOverlay(),
- 1.0F);
- }
- if (selectedTabIndex != i && unSelected != null) {
- tabInfos.get(i).renderTab(unSelected, x, y, width, height, false);
- GlStateManager.color(gui.getRColorForOverlay(), gui.getGColorForOverlay(), gui.getBColorForOverlay(),
- 1.0F);
- }
- }
- }
-
- @Override
- public int[] getTabPos(int guiWidth, int guiHeight, int tabIndex) {
- return new int[] { width * guiWidth, -height, width, height };
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/AnimaWidgetGroup.java b/src/main/java/gregtech/api/terminal/gui/widgets/AnimaWidgetGroup.java
deleted file mode 100644
index acd2a58bed4..00000000000
--- a/src/main/java/gregtech/api/terminal/gui/widgets/AnimaWidgetGroup.java
+++ /dev/null
@@ -1,111 +0,0 @@
-package gregtech.api.terminal.gui.widgets;
-
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.widgets.WidgetGroup;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-import gregtech.api.util.interpolate.Eases;
-import gregtech.api.util.interpolate.Interpolator;
-
-import net.minecraft.client.renderer.GlStateManager;
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-import java.util.function.Consumer;
-
-public abstract class AnimaWidgetGroup extends WidgetGroup {
-
- @SideOnly(Side.CLIENT)
- protected Interpolator interpolator;
- protected float scale = 1;
-
- public AnimaWidgetGroup(Position position, Size size) {
- super(position, size);
- }
-
- public AnimaWidgetGroup(int x, int y, int width, int height) {
- super(new Position(x, y), new Size(width, height));
- }
-
- @Override
- public void updateScreenOnFrame() {
- if (interpolator != null) {
- interpolator.update();
- }
- super.updateScreenOnFrame();
- }
-
- @SideOnly(Side.CLIENT)
- public final void maximizeWidget(Consumer callback) {
- this.scale = 0;
- setVisible(true);
- interpolator = new Interpolator(0, 1, 10, Eases.LINEAR,
- value -> scale = value.floatValue(),
- value -> {
- interpolator = null;
- if (callback != null) {
- callback.accept(this);
- }
- });
- interpolator.start();
- }
-
- @SideOnly(Side.CLIENT)
- public final void minimizeWidget(Consumer callback) {
- this.scale = 1;
- interpolator = new Interpolator(1, 0, 10, Eases.LINEAR,
- value -> scale = value.floatValue(),
- value -> {
- setVisible(false);
- interpolator = null;
- if (callback != null) {
- callback.accept(this);
- }
- });
- interpolator.start();
- }
-
- @SideOnly(Side.CLIENT)
- protected void hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- super.drawInBackground(mouseX, mouseY, partialTicks, context);
- }
-
- @SideOnly(Side.CLIENT)
- protected void hookDrawInForeground(int mouseX, int mouseY) {
- super.drawInForeground(mouseX, mouseY);
- }
-
- @Override
- public final void drawInForeground(int mouseX, int mouseY) {
- if (scale == 0) {
- return;
- }
- if (scale != 1) {
- GlStateManager.pushMatrix();
- GlStateManager.translate((this.gui.getScreenWidth() - this.gui.getScreenWidth() * scale) / 2,
- (this.gui.getScreenHeight() - this.gui.getScreenHeight() * scale) / 2, 0);
- GlStateManager.scale(scale, scale, 1);
- hookDrawInForeground(0, 0);
- GlStateManager.popMatrix();
- } else {
- hookDrawInForeground(mouseX, mouseY);
- }
- }
-
- @Override
- public final void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- if (scale == 0) {
- return;
- }
- if (scale != 1) {
- GlStateManager.pushMatrix();
- GlStateManager.translate((this.gui.getScreenWidth() - this.gui.getScreenWidth() * scale) / 2,
- (this.gui.getScreenHeight() - this.gui.getScreenHeight() * scale) / 2, 0);
- GlStateManager.scale(scale, scale, 1);
- hookDrawInBackground(0, 0, partialTicks, context);
- GlStateManager.popMatrix();
- } else {
- hookDrawInBackground(mouseX, mouseY, partialTicks, context);
- }
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/ColorWidget.java b/src/main/java/gregtech/api/terminal/gui/widgets/ColorWidget.java
deleted file mode 100644
index 673c049b5f6..00000000000
--- a/src/main/java/gregtech/api/terminal/gui/widgets/ColorWidget.java
+++ /dev/null
@@ -1,305 +0,0 @@
-package gregtech.api.terminal.gui.widgets;
-
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.Widget;
-import gregtech.api.gui.resources.ColorRectTexture;
-import gregtech.api.gui.resources.IGuiTexture;
-import gregtech.api.gui.widgets.TextFieldWidget;
-import gregtech.api.gui.widgets.WidgetGroup;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-
-import net.minecraft.network.PacketBuffer;
-import net.minecraft.util.math.MathHelper;
-
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-
-public class ColorWidget extends WidgetGroup {
-
- private int red = 255;
- private int green = 255;
- private int blue = 255;
- private int alpha = 255;
- private Consumer onColorChanged;
- private final int barWidth;
- private final int barHeight;
- private final CircleButtonWidget redButton;
- private final CircleButtonWidget greenButton;
- private final CircleButtonWidget blueButton;
- private final CircleButtonWidget alphaButton;
- private int lastMouseX;
- private CircleButtonWidget dragged;
- private Supplier colorSupplier;
- private boolean isClient;
-
- public ColorWidget(int x, int y, int barWidth, int barHeight) {
- super(new Position(x, y), new Size(barWidth + 35, 3 * (barHeight + 5) + 10));
- this.barWidth = barWidth;
- this.barHeight = barHeight;
- IGuiTexture textFieldBackground = new ColorRectTexture(0x9f000000);
- TextFieldWidget redField = new TextFieldWidget(barWidth + 5, 0, 30, barHeight, textFieldBackground, null, null)
- .setTextResponder((t) -> {
- setRed(t.isEmpty() ? 0 : Integer.parseInt(t));
- if (onColorChanged != null) {
- onColorChanged.accept(getColor());
- }
- writeClientAction(2, buffer -> buffer.writeInt(getColor()));
- }, true)
- .setTextSupplier(() -> Integer.toString(red), true)
- .setValidator(ColorWidget::checkValid);
- TextFieldWidget greenField = new TextFieldWidget(barWidth + 5, barHeight + 5, 30, barHeight,
- textFieldBackground, null, null)
- .setTextResponder((t) -> {
- setGreen(t.isEmpty() ? 0 : Integer.parseInt(t));
- if (onColorChanged != null) {
- onColorChanged.accept(getColor());
- }
- writeClientAction(2, buffer -> buffer.writeInt(getColor()));
- }, true)
- .setTextSupplier(() -> Integer.toString(green), true)
- .setValidator(ColorWidget::checkValid);
- TextFieldWidget blueField = new TextFieldWidget(barWidth + 5, (barHeight + 5) * 2, 30, barHeight,
- textFieldBackground, null, null)
- .setTextResponder((t) -> {
- setBlue(t.isEmpty() ? 0 : Integer.parseInt(t));
- if (onColorChanged != null) {
- onColorChanged.accept(getColor());
- }
- writeClientAction(2, buffer -> buffer.writeInt(getColor()));
- }, true)
- .setTextSupplier(() -> Integer.toString(blue), true)
- .setValidator(ColorWidget::checkValid);
- TextFieldWidget alphaField = new TextFieldWidget(barWidth + 5, (barHeight + 5) * 3, 30, barHeight,
- textFieldBackground, null, null)
- .setTextResponder((t) -> {
- setAlpha(t.isEmpty() ? 0 : Integer.parseInt(t));
- if (onColorChanged != null) {
- onColorChanged.accept(getColor());
- }
- writeClientAction(2, buffer -> buffer.writeInt(getColor()));
- }, true)
- .setTextSupplier(() -> Integer.toString(alpha), true)
- .setValidator(ColorWidget::checkValid);
- this.addWidget(redField);
- this.addWidget(greenField);
- this.addWidget(blueField);
- this.addWidget(alphaField);
- redButton = new CircleButtonWidget(barWidth, barHeight / 2, 4, 1, 0).setFill(0xffff0000).setStrokeAnima(-1);
- greenButton = new CircleButtonWidget(barWidth, barHeight / 2 + barHeight + 5, 4, 1, 0).setFill(0xff00ff00)
- .setStrokeAnima(-1);
- blueButton = new CircleButtonWidget(barWidth, barHeight / 2 + 2 * (barHeight + 5), 4, 1, 0).setFill(0xff0000ff)
- .setStrokeAnima(-1);
- alphaButton = new CircleButtonWidget(barWidth, barHeight / 2 + 3 * (barHeight + 5), 4, 1, 0).setFill(-1)
- .setStrokeAnima(-1);
- this.addWidget(redButton);
- this.addWidget(greenButton);
- this.addWidget(blueButton);
- this.addWidget(alphaButton);
- }
-
- public ColorWidget setOnColorChanged(Consumer onColorChanged) {
- this.onColorChanged = onColorChanged;
- return this;
- }
-
- public ColorWidget setColorSupplier(Supplier colorSupplier, boolean isClient) {
- this.colorSupplier = colorSupplier;
- this.isClient = isClient;
- return this;
- }
-
- public ColorWidget setStartColor(int color) {
- setRed((color >> 16) & 0xFF);
- setGreen((color >> 8) & 0xFF);
- setBlue(color & 0xFF);
- setAlpha((color >> 24) & 0xFF);
- return this;
- }
-
- public int getColor() {
- return (alpha << 24) | (red << 16) | (green << 8) | (blue);
- }
-
- @Override
- public void detectAndSendChanges() {
- super.detectAndSendChanges();
- if (!isClient && colorSupplier != null) {
- int c = colorSupplier.get();
- int r = (c & 0x00ff0000) >>> 16;
- int g = (c & 0x0000ff00) >>> 8;
- int b = (c & 0x000000ff);
- int a = (c & 0xff000000) >>> 24;
- if (r != red || g != green || b != blue || a != alpha) {
- setRed(r);
- setGreen(g);
- setBlue(b);
- setAlpha(a);
- writeUpdateInfo(2, buffer -> buffer.writeInt(c));
- }
- }
- }
-
- @Override
- public void updateScreen() {
- super.updateScreen();
- if (isClient && colorSupplier != null) {
- int c = colorSupplier.get();
- int r = (c & 0x00ff0000) >>> 16;
- int g = (c & 0x0000ff00) >>> 8;
- int b = (c & 0x000000ff);
- int a = (c & 0xff000000) >>> 24;
- if (r != red || g != green || b != blue || a != alpha) {
- setRed(r);
- setGreen(g);
- setBlue(b);
- setAlpha(a);
- writeClientAction(2, buffer -> buffer.writeInt(c));
- }
- }
- }
-
- @Override
- public void readUpdateInfo(int id, PacketBuffer buffer) {
- handleColor(id, buffer);
- }
-
- private void handleColor(int id, PacketBuffer buffer) {
- if (id == 2) {
- int c = buffer.readInt();
- int r = (c & 0x00ff0000) >>> 16;
- int g = (c & 0x0000ff00) >>> 8;
- int b = (c & 0x000000ff);
- int a = (c & 0xff000000) >>> 24;
- if (r != red || g != green || b != blue || a != alpha) {
- setRed(r);
- setGreen(g);
- setBlue(b);
- setAlpha(a);
- if (onColorChanged != null) {
- onColorChanged.accept(getColor());
- }
- }
- }
- }
-
- @Override
- public void handleClientAction(int id, PacketBuffer buffer) {
- handleColor(id, buffer);
- }
-
- private void setRed(int red) {
- if (this.red != red) {
- this.red = red;
- redButton.setSelfPosition(new Position(red * barWidth / 255 - 4, redButton.getSelfPosition().y));
- }
- }
-
- private void setGreen(int green) {
- if (this.green != green) {
- this.green = green;
- greenButton.setSelfPosition(new Position(green * barWidth / 255 - 4, greenButton.getSelfPosition().y));
- }
- }
-
- private void setBlue(int blue) {
- if (this.blue != blue) {
- this.blue = blue;
- blueButton.setSelfPosition(new Position(blue * barWidth / 255 - 4, blueButton.getSelfPosition().y));
- }
- }
-
- private void setAlpha(int alpha) {
- if (this.alpha != alpha) {
- this.alpha = alpha;
- alphaButton.setSelfPosition(new Position(alpha * barWidth / 255 - 4, alphaButton.getSelfPosition().y));
- }
- }
-
- private static boolean checkValid(String input) {
- if (input.length() > 3) return false;
- if (input.isEmpty()) return true;
- try {
- int value = Integer.parseInt(input);
- if (value >= 0 && value <= 255) {
- return true;
- }
- } catch (Exception e) {
- return false;
- }
- return false;
- }
-
- @Override
- public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- int x = getPosition().x;
- int y = getPosition().y;
- drawGradientRect(x, y + 2, barWidth, 5, (255 << 24) | (0) | (green << 8) | (blue),
- (255 << 24) | (255 << 16) | (green << 8) | (blue), true);
- drawGradientRect(x, y + barHeight + 5 + 2, barWidth, 5, (255 << 24) | (red << 16) | (0) | (blue),
- (255 << 24) | (red << 16) | (255 << 8) | (blue), true);
- drawGradientRect(x, y + 2 * (barHeight + 5) + 2, barWidth, 5, (255 << 24) | (red << 16) | (green << 8) | (0),
- (255 << 24) | (red << 16) | (green << 8) | (255), true);
- drawGradientRect(x, y + 3 * (barHeight + 5) + 2, barWidth, 5, (0) | (red << 16) | (green << 8) | (blue),
- (255 << 24) | (red << 16) | (green << 8) | (blue), true);
- super.drawInBackground(mouseX, mouseY, partialTicks, context);
- }
-
- @Override
- public boolean mouseClicked(int mouseX, int mouseY, int button) {
- lastMouseX = mouseX;
- dragged = null;
- if (redButton.isMouseOverElement(mouseX, mouseY)) {
- dragged = redButton;
- return true;
- } else if (greenButton.isMouseOverElement(mouseX, mouseY)) {
- dragged = greenButton;
- return true;
- } else if (blueButton.isMouseOverElement(mouseX, mouseY)) {
- dragged = blueButton;
- return true;
- } else if (alphaButton.isMouseOverElement(mouseX, mouseY)) {
- dragged = alphaButton;
- return true;
- }
- boolean flag = false;
- for (int i = widgets.size() - 1; i >= 0; i--) {
- Widget widget = widgets.get(i);
- if (widget.isVisible() && widget.mouseClicked(mouseX, mouseY, button)) {
- flag = true;
- }
- }
- return flag;
- }
-
- @Override
- public boolean mouseDragged(int mouseX, int mouseY, int button, long timeDragged) {
- int xDelta = mouseX - lastMouseX;
- lastMouseX = mouseX;
- if (dragged != null) {
- int newX = MathHelper.clamp(dragged.getSelfPosition().x + 4 + xDelta, 0, barWidth);
- if (dragged == redButton) {
- setRed(newX * 255 / barWidth);
- } else if (dragged == greenButton) {
- setGreen(newX * 255 / barWidth);
- } else if (dragged == blueButton) {
- setBlue(newX * 255 / barWidth);
- } else if (dragged == alphaButton) {
- setAlpha(newX * 255 / barWidth);
- }
- if (onColorChanged != null) {
- onColorChanged.accept(getColor());
- }
- writeClientAction(2, buffer -> buffer.writeInt(getColor()));
- dragged.setSelfPosition(new Position(newX - 4, dragged.getSelfPosition().y));
- return true;
- }
- return super.mouseDragged(mouseX, mouseY, button, timeDragged);
- }
-
- @Override
- public boolean mouseReleased(int mouseX, int mouseY, int button) {
- dragged = null;
- return super.mouseReleased(mouseX, mouseY, button);
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/CustomPositionSizeWidget.java b/src/main/java/gregtech/api/terminal/gui/widgets/CustomPositionSizeWidget.java
deleted file mode 100644
index a499d12ebb0..00000000000
--- a/src/main/java/gregtech/api/terminal/gui/widgets/CustomPositionSizeWidget.java
+++ /dev/null
@@ -1,217 +0,0 @@
-package gregtech.api.terminal.gui.widgets;
-
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.Widget;
-import gregtech.api.terminal.gui.IDraggable;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-
-import java.util.function.BiConsumer;
-
-public class CustomPositionSizeWidget extends Widget implements IDraggable {
-
- private Widget controlled;
- private final int borderColor;
- private final int hoverColor;
- private final int border;
- private boolean dragUp;
- private boolean dragDown;
- private boolean dragLeft;
- private boolean dragRight;
- private boolean dragPos;
-
- private BiConsumer onUpdated;
-
- public CustomPositionSizeWidget(Widget controlled, int borderColor, int hoverColor, int border) {
- super(controlled.getSelfPosition(), controlled.getSize());
- this.controlled = controlled;
- this.borderColor = borderColor;
- this.hoverColor = hoverColor;
- this.border = border;
- }
-
- public CustomPositionSizeWidget(int borderColor, int hoverColor, int border) {
- super(Position.ORIGIN, Size.ZERO);
- this.borderColor = borderColor;
- this.hoverColor = hoverColor;
- this.border = border;
- }
-
- public CustomPositionSizeWidget setControlled(Widget controlled) {
- this.controlled = controlled;
- if (controlled != null) {
- this.setSelfPosition(controlled.getSelfPosition());
- this.setSize(controlled.getSize());
- }
- return this;
- }
-
- public Widget getControlled() {
- return controlled;
- }
-
- public CustomPositionSizeWidget setOnUpdated(BiConsumer onUpdated) {
- this.onUpdated = onUpdated;
- return this;
- }
-
- @Override
- public void updateScreen() {
- if (controlled != null) {
- Position pos = controlled.getSelfPosition();
- Size size = controlled.getSize();
- if (!this.getSelfPosition().equals(pos)) {
- this.setSelfPosition(pos);
- }
- if (this.getSize().equals(size)) {
- this.setSize(size);
- }
- }
- }
-
- private boolean hoverUp(int x, int y, int width, int height, int mouseX, int mouseY) {
- return isMouseOver(x, y, width / 5, border, mouseX, mouseY) ||
- isMouseOver(x + width * 2 / 5, y, width / 5, border, mouseX, mouseY) ||
- isMouseOver(x + width * 4 / 5, y, width / 5, border, mouseX, mouseY) ||
- isMouseOver(x, y, border, height / 5, mouseX, mouseY) ||
- isMouseOver(x + width - border, y, border, height / 5, mouseX, mouseY);
- }
-
- private boolean hoverDown(int x, int y, int width, int height, int mouseX, int mouseY) {
- return isMouseOver(x, y + height - border, width / 5, border, mouseX, mouseY) ||
- isMouseOver(x + width * 2 / 5, y + height - border, width / 5, border, mouseX, mouseY) ||
- isMouseOver(x + width * 4 / 5, y + height - border, width / 5, border, mouseX, mouseY) ||
- isMouseOver(x, y + height * 4 / 5, border, height / 5, mouseX, mouseY) ||
- isMouseOver(x + width - border, y + height * 4 / 5, border, height / 5, mouseX, mouseY);
- }
-
- private boolean hoverLeft(int x, int y, int width, int height, int mouseX, int mouseY) {
- return isMouseOver(x, y, border, height / 5, mouseX, mouseY) ||
- isMouseOver(x, y + height * 2 / 5, border, height / 5, mouseX, mouseY) ||
- isMouseOver(x, y + height * 4 / 5, border, height / 5, mouseX, mouseY) ||
- isMouseOver(x, y, width / 5, border, mouseX, mouseY) ||
- isMouseOver(x, y + height - border, width / 5, border, mouseX, mouseY);
- }
-
- private boolean hoverRight(int x, int y, int width, int height, int mouseX, int mouseY) {
- return isMouseOver(x + width - border, y, border, height / 5, mouseX, mouseY) ||
- isMouseOver(x + width - border, y + height * 2 / 5, border, height / 5, mouseX, mouseY) ||
- isMouseOver(x + width - border, y + height * 4 / 5, border, height / 5, mouseX, mouseY) ||
- isMouseOver(x + width * 4 / 5, y, width / 5, border, mouseX, mouseY) ||
- isMouseOver(x + width * 4 / 5, y + height - border, width / 5, border, mouseX, mouseY);
- }
-
- @Override
- public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- if (controlled == null) return;
- int x = controlled.getPosition().x;
- int y = controlled.getPosition().y;
- int width = controlled.getSize().width;
- int height = controlled.getSize().height;
-
- boolean hoverUp = false;
- boolean hoverDown = false;
- boolean hoverLeft = false;
- boolean hoverRight = false;
- // UP
- if (dragUp || hoverUp(x, y, width, height, mouseX, mouseY)) {
- hoverUp = true;
- }
- if (dragDown || hoverDown(x, y, width, height, mouseX, mouseY)) {
- hoverDown = true;
- }
- if (dragLeft || hoverLeft(x, y, width, height, mouseX, mouseY)) {
- hoverLeft = true;
- }
- if (dragRight || hoverRight(x, y, width, height, mouseX, mouseY)) {
- hoverRight = true;
- }
- // UP
- drawSolidRect(x, y, width / 5, border, hoverUp && !hoverRight ? hoverColor : borderColor);
- drawSolidRect(x + width * 2 / 5, y, width / 5, border,
- hoverUp && !hoverLeft && !hoverRight ? hoverColor : borderColor);
- drawSolidRect(x + width * 4 / 5, y, width / 5, border, hoverUp && !hoverLeft ? hoverColor : borderColor);
- // DOWN
- drawSolidRect(x, y + height - border, width / 5, border, hoverDown && !hoverRight ? hoverColor : borderColor);
- drawSolidRect(x + width * 2 / 5, y + height - border, width / 5, border,
- hoverDown && !hoverLeft && !hoverRight ? hoverColor : borderColor);
- drawSolidRect(x + width * 4 / 5, y + height - border, width / 5, border,
- hoverDown && !hoverLeft ? hoverColor : borderColor);
- // LEFT
- drawSolidRect(x, y, border, height / 5, hoverLeft && !hoverDown ? hoverColor : borderColor);
- drawSolidRect(x, y + height * 2 / 5, border, height / 5,
- hoverLeft && !hoverDown && !hoverUp ? hoverColor : borderColor);
- drawSolidRect(x, y + height * 4 / 5, border, height / 5, hoverLeft && !hoverUp ? hoverColor : borderColor);
- // RIGHT
- drawSolidRect(x + width - border, y, border, height / 5, hoverRight && !hoverDown ? hoverColor : borderColor);
- drawSolidRect(x + width - border, y + height * 2 / 5, border, height / 5,
- hoverRight && !hoverDown && !hoverUp ? hoverColor : borderColor);
- drawSolidRect(x + width - border, y + height * 4 / 5, border, height / 5,
- hoverRight && !hoverUp ? hoverColor : borderColor);
- }
-
- @Override
- public boolean allowDrag(int mouseX, int mouseY, int button) {
- if (controlled == null || !isActive()) return false;
- int x = controlled.getPosition().x;
- int y = controlled.getPosition().y;
- int width = controlled.getSize().width;
- int height = controlled.getSize().height;
- if (isMouseOver(x, y, width, height, mouseX, mouseY)) {
- // UP
- dragUp = hoverUp(x, y, width, height, mouseX, mouseY);
- // DOWN
- dragDown = hoverDown(x, y, width, height, mouseX, mouseY);
- // LEFT
- dragLeft = hoverLeft(x, y, width, height, mouseX, mouseY);
- // RIGHT
- dragRight = hoverRight(x, y, width, height, mouseX, mouseY);
- dragPos = !dragUp && !dragDown && !dragLeft && !dragRight;
- return true;
- }
- return false;
- }
-
- @Override
- public boolean dragging(int mouseX, int mouseY, int deltaX, int deltaY) {
- if (controlled == null || !isActive()) return false;
- int width = controlled.getSize().width;
- int height = controlled.getSize().height;
- int addX = 0, addY = 0;
- if (!dragPos) {
- if (dragUp) {
- addY = deltaY;
- height = Math.max(1, height - deltaY);
- }
- if (dragDown) {
- height = Math.max(1, height + deltaY);
- }
- if (dragLeft) {
- addX = deltaX;
- width = Math.max(1, width - deltaX);
- }
- if (dragRight) {
- width = Math.max(1, width + deltaX);
- }
- controlled.addSelfPosition(addX, addY);
- controlled.setSize(new Size(width, height));
- } else {
- controlled.addSelfPosition(deltaX, deltaY);
- }
- if (onUpdated != null) {
- onUpdated.accept(controlled.getSelfPosition(), controlled.getSize());
- }
- this.setSelfPosition(controlled.getSelfPosition());
- this.setSize(controlled.getSize());
- return false;
- }
-
- @Override
- public void endDrag(int mouseX, int mouseY) {
- dragDown = false;
- dragUp = false;
- dragLeft = false;
- dragRight = false;
- dragPos = false;
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/MachineSceneWidget.java b/src/main/java/gregtech/api/terminal/gui/widgets/MachineSceneWidget.java
deleted file mode 100644
index 43fceb358f9..00000000000
--- a/src/main/java/gregtech/api/terminal/gui/widgets/MachineSceneWidget.java
+++ /dev/null
@@ -1,345 +0,0 @@
-package gregtech.api.terminal.gui.widgets;
-
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.Widget;
-import gregtech.api.gui.resources.TextTexture;
-import gregtech.api.gui.widgets.WidgetGroup;
-import gregtech.api.metatileentity.MetaTileEntity;
-import gregtech.api.metatileentity.interfaces.IGregTechTileEntity;
-import gregtech.api.metatileentity.multiblock.IMultiblockPart;
-import gregtech.api.metatileentity.multiblock.MultiblockControllerBase;
-import gregtech.api.pattern.PatternMatchContext;
-import gregtech.api.terminal.os.TerminalTheme;
-import gregtech.api.util.FacingPos;
-import gregtech.client.renderer.scene.FBOWorldSceneRenderer;
-import gregtech.client.renderer.scene.WorldSceneRenderer;
-import gregtech.client.utils.RenderUtil;
-
-import net.minecraft.block.state.IBlockState;
-import net.minecraft.client.renderer.GlStateManager;
-import net.minecraft.client.resources.I18n;
-import net.minecraft.init.Blocks;
-import net.minecraft.tileentity.TileEntity;
-import net.minecraft.util.BlockRenderLayer;
-import net.minecraft.util.EnumFacing;
-import net.minecraft.util.math.BlockPos;
-import net.minecraft.util.math.MathHelper;
-import net.minecraft.util.math.RayTraceResult;
-import net.minecraft.util.math.Vec3d;
-import net.minecraft.world.World;
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-import org.lwjgl.opengl.GL11;
-import org.lwjgl.opengl.GL14;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.function.BiConsumer;
-import java.util.stream.Collectors;
-
-import javax.vecmath.Vector3f;
-
-/**
- * Created with IntelliJ IDEA.
- *
- * @Author: KilaBash
- * @Date: 2021/08/23/19:21
- * @Description:
- */
-public class MachineSceneWidget extends WidgetGroup {
-
- private static FBOWorldSceneRenderer worldSceneRenderer;
- private boolean dragging;
- private int lastMouseX;
- private int lastMouseY;
- private int currentMouseX;
- private int currentMouseY;
- private Vector3f center;
- private float rotationYaw = 45;
- private float rotationPitch;
- private float zoom = 5;
- private float alpha = 1f;
- private boolean blendColor = true;
- private Set cores;
- private Set around;
- private FacingPos hoveredFacingPos;
- private FacingPos selectedFacingPos;
- private BiConsumer onSelected;
-
- protected MetaTileEntity mte;
- protected final BlockPos pos;
-
- public MachineSceneWidget(int x, int y, int width, int height, MetaTileEntity mte) {
- this(x, y, width, height, mte.getPos());
- this.mte = mte;
- updateScene();
- }
-
- public MachineSceneWidget(int x, int y, int width, int height, BlockPos pos) {
- super(x, y, width, height);
- this.pos = pos;
- this.addWidget(new ScrollBarWidget(5, height - 13, width - 50, 8, 0, 1, 0.05f)
- .setOnChanged(value -> alpha = value, true).setInitValue(1f));
- this.addWidget(new RectButtonWidget(width - 40, height - 15, 35, 12, 1)
- .setToggleButton(new TextTexture("COLOR", -1), (c, b) -> blendColor = b)
- .setValueSupplier(true, () -> blendColor)
- .setColors(TerminalTheme.COLOR_7.getColor(), TerminalTheme.COLOR_F_1.getColor(), 0)
- .setIcon(new TextTexture("ALPHA", -1)));
- if (worldSceneRenderer != null) {
- worldSceneRenderer.releaseFBO();
- worldSceneRenderer = null;
- }
- }
-
- public Set getCores() {
- return cores;
- }
-
- public Set getAround() {
- return around;
- }
-
- public static FBOWorldSceneRenderer getWorldSceneRenderer() {
- return worldSceneRenderer;
- }
-
- public MachineSceneWidget setOnSelected(BiConsumer onSelected) {
- this.onSelected = onSelected;
- return this;
- }
-
- @SideOnly(Side.CLIENT)
- private void renderBlockOverLay(WorldSceneRenderer renderer) {
- hoveredFacingPos = null;
- if (isMouseOverElement(currentMouseX, currentMouseY)) {
- int x = getPosition().x;
- int y = getPosition().y;
- int width = getSize().width;
- int height = getSize().height;
- int resolutionWidth = worldSceneRenderer.getResolutionWidth();
- int resolutionHeight = worldSceneRenderer.getResolutionHeight();
- int mouseX = resolutionWidth * (currentMouseX - x) / width;
- int mouseY = (int) (resolutionHeight * (1 - (currentMouseY - y) / (float) height));
- Vector3f hitPos = WorldSceneRenderer.unProject(mouseX, mouseY);
- World world = renderer.world;
- Vec3d eyePos = new Vec3d(renderer.getEyePos().x, renderer.getEyePos().y, renderer.getEyePos().z);
- hitPos.scale(2); // Double view range to ensure pos can be seen.
- Vec3d endPos = new Vec3d((hitPos.x - eyePos.x), (hitPos.y - eyePos.y), (hitPos.z - eyePos.z));
- double min = Float.MAX_VALUE;
- for (BlockPos core : cores) {
- IBlockState blockState = world.getBlockState(core);
- if (blockState.getBlock() == Blocks.AIR) {
- continue;
- }
- RayTraceResult hit = blockState.collisionRayTrace(world, core, eyePos, endPos);
- if (hit != null && hit.typeOfHit != RayTraceResult.Type.MISS) {
- double dist = eyePos.distanceTo(new Vec3d(hit.getBlockPos()));
- if (dist < min) {
- min = dist;
- hoveredFacingPos = new FacingPos(hit.getBlockPos(), hit.sideHit);
- }
- }
- }
- }
- if (selectedFacingPos != null || hoveredFacingPos != null) {
- GlStateManager.pushMatrix();
- RenderUtil.useLightMap(240, 240, () -> {
- GlStateManager.disableDepth();
- if (selectedFacingPos != null) {
- drawFacingBorder(selectedFacingPos, 0xff00ff00);
- }
- if (hoveredFacingPos != null && !hoveredFacingPos.equals(selectedFacingPos)) {
- drawFacingBorder(hoveredFacingPos, 0xffffffff);
- }
- GlStateManager.enableDepth();
- });
- GlStateManager.popMatrix();
- }
- GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
- GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA,
- GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE,
- GlStateManager.DestFactor.ZERO);
- }
-
- private static void drawFacingBorder(FacingPos posFace, int color) {
- GlStateManager.pushMatrix();
- RenderUtil.moveToFace(posFace.getPos().getX(), posFace.getPos().getY(), posFace.getPos().getZ(),
- posFace.getFacing());
- RenderUtil.rotateToFace(posFace.getFacing(), null);
- GlStateManager.scale(1f / 16, 1f / 16, 0);
- GlStateManager.translate(-8, -8, 0);
- Widget.drawBorder(1, 1, 14, 14, color, 1);
- GlStateManager.popMatrix();
- }
-
- @Override
- public void updateScreen() {
- super.updateScreen();
- if (mte == null) {
- World world = this.gui.entityPlayer.world;
- TileEntity tileEntity = world.getTileEntity(pos);
- if (tileEntity instanceof IGregTechTileEntity &&
- ((IGregTechTileEntity) tileEntity).getMetaTileEntity() != null) {
- mte = ((IGregTechTileEntity) tileEntity).getMetaTileEntity();
- updateScene();
- }
- } else if (!mte.isValid()) {
- worldSceneRenderer.releaseFBO();
- worldSceneRenderer = null;
- mte = null;
- }
- }
-
- private void updateScene() {
- if (!mte.isValid()) return;
- World world = mte.getWorld();
- if (worldSceneRenderer != null) {
- worldSceneRenderer.releaseFBO();
- }
- worldSceneRenderer = new FBOWorldSceneRenderer(world, 1080, 1080);
- worldSceneRenderer.setAfterWorldRender(this::renderBlockOverLay);
- cores = new HashSet<>();
- around = new HashSet<>();
- cores.add(pos);
- if (mte instanceof MultiblockControllerBase multi && multi.isStructureFormed()) {
- PatternMatchContext context = multi.structurePattern.checkPatternFastAt(
- world, pos, mte.getFrontFacing().getOpposite(), multi.getUpwardsFacing(), multi.allowsFlip());
- if (context != null) {
- List validPos = multi.structurePattern.cache.keySet().stream().map(BlockPos::fromLong)
- .collect(Collectors.toList());
- Set parts = context.getOrCreate("MultiblockParts", HashSet::new);
- for (IMultiblockPart part : parts) {
- if (part instanceof MetaTileEntity) {
- cores.add(((MetaTileEntity) part).getPos());
- }
- }
- for (EnumFacing facing : EnumFacing.VALUES) {
- cores.forEach(pos -> around.add(pos.offset(facing)));
- }
- int minX = Integer.MAX_VALUE;
- int minY = Integer.MAX_VALUE;
- int minZ = Integer.MAX_VALUE;
- int maxX = Integer.MIN_VALUE;
- int maxY = Integer.MIN_VALUE;
- int maxZ = Integer.MIN_VALUE;
- for (BlockPos vPos : validPos) {
- around.add(vPos);
- minX = Math.min(minX, vPos.getX());
- minY = Math.min(minY, vPos.getY());
- minZ = Math.min(minZ, vPos.getZ());
- maxX = Math.max(maxX, vPos.getX());
- maxY = Math.max(maxY, vPos.getY());
- maxZ = Math.max(maxZ, vPos.getZ());
- }
- around.removeAll(cores);
- center = new Vector3f((minX + maxX) / 2f, (minY + maxY) / 2f, (minZ + maxZ) / 2f);
- } else {
- for (EnumFacing facing : EnumFacing.VALUES) {
- around.add(pos.offset(facing));
- }
- center = new Vector3f(pos.getX() + 0.5f, pos.getY() + 0.5f, pos.getZ() + 0.5f);
- }
- } else {
- for (EnumFacing facing : EnumFacing.VALUES) {
- around.add(pos.offset(facing));
- }
- center = new Vector3f(pos.getX() + 0.5f, pos.getY() + 0.5f, pos.getZ() + 0.5f);
- }
- worldSceneRenderer.addRenderedBlocks(cores, null);
- worldSceneRenderer.addRenderedBlocks(around, this::aroundBlocksRenderHook);
- worldSceneRenderer.setCameraLookAt(center, zoom, Math.toRadians(rotationPitch), Math.toRadians(rotationYaw));
- }
-
- private void aroundBlocksRenderHook(boolean isTESR, int pass, BlockRenderLayer layer) {
- GlStateManager.color(1, 1, 1, 1);
- GlStateManager.enableDepth();
- GlStateManager.enableBlend();
- if (blendColor) {
- GlStateManager.tryBlendFuncSeparate(
- GlStateManager.SourceFactor.CONSTANT_ALPHA, GlStateManager.DestFactor.CONSTANT_COLOR,
- GlStateManager.SourceFactor.CONSTANT_ALPHA, GlStateManager.DestFactor.DST_ALPHA);
- } else {
- GlStateManager.blendFunc(GL11.GL_CONSTANT_ALPHA, GL11.GL_ONE_MINUS_CONSTANT_ALPHA);
- }
- GL14.glBlendColor(1, 1, 1, alpha);
- }
-
- @Override
- public boolean mouseClicked(int mouseX, int mouseY, int button) {
- if (super.mouseClicked(mouseX, mouseY, button)) {
- return true;
- }
- if (isMouseOverElement(mouseX, mouseY)) {
- dragging = true;
- lastMouseX = mouseX;
- lastMouseY = mouseY;
- if (hoveredFacingPos != null && !hoveredFacingPos.equals(selectedFacingPos)) {
- selectedFacingPos = hoveredFacingPos;
- if (onSelected != null) {
- onSelected.accept(selectedFacingPos.getPos(), selectedFacingPos.getFacing());
- }
- }
- return true;
- }
- dragging = false;
- return false;
- }
-
- @Override
- public boolean mouseWheelMove(int mouseX, int mouseY, int wheelDelta) {
- if (isMouseOverElement(mouseX, mouseY)) {
- zoom = (float) MathHelper.clamp(zoom + (wheelDelta < 0 ? 0.5 : -0.5), 3, 999);
- if (worldSceneRenderer != null) {
- worldSceneRenderer.setCameraLookAt(center, zoom, Math.toRadians(rotationPitch),
- Math.toRadians(rotationYaw));
- }
- }
- return super.mouseWheelMove(mouseX, mouseY, wheelDelta);
- }
-
- @Override
- public boolean mouseDragged(int mouseX, int mouseY, int button, long timeDragged) {
- if (dragging) {
- rotationPitch += mouseX - lastMouseX + 360;
- rotationPitch = rotationPitch % 360;
- rotationYaw = (float) MathHelper.clamp(rotationYaw + (mouseY - lastMouseY), -89.9, 89.9);
- lastMouseY = mouseY;
- lastMouseX = mouseX;
- if (worldSceneRenderer != null) {
- worldSceneRenderer.setCameraLookAt(center, zoom, Math.toRadians(rotationPitch),
- Math.toRadians(rotationYaw));
- }
- return true;
- }
- return super.mouseDragged(mouseX, mouseY, button, timeDragged);
- }
-
- @Override
- public boolean mouseReleased(int mouseX, int mouseY, int button) {
- dragging = false;
- return super.mouseReleased(mouseX, mouseY, button);
- }
-
- @Override
- public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- int x = getPosition().x;
- int y = getPosition().y;
- int width = getSize().width;
- int height = getSize().height;
- drawSolidRect(x, y, width, height, 0xaf000000);
- if (worldSceneRenderer != null) {
- GL11.glDisable(GL11.GL_SCISSOR_TEST);
- worldSceneRenderer.render(x, y, width, height, mouseX - x, mouseY - y);
- GL11.glEnable(GL11.GL_SCISSOR_TEST);
- }
- drawBorder(x + 1, y + 1, width - 2, height - 2, 0xff000000, 1);
- if (mte != null) {
- drawStringSized(I18n.format(mte.getMetaFullName()), x + width / 2f, y + 10, -1, true, 1, true);
- }
- super.drawInBackground(mouseX, mouseY, partialTicks, context);
- currentMouseX = mouseX;
- currentMouseY = mouseY;
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/ScrollBarWidget.java b/src/main/java/gregtech/api/terminal/gui/widgets/ScrollBarWidget.java
deleted file mode 100644
index 619fd1cbd6d..00000000000
--- a/src/main/java/gregtech/api/terminal/gui/widgets/ScrollBarWidget.java
+++ /dev/null
@@ -1,137 +0,0 @@
-package gregtech.api.terminal.gui.widgets;
-
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.Widget;
-import gregtech.api.gui.resources.ColorRectTexture;
-import gregtech.api.gui.resources.IGuiTexture;
-import gregtech.api.gui.resources.TextureArea;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-
-import net.minecraft.network.PacketBuffer;
-import net.minecraft.util.math.MathHelper;
-
-import java.util.function.Consumer;
-
-public class ScrollBarWidget extends Widget {
-
- protected final float min;
- protected final float max;
- protected final float dur;
- protected int xOffset;
- protected boolean draggedOnScrollBar;
- protected IGuiTexture background;
- protected IGuiTexture buttonTexture;
- protected int buttonWidth;
- protected int buttonHeight;
- protected Consumer onChanged;
- protected boolean isClient;
-
- public ScrollBarWidget(int x, int y, int width, int height, float min, float max, float dur) {
- super(new Position(x, y), new Size(width, height));
- this.max = max;
- this.min = min;
- this.dur = dur;
- this.xOffset = width / 2;
- this.buttonTexture = new ColorRectTexture(-1);
- this.buttonWidth = Math.max((int) (width / ((max - min) / dur)), 5);
- this.buttonHeight = height;
- }
-
- public ScrollBarWidget setOnChanged(Consumer onChanged, boolean isClient) {
- this.onChanged = onChanged;
- this.isClient = isClient;
- return this;
- }
-
- public ScrollBarWidget setBackground(IGuiTexture background) {
- this.background = background;
- return this;
- }
-
- public ScrollBarWidget setInitValue(float value) {
- if (value >= min && value <= max) {
- this.xOffset = (int) ((value - min) / (max - min) * (this.getSize().width - buttonWidth));
- }
- return this;
- }
-
- public ScrollBarWidget setButtonTexture(TextureArea buttonTexture, int buttonWidth, int buttonHeight) {
- this.buttonTexture = buttonTexture;
- this.buttonWidth = buttonWidth;
- this.buttonHeight = buttonHeight;
- return this;
- }
-
- @Override
- public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- int x = getPosition().x;
- int y = getPosition().y;
- int width = getSize().width;
- int height = getSize().height;
- if (this.background != null) {
- this.background.draw(x, y, width, height);
- } else {
- drawBorder(x - 1, y - 1, width + 2, height + 2, -1, 1);
- }
- if (this.buttonTexture != null) {
- this.buttonTexture.draw(x + xOffset, y + (height - buttonHeight) / 2f, buttonWidth, buttonHeight);
- }
- }
-
- private boolean isOnScrollPane(int mouseX, int mouseY) {
- Position position = this.getPosition();
- Size size = this.getSize();
- return isMouseOver(position.x, position.y, size.width, buttonHeight, mouseX, mouseY);
- }
-
- private float getValue() {
- return (float) (min +
- Math.floor((max - min) * xOffset * 1.0f / (this.getSize().width - buttonWidth) / dur) * dur);
- }
-
- @Override
- public boolean mouseClicked(int mouseX, int mouseY, int button) {
- if (this.isOnScrollPane(mouseX, mouseY)) {
- this.xOffset = MathHelper.clamp(mouseX - this.getPosition().x - buttonWidth / 2, 0,
- this.getSize().width - buttonWidth);
- this.draggedOnScrollBar = true;
- }
- return this.isMouseOverElement(mouseX, mouseY);
- }
-
- @Override
- public boolean mouseDragged(int mouseX, int mouseY, int button, long timeDragged) {
- if (draggedOnScrollBar) {
- this.xOffset = MathHelper.clamp(mouseX - this.getPosition().x - buttonWidth / 2, 0,
- this.getSize().width - buttonWidth);
- if (onChanged != null) {
- onChanged.accept(getValue());
- }
- return true;
- }
- return false;
- }
-
- @Override
- public boolean mouseReleased(int mouseX, int mouseY, int button) {
- if (this.draggedOnScrollBar) {
- if (!isClient) {
- this.writeClientAction(2, packetBuffer -> packetBuffer.writeFloat(getValue()));
- }
- }
- this.draggedOnScrollBar = false;
- return this.isMouseOverElement(mouseX, mouseY);
- }
-
- @Override
- public void handleClientAction(int id, PacketBuffer buffer) {
- super.handleClientAction(id, buffer);
- if (id == 2) {
- float value = buffer.readFloat();
- if (this.onChanged != null) {
- onChanged.accept(value);
- }
- }
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/TextEditorWidget.java b/src/main/java/gregtech/api/terminal/gui/widgets/TextEditorWidget.java
deleted file mode 100644
index 4837420bcc5..00000000000
--- a/src/main/java/gregtech/api/terminal/gui/widgets/TextEditorWidget.java
+++ /dev/null
@@ -1,463 +0,0 @@
-package gregtech.api.terminal.gui.widgets;
-
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.resources.ColorRectTexture;
-import gregtech.api.gui.resources.IGuiTexture;
-import gregtech.api.gui.resources.TextureArea;
-import gregtech.api.gui.widgets.WidgetGroup;
-import gregtech.api.terminal.os.TerminalTheme;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-
-import net.minecraft.client.Minecraft;
-import net.minecraft.client.gui.FontRenderer;
-import net.minecraft.client.gui.GuiScreen;
-import net.minecraft.util.ChatAllowedCharacters;
-import net.minecraft.util.text.TextFormatting;
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-import java.util.*;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.function.Consumer;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class TextEditorWidget extends WidgetGroup {
-
- private static final TextureArea PALETTE = TextureArea.fullImage("textures/gui/widget/palette.png");
- private static final TextureArea STYLE = TextureArea.fullImage("textures/gui/widget/formatting.png");
- private final TextPanelWidget textPanelWidget;
-
- private static final Pattern COMMENT = Pattern.compile("(//.*|/\\*[\\s\\S]*?\\*/)|(#.*)");
- private static final Pattern STRING = Pattern
- .compile("(\"(?:[^\"\\\\]|\\\\[\\s\\S])*\"|'(?:[^'\\\\]|\\\\[\\s\\S])*')");
- private static final Pattern BOOL = Pattern.compile("\\b(true|false|null|undefined|NaN)\\b");
- private static final Pattern KEYWORD = Pattern.compile(
- "\\b(import|var|for|if|else|return|this|while|new|function|switch|case|typeof|do|in|throw|try|catch|finally|with|instance|delete|void|break|continue)\\b");
- private static final Pattern KEYWORD_2 = Pattern.compile(
- "\\b(String|int|long|boolean|float|double|byte|short|document|Date|Math|window|Object|location|navigator|Array|Number|Boolean|Function|RegExp)\\b");
- private static final Pattern VARIABLE = Pattern.compile("(?:[^\\W\\d]|\\$)[\\$\\w]*");
- private static final Pattern NUMBER = Pattern
- .compile("(0[xX][0-9a-fA-F]+|\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?|\\.\\d+(?:[eE][+-]?\\d+)?)");
- private static final Pattern ANY = Pattern.compile("[\\s\\S]");
-
- public TextEditorWidget(int x, int y, int width, int height, Consumer stringUpdate, boolean allowToolBox) {
- super(new Position(x, y),
- new Size(Math.max(width, allowToolBox ? 80 : width), Math.max(height, allowToolBox ? 32 : height)));
- textPanelWidget = new TextPanelWidget(0, 32, Math.max(width, allowToolBox ? 80 : width),
- Math.max(height, allowToolBox ? 32 : height) - 32, stringUpdate);
- this.addWidget(textPanelWidget);
- if (allowToolBox) {
- initToolBox();
- }
- }
-
- public TextEditorWidget setBackground(IGuiTexture background) {
- textPanelWidget.setBackground(background);
- return this;
- }
-
- public TextEditorWidget setContent(String content) {
- textPanelWidget.pageSetCurrent(content);
- return this;
- }
-
- @Override
- public void setActive(boolean active) {
- super.setActive(active);
- textPanelWidget.setActive(active);
- }
-
- private void initToolBox() {
- TextFormatting[] formatting = TextFormatting.values();
- // palette
- for (int y = 0; y < 4; y++) {
- for (int x = 0; x < 4; x++) {
- TextFormatting colorFormatting = formatting[y * 4 + x];
- this.addWidget(new RectButtonWidget(x * 8, y * 8, 8, 8, 1)
- .setToggleButton(PALETTE.getSubArea(0.5 + x * 0.125, y * 0.25, 0.125, 0.25),
- (cd, pressed) -> {
- if (pressed) {
- textPanelWidget.addFormatting(colorFormatting);
- } else {
- textPanelWidget.removeFormatting(colorFormatting);
- }
- })
- .setValueSupplier(true, () -> colorFormatting == textPanelWidget.getFrontColorFormatting())
- .setIcon(PALETTE.getSubArea(x * 0.125, y * 0.25, 0.125, 0.25))
- .setColors(0, -1, 0)
- .setHoverText(colorFormatting.getFriendlyName()));
- }
- }
- // style
- for (int y = 0; y < 2; y++) {
- for (int x = 0; x < 3; x++) {
- TextFormatting styleFormatting = formatting[16 + y * 3 + x];
- if (styleFormatting == TextFormatting.RESET) break;
- this.addWidget(new RectButtonWidget(x * 16 + 32, y * 16, 16, 16, 1)
- .setToggleButton(STYLE.getSubArea(0.5 + x * 1.0 / 6, y * 0.5, 1.0 / 6, 0.5),
- (cd, pressed) -> {
- if (pressed) {
- textPanelWidget.addFormatting(styleFormatting);
- } else {
- textPanelWidget.removeFormatting(styleFormatting);
- }
- })
- .setValueSupplier(true,
- () -> textPanelWidget.getFrontStyleFormatting().contains(styleFormatting))
- .setIcon(STYLE.getSubArea(x * 1.0 / 6, y * 0.5, 1.0 / 6, 0.5))
- .setColors(0, -1, 0)
- .setHoverText(styleFormatting.getFriendlyName()));
- }
- }
- this.addWidget(new RectButtonWidget(3 * 16 + 32, 0, 16, 16, 3)
- .setToggleButton(new ColorRectTexture(TerminalTheme.COLOR_B_2.getColor()),
- (c, p) -> textPanelWidget.allowMarkdown = !p)
- .setValueSupplier(true, () -> !textPanelWidget.allowMarkdown)
- .setColors(TerminalTheme.COLOR_B_3.getColor(), TerminalTheme.COLOR_1.getColor(),
- TerminalTheme.COLOR_B_3.getColor())
- .setIcon(new ColorRectTexture(TerminalTheme.COLOR_7.getColor()))
- .setHoverText("Check Markdown when Ctrl+V"));
- this.addWidget(new RectButtonWidget(3 * 16 + 32, 16, 16, 16, 3)
- .setClickListener(clickData -> textPanelWidget.pageSetCurrent(""))
- .setColors(TerminalTheme.COLOR_B_3.getColor(), TerminalTheme.COLOR_1.getColor(),
- TerminalTheme.COLOR_B_3.getColor())
- .setIcon(new ColorRectTexture(TerminalTheme.COLOR_7.getColor()))
- .setHoverText("Clean Up"));
- }
-
- private static class TextPanelWidget extends DraggableScrollableWidgetGroup {
-
- public final static int SPACE = 0;
- public int updateCount;
- public String content;
- public int textHeight;
- public final Consumer stringUpdate;
- public TextFormatting frontColor;
- public List frontStyle;
- public boolean allowMarkdown;
-
- private static final char SECTION_SIGN = '\u00A7';
-
- @SideOnly(Side.CLIENT)
- public FontRenderer fontRenderer;
- @SideOnly(Side.CLIENT)
- private static final Pattern R_CODE_PATTERN = Pattern.compile("(?i)" + SECTION_SIGN + "[R]");
- @SideOnly(Side.CLIENT)
- private static final Pattern COLOR_CODE_PATTERN = Pattern.compile("(?i)" + SECTION_SIGN + "[0-9A-F]");
-
- public TextPanelWidget(int x, int y, int width, int height, Consumer stringUpdate) {
- super(x, y, width, height);
- this.stringUpdate = stringUpdate;
- this.content = "";
- this.allowMarkdown = true;
- if (isClientSide()) {
- fontRenderer = Minecraft.getMinecraft().fontRenderer;
- textHeight = fontRenderer.getWordWrappedHeight(content, width - yBarWidth);
- frontColor = null;
- frontStyle = new ArrayList<>();
- }
- }
-
- @Override
- public int getMaxHeight() {
- return textHeight + SPACE + xBarHeight;
- }
-
- public void updateScreen() {
- super.updateScreen();
- ++this.updateCount;
- }
-
- @Override
- public boolean keyTyped(char typedChar, int keyCode) {
- if (!focus || !isActive()) return false;
- if (GuiScreen.isKeyComboCtrlV(keyCode)) {
- this.pageInsertIntoCurrent(allowMarkdown ? formatFromMarkdown(GuiScreen.getClipboardString()) :
- GuiScreen.getClipboardString());
- findFrontFormatting();
- } else {
- switch (keyCode) {
- case 14:
- if (!content.isEmpty()) {
- this.pageSetCurrent(content.substring(0, content.length() - 1));
- }
- break;
- case 28:
- case 156:
- this.pageInsertIntoCurrent("\n");
- break;
- default:
- if (ChatAllowedCharacters.isAllowedCharacter(typedChar)) {
- this.pageInsertIntoCurrent(Character.toString(typedChar));
- }
- }
- }
- if (getMaxHeight() > getSize().height) {
- setScrollYOffset(getMaxHeight() - getSize().height);
- } else {
- setScrollYOffset(0);
- }
- return true;
- }
-
- private static String formatFromMarkdown(String markdown) {
- StringBuilder builder = new StringBuilder();
- Deque stack = new ArrayDeque<>();
- int[] chars = markdown.chars().toArray();
- for (int i = 0; i < chars.length; i++) {
- if (chars[i] == '\\' && i + 1 < chars.length) {
- if (chars[i + 1] == '*' || chars[i + 1] == '_' || chars[i + 1] == '~' || chars[i + 1] == '`') {
- builder.append(chars[i + 1]);
- i++;
- } else {
- builder.append('\\');
- }
- } else if (chars[i] == '*' && i + 1 < chars.length && chars[i + 1] == ' ') { // SUBLINE
- builder.append(' ').append(TextFormatting.BOLD).append('*').append(TextFormatting.RESET)
- .append(' ');
- i++;
- } else if (chars[i] == '*' && i + 1 < chars.length && chars[i + 1] == '*') { // BOLD
- checkTextFormatting(builder, TextFormatting.BOLD, stack);
- i++;
- } else if (chars[i] == '_') {
- if (i - 1 == -1 || !Character.isLetterOrDigit(chars[i - 1])) { // ITALIC
- checkTextFormatting(builder, TextFormatting.ITALIC, stack);
- } else if (i + 1 == chars.length || !Character.isLetterOrDigit(chars[i + 1])) {
- checkTextFormatting(builder, TextFormatting.ITALIC, stack);
- } else {
- builder.append('_');
- }
- } else if (chars[i] == '~') { // STRIKETHROUGH
- checkTextFormatting(builder, TextFormatting.STRIKETHROUGH, stack);
- } else if (chars[i] == '`' && i + 1 < chars.length && chars[i + 1] == '`' && i + 2 < chars.length &&
- chars[i + 2] == '`') { // code
- boolean find = false;
- for (int j = i + 3; j < chars.length - 2; j++) {
- if (chars[j] == '`' && chars[j + 1] == '`' && chars[j + 2] == '`') {
- find = true;
- builder.append(checkCode(markdown.substring(i + 3, j)));
- i += j - i;
- }
- }
- if (!find) {
- builder.append("```");
- }
- i += 2;
- } else
- if (chars[i] == '`') {
- checkTextFormatting(builder, TextFormatting.UNDERLINE, stack);
- } else {
- builder.append((char) chars[i]);
- }
- }
- return builder.toString();
- }
-
- private static String checkCode(String code) {
- Pattern[] patterns = new Pattern[] { COMMENT, STRING, BOOL, KEYWORD, KEYWORD_2, VARIABLE, NUMBER, ANY };
- TextFormatting[] colors = new TextFormatting[] {
- TextFormatting.DARK_GRAY, // comment
- TextFormatting.DARK_GREEN, // string
- TextFormatting.RED, // value
- TextFormatting.BLUE, // keyword
- TextFormatting.LIGHT_PURPLE, // keyword2
- TextFormatting.BLACK, // variable
- TextFormatting.RED, // variable
- TextFormatting.DARK_PURPLE }; // else
- StringBuilder builder = new StringBuilder();
- while (code.length() > 0) {
- boolean find = false;
- for (int i = 0; i < patterns.length; i++) {
- Matcher matcher = patterns[i].matcher(code);
- if (matcher.find() && matcher.start() == 0) {
- builder.append(colors[i]).append(code, 0, matcher.end()).append(TextFormatting.RESET);
- find = true;
- code = code.substring(matcher.end());
- break;
- }
- }
- if (!find) {
- builder.append(code.charAt(0));
- code = code.substring(1);
- }
- }
- return builder.toString();
- }
-
- private static void checkTextFormatting(StringBuilder builder, TextFormatting formatting,
- Deque stack) {
- if (!stack.isEmpty() && stack.peek() == formatting) {
- builder.append(TextFormatting.RESET);
- stack.pop();
- for (TextFormatting pre : stack) {
- builder.append(pre.toString());
- }
- } else {
- stack.push(formatting);
- builder.append(formatting.toString());
- }
- }
-
- private static TextFormatting lookAheadChars(final String content, int index) {
- if (index > 1 && content.charAt(index - 2) == SECTION_SIGN) {
- int t = content.charAt(index - 1);
- if ('0' <= t && t <= '9') {
- return TextFormatting.values()[t - '0'];
- } else if ('a' <= t && t <= 'f') {
- return TextFormatting.values()[t - 'a' + 10];
- } else if ('k' <= t && t <= 'o') {
- return TextFormatting.values()[t - 'k' + 16];
- } else if (t == 'r') {
- return TextFormatting.values()[21];
- }
- }
- return null;
- }
-
- public static String cleanUpFormatting(final String content) {
- Set removed = new HashSet<>();
- Matcher marcher = R_CODE_PATTERN.matcher(content);
- while (marcher.find()) {
- int index = marcher.start();
- while (index > 1) {
- TextFormatting ahead = lookAheadChars(content, index);
- if (ahead != null) {
- removed.add(index - 2);
- } else {
- break;
- }
- index -= 2;
- }
- }
- marcher = COLOR_CODE_PATTERN.matcher(content);
- while (marcher.find()) {
- int index = marcher.start();
- while (index > 1) {
- TextFormatting ahead = lookAheadChars(content, index);
- if (ahead == null) {
- break;
- } else if (TextFormatting.RESET != ahead) {
- if (!removed.add(index - 2)) {
- break;
- }
- } else {
- break;
- }
- index -= 2;
- }
- }
- StringBuilder builder = new StringBuilder();
- AtomicInteger start = new AtomicInteger();
- removed.stream().sorted().forEach(remove -> {
- builder.append(content, start.get(), remove);
- start.set(remove + 2);
- });
- builder.append(content, start.get(), content.length());
- return builder.toString();
- }
-
- private void findFrontFormatting() {
- int lastReset = content.lastIndexOf(SECTION_SIGN + "r");
- int lastColor = -1;
- frontColor = null;
- frontStyle.clear();
- for (TextFormatting value : TextFormatting.values()) {
- int index = content.lastIndexOf(value.toString());
- if (index > lastReset) {
- if (value.isColor()) {
- if (index > lastColor) {
- lastColor = index;
- frontColor = value;
- }
- } else if (value.isFancyStyling() && index > lastColor) {
- frontStyle.add(value);
- }
- }
- }
- }
-
- public void addFormatting(TextFormatting formatting) {
- if (formatting.isColor()) {
- frontColor = formatting;
- pageInsertIntoCurrent(formatting.toString());
- for (TextFormatting style : frontStyle) {
- pageInsertIntoCurrent(style.toString());
- }
- } else if (formatting.isFancyStyling()) {
- if (frontStyle.contains(formatting)) {
- return;
- }
- frontStyle.add(formatting);
- pageInsertIntoCurrent(formatting.toString());
- }
- }
-
- public void removeFormatting(TextFormatting formatting) {
- if (formatting.isColor()) {
- frontColor = null;
- pageInsertIntoCurrent(TextFormatting.RESET.toString());
- frontStyle.forEach(style -> pageInsertIntoCurrent(style.toString()));
- } else if (formatting.isFancyStyling()) {
- pageInsertIntoCurrent(TextFormatting.RESET.toString());
- if (frontColor != null) {
- pageInsertIntoCurrent(frontColor.toString());
- }
- frontStyle.remove(formatting);
- frontStyle.forEach(style -> pageInsertIntoCurrent(style.toString()));
- }
- }
-
- public TextFormatting getFrontColorFormatting() {
- return frontColor;
- }
-
- public List getFrontStyleFormatting() {
- return frontStyle;
- }
-
- public void pageSetCurrent(String string) {
- if (!content.equals(string)) {
- content = cleanUpFormatting(string);
- findFrontFormatting();
- if (stringUpdate != null) {
- stringUpdate.accept(content);
- }
- textHeight = this.fontRenderer.getWordWrappedHeight(content + TextFormatting.BLACK + "_",
- this.getSize().width - yBarWidth);
- }
- }
-
- public void pageInsertIntoCurrent(String string) {
- content = cleanUpFormatting(content + string);
- if (stringUpdate != null) {
- stringUpdate.accept(content);
- }
- textHeight = this.fontRenderer.getWordWrappedHeight(content + TextFormatting.BLACK + "_",
- this.getSize().width - yBarWidth);
- }
-
- @Override
- public boolean hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- String contentString = content;
- if (focus && isActive()) {
- if (this.fontRenderer.getBidiFlag()) {
- contentString += "_";
- } else if (this.updateCount / 6 % 2 == 0) {
- contentString += TextFormatting.BLACK + "_";
- } else {
- contentString += TextFormatting.GRAY + "_";
- }
- }
- int x = getPosition().x - scrollXOffset;
- int y = getPosition().y + SPACE - scrollYOffset;
- for (String textLine : this.fontRenderer.listFormattedStringToWidth(contentString,
- getSize().width - yBarWidth)) {
- fontRenderer.drawString(textLine, x, y, 0xff000000, false);
- y += fontRenderer.FONT_HEIGHT;
- }
- return true;
- }
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/TreeListWidget.java b/src/main/java/gregtech/api/terminal/gui/widgets/TreeListWidget.java
deleted file mode 100644
index 45e5c12d55e..00000000000
--- a/src/main/java/gregtech/api/terminal/gui/widgets/TreeListWidget.java
+++ /dev/null
@@ -1,247 +0,0 @@
-package gregtech.api.terminal.gui.widgets;
-
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.Widget;
-import gregtech.api.gui.resources.IGuiTexture;
-import gregtech.api.terminal.util.TreeNode;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-import gregtech.client.utils.RenderUtil;
-
-import net.minecraft.client.Minecraft;
-import net.minecraft.client.gui.FontRenderer;
-import net.minecraft.client.renderer.GlStateManager;
-import net.minecraft.client.resources.I18n;
-import net.minecraft.util.math.MathHelper;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.function.Consumer;
-import java.util.function.Function;
-
-public class TreeListWidget extends Widget {
-
- private static final int ITEM_HEIGHT = 11;
- protected int scrollOffset;
- protected List> list;
- protected TreeNode selected;
- protected IGuiTexture background;
- protected IGuiTexture nodeTexture;
- protected IGuiTexture leafTexture;
- protected Consumer> onSelected;
- protected Function keyIconSupplier;
- protected Function keyNameSupplier;
- protected Function contentIconSupplier;
- protected Function contentNameSupplier;
- protected boolean canSelectNode;
- private int tick;
-
- public TreeListWidget(int xPosition, int yPosition, int width, int height,
- TreeNode root,
- Consumer> onSelected) {
- super(new Position(xPosition, yPosition), new Size(width, height));
- list = new ArrayList<>();
- if (root.getChildren() != null) {
- list.addAll(root.getChildren());
- }
- this.onSelected = onSelected;
- }
-
- public TreeListWidget canSelectNode(boolean canSelectNode) {
- this.canSelectNode = canSelectNode;
- return this;
- }
-
- public TreeListWidget setBackground(IGuiTexture background) {
- this.background = background;
- return this;
- }
-
- public TreeListWidget setNodeTexture(IGuiTexture nodeTexture) {
- this.nodeTexture = nodeTexture;
- return this;
- }
-
- public TreeListWidget setLeafTexture(IGuiTexture leafTexture) {
- this.leafTexture = leafTexture;
- return this;
- }
-
- public TreeListWidget setContentIconSupplier(Function iconSupplier) {
- contentIconSupplier = iconSupplier;
- return this;
- }
-
- public TreeListWidget setKeyIconSupplier(Function iconSupplier) {
- keyIconSupplier = iconSupplier;
- return this;
- }
-
- public TreeListWidget setContentNameSupplier(Function nameSupplier) {
- contentNameSupplier = nameSupplier;
- return this;
- }
-
- public TreeListWidget setKeyNameSupplier(Function nameSupplier) {
- keyNameSupplier = nameSupplier;
- return this;
- }
-
- @Override
- public void updateScreen() {
- tick++;
- }
-
- @Override
- public boolean mouseWheelMove(int mouseX, int mouseY, int wheelDelta) {
- if (this.isMouseOverElement(mouseX, mouseY)) {
- int moveDelta = -MathHelper.clamp(wheelDelta, -1, 1) * 5;
- this.scrollOffset = MathHelper.clamp(scrollOffset + moveDelta, 0,
- Math.max(list.size() * ITEM_HEIGHT - getSize().height, 0));
- return true;
- }
- return false;
- }
-
- @Override
- public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- int x = getPosition().x;
- int y = getPosition().y;
- int width = getSize().width;
- int height = getSize().height;
- if (background != null) {
- background.draw(x, y, width, height);
- } else {
- drawGradientRect(x, y, width, height, 0x8f000000, 0x8f000000);
- }
- RenderUtil.useScissor(x, y, width, height, () -> {
- FontRenderer fr = Minecraft.getMinecraft().fontRenderer;
- int minToRender = scrollOffset / ITEM_HEIGHT;
- int maxToRender = Math.min(list.size(), height / ITEM_HEIGHT + 2 + minToRender);
- for (int i = minToRender; i < maxToRender; i++) {
- GlStateManager.color(1, 1, 1, 1);
- TreeNode node = list.get(i);
- int sX = x + 10 * node.dimension;
- int sY = y - scrollOffset + i * ITEM_HEIGHT;
- String name = node.toString();
- if (node.isLeaf()) {
- if (leafTexture != null) {
- leafTexture.draw(x, sY, width, ITEM_HEIGHT);
- } else {
- drawSolidRect(x, sY, width, ITEM_HEIGHT, 0xffff0000);
- }
- if (node.getContent() != null) {
- String nameS = contentNameSupplier == null ? null :
- contentNameSupplier.apply(node.getContent());
- name = nameS == null ? name : nameS;
- IGuiTexture icon = contentIconSupplier == null ? null :
- contentIconSupplier.apply(node.getContent());
- if (icon != null) {
- icon.draw(sX - 9, sY + 1, 8, 8);
- }
- }
- } else {
- if (nodeTexture != null) {
- nodeTexture.draw(x, sY, width, ITEM_HEIGHT);
- } else {
- drawSolidRect(x, sY, width, ITEM_HEIGHT, 0xffffff00);
- }
- String nameS = keyNameSupplier == null ? null : keyNameSupplier.apply(node.getKey());
- name = nameS == null ? name : nameS;
- IGuiTexture icon = keyIconSupplier == null ? null : keyIconSupplier.apply(node.getKey());
- if (icon != null) {
- icon.draw(sX - 9, sY + 1, 8, 8);
- }
- }
- if (node == selected) {
- drawSolidRect(x, sY, width, ITEM_HEIGHT, 0x7f000000);
- }
- int textW = Math.max(width - 10 * node.dimension, 10);
- List list = fr.listFormattedStringToWidth(I18n.format(name), textW);
- fr.drawString(list.get(Math.abs((tick / 20) % list.size())), sX, sY + 2, 0xff000000);
- }
- });
- GlStateManager.enableBlend();
- GlStateManager.color(1, 1, 1, 1);
- }
-
- public TreeNode jumpTo(List path) {
- list.removeIf(node -> node.dimension != 1);
- this.selected = null;
- int dim = 1;
- int index = 0;
- boolean flag = false;
- TreeNode node = null;
- for (K key : path) {
- flag = false;
- for (int i = index; i < list.size(); i++) {
- node = list.get(i);
- if (node.dimension != dim) {
- return null;
- } else if (node.getKey().equals(key)) { // expand
- if (!node.isLeaf() && path.size() > dim) {
- for (int j = 0; j < node.getChildren().size(); j++) {
- list.add(index + 1 + j, node.getChildren().get(j));
- }
- }
- index++;
- dim++;
- flag = true;
- break;
- } else {
- index++;
- }
- }
- if (!flag) return null;
- }
- if (flag) {
- this.selected = node;
- this.scrollOffset = MathHelper.clamp(ITEM_HEIGHT * (index - 1), 0,
- Math.max(list.size() * ITEM_HEIGHT - getSize().height, 0));
- return this.selected;
- }
- return null;
- }
-
- @Override
- public boolean mouseClicked(int mouseX, int mouseY, int button) {
- if (this.isMouseOverElement(mouseX, mouseY)) {
- int index = ((mouseY - getPosition().y) + scrollOffset) / ITEM_HEIGHT;
- if (index < list.size()) {
- TreeNode node = list.get(index);
- if (node.isLeaf()) {
- if (node != this.selected) {
- this.selected = node;
- if (onSelected != null) {
- onSelected.accept(node);
- }
- }
- } else {
- if (canSelectNode && this.selected != node) {
- this.selected = node;
- if (onSelected != null) {
- onSelected.accept(node);
- }
- } else if (node.getChildren().size() > 0 && list.contains(node.getChildren().get(0))) {
- removeNode(node);
- } else {
- for (int i = 0; i < node.getChildren().size(); i++) {
- list.add(index + 1 + i, node.getChildren().get(i));
- }
- }
- }
- playButtonClickSound();
- }
- return true;
- }
- return false;
- }
-
- private void removeNode(TreeNode, T> node) {
- if (node.isLeaf()) return;
- for (TreeNode, T> child : node.getChildren()) {
- list.remove(child);
- removeNode(child);
- }
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/hardware/Hardware.java b/src/main/java/gregtech/api/terminal/hardware/Hardware.java
deleted file mode 100644
index 6a34ff4de48..00000000000
--- a/src/main/java/gregtech/api/terminal/hardware/Hardware.java
+++ /dev/null
@@ -1,101 +0,0 @@
-package gregtech.api.terminal.hardware;
-
-import gregtech.api.gui.GuiTextures;
-import gregtech.api.gui.resources.IGuiTexture;
-
-import net.minecraft.client.resources.I18n;
-import net.minecraft.item.ItemStack;
-import net.minecraft.nbt.NBTTagCompound;
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-/**
- * Created with IntelliJ IDEA.
- *
- * @Author: KilaBash
- * @Date: 2021/08/27
- * @Description: Hardware
- */
-public abstract class Hardware {
-
- protected HardwareProvider provider;
-
- public abstract String getRegistryName();
-
- @SideOnly(Side.CLIENT)
- public String getLocalizedName() {
- return I18n.format("terminal.hw." + getRegistryName());
- }
-
- @SideOnly(Side.CLIENT)
- public IGuiTexture getIcon() {
- return GuiTextures.ICON_REMOVE;
- }
-
- /**
- * Check whether the current hardware (this) meets requirement (demand);
- */
- public boolean isHardwareAdequate(Hardware demand) {
- return this.getClass() == demand.getClass() || this.getRegistryName().equals(demand.getRegistryName());
- }
-
- /**
- * Check whether the terminal has this hardware.
- */
- public final boolean hasHW() {
- return provider != null && provider.hasHardware(getRegistryName());
- }
-
- public final ItemStack getItem() {
- return provider.getHardwareItem(getRegistryName());
- }
-
- /**
- * Returns the NBT of the this hardware.
- */
- public final NBTTagCompound getNBT() {
- return provider.getHardwareNBT(getRegistryName());
- }
-
- /**
- * Check whether the terminal is in creative mode.
- */
- public final boolean isCreative() {
- return provider != null && provider.isCreative();
- }
-
- /**
- * information added to tooltips
- *
- * @return null->nothing added.
- */
- @SideOnly(Side.CLIENT)
- public String addInformation() {
- return null;
- }
-
- /**
- * Create the hardware instance, NOTE!!! do not check nbt or anything here. Terminal has not been initialized here.
- *
- * @param itemStack terminal
- * @return instance
- */
- protected abstract Hardware createHardware(ItemStack itemStack);
-
- /**
- * Use the item to install this hardware.
- *
- * @return The NBT of the hardware is returned if the item is valid, otherwise NULL is returned
- */
- public abstract NBTTagCompound acceptItemStack(ItemStack itemStack);
-
- /**
- * Called when the hardware is removed and back to the player inventory.
- *
- * @param itemStack (original one)
- * @return result
- */
- public ItemStack onHardwareRemoved(ItemStack itemStack) {
- return itemStack;
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/hardware/HardwareProvider.java b/src/main/java/gregtech/api/terminal/hardware/HardwareProvider.java
deleted file mode 100644
index 1df64c9efc0..00000000000
--- a/src/main/java/gregtech/api/terminal/hardware/HardwareProvider.java
+++ /dev/null
@@ -1,143 +0,0 @@
-package gregtech.api.terminal.hardware;
-
-import gregtech.api.capability.GregtechCapabilities;
-import gregtech.api.items.metaitem.stats.IItemCapabilityProvider;
-import gregtech.api.terminal.TerminalRegistry;
-import gregtech.common.items.behaviors.TerminalBehaviour;
-
-import net.minecraft.item.ItemStack;
-import net.minecraft.nbt.NBTTagCompound;
-import net.minecraft.util.EnumFacing;
-import net.minecraftforge.common.capabilities.Capability;
-import net.minecraftforge.common.capabilities.ICapabilityProvider;
-
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * Created with IntelliJ IDEA.
- *
- * @Author: KilaBash
- * @Date: 2021/08/28
- * @Description:
- */
-public class HardwareProvider implements ICapabilityProvider, IItemCapabilityProvider {
-
- private Map providers;
- private Map itemCache;
- private Boolean isCreative;
- private ItemStack itemStack;
- private NBTTagCompound tag;
-
- public HardwareProvider() {}
-
- public void cleanCache(String name) {
- itemCache.remove(name);
- }
-
- public boolean isCreative() {
- if (isCreative == null) {
- isCreative = TerminalBehaviour.isCreative(getItemStack());
- }
- return isCreative;
- }
-
- public Map getProviders() {
- return providers;
- }
-
- public ItemStack getItemStack() {
- return itemStack;
- }
-
- public NBTTagCompound getOrCreateHardwareCompound() {
- if (tag == null) {
- NBTTagCompound terminal = itemStack.getOrCreateSubCompound("terminal");
- if (!terminal.hasKey("_hw")) {
- terminal.setTag("_hw", new NBTTagCompound());
- }
- tag = terminal.getCompoundTag("_hw");
- }
- return tag;
- }
-
- public List getHardware() {
- if (TerminalBehaviour.isCreative(itemStack)) {
- return new ArrayList<>(providers.values());
- }
- return getOrCreateHardwareCompound().getKeySet().stream().map(providers::get).filter(Objects::nonNull)
- .collect(Collectors.toList());
- }
-
- public boolean hasHardware(String name) {
- return itemStack != null &&
- (TerminalBehaviour.isCreative(getItemStack()) || getOrCreateHardwareCompound().hasKey(name));
- }
-
- public NBTTagCompound getHardwareNBT(String name) {
- return getOrCreateHardwareCompound().getCompoundTag(name);
- }
-
- public ItemStack getHardwareItem(String name) {
- if (!itemCache.containsKey(name)) {
- NBTTagCompound tag = getHardwareNBT(name);
- if (tag.hasKey("item")) {
- itemCache.put(name, new ItemStack(tag.getCompoundTag("item")));
- } else {
- itemCache.put(name, ItemStack.EMPTY);
- }
- }
- return itemCache.get(name);
- }
-
- @Override
- public ICapabilityProvider createProvider(ItemStack itemStack) {
- HardwareProvider provider = new HardwareProvider();
- provider.providers = new LinkedHashMap<>();
- provider.itemCache = new HashMap<>();
- provider.itemStack = itemStack;
- for (Hardware hardware : TerminalRegistry.getAllHardware()) {
- Hardware instance = hardware.createHardware(itemStack);
- if (instance != null) {
- instance.provider = provider;
- provider.providers.put(hardware.getRegistryName(), instance);
- }
- }
- return provider;
- }
-
- @Override
- public boolean hasCapability(@NotNull Capability> capability, @Nullable EnumFacing facing) {
- if (providers != null) {
- for (Map.Entry entry : providers.entrySet()) {
- Hardware provider = entry.getValue();
- if (provider instanceof IHardwareCapability &&
- hasHardware(entry.getKey()) &&
- ((IHardwareCapability) provider).hasCapability(capability)) {
- return true;
- }
- }
- }
- return capability == GregtechCapabilities.CAPABILITY_HARDWARE_PROVIDER;
- }
-
- @Nullable
- @Override
- public T getCapability(@NotNull Capability capability, @Nullable EnumFacing facing) {
- if (providers != null) {
- for (Map.Entry entry : providers.entrySet()) {
- Hardware provider = entry.getValue();
- if (provider instanceof IHardwareCapability &&
- hasHardware(entry.getKey()) &&
- ((IHardwareCapability) provider).hasCapability(capability)) {
- return ((IHardwareCapability) provider).getCapability(capability);
- }
- }
- }
- return capability == GregtechCapabilities.CAPABILITY_HARDWARE_PROVIDER ?
- GregtechCapabilities.CAPABILITY_HARDWARE_PROVIDER.cast(this) : null;
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/hardware/IHardwareCapability.java b/src/main/java/gregtech/api/terminal/hardware/IHardwareCapability.java
deleted file mode 100644
index a02caa5b76f..00000000000
--- a/src/main/java/gregtech/api/terminal/hardware/IHardwareCapability.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package gregtech.api.terminal.hardware;
-
-import net.minecraftforge.common.capabilities.Capability;
-
-import org.jetbrains.annotations.NotNull;
-
-public interface IHardwareCapability {
-
- default boolean hasCapability(@NotNull Capability> capability) {
- return getCapability(capability) != null;
- }
-
- T getCapability(@NotNull Capability capability);
-}
diff --git a/src/main/java/gregtech/api/terminal/os/SystemCall.java b/src/main/java/gregtech/api/terminal/os/SystemCall.java
deleted file mode 100644
index 2110775b5db..00000000000
--- a/src/main/java/gregtech/api/terminal/os/SystemCall.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package gregtech.api.terminal.os;
-
-import gregtech.api.terminal.TerminalRegistry;
-import gregtech.api.terminal.app.AbstractApplication;
-import gregtech.api.util.function.TriConsumer;
-
-public enum SystemCall {
-
- CALL_MENU("call_menu", 0, (os, side, args) -> os.callMenu(side)),
- FULL_SCREEN("full_screen", 1, (os, side, args) -> os.maximize(side)),
- MINIMIZE_FOCUS_APP("minimize_focus_app", 2, (os, side, args) -> os.minimizeApplication(os.getFocusApp(), side)),
- CLOSE_FOCUS_APP("close_focus_app", 3, (os, side, args) -> os.closeApplication(os.getFocusApp(), side)),
- SHUT_DOWN("shutdown", 4, (os, side, args) -> os.shutdown(side)),
- OPEN_APP("open_app", 5, (os, side, args) -> {
- if (args.length > 0 && args[0] != null) {
- AbstractApplication app = TerminalRegistry.getApplication(args[0]);
- if (app != null) {
- os.openApplication(app, side);
- }
- }
- });
-
- TriConsumer action;
- String name;
- int index;
-
- SystemCall(String name, int index, TriConsumer action) {
- this.action = action;
- this.name = name;
- this.index = index;
- }
-
- public void call(TerminalOSWidget os, boolean isClient, String... args) {
- action.accept(os, isClient, args);
- }
-
- public String getTranslateKey() {
- return "terminal.system_call." + name;
- }
-
- public static SystemCall getFromName(String name) {
- for (SystemCall value : SystemCall.values()) {
- if (value.name.equalsIgnoreCase(name)) {
- return value;
- } else if (value.getTranslateKey().equals(name)) {
- return value;
- }
- }
- return null;
- }
-
- public static SystemCall getFromIndex(int index) {
- for (SystemCall value : SystemCall.values()) {
- if (value.index == index) {
- return value;
- }
- }
- return null;
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/os/TerminalDesktopWidget.java b/src/main/java/gregtech/api/terminal/os/TerminalDesktopWidget.java
deleted file mode 100644
index 19ad7f969b2..00000000000
--- a/src/main/java/gregtech/api/terminal/os/TerminalDesktopWidget.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package gregtech.api.terminal.os;
-
-import gregtech.api.gui.Widget;
-import gregtech.api.gui.widgets.WidgetGroup;
-import gregtech.api.terminal.app.AbstractApplication;
-import gregtech.api.terminal.gui.widgets.CircleButtonWidget;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-import java.util.LinkedList;
-import java.util.List;
-
-public class TerminalDesktopWidget extends WidgetGroup {
-
- private final TerminalOSWidget os;
- private final WidgetGroup appDiv;
- private final List topWidgets;
- private int rowCount = 7;
-
- public TerminalDesktopWidget(Position position, Size size, TerminalOSWidget os) {
- super(position, size);
- this.os = os;
- this.appDiv = new WidgetGroup();
- this.addWidget(appDiv);
- this.topWidgets = new LinkedList<>();
- }
-
- public void installApplication(AbstractApplication application) {
- int r = 12;
- int index = appDiv.widgets.size();
- int x = this.getSize().width / 2 + (3 * r) * (index % rowCount - rowCount / 2);
- int y = (index / rowCount) * (3 * r) + 40;
- CircleButtonWidget button = new CircleButtonWidget(x, y)
- .setColors(TerminalTheme.COLOR_B_2.getColor(),
- application.getThemeColor(),
- TerminalTheme.COLOR_B_2.getColor())
- .setIcon(application.getIcon())
- .setHoverText(application.getUnlocalizedName());
- button.setClickListener(clickData -> os.openApplication(application, clickData.isClient));
- appDiv.addWidget(button);
- }
-
- @SideOnly(Side.CLIENT)
- public void addTopWidget(Widget widget) {
- topWidgets.add(widget);
- }
-
- @SideOnly(Side.CLIENT)
- public void removeTopWidget(Widget widget) {
- topWidgets.remove(widget);
- }
-
- @SideOnly(Side.CLIENT)
- private static boolean topWidgetsMouseOver(Widget widget, int mouseX, int mouseY) {
- if (widget.isMouseOverElement(mouseX, mouseY)) {
- return true;
- }
- if (widget instanceof WidgetGroup) {
- for (Widget child : ((WidgetGroup) widget).widgets) {
- if (child.isVisible() && topWidgetsMouseOver(child, mouseX, mouseY)) {
- return true;
- }
- }
- }
- return false;
- }
-
- @Override
- public void drawInForeground(int mouseX, int mouseY) {
- boolean isBlocked = false;
- for (Widget topWidget : topWidgets) {
- if (topWidgetsMouseOver(topWidget, mouseX, mouseY)) {
- isBlocked = true;
- break;
- }
- }
- for (Widget widget : widgets) {
- if (widget.isVisible() && !(isBlocked && widget instanceof AbstractApplication)) {
- widget.drawInForeground(mouseX, mouseY);
- }
- }
- }
-
- public void showDesktop() {
- appDiv.setActive(true);
- appDiv.setVisible(true);
- }
-
- public void hideDesktop() {
- appDiv.setActive(false);
- appDiv.setVisible(false);
- }
-
- public void removeAllDialogs() {
- for (Widget widget : widgets) {
- if (widget instanceof TerminalDialogWidget) {
- ((TerminalDialogWidget) widget).close();
- }
- }
- }
-
- @Override
- public void setSize(Size size) {
- super.setSize(size);
- this.rowCount = (size.width - 81) / 36;
- int r = 12;
- for (int i = appDiv.widgets.size() - 1; i >= 0; i--) {
- Widget widget = appDiv.widgets.get(i);
- int x = this.getSize().width / 2 + (3 * r) * (i % rowCount - rowCount / 2);
- int y = (i / rowCount) * (3 * r) + 40;
- widget.setSelfPosition(new Position(x - r, y - r));
- }
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/os/TerminalDialogWidget.java b/src/main/java/gregtech/api/terminal/os/TerminalDialogWidget.java
deleted file mode 100644
index 30cd7ee1150..00000000000
--- a/src/main/java/gregtech/api/terminal/os/TerminalDialogWidget.java
+++ /dev/null
@@ -1,421 +0,0 @@
-package gregtech.api.terminal.os;
-
-import gregtech.api.gui.GuiTextures;
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.Widget;
-import gregtech.api.gui.resources.ColorRectTexture;
-import gregtech.api.gui.resources.IGuiTexture;
-import gregtech.api.gui.resources.TextureArea;
-import gregtech.api.gui.widgets.*;
-import gregtech.api.terminal.gui.widgets.AnimaWidgetGroup;
-import gregtech.api.terminal.gui.widgets.CircleButtonWidget;
-import gregtech.api.terminal.gui.widgets.ColorWidget;
-import gregtech.api.terminal.gui.widgets.TreeListWidget;
-import gregtech.api.terminal.util.FileTree;
-import gregtech.api.util.GTLog;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-
-import net.minecraft.client.renderer.GlStateManager;
-import net.minecraft.client.resources.I18n;
-import net.minecraft.inventory.IInventory;
-import net.minecraft.item.ItemStack;
-import net.minecraft.network.PacketBuffer;
-
-import java.awt.*;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.Consumer;
-import java.util.function.Predicate;
-
-public class TerminalDialogWidget extends AnimaWidgetGroup {
-
- private static final IGuiTexture DIALOG_BACKGROUND = TextureArea
- .fullImage("textures/gui/terminal/terminal_dialog.png");
- private static final IGuiTexture OK_NORMAL = TextureArea.fullImage("textures/gui/terminal/icon/ok_normal.png");
- private static final IGuiTexture OK_HOVER = TextureArea.fullImage("textures/gui/terminal/icon/ok_hover.png");
- // private static final IGuiTexture OK_DISABLE = TextureArea.fullImage("textures/gui/terminal/icon/ok_disable.png");
- private static final IGuiTexture CANCEL_NORMAL = TextureArea
- .fullImage("textures/gui/terminal/icon/cancel_normal.png");
- private static final IGuiTexture CANCEL_HOVER = TextureArea
- .fullImage("textures/gui/terminal/icon/cancel_hover.png");
- // private static final IGuiTexture CANCEL_DISABLE =
- // TextureArea.fullImage("textures/gui/terminal/icon/cancel_disable.png");
- private static final int HEIGHT = 128;
- private static final int WIDTH = 184;
-
- private final TerminalOSWidget os;
- private IGuiTexture background;
- private boolean isClient;
- private List iNativeWidgets;
- boolean isClosed;
-
- public TerminalDialogWidget(TerminalOSWidget os, int x, int y, int width, int height) {
- super(x, y, width, height);
- this.os = os;
- }
-
- public boolean isClient() {
- return isClient;
- }
-
- public TerminalDialogWidget open() {
- os.openDialog(this);
- if (iNativeWidgets != null) {
- iNativeWidgets.forEach(this::addWidget);
- }
- if (isRemote()) {
- os.desktop.addTopWidget(this);
- }
- return this;
- }
-
- public void close() {
- if (isClosed) return;
- isClosed = true;
- os.closeDialog(this);
- if (isRemote()) {
- os.desktop.removeTopWidget(this);
- }
- }
-
- /**
- * Should be a client side dialog.
- * This is very important, please make sure the right side.
- */
- public TerminalDialogWidget setClientSide() {
- this.isClient = true;
- return this;
- }
-
- public TerminalDialogWidget setBackground(IGuiTexture background) {
- this.background = background;
- return this;
- }
-
- public TerminalDialogWidget addOkButton(Runnable callback) {
- addWidget(new CircleButtonWidget(WIDTH / 2, HEIGHT - 22, 12, 0, 24)
- .setClickListener(cd -> {
- close();
- if (callback != null)
- callback.run();
- })
- .setColors(0, 0, 0)
- .setIcon(OK_NORMAL)
- .setHoverIcon(OK_HOVER));
- return this;
- }
-
- public TerminalDialogWidget addConfirmButton(Consumer result) {
- addWidget(new CircleButtonWidget(WIDTH / 2 - 30, HEIGHT - 22, 12, 0, 24)
- .setClickListener(cd -> {
- close();
- if (result != null)
- result.accept(true);
- })
- .setColors(0, 0, 0)
- .setIcon(OK_NORMAL)
- .setHoverIcon(OK_HOVER));
- addWidget(new CircleButtonWidget(WIDTH / 2 + 30, HEIGHT - 22, 12, 0, 24)
- .setClickListener(cd -> {
- close();
- if (result != null)
- result.accept(false);
- })
- .setColors(0, 0, 0)
- .setIcon(CANCEL_NORMAL)
- .setHoverIcon(CANCEL_HOVER));
- return this;
- }
-
- public TerminalDialogWidget addTitle(String title) {
- this.addWidget(new LabelWidget(WIDTH / 2, 11, title, -1).setXCentered(true));
- return this;
- }
-
- public TerminalDialogWidget addInfo(String info) {
- this.addWidget(new LabelWidget(WIDTH / 2, HEIGHT / 2, info, -1).setWidth(WIDTH - 16).setYCentered(true)
- .setXCentered(true));
- return this;
- }
-
- public static TerminalDialogWidget createEmptyTemplate(TerminalOSWidget os) {
- Size size = os.getSize();
- return new TerminalDialogWidget(os, (size.width - WIDTH) / 2, (size.height - HEIGHT) / 2, WIDTH, HEIGHT)
- .setBackground(DIALOG_BACKGROUND);
- }
-
- public static TerminalDialogWidget showInfoDialog(TerminalOSWidget os, String title, String info,
- Runnable callback) {
- return createEmptyTemplate(os).addTitle(title).addInfo(info).addOkButton(callback);
- }
-
- public static TerminalDialogWidget showInfoDialog(TerminalOSWidget os, String title, String info) {
- return createEmptyTemplate(os).addTitle(title).addInfo(info).addOkButton(null);
- }
-
- public static TerminalDialogWidget showConfirmDialog(TerminalOSWidget os, String title, String info,
- Consumer result) {
- return createEmptyTemplate(os).addConfirmButton(result).addTitle(title).addInfo(info);
- }
-
- public static TerminalDialogWidget showTextFieldDialog(TerminalOSWidget os, String title,
- Predicate validator, Consumer result) {
- TextFieldWidget textFieldWidget = new TextFieldWidget(WIDTH / 2 - 50, HEIGHT / 2 - 15, 100, 20,
- new ColorRectTexture(0x2fffffff), null, null).setValidator(validator);
- TerminalDialogWidget dialog = createEmptyTemplate(os).addTitle(title).addConfirmButton(b -> {
- if (b) {
- if (result != null)
- result.accept(textFieldWidget.getCurrentString());
- } else {
- if (result != null)
- result.accept(null);
- }
- });
- dialog.addWidget(textFieldWidget);
- return dialog;
- }
-
- /**
- * Show Color Dialog
- *
- * @return color (rgba)
- */
- public static TerminalDialogWidget showColorDialog(TerminalOSWidget os, String title, Consumer result,
- int startColor) {
- TerminalDialogWidget dialog = createEmptyTemplate(os).addTitle(title);
- ColorWidget colorWidget = new ColorWidget(WIDTH / 2 - 60, HEIGHT / 2 - 35, 80, 10);
- colorWidget.setStartColor(startColor);
- dialog.addWidget(colorWidget);
- dialog.addConfirmButton(b -> {
- if (b) {
- if (result != null)
- result.accept(colorWidget.getColor());
- } else {
- if (result != null)
- result.accept(null);
- }
- });
- return dialog;
- }
-
- /**
- * Show FileDialog
- *
- * @param dir root directory
- * @param isSelector select a file or save a file
- * @param result selected file or (saved)
- */
- public static TerminalDialogWidget showFileDialog(TerminalOSWidget os, String title, File dir, boolean isSelector,
- Consumer result) {
- Size size = os.getSize();
- TerminalDialogWidget dialog = new TerminalDialogWidget(os, 0, 0, size.width, size.height)
- .setBackground(new ColorRectTexture(0x4f000000));
- if (!dir.isDirectory()) {
- if (!dir.mkdirs()) {
- return dialog.addInfo(I18n.format("terminal.dialog.error_path") + dir.getPath()).addOkButton(null);
- }
- }
- AtomicReference selected = new AtomicReference<>();
- selected.set(dir);
- dialog.addWidget(
- new TreeListWidget<>(0, 0, 130, size.height, new FileTree(dir), node -> selected.set(node.getKey()))
- .setNodeTexture(GuiTextures.BORDERED_BACKGROUND)
- .canSelectNode(true)
- .setLeafTexture(GuiTextures.SLOT_DARKENED));
- int x = 130 + (size.width - 133 - WIDTH) / 2;
- int y = (size.height - HEIGHT) / 2;
- dialog.addWidget(new ImageWidget(x, y, WIDTH, HEIGHT, DIALOG_BACKGROUND));
- dialog.addWidget(new CircleButtonWidget(x + WIDTH / 2 - 30, y + HEIGHT - 22, 12, 0, 24)
- .setClickListener(cd -> {
- dialog.close();
- if (result != null)
- result.accept(selected.get());
- })
- .setColors(0, 0, 0)
- .setIcon(OK_NORMAL)
- .setHoverIcon(OK_HOVER));
- dialog.addWidget(new CircleButtonWidget(x + WIDTH / 2 + 30, y + HEIGHT - 22, 12, 0, 24)
- .setClickListener(cd -> {
- dialog.close();
- if (result != null)
- result.accept(null);
- })
- .setColors(0, 0, 0)
- .setIcon(CANCEL_NORMAL)
- .setHoverIcon(CANCEL_HOVER));
- if (isSelector) {
- dialog.addWidget(new SimpleTextWidget(x + WIDTH / 2, y + HEIGHT / 2 - 5, "", -1, () -> {
- if (selected.get() != null) {
- return selected.get().toString();
- }
- return "terminal.dialog.no_file_selected";
- }, true).setWidth(WIDTH - 16));
- } else {
- dialog.addWidget(new TextFieldWidget(x + WIDTH / 2 - 38, y + HEIGHT / 2 - 10, 76, 20,
- new ColorRectTexture(0x4f000000), null, null)
- .setTextResponder(res -> {
- File file = selected.get();
- if (file == null) return;
- if (file.isDirectory()) {
- selected.set(new File(file, res));
- } else {
- selected.set(new File(file.getParent(), res));
- }
- }, true)
- .setTextSupplier(() -> {
- File file = selected.get();
- if (file != null && !file.isDirectory()) {
- return selected.get().getName();
- }
- return "";
- }, true)
- .setMaxStringLength(Integer.MAX_VALUE)
- .setValidator(s -> true));
- }
- dialog.addWidget(new CircleButtonWidget(x + 17, y + 15, 10, 1, 16)
- .setClickListener(cd -> {
- File file = selected.get();
- if (file != null && Desktop.isDesktopSupported()) {
- try {
- Desktop.getDesktop().open(file.isDirectory() ? file : file.getParentFile());
- } catch (IOException e) {
- GTLog.logger.error("Error reading opening file " + file.getPath(), e);
- }
- }
- })
- .setColors(0, 0xFFFFFFFF, 0)
- .setHoverText("terminal.dialog.folder")
- .setIcon(GuiTextures.ICON_LOAD));
- dialog.addWidget(new LabelWidget(x + WIDTH / 2, y + 11, title, -1).setXCentered(true));
- if (os.isRemote()) {
- os.menu.hideMenu();
- }
- return dialog.setClientSide();
- }
-
- public static TerminalDialogWidget showItemSelector(TerminalOSWidget os, String title, boolean cost,
- Predicate filter, Consumer result) {
- TerminalDialogWidget dialog = createEmptyTemplate(os);
- dialog.addWidget(new LabelWidget(WIDTH / 2, -7, title, -1).setShadow(true).setXCentered(true));
- IInventory inventoryPlayer = os.getModularUI().entityPlayer.inventory;
- if (dialog.iNativeWidgets == null) {
- dialog.iNativeWidgets = new ArrayList<>();
- }
- int x = 11;
- int y = 30;
- final SlotWidget[] selected = { null };
- for (int row = 0; row < 4; row++) {
- for (int col = 0; col < 9; col++) {
- boolean pass = filter == null || filter.test(inventoryPlayer.getStackInSlot(col + row * 9));
- SlotWidget slotWidget = new SlotWidget(inventoryPlayer, col + row * 9, x + col * 18,
- (int) (y + (row == 0 ? -1.2 : (row - 1)) * 18), false, false) {
-
- @Override
- public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- super.drawInBackground(mouseX, mouseY, partialTicks, context);
- if (selected[0] == this) {
- drawBorder(getPosition().x, getPosition().y, getSize().width, getSize().height, -1, 1);
- }
- }
-
- @Override
- public boolean mouseClicked(int mouseX, int mouseY, int button) {
- if (pass && isMouseOverElement(mouseX, mouseY)) {
- if (selected[0] == this) {
- selected[0] = null;
- } else {
- selected[0] = this;
- }
- writeClientAction(7, buffer -> buffer.writeBoolean(selected[0] == this));
- }
- return super.mouseClicked(mouseX, mouseY, button);
- }
-
- @Override
- public void handleClientAction(int id, PacketBuffer buffer) {
- if (id == 7) {
- if (buffer.readBoolean()) {
- selected[0] = this;
- } else {
- selected[0] = null;
- }
- }
- super.readUpdateInfo(id, buffer);
- }
- }.setBackgroundTexture(TerminalTheme.COLOR_B_1).setLocationInfo(true, false);
- slotWidget.setActive(pass);
- dialog.iNativeWidgets.add(slotWidget);
- }
- }
- dialog.addConfirmButton(confirm -> {
- if (result != null && confirm && selected[0] != null && !selected[0].getHandle().getStack().isEmpty()) {
- ItemStack stack = selected[0].getHandle().getStack().copy();
- if (cost) {
- selected[0].getHandle().getStack().setCount(stack.getCount() - 1);
- }
- stack.setCount(1);
- result.accept(stack);
- }
- });
- return dialog;
- }
-
- @Override
- public void hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- GlStateManager.disableDepth();
- if (background != null) {
- background.draw(getPosition().x, getPosition().y, getSize().width, getSize().height);
- }
- super.hookDrawInBackground(mouseX, mouseY, partialTicks, context);
- GlStateManager.enableDepth();
- }
-
- @Override
- public boolean mouseClicked(int mouseX, int mouseY, int button) {
- for (int i = widgets.size() - 1; i >= 0; i--) {
- Widget widget = widgets.get(i);
- if (widget.isVisible()) {
- if (widget.mouseClicked(mouseX, mouseY, button)) {
- return true;
- }
- }
- }
- return true;
- }
-
- @Override
- protected void writeClientAction(int id, Consumer packetBufferWriter) {
- if (isClient || isClosed) return;
- super.writeClientAction(id, packetBufferWriter);
- }
-
- @Override
- public void handleClientAction(int id, PacketBuffer buffer) {
- if (id == -1) { // esc close
- if (buffer.readBoolean()) {
- close();
- }
- } else {
- super.handleClientAction(id, buffer);
- }
- }
-
- @Override
- public boolean keyTyped(char charTyped, int keyCode) {
- if (keyCode == 1 && super.interpolator == null) {
- writeClientAction(-1, buffer -> buffer.writeBoolean(true));
- close();
- return true;
- }
- return super.keyTyped(charTyped, keyCode);
- }
-
- public void onOSSizeUpdate(int width, int height) {
- setSelfPosition(
- Position.ORIGIN.add(new Position((width - getSize().width) / 2, (height - getSize().height) / 2)));
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/os/TerminalHomeButtonWidget.java b/src/main/java/gregtech/api/terminal/os/TerminalHomeButtonWidget.java
deleted file mode 100644
index 0b9c7683e4c..00000000000
--- a/src/main/java/gregtech/api/terminal/os/TerminalHomeButtonWidget.java
+++ /dev/null
@@ -1,145 +0,0 @@
-package gregtech.api.terminal.os;
-
-import gregtech.api.terminal.TerminalRegistry;
-import gregtech.api.terminal.gui.widgets.CircleButtonWidget;
-import gregtech.api.util.GTLog;
-
-import net.minecraft.nbt.CompressedStreamTools;
-import net.minecraft.nbt.NBTTagCompound;
-import net.minecraft.network.PacketBuffer;
-import net.minecraftforge.fml.common.FMLCommonHandler;
-
-import org.apache.commons.lang3.tuple.MutablePair;
-import org.apache.commons.lang3.tuple.Pair;
-
-import java.io.File;
-import java.io.IOException;
-
-public class TerminalHomeButtonWidget extends CircleButtonWidget {
-
- private final TerminalOSWidget os;
- private int mouseClickTime = -1;
- private final Pair[] actions;
-
- public TerminalHomeButtonWidget(TerminalOSWidget os) {
- super(351, 115, 11, 2, 18);
- this.os = os;
- this.setColors(0, TerminalTheme.COLOR_F_1.getColor(), 0);
- this.actions = new Pair[8];
- if (FMLCommonHandler.instance().getSide().isClient()) {
- NBTTagCompound nbt = null;
- try {
- nbt = CompressedStreamTools.read(new File(TerminalRegistry.TERMINAL_PATH, "config/home_button.nbt"));
- } catch (IOException e) {
- GTLog.logger.error("error while loading local nbt for the home button", e);
- }
- if (nbt == null) {
- actions[actionMap(false, false, false)] = new MutablePair<>(SystemCall.CALL_MENU, null);
- actions[actionMap(true, false, false)] = new MutablePair<>(SystemCall.MINIMIZE_FOCUS_APP, null);
- } else {
- for (int i = 0; i < actions.length; i++) {
- if (nbt.hasKey(String.valueOf(i))) {
- NBTTagCompound tag = nbt.getCompoundTag(String.valueOf(i));
- actions[i] = new MutablePair<>(SystemCall.getFromIndex(tag.getInteger("action")),
- tag.hasKey("arg") ? tag.getString("arg") : null);
- }
- }
- }
- }
- }
-
- public Pair[] getActions() {
- return actions;
- }
-
- public static int actionMap(boolean doubleClick, boolean isCtrl, boolean isShift) {
- return (doubleClick ? 1 : 0) + (isCtrl ? 2 : 0) + (isShift ? 4 : 0);
- }
-
- public void saveConfig() {
- if (FMLCommonHandler.instance().getSide().isClient()) {
- NBTTagCompound nbt = new NBTTagCompound();
- for (int i = 0; i < actions.length; i++) {
- if (actions[i] != null) {
- NBTTagCompound tag = new NBTTagCompound();
- tag.setInteger("action", actions[i].getKey().index);
- if (actions[i].getValue() != null) {
- tag.setString("arg", actions[i].getValue());
- }
- nbt.setTag(String.valueOf(i), tag);
- }
- }
- try {
- if (!nbt.isEmpty()) {
- CompressedStreamTools.safeWrite(nbt,
- new File(TerminalRegistry.TERMINAL_PATH, "config/home_button.nbt"));
- }
- } catch (IOException e) {
- GTLog.logger.error("error while saving local nbt for the home button", e);
- }
- }
- }
-
- private void click(int index, boolean isClient, String... args) {
- SystemCall action = SystemCall.getFromIndex(index);
- if (action != null) {
- action.call(os, isClient, args);
- }
- }
-
- @Override
- public void handleClientAction(int id, PacketBuffer buffer) {
- if (id == 1) {
- int index = buffer.readVarInt();
- int length = buffer.readVarInt();
- String[] args = new String[length];
- for (int i = 0; i < length; i++) {
- args[i] = buffer.readString(32767);
- }
- click(index, false, args);
- }
- }
-
- @Override
- public void updateScreen() {
- super.updateScreen();
- if (mouseClickTime > 3) { // click
- Pair pair = actions[actionMap(false, isCtrlDown(), isShiftDown())];
- sendToServer(pair);
- playButtonClickSound();
- mouseClickTime = -1;
- } else if (mouseClickTime > -1) {
- mouseClickTime++;
- }
- }
-
- @Override
- public boolean mouseClicked(int mouseX, int mouseY, int button) {
- if (isMouseOverElement(mouseX, mouseY)) {
- if (mouseClickTime == -1) {
- mouseClickTime = 0;
- } else if (mouseClickTime <= 3) { // double click
- Pair pair = actions[actionMap(true, isCtrlDown(), isShiftDown())];
- sendToServer(pair);
- playButtonClickSound();
- mouseClickTime = -1;
- }
- return true;
- }
- return false;
- }
-
- private void sendToServer(Pair pair) {
- if (pair != null) {
- String[] args = pair.getValue() == null ? new String[0] : pair.getValue().split(" ");
- writeClientAction(1, buffer -> {
- buffer.writeVarInt(pair.getKey().index);
- buffer.writeVarInt(args.length);
- for (String arg : args) {
- buffer.writeString(arg);
- }
- });
- click(pair.getKey().index, true, args);
- }
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/os/TerminalOSWidget.java b/src/main/java/gregtech/api/terminal/os/TerminalOSWidget.java
deleted file mode 100644
index 518609c585a..00000000000
--- a/src/main/java/gregtech/api/terminal/os/TerminalOSWidget.java
+++ /dev/null
@@ -1,543 +0,0 @@
-package gregtech.api.terminal.os;
-
-import gregtech.api.capability.GregtechCapabilities;
-import gregtech.api.capability.IElectricItem;
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.ModularUI;
-import gregtech.api.gui.Widget;
-import gregtech.api.gui.resources.IGuiTexture;
-import gregtech.api.gui.resources.TextureArea;
-import gregtech.api.gui.widgets.AbstractWidgetGroup;
-import gregtech.api.terminal.TerminalRegistry;
-import gregtech.api.terminal.app.AbstractApplication;
-import gregtech.api.terminal.hardware.Hardware;
-import gregtech.api.terminal.hardware.HardwareProvider;
-import gregtech.api.terminal.os.menu.TerminalMenuWidget;
-import gregtech.api.util.GTLog;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-import gregtech.client.utils.RenderUtil;
-import gregtech.common.items.behaviors.TerminalBehaviour;
-import gregtech.common.terminal.app.settings.widgets.OsSettings;
-import gregtech.common.terminal.hardware.BatteryHardware;
-import gregtech.common.terminal.hardware.DeviceHardware;
-
-import net.minecraft.client.Minecraft;
-import net.minecraft.client.resources.I18n;
-import net.minecraft.item.ItemStack;
-import net.minecraft.nbt.*;
-import net.minecraft.network.PacketBuffer;
-import net.minecraft.util.math.BlockPos;
-import net.minecraftforge.common.util.Constants;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.stream.Collectors;
-
-public class TerminalOSWidget extends AbstractWidgetGroup {
-
- public static final TextureArea TERMINAL_FRAME = TextureArea.fullImage("textures/gui/terminal/terminal_frame.png");
- public static final TextureArea TERMINAL_HOME = TextureArea.fullImage("textures/gui/terminal/terminal_home.png");
- public static final int DEFAULT_WIDTH = 333;
- public static final int DEFAULT_HEIGHT = 232;
-
- private IGuiTexture background;
- private AbstractApplication focusApp;
- public final NBTTagCompound tabletNBT;
- public final List openedApps;
- public final List installedApps;
- public final TerminalMenuWidget menu;
- public final TerminalDesktopWidget desktop;
- public final TerminalHomeButtonWidget home;
- public final BlockPos clickPos;
- public final ItemStack itemStack;
- public final HardwareProvider hardwareProvider;
- private int tickCounter;
- private long lastCharge;
- private boolean maximize;
- private boolean showMenuHover = false;
-
- public TerminalOSWidget(int xPosition, int yPosition, ItemStack itemStack) {
- super(new Position(xPosition, yPosition), new Size(DEFAULT_WIDTH, DEFAULT_HEIGHT));
- this.background = TerminalTheme.WALL_PAPER;
- this.openedApps = new ArrayList<>();
- this.installedApps = new ArrayList<>();
- this.desktop = new TerminalDesktopWidget(Position.ORIGIN, new Size(DEFAULT_WIDTH, DEFAULT_HEIGHT), this);
- this.menu = new TerminalMenuWidget(Position.ORIGIN, new Size(31, DEFAULT_HEIGHT), this)
- .setBackground(TerminalTheme.COLOR_B_2);
- this.home = new TerminalHomeButtonWidget(this);
- this.addWidget(desktop);
- this.addWidget(menu);
- this.addWidget(home);
- this.itemStack = itemStack;
- this.tabletNBT = itemStack.getOrCreateSubCompound("terminal");
- this.tabletNBT.removeTag("_ar");
- this.hardwareProvider = itemStack.getCapability(GregtechCapabilities.CAPABILITY_HARDWARE_PROVIDER, null);
- if (TerminalBehaviour.isCreative(itemStack)) {
- TerminalRegistry.getAllApps().forEach(this::installApplication);
- } else {
- TerminalRegistry.getDefaultApps().forEach(this::installApplication);
- NBTTagList installed = tabletNBT.getTagList("_installed", Constants.NBT.TAG_STRING);
- for (NBTBase nbtBase : installed) {
- if (nbtBase instanceof NBTTagString) {
- AbstractApplication app = TerminalRegistry.getApplication(((NBTTagString) nbtBase).getString());
- if (app != null) {
- installApplication(app);
- }
- }
- }
- }
- if (tabletNBT.hasKey("_click")) {
- clickPos = NBTUtil.getPosFromTag(tabletNBT.getCompoundTag("_click"));
- } else {
- clickPos = null;
- }
- }
-
- public ModularUI getModularUI() {
- return this.gui;
- }
-
- public TerminalOSWidget setBackground(IGuiTexture background) {
- this.background = background;
- return this;
- }
-
- public AbstractApplication getFocusApp() {
- return focusApp;
- }
-
- public List getHardware() {
- if (hardwareProvider == null) {
- return Collections.emptyList();
- }
- return hardwareProvider.getHardware();
- }
-
- public List getHardware(Class clazz) {
- return getHardware().stream().filter(hw -> hw.getClass() == clazz).map(hw -> (T) hw)
- .collect(Collectors.toList());
- }
-
- public void installApplication(AbstractApplication application) {
- desktop.installApplication(application);
- installedApps.add(application);
- }
-
- public void openApplication(AbstractApplication application, boolean isClient) {
- desktop.removeAllDialogs();
- NBTTagCompound nbt = tabletNBT.getCompoundTag(application.getRegistryName());
- if (!TerminalBehaviour.isCreative(itemStack)) {
- List hwDemand = TerminalRegistry.getAppHardwareDemand(application.getRegistryName(),
- Math.min(nbt.getInteger("_tier"), application.getMaxTier()));
- List unMatch = hwDemand.stream()
- .filter(demand -> getHardware().stream().noneMatch(hw -> hw.isHardwareAdequate(demand)))
- .collect(Collectors.toList());
- if (unMatch.size() > 0) {
- if (isClient) {
- StringBuilder tooltips = new StringBuilder("\n");
- for (Hardware match : unMatch) {
- String info = match.addInformation();
- String name = match.getLocalizedName();
- if (info == null) {
- tooltips.append(name);
- } else if (match instanceof BatteryHardware) {
- IElectricItem energyItem = itemStack
- .getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
- if (energyItem != null && energyItem.getCharge() <= 0) {
- tooltips.append(I18n.format("terminal.battery.low_energy"));
- } else {
- tooltips.append(String.format("%s (%s+)", name, info));
- }
- } else {
- tooltips.append(String.format("%s (%s)", name, info));
- }
- tooltips.append(" ");
- }
- TerminalDialogWidget.showInfoDialog(this,
- "terminal.component.error",
- I18n.format("terminal.os.hw_demand") + tooltips).setClientSide().open();
- }
- return;
- }
- }
- if (!application.canPlayerUse(gui.entityPlayer)) {
- return;
- }
- if (focusApp != null) {
- closeApplication(focusApp, isClient);
- }
- for (AbstractApplication app : openedApps) {
- if (app.getRegistryName().equals(application.getRegistryName()) && application.canLaunchConcurrently(app)) {
- app.onOSSizeUpdate(this.getSize().width, this.getSize().height);
- maximizeApplication(app, isClient);
- return;
- }
- }
- AbstractApplication app = application.createAppInstance(this, isClient, nbt);
- if (app != null) {
- desktop.addWidget(app);
- app.setOs(this).initApp();
- app.onOSSizeUpdate(this.getSize().width, this.getSize().height);
- openedApps.add(app);
- maximizeApplication(app, isClient);
- }
- }
-
- public void maximizeApplication(AbstractApplication application, boolean isClient) {
- application.setActive(true);
- if (isClient) {
- application.maximizeWidget(app -> desktop.hideDesktop());
- if (!menu.isHide) {
- menu.hideMenu();
- }
- }
- focusApp = application;
- menu.loadComponents(focusApp);
- desktop.hideDesktop();
- }
-
- public void minimizeApplication(AbstractApplication application, boolean isClient) {
- desktop.removeAllDialogs();
- if (application != null) {
- if (focusApp == application) {
- if (isClient) {
- application.minimizeWidget(app -> {
- if (!application.isBackgroundApp()) {
- application.setActive(false);
- }
- });
- } else if (!application.isBackgroundApp()) {
- application.setActive(false);
- }
- focusApp = null;
- }
- menu.removeComponents();
- desktop.showDesktop();
- }
- }
-
- public void closeApplication(AbstractApplication application, boolean isClient) {
- desktop.removeAllDialogs();
- if (application != null) {
- String appName = application.getRegistryName();
- NBTTagCompound synced = application.closeApp();
-
- if (synced != null && !synced.isEmpty()) {
- tabletNBT.setTag(appName, synced);
- if (application.isClientSideApp() && isClient) {
- writeClientAction(-2, buffer -> {
- buffer.writeString(appName);
- buffer.writeCompoundTag(synced);
- });
- }
- }
-
- if (isClient && focusApp == application) {
- application.minimizeWidget(desktop::waitToRemoved);
- } else {
- desktop.waitToRemoved(application);
- }
- openedApps.remove(application);
- if (focusApp == application) {
- focusApp = null;
- }
- menu.removeComponents();
- desktop.showDesktop();
- }
- }
-
- public void callMenu(boolean isClient) {
- if (isClient) {
- if (menu.isHide) {
- menu.showMenu();
- } else {
- menu.hideMenu();
- }
- }
- }
-
- public void shutdown(boolean isClient) {
- if (isClient) {
- NBTTagCompound nbt = new NBTTagCompound();
- for (AbstractApplication openedApp : openedApps) {
- String appName = openedApp.getRegistryName();
- NBTTagCompound synced = openedApp.closeApp();
- if (synced != null && !synced.isEmpty()) {
- tabletNBT.setTag(appName, synced);
- if (openedApp.isClientSideApp()) {// if its a clientSideApp and the nbt not null, meaning this nbt
- // should be synced to the server side.
- nbt.setTag(appName, synced);
- }
- }
- }
- writeClientAction(-1, buffer -> buffer.writeCompoundTag(nbt));
- } else { // request shutdown from the server side
- writeUpdateInfo(-2, packetBuffer -> {});
- }
- }
-
- protected void openDialog(TerminalDialogWidget widget) {
- if (isRemote()) {
- widget.onOSSizeUpdate(getSize().width, getSize().height);
- widget.maximizeWidget(null);
- } else if (widget.isClient()) {
- return;
- }
- desktop.addWidget(widget);
- }
-
- protected void closeDialog(TerminalDialogWidget widget) {
- if (isRemote()) {
- widget.minimizeWidget(desktop::waitToRemoved);
- } else if (!widget.isClient()) {
- desktop.waitToRemoved(widget);
- }
- }
-
- @Override
- public void handleClientAction(int id, PacketBuffer buffer) {
- if (id == -1) { // shutdown
- NBTTagCompound nbt = null;
- try {
- nbt = buffer.readCompoundTag();
- } catch (IOException e) {
- GTLog.logger.error("TerminalOSWidget Shutdown could not read NBT tag from buffer", e);
- }
- for (AbstractApplication openedApp : openedApps) {
- String appName = openedApp.getRegistryName();
- NBTTagCompound data = openedApp.closeApp();
- if (data != null && !data.isEmpty()) {
- tabletNBT.setTag(appName, data);
- } else if (nbt != null && openedApp.isClientSideApp() && nbt.hasKey(appName)) {
- tabletNBT.setTag(appName, nbt.getCompoundTag(appName));
- }
- }
- this.getModularUI().entityPlayer.closeScreen(); // must close tablet from server side.
- } else if (id == -2) { // closeApp sync
- String appName = buffer.readString(32767);
- NBTTagCompound nbt = null;
- try {
- nbt = buffer.readCompoundTag();
- } catch (IOException e) {
- GTLog.logger.error("TerminalOSWidget CloseApp could not read NBT tag from buffer", e);
- }
- if (nbt != null) {
- tabletNBT.setTag(appName, nbt);
- }
- } else {
- super.handleClientAction(id, buffer);
- }
- }
-
- @Override
- public void readUpdateInfo(int id, PacketBuffer buffer) {
- if (id == -1) { // disCharge
- long charge = buffer.readLong();
- IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
- if (electricItem instanceof BatteryHardware) {
- ((BatteryHardware) electricItem).setCharge(charge);
- }
- if (charge <= 0) {
- List toClosed = new LinkedList<>();
- for (AbstractApplication openedApp : openedApps) {
- TerminalRegistry.getAppHardwareDemand(openedApp.getRegistryName(), openedApp.getAppTier()).stream()
- .filter(i -> i instanceof BatteryHardware).findFirst()
- .ifPresent(x -> toClosed.add(openedApp));
- }
- for (AbstractApplication close : toClosed) {
- this.closeApplication(close, true);
- }
- TerminalDialogWidget.showInfoDialog(this, "terminal.component.warning", "terminal.battery.low_energy")
- .setClientSide().open();
- }
- } else if (id == -2) { // shutdown
- shutdown(true);
- } else {
- super.readUpdateInfo(id, buffer);
- }
- }
-
- @Override
- public void updateScreen() {
- super.updateScreen();
- tickCounter++;
- if (background != null) {
- background.updateTick();
- }
- }
-
- @Override
- public void detectAndSendChanges() {
- super.detectAndSendChanges();
- tickCounter++;
- if (tickCounter % 20 == 0) {
- long energyStore = disCharge();
- if (lastCharge != energyStore) {
- lastCharge = energyStore;
- writeUpdateInfo(-1, packetBuffer -> packetBuffer.writeLong(lastCharge));
- }
- }
- }
-
- private long disCharge() {
- IElectricItem electricItem = hardwareProvider.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM,
- null);
- if (electricItem != null && !TerminalBehaviour.isCreative(itemStack)) {
- AtomicLong costs = new AtomicLong(0);
- List charged = new ArrayList<>();
- for (AbstractApplication openedApp : openedApps) {
- TerminalRegistry.getAppHardwareDemand(openedApp.getRegistryName(), openedApp.getAppTier()).stream()
- .filter(i -> i instanceof BatteryHardware).findFirst()
- .ifPresent(battery -> {
- costs.addAndGet(((BatteryHardware) battery).getCharge());
- charged.add(openedApp);
- });
- }
- for (DeviceHardware hardware : getHardware(DeviceHardware.class)) {
- if (hardware.getDevice() == DeviceHardware.DEVICE.SOLAR_LV) {
- costs.addAndGet(-200);
- }
- }
- if (costs.get() > 0 && electricItem.discharge(costs.get(), 999, true, false, false) != costs.get()) {
- charged.forEach(app -> closeApplication(app, false));
- } else if (costs.get() < 0) {
- electricItem.charge(-costs.get(), 999, true, false);
- }
- return electricItem.getCharge();
- }
- return lastCharge;
- }
-
- @Override
- public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- Position position = getPosition();
- Size size = getSize();
-
- // show menu when mouse near the left edge
- if ((focusApp == null || focusApp.canOpenMenuOnEdge()) &&
- isMouseOver(position.x, position.y, 7, size.height, mouseX, mouseY)) {
- if (menu.isHide && !showMenuHover) {
- menu.showMenu();
- showMenuHover = true;
- }
- } else if (!menu.isHide && showMenuHover &&
- !isMouseOver(position.x - 10, position.y, 41, size.height, mouseX, mouseY)) {
- menu.hideMenu();
- showMenuHover = false;
- }
-
- if (background != null) {
- background.draw(position.x, position.y, size.width, size.height);
- } else {
- drawGradientRect(position.x, position.y, size.width, size.height, -1, -1);
- }
- if (maximize) {
- desktop.drawInBackground(mouseX, mouseY, partialTicks, context);
- if (menu.isVisible()) {
- menu.drawInBackground(mouseX, mouseY, partialTicks, context);
- }
- } else {
- RenderUtil.useScissor(position.x, position.y, size.width, size.height, () -> {
- desktop.drawInBackground(mouseX, mouseY, partialTicks, context);
- if (menu.isVisible()) {
- menu.drawInBackground(mouseX, mouseY, partialTicks, context);
- }
- });
- TERMINAL_FRAME.draw(position.x - 12, position.y - 11, 380, 256);
- }
- home.drawInBackground(mouseX, mouseY, partialTicks, context);
- }
-
- boolean waitShutdown;
-
- @Override
- public boolean keyTyped(char charTyped, int keyCode) {
- if (waitShutdown &&
- (keyCode == 1 || Minecraft.getMinecraft().gameSettings.keyBindInventory.isActiveAndMatches(keyCode))) {
- shutdown(true);
- return true;
- }
- if (super.keyTyped(charTyped, keyCode)) {
- return true;
- }
- if (keyCode == 1 || Minecraft.getMinecraft().gameSettings.keyBindInventory.isActiveAndMatches(keyCode)) { // hook
- // esc
- // and
- // e
- waitShutdown = true;
- if (!OsSettings.DOUBLE_CHECK) {
- shutdown(true);
- return true;
- }
- TerminalDialogWidget
- .showConfirmDialog(this, "terminal.component.warning", "terminal.os.shutdown_confirm", result -> {
- if (result) {
- shutdown(true);
- } else {
- waitShutdown = false;
- }
- }).setClientSide().open();
- return true;
- }
- waitShutdown = false;
- return false;
- }
-
- public boolean isMaximize() {
- return maximize;
- }
-
- private void updateOSSize() {
- int osWidth = getSize().width;
- int osHeight = getSize().height;
- if (this.maximize && (osWidth != gui.getScreenWidth() || osHeight != gui.getScreenHeight())) {
- osWidth = gui.getScreenWidth();
- osHeight = gui.getScreenHeight();
- } else if (!this.maximize && (osWidth != DEFAULT_WIDTH || osHeight != DEFAULT_HEIGHT)) {
- osWidth = DEFAULT_WIDTH;
- osHeight = DEFAULT_HEIGHT;
- } else {
- return;
- }
- this.setSize(new Size(osWidth, osHeight));
- this.desktop.setSize(new Size(osWidth, osHeight));
- this.menu.setSize(new Size(31, osHeight));
- this.home.setSelfPosition(this.maximize ?
- new Position((osWidth - this.home.getSize().width) / 2, osHeight - this.home.getSize().height - 10) :
- new Position(340, 104));
- this.home.setIcon(this.maximize ? TERMINAL_HOME : null);
- gui.setSize(this.maximize ? osWidth : 380, this.maximize ? osHeight : 256);
- if (this.focusApp != null) {
- this.focusApp.onOSSizeUpdate(osWidth, osHeight);
- }
- for (Widget widget : desktop.widgets) {
- if (widget instanceof TerminalDialogWidget) {
- ((TerminalDialogWidget) widget).onOSSizeUpdate(osWidth, osHeight);
- }
- }
- }
-
- public void maximize(boolean isClient) {
- if (isClient) {
- this.maximize = !this.maximize;
- updateOSSize();
- }
- }
-
- @Override
- public void setParentPosition(Position parentPosition) {
- if (this.maximize) {
- super.setParentPosition(parentPosition.subtract(this.getSelfPosition()));
- if (isRemote()) {
- updateOSSize();
- }
- } else {
- super.setParentPosition(parentPosition);
- }
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/os/TerminalTheme.java b/src/main/java/gregtech/api/terminal/os/TerminalTheme.java
deleted file mode 100644
index 66bf68c5bfd..00000000000
--- a/src/main/java/gregtech/api/terminal/os/TerminalTheme.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package gregtech.api.terminal.os;
-
-import gregtech.api.gui.resources.ColorRectTexture;
-import gregtech.api.gui.resources.ModifyGuiTexture;
-import gregtech.api.gui.resources.TextureArea;
-import gregtech.api.util.FileUtility;
-
-import net.minecraftforge.fml.common.FMLCommonHandler;
-
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-
-import java.awt.*;
-import java.io.File;
-
-import static gregtech.api.terminal.TerminalRegistry.TERMINAL_PATH;
-
-public class TerminalTheme {
-
- private static final String FILE_PATH = "config/theme.json";
- public static final ColorRectTexture COLOR_1 = new ColorRectTexture(new Color(144, 243, 116));
- public static final ColorRectTexture COLOR_2 = new ColorRectTexture(new Color(243, 208, 116));
- public static final ColorRectTexture COLOR_3 = new ColorRectTexture(new Color(231, 95, 95));
- public static final ColorRectTexture COLOR_4 = new ColorRectTexture(new Color(0, 115, 255));
- public static final ColorRectTexture COLOR_5 = new ColorRectTexture(new Color(113, 27, 217));
- public static final ColorRectTexture COLOR_6 = new ColorRectTexture(new Color(30, 30, 30, 255));
- public static final ColorRectTexture COLOR_7 = new ColorRectTexture(new Color(230, 230, 230, 255));
-
- public static final ColorRectTexture COLOR_F_1 = new ColorRectTexture(new Color(148, 226, 193));
- public static final ColorRectTexture COLOR_F_2 = new ColorRectTexture(new Color(175, 0, 0, 131));
-
- public static final ColorRectTexture COLOR_B_1 = new ColorRectTexture(new Color(0, 0, 0, 80));
- public static final ColorRectTexture COLOR_B_2 = new ColorRectTexture(new Color(0, 0, 0, 160));
- public static final ColorRectTexture COLOR_B_3 = new ColorRectTexture(new Color(246, 120, 120, 160));
-
- public static final ModifyGuiTexture WALL_PAPER = new ModifyGuiTexture(
- TextureArea.fullImage("textures/gui/terminal/terminal_background.png"));
-
- static {
- if (FMLCommonHandler.instance().getSide().isClient()) {
- JsonElement element = FileUtility.loadJson(new File(TERMINAL_PATH, FILE_PATH));
- if (element == null || !element.isJsonObject()) {
- saveConfig();
- } else {
- JsonObject config = element.getAsJsonObject();
- if (config.has("COLOR_1")) {
- COLOR_1.setColor(config.get("COLOR_1").getAsInt());
- }
- if (config.has("COLOR_2")) {
- COLOR_2.setColor(config.get("COLOR_2").getAsInt());
- }
- if (config.has("COLOR_3")) {
- COLOR_3.setColor(config.get("COLOR_3").getAsInt());
- }
- if (config.has("COLOR_4")) {
- COLOR_4.setColor(config.get("COLOR_4").getAsInt());
- }
- if (config.has("COLOR_5")) {
- COLOR_5.setColor(config.get("COLOR_5").getAsInt());
- }
- if (config.has("COLOR_6")) {
- COLOR_6.setColor(config.get("COLOR_6").getAsInt());
- }
- if (config.has("COLOR_7")) {
- COLOR_7.setColor(config.get("COLOR_7").getAsInt());
- }
- if (config.has("COLOR_F_1")) {
- COLOR_F_1.setColor(config.get("COLOR_F_1").getAsInt());
- }
- if (config.has("COLOR_F_2")) {
- COLOR_F_2.setColor(config.get("COLOR_F_2").getAsInt());
- }
- if (config.has("COLOR_B_1")) {
- COLOR_B_1.setColor(config.get("COLOR_B_1").getAsInt());
- }
- if (config.has("COLOR_B_2")) {
- COLOR_B_2.setColor(config.get("COLOR_B_2").getAsInt());
- }
- if (config.has("COLOR_B_3")) {
- COLOR_B_3.setColor(config.get("COLOR_B_3").getAsInt());
- }
- if (config.has("WALL_PAPER")) {
- WALL_PAPER.loadConfig(config.get("WALL_PAPER").getAsJsonObject());
- }
- }
- }
- }
-
- public static boolean saveConfig() {
- JsonObject config = new JsonObject();
- config.addProperty("COLOR_1", COLOR_1.getColor());
- config.addProperty("COLOR_2", COLOR_2.getColor());
- config.addProperty("COLOR_3", COLOR_3.getColor());
- config.addProperty("COLOR_4", COLOR_4.getColor());
- config.addProperty("COLOR_5", COLOR_5.getColor());
- config.addProperty("COLOR_6", COLOR_6.getColor());
- config.addProperty("COLOR_7", COLOR_7.getColor());
- config.addProperty("COLOR_F_1", COLOR_F_1.getColor());
- config.addProperty("COLOR_F_2", COLOR_F_2.getColor());
- config.addProperty("COLOR_B_1", COLOR_B_1.getColor());
- config.addProperty("COLOR_B_2", COLOR_B_2.getColor());
- config.addProperty("COLOR_B_3", COLOR_B_3.getColor());
- config.add("WALL_PAPER", WALL_PAPER.saveConfig());
- return FileUtility.saveJson(new File(TERMINAL_PATH, FILE_PATH), config);
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/os/menu/TerminalMenuWidget.java b/src/main/java/gregtech/api/terminal/os/menu/TerminalMenuWidget.java
deleted file mode 100644
index daeaf572d4e..00000000000
--- a/src/main/java/gregtech/api/terminal/os/menu/TerminalMenuWidget.java
+++ /dev/null
@@ -1,189 +0,0 @@
-package gregtech.api.terminal.os.menu;
-
-import gregtech.api.gui.IRenderContext;
-import gregtech.api.gui.Widget;
-import gregtech.api.gui.resources.IGuiTexture;
-import gregtech.api.gui.widgets.WidgetGroup;
-import gregtech.api.terminal.app.AbstractApplication;
-import gregtech.api.terminal.gui.widgets.CircleButtonWidget;
-import gregtech.api.terminal.os.SystemCall;
-import gregtech.api.terminal.os.TerminalOSWidget;
-import gregtech.api.terminal.os.TerminalTheme;
-import gregtech.api.util.Position;
-import gregtech.api.util.Size;
-import gregtech.api.util.interpolate.Eases;
-import gregtech.api.util.interpolate.Interpolator;
-
-import net.minecraft.client.renderer.GlStateManager;
-import net.minecraft.util.Tuple;
-import net.minecraftforge.fml.relauncher.Side;
-import net.minecraftforge.fml.relauncher.SideOnly;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class TerminalMenuWidget extends WidgetGroup {
-
- @SideOnly(Side.CLIENT)
- private Interpolator interpolator;
- private IGuiTexture background;
- private final TerminalOSWidget os;
- private final List> components;
- public boolean isHide;
-
- public TerminalMenuWidget(Position position, Size size, TerminalOSWidget os) {
- super(position, size);
- addSelfPosition(-size.width, 0);
- setVisible(false);
- isHide = true;
- this.os = os;
- components = new ArrayList<>();
- this.addWidget(new CircleButtonWidget(5, 10, 4, 1, 0)
- .setColors(0,
- TerminalTheme.COLOR_7.getColor(),
- TerminalTheme.COLOR_3.getColor())
- .setHoverText("terminal.menu.close")
- .setClickListener(this::close));
- this.addWidget(new CircleButtonWidget(15, 10, 4, 1, 0)
- .setColors(0,
- TerminalTheme.COLOR_7.getColor(),
- TerminalTheme.COLOR_2.getColor())
- .setHoverText("terminal.menu.minimize")
- .setClickListener(this::minimize));
- this.addWidget(new CircleButtonWidget(25, 10, 4, 1, 0)
- .setColors(0,
- TerminalTheme.COLOR_7.getColor(),
- TerminalTheme.COLOR_1.getColor())
- .setHoverText("terminal.menu.maximize")
- .setClickListener(this::maximize));
- }
-
- public TerminalMenuWidget setBackground(IGuiTexture background) {
- this.background = background;
- return this;
- }
-
- public void close(ClickData clickData) {
- SystemCall.CLOSE_FOCUS_APP.call(os, clickData.isClient);
- }
-
- public void minimize(ClickData clickData) {
- SystemCall.MINIMIZE_FOCUS_APP.call(os, clickData.isClient);
- }
-
- public void maximize(ClickData clickData) {
- SystemCall.FULL_SCREEN.call(os, clickData.isClient);
- }
-
- public void addComponent(IMenuComponent component) {
- WidgetGroup group = new WidgetGroup();
- int x = 15;
- int y = 40 + components.size() * 25;
- CircleButtonWidget button = new CircleButtonWidget(x, y, 10, 1, 16)
- .setColors(0, 0xFFFFFFFF, 0)
- .setHoverText(component.hoverText())
- .setIcon(component.buttonIcon());
- button.setClickListener(c -> {
- components.forEach(tuple -> {
- if (tuple.getFirst() instanceof Widget && tuple.getFirst() != component) {
- ((Widget) tuple.getFirst()).setActive(false);
- ((Widget) tuple.getFirst()).setVisible(false);
- ((CircleButtonWidget) tuple.getSecond().widgets.get(0)).setFill(0);
- }
- });
- if (component instanceof Widget) {
- Widget widget = (Widget) component;
- widget.setVisible(!widget.isVisible());
- widget.setActive(!widget.isActive());
- button.setFill(widget.isVisible() ? 0xFF94E2C1 : 0);
- }
- component.click(c);
- });
- group.addWidget(button);
- if (component instanceof Widget) {
- Widget widget = (Widget) component;
- widget.setSelfPosition(new Position(x + 20, 0));
- widget.setVisible(false);
- widget.setActive(false);
- group.addWidget(widget);
- }
- this.addWidget(group);
- components.add(new Tuple<>(component, group));
- }
-
- public void loadComponents(AbstractApplication app) {
- removeComponents();
- if (app != null) {
- app.getMenuComponents().forEach(this::addComponent);
- }
- }
-
- public void removeComponents() {
- components.forEach(component -> this.removeWidget(component.getSecond()));
- components.clear();
- }
-
- @SideOnly(Side.CLIENT)
- public void hideMenu() {
- if (!isHide && interpolator == null) {
- int y = getSelfPosition().y;
- interpolator = new Interpolator(getSelfPosition().x, getSelfPosition().x - getSize().width, 6, Eases.LINEAR,
- value -> setSelfPosition(new Position(value.intValue(), y)),
- value -> {
- setVisible(false);
- interpolator = null;
- isHide = true;
- });
- interpolator.start();
- os.desktop.removeTopWidget(this);
- }
- }
-
- @SideOnly(Side.CLIENT)
- public void showMenu() {
- if (isHide && interpolator == null) {
- setVisible(true);
- int y = getSelfPosition().y;
- interpolator = new Interpolator(getSelfPosition().x, getSelfPosition().x + getSize().width, 6, Eases.LINEAR,
- value -> setSelfPosition(new Position(value.intValue(), y)),
- value -> {
- interpolator = null;
- isHide = false;
- });
- interpolator.start();
- os.desktop.addTopWidget(this);
- }
- }
-
- @Override
- public void updateScreenOnFrame() {
- if (interpolator != null) interpolator.update();
- super.updateScreenOnFrame();
- }
-
- @Override
- public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) {
- GlStateManager.color(1, 1, 1, 0.5f);
- if (background != null) {
- background.draw(this.getPosition().x, this.getPosition().y, this.getSize().width, this.getSize().height);
- } else {
- drawGradientRect(this.getPosition().x, this.getPosition().y, this.getSize().width, this.getSize().height,
- 0xff000000, 0xff000000);
- }
- GlStateManager.color(1, 1, 1, 1);
- super.drawInBackground(mouseX, mouseY, partialTicks, context);
- }
-
- @Override
- public boolean mouseClicked(int mouseX, int mouseY, int button) {
- if (!super.mouseClicked(mouseX, mouseY, button)) {
- if (isMouseOverElement(mouseX, mouseY)) {
- return true;
- } else if (!isHide) {
- hideMenu();
- }
- return false;
- }
- return true;
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/util/FileTree.java b/src/main/java/gregtech/api/terminal/util/FileTree.java
deleted file mode 100644
index 5097c478aff..00000000000
--- a/src/main/java/gregtech/api/terminal/util/FileTree.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package gregtech.api.terminal.util;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-public class FileTree extends TreeNode {
-
- public FileTree(File dir) {
- this(0, dir);
- }
-
- private FileTree(int dimension, File key) {
- super(dimension, key);
- }
-
- @Override
- public boolean isLeaf() {
- return getKey().isFile();
- }
-
- @Override
- public File getContent() {
- return isLeaf() ? getKey() : null;
- }
-
- @Override
- public List> getChildren() {
- if (children == null && !isLeaf()) {
- children = new ArrayList<>();
- File[] listFiles = key.listFiles();
- if (listFiles != null) {
- Arrays.stream(listFiles).sorted((a, b) -> {
- if (a.isFile() && b.isFile()) {
- return a.compareTo(b);
- } else if (a.isDirectory() && b.isDirectory()) {
- return a.compareTo(b);
- } else if (a.isDirectory()) {
- return -1;
- }
- return 1;
- }).forEach(file -> children.add(new FileTree(dimension + 1, file)));
- }
- }
- return super.getChildren();
- }
-
- @Override
- public String toString() {
- return getKey().getName();
- }
-}
diff --git a/src/main/java/gregtech/api/terminal/util/TreeNode.java b/src/main/java/gregtech/api/terminal/util/TreeNode.java
deleted file mode 100644
index 7f99ac830ae..00000000000
--- a/src/main/java/gregtech/api/terminal/util/TreeNode.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package gregtech.api.terminal.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/***
- * Tree
- *
- * @param