diff --git a/dependencies.gradle b/dependencies.gradle index ce3f8136297..91d6a5d5c7e 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -40,8 +40,8 @@ dependencies { // Published dependencies api("codechicken:codechickenlib:3.2.3.358") - api("com.cleanroommc:modularui:2.5.0-rc1") { transitive = false } - api("com.cleanroommc:groovyscript:1.1.1") { transitive = false } + api("com.cleanroommc:modularui:2.5.0-rc2") { transitive = false } + api("com.cleanroommc:groovyscript:1.2.0-hotfix1") { transitive = false } api("CraftTweaker2:CraftTweaker2-MC1120-Main:1.12-4.1.20.700") api("appeng:ae2-uel:v0.56.4") { transitive = false } api rfg.deobf("curse.maven:ctm-267602:2915363") // CTM 1.0.2.31 diff --git a/src/api/java/meldexun/nothirium/api/renderer/chunk/ChunkRenderPass.java b/src/api/java/meldexun/nothirium/api/renderer/chunk/ChunkRenderPass.java new file mode 100644 index 00000000000..355ce0daa04 --- /dev/null +++ b/src/api/java/meldexun/nothirium/api/renderer/chunk/ChunkRenderPass.java @@ -0,0 +1,12 @@ +package meldexun.nothirium.api.renderer.chunk; + +/** + * Adapted and minimized from ChunkRenderPass.java + */ +public enum ChunkRenderPass { + ; + + public static final ChunkRenderPass[] ALL = ChunkRenderPass.values(); + +} diff --git a/src/main/java/gregtech/GregTechMod.java b/src/main/java/gregtech/GregTechMod.java index 59a72f3db03..04fcd09786c 100644 --- a/src/main/java/gregtech/GregTechMod.java +++ b/src/main/java/gregtech/GregTechMod.java @@ -33,7 +33,7 @@ dependencies = "required:forge@[14.23.5.2847,);" + "required-after:codechickenlib@[3.2.3,);" + "required-after:modularui@[2.3,);" + "required-after:mixinbooter@[8.0,);" + "after:appliedenergistics2;" + "after:forestry;" + "after:extrabees;" + "after:extratrees;" + "after:genetics;" + "after:magicbees;" + - "after:jei@[4.15.0,);" + "after:crafttweaker@[4.1.20,);" + "after:groovyscript@[1.1.0,);" + + "after:jei@[4.15.0,);" + "after:crafttweaker@[4.1.20,);" + "after:groovyscript@[1.2.0,);" + "after:theoneprobe;" + "after:hwyla;") public class GregTechMod { diff --git a/src/main/java/gregtech/api/GTValues.java b/src/main/java/gregtech/api/GTValues.java index 2048c61affe..9d3bb3f2534 100644 --- a/src/main/java/gregtech/api/GTValues.java +++ b/src/main/java/gregtech/api/GTValues.java @@ -54,7 +54,7 @@ public class GTValues { * The Voltage Tiers. Use this Array instead of the old named Voltage Variables */ public static final long[] V = { 8, 32, 128, 512, 2048, 8192, 32768, 131072, 524288, 2097152, 8388608, 33554432, - 134217728, 536870912, Integer.MAX_VALUE }; + 134217728, 536870912, 2147483648L }; /** * The Voltage Tiers divided by 2. @@ -74,6 +74,15 @@ public class GTValues { public static final int[] VHA = { 7, 16, 60, 240, 960, 3840, 15360, 61440, 245760, 983040, 3932160, 15728640, 62914560, 251658240, 1006632960 }; + /** + * The Voltage Tiers extended all the way to max Long value for overclocking + */ + public static final long[] VOC = { 8, 32, 128, 512, 2048, 8192, 32768, 131072, 524288, 2097152, 8388608, 33554432, + 134217728, 536870912, 2147483648L, 8589934592L, 34359738368L, 137438953472L, 549755813888L, + 2199023255552L, 8796093022208L, 35184372088832L, 140737488355328L, 562949953421312L, 2251799813685248L, + 9007199254740992L, 36028797018963968L, 144115188075855872L, 576460752303423488L, 2305843009213693952L, + Long.MAX_VALUE }; + public static final int ULV = 0; public static final int LV = 1; public static final int MV = 2; @@ -90,6 +99,7 @@ public class GTValues { public static final int UXV = 12; public static final int OpV = 13; public static final int MAX = 14; + public static final int MAX_TRUE = 30; /** * The short names for the voltages, used for registration primarily @@ -97,6 +107,17 @@ public class GTValues { public static final String[] VN = new String[] { "ULV", "LV", "MV", "HV", "EV", "IV", "LuV", "ZPM", "UV", "UHV", "UEV", "UIV", "UXV", "OpV", "MAX" }; + /** + * The short names for the voltages, up to max Long, used for registration primarily + */ + public static final String[] VOCN = new String[] { "ULV", "LV", "MV", "HV", "EV", "IV", "LuV", "ZPM", "UV", "UHV", + "UEV", "UIV", "UXV", "OpV", "MAX", "MAX+1", "MAX+2", "MAX+3", "MAX+4", "MAX+5", "MAX+6", "MAX+7", "MAX+8", + "MAX+9", "MAX+10", "MAX+11", "MAX+12", "MAX+13", "MAX+14", "MAX+15", "MAX+16", + }; + + private static final String MAX_PLUS = RED.toString() + BOLD + "M" + YELLOW + BOLD + "A" + GREEN + BOLD + "X" + + AQUA + BOLD + "+" + LIGHT_PURPLE + BOLD; + /** * The short names for the voltages, formatted for text */ @@ -107,6 +128,20 @@ public class GTValues { DARK_RED + "UHV", GREEN + "UEV", DARK_GREEN + "UIV", YELLOW + "UXV", BLUE + "OpV", RED.toString() + BOLD + "MAX" }; + /** + * The short names for the voltages, up to max Long, formatted for text + */ + public static final String[] VOCNF = new String[] { + DARK_GRAY + "ULV", GRAY + "LV", AQUA + "MV", + GOLD + "HV", DARK_PURPLE + "EV", DARK_BLUE + "IV", + LIGHT_PURPLE + "LuV", RED + "ZPM", DARK_AQUA + "UV", + DARK_RED + "UHV", GREEN + "UEV", DARK_GREEN + "UIV", + YELLOW + "UXV", BLUE + "OpV", RED.toString() + BOLD + "MAX", + MAX_PLUS + "1", MAX_PLUS + "2", MAX_PLUS + "3", MAX_PLUS + "4", + MAX_PLUS + "5", MAX_PLUS + "6", MAX_PLUS + "7", MAX_PLUS + "8", + MAX_PLUS + "9", MAX_PLUS + "10", MAX_PLUS + "11", MAX_PLUS + "12", + MAX_PLUS + "13", MAX_PLUS + "14", MAX_PLUS + "15", MAX_PLUS + "16", }; + /** * Color values for the voltages */ diff --git a/src/main/java/gregtech/api/GregTechAPI.java b/src/main/java/gregtech/api/GregTechAPI.java index 01845f8b047..4e3bc8bc69c 100644 --- a/src/main/java/gregtech/api/GregTechAPI.java +++ b/src/main/java/gregtech/api/GregTechAPI.java @@ -11,6 +11,7 @@ import gregtech.api.metatileentity.registry.MTEManager; import gregtech.api.modules.IModuleManager; import gregtech.api.network.INetworkHandler; +import gregtech.api.recipes.properties.RecipePropertyRegistry; import gregtech.api.sound.ISoundManager; import gregtech.api.unification.material.Material; import gregtech.api.unification.material.registry.IMaterialRegistryManager; @@ -56,6 +57,7 @@ public class GregTechAPI { public static MTEManager mteManager; /** GT's data migrations API */ public static final MigrationAPI MIGRATIONS = new MigrationAPI(); + public static final RecipePropertyRegistry RECIPE_PROPERTIES = new RecipePropertyRegistry(); /** Will be available at the Pre-Initialization stage */ private static boolean highTier; diff --git a/src/main/java/gregtech/api/block/IHeatingCoilBlockStats.java b/src/main/java/gregtech/api/block/IHeatingCoilBlockStats.java index 5f6e5c49c06..0e2b7427591 100644 --- a/src/main/java/gregtech/api/block/IHeatingCoilBlockStats.java +++ b/src/main/java/gregtech/api/block/IHeatingCoilBlockStats.java @@ -1,6 +1,6 @@ package gregtech.api.block; -import gregtech.api.recipes.recipeproperties.TemperatureProperty; +import gregtech.api.recipes.properties.impl.TemperatureProperty; import gregtech.api.unification.material.Material; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/gregtech/api/block/machines/BlockMachine.java b/src/main/java/gregtech/api/block/machines/BlockMachine.java index b6baf911627..2a04cf5d441 100644 --- a/src/main/java/gregtech/api/block/machines/BlockMachine.java +++ b/src/main/java/gregtech/api/block/machines/BlockMachine.java @@ -271,34 +271,38 @@ public void onBlockPlacedBy(World worldIn, @NotNull BlockPos pos, @NotNull IBloc Objects.requireNonNull(stack.getItem().getRegistryName()).getNamespace()); MetaTileEntity sampleMetaTileEntity = registry.getObjectById(stack.getItemDamage()); - if (holder != null && sampleMetaTileEntity != null) { - // TODO Fix this - if (stack.hasDisplayName() && holder instanceof MetaTileEntityHolder) { - ((MetaTileEntityHolder) holder).setCustomName(stack.getDisplayName()); - } - MetaTileEntity metaTileEntity = holder.setMetaTileEntity(sampleMetaTileEntity); - var stackTag = stack.getTagCompound(); - if (stackTag != null && !stackTag.isEmpty()) { - if (stackTag.hasKey(GregtechDataCodes.BLOCK_ENTITY_TAG)) { - var blockTag = stackTag.getCompoundTag(GregtechDataCodes.BLOCK_ENTITY_TAG); - String customName = blockTag.getString(GregtechDataCodes.CUSTOM_NAME); - if (!customName.isEmpty()) - ((MetaTileEntityHolder) holder).setCustomName(customName); - - var mteTag = blockTag.getCompoundTag(GregtechDataCodes.TAG_KEY_MTE); - List removed = new ArrayList<>(); - for (var key : mteTag.getKeySet()) { - var trait = metaTileEntity.getMTETrait(key); - if (trait == null) continue; - - removed.add(key); - } - removed.forEach(mteTag::removeTag); - metaTileEntity.readFromNBT(mteTag); - } else { - metaTileEntity.initFromItemStackData(stackTag); + if (holder == null || sampleMetaTileEntity == null) + return; + + // TODO Fix this + if (stack.hasDisplayName() && holder instanceof MetaTileEntityHolder) { + ((MetaTileEntityHolder) holder).setCustomName(stack.getDisplayName()); + } + var stackTag = stack.getTagCompound(); + NBTTagCompound mteTag = null; + if (stackTag != null && !stackTag.isEmpty()) { + if (stackTag.hasKey(GregtechDataCodes.BLOCK_ENTITY_TAG)) { + var blockTag = stackTag.getCompoundTag(GregtechDataCodes.BLOCK_ENTITY_TAG); + String customName = blockTag.getString(GregtechDataCodes.CUSTOM_NAME); + if (!customName.isEmpty()) + ((MetaTileEntityHolder) holder).setCustomName(customName); + + mteTag = blockTag.getCompoundTag(GregtechDataCodes.TAG_KEY_MTE); + List removed = new ArrayList<>(); + for (var key : mteTag.getKeySet()) { + var trait = sampleMetaTileEntity.getMTETrait(key); + if (trait == null) continue; + + removed.add(key); } + removed.forEach(mteTag::removeTag); } + } + MetaTileEntity metaTileEntity = holder.setMetaTileEntity(sampleMetaTileEntity, mteTag); + if (mteTag == null) { + if (stackTag != null && !stackTag.isEmpty()) + metaTileEntity.initFromItemStackData(stackTag); + if (metaTileEntity.isValidFrontFacing(EnumFacing.UP)) { metaTileEntity.setFrontFacing(EnumFacing.getDirectionFromEntityLiving(pos, placer)); } else { @@ -314,26 +318,26 @@ public void onBlockPlacedBy(World worldIn, @NotNull BlockPos pos, @NotNull IBloc } } } - if (Mods.AppliedEnergistics2.isModLoaded()) { - if (metaTileEntity.getProxy() != null) { - metaTileEntity.getProxy().setOwner((EntityPlayer) placer); - } + } + if (Mods.AppliedEnergistics2.isModLoaded()) { + if (metaTileEntity.getProxy() != null) { + metaTileEntity.getProxy().setOwner((EntityPlayer) placer); } + } - // Color machines on place if holding spray can in off-hand - if (placer instanceof EntityPlayer) { - ItemStack offhand = placer.getHeldItemOffhand(); - for (int i = 0; i < EnumDyeColor.values().length; i++) { - if (offhand.isItemEqual(MetaItems.SPRAY_CAN_DYES[i].getStackForm())) { - MetaItems.SPRAY_CAN_DYES[i].getBehaviours().get(0).onItemUse((EntityPlayer) placer, worldIn, - pos, EnumHand.OFF_HAND, EnumFacing.UP, 0, 0, 0); - break; - } + // Color machines on place if holding spray can in off-hand + if (placer instanceof EntityPlayer) { + ItemStack offhand = placer.getHeldItemOffhand(); + for (int i = 0; i < EnumDyeColor.values().length; i++) { + if (offhand.isItemEqual(MetaItems.SPRAY_CAN_DYES[i].getStackForm())) { + MetaItems.SPRAY_CAN_DYES[i].getBehaviours().get(0).onItemUse((EntityPlayer) placer, worldIn, + pos, EnumHand.OFF_HAND, EnumFacing.UP, 0, 0, 0); + break; } } - - metaTileEntity.onPlacement(); } + + metaTileEntity.onPlacement(placer); } @Override diff --git a/src/main/java/gregtech/api/capability/GregtechCapabilities.java b/src/main/java/gregtech/api/capability/GregtechCapabilities.java index 985d6c5a7fe..df163402aeb 100644 --- a/src/main/java/gregtech/api/capability/GregtechCapabilities.java +++ b/src/main/java/gregtech/api/capability/GregtechCapabilities.java @@ -2,7 +2,6 @@ import gregtech.api.GTValues; import gregtech.api.capability.impl.EUToFEProvider; -import gregtech.api.terminal.hardware.HardwareProvider; import gregtech.api.util.GTUtility; import gregtech.common.metatileentities.converter.ConverterTrait; @@ -26,9 +25,6 @@ public class GregtechCapabilities { @CapabilityInject(IMultiblockController.class) public static Capability CAPABILITY_MULTIBLOCK_CONTROLLER = null; - @CapabilityInject(HardwareProvider.class) - public static Capability CAPABILITY_HARDWARE_PROVIDER = null; - @CapabilityInject(ConverterTrait.class) public static Capability CAPABILITY_CONVERTER = null; diff --git a/src/main/java/gregtech/api/capability/GregtechDataCodes.java b/src/main/java/gregtech/api/capability/GregtechDataCodes.java index 56078a8e64f..379f791465c 100644 --- a/src/main/java/gregtech/api/capability/GregtechDataCodes.java +++ b/src/main/java/gregtech/api/capability/GregtechDataCodes.java @@ -1,7 +1,16 @@ package gregtech.api.capability; +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import org.apache.commons.lang3.ArrayUtils; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + public class GregtechDataCodes { + public static final int UPDATE_PRIVATE = assignId(); + public static final int LOCK_FILL = assignId(); private static int nextId = 0; public static int assignId() { @@ -140,6 +149,11 @@ public static int assignId() { public static final int UPDATE_ITEM_COUNT = assignId(); public static final int UPDATE_FLUID_AMOUNT = assignId(); + // Quantum Storage Controller + public static final int UPDATE_CONTROLLER_POS = assignId(); + public static final int REMOVE_CONTROLLER = assignId(); + public static final int LOCATE_CONTROLLER = assignId(); + // Detector Covers public static final int UPDATE_INVERTED = assignId(); @@ -175,4 +189,36 @@ public static int assignId() { // ME Parts public static final int UPDATE_AUTO_PULL = assignId(); public static final int UPDATE_ONLINE_STATUS = assignId(); + + // Everything below MUST be last in the class! + public static final Int2ObjectMap NAMES = new Int2ObjectArrayMap<>(); + + static { + registerFields(GregtechDataCodes.class); + } + + public static String getNameFor(int id) { + return NAMES.getOrDefault(id, "Unknown_DataCode:" + id); + } + + /** + * Registers all fields from the passed in class to the name registry. + * Optionally, you can pass in a list of valid ids to check against so that errant ids are not added + * + * @param clazz Class to iterate fields + * @param validIds optional array of valid ids to check against class fields + */ + public static void registerFields(Class clazz, int... validIds) { + try { + for (Field field : clazz.getDeclaredFields()) { + if (field.getType() != Integer.TYPE) continue; + if (!Modifier.isStatic(field.getModifiers())) continue; + if (!Modifier.isFinal(field.getModifiers())) continue; + int id = field.getInt(null); + if (!ArrayUtils.isEmpty(validIds) && !ArrayUtils.contains(validIds, id)) + continue; + NAMES.put(id, field.getName() + ":" + id); + } + } catch (IllegalAccessException ignored) {} + } } diff --git a/src/main/java/gregtech/api/capability/IDualHandler.java b/src/main/java/gregtech/api/capability/IDualHandler.java new file mode 100644 index 00000000000..595efc6a9f2 --- /dev/null +++ b/src/main/java/gregtech/api/capability/IDualHandler.java @@ -0,0 +1,14 @@ +package gregtech.api.capability; + +import net.minecraftforge.items.IItemHandler; + +public interface IDualHandler { + + boolean hasFluidTanks(); + + boolean hasItemHandlers(); + + IMultipleTankHandler getFluidTanks(); + + IItemHandler getItemHandlers(); +} diff --git a/src/main/java/gregtech/api/capability/IQuantumController.java b/src/main/java/gregtech/api/capability/IQuantumController.java new file mode 100644 index 00000000000..f2e5d333a5a --- /dev/null +++ b/src/main/java/gregtech/api/capability/IQuantumController.java @@ -0,0 +1,34 @@ +package gregtech.api.capability; + +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.common.capabilities.ICapabilityProvider; + +// ICapabilityProvider is needed because getCapability is called in the quantum proxy against this interface +public interface IQuantumController extends ICapabilityProvider { + + /** + * Constructs the network upon placement and when storages are added/removed + *
+ */ + void rebuildNetwork(); + + /** + * Return whether this storage block can connect. Can be used to implement a maximum distance from controller for + * example. + */ + boolean canConnect(IQuantumStorage storage); + + BlockPos getPos(); + + IDualHandler getHandler(); + + boolean isPowered(); + + long getEnergyUsage(); + + int getCount(IQuantumStorage.Type type); + + long getTypeEnergy(IQuantumStorage storage); + + void updateHandler(); +} diff --git a/src/main/java/gregtech/api/capability/IQuantumStorage.java b/src/main/java/gregtech/api/capability/IQuantumStorage.java new file mode 100644 index 00000000000..8a60ca63bf9 --- /dev/null +++ b/src/main/java/gregtech/api/capability/IQuantumStorage.java @@ -0,0 +1,77 @@ +package gregtech.api.capability; + +import gregtech.api.cover.CoverableView; +import gregtech.api.metatileentity.MetaTileEntity; +import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; + +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; + +import org.jetbrains.annotations.Nullable; + +public interface IQuantumStorage extends CoverableView { + + Type getType(); + + void setConnected(IQuantumController controller); + + void setDisconnected(); + + BlockPos getControllerPos(); + + @Nullable + IQuantumController getQuantumController(); + + BlockPos getPos(); + + default boolean isConnected() { + // use controllerPos here because it is synced + // on both sides, where controller is not + return getControllerPos() != null; + } + + default void tryFindNetwork() { + for (EnumFacing facing : EnumFacing.VALUES) { + var offset = getPos().offset(facing); + var state = getWorld().getBlockState(offset); + if (state.getBlock().isAir(state, getWorld(), offset)) continue; + MetaTileEntity mte; + if (getNeighbor(facing) instanceof IGregTechTileEntity gtte) { + mte = gtte.getMetaTileEntity(); + } else { + continue; + } + + IQuantumController candidate = null; + if (mte instanceof IQuantumStoragestorage) { + if (storage.isConnected()) { + IQuantumController controller = storage.getQuantumController(); + if (controller != null && controller.canConnect(this)) { + candidate = controller; + } + } + } else if (mte instanceof IQuantumController quantumController) { + if (quantumController.canConnect(this)) { + candidate = quantumController; + } + } + if (candidate != null) { + candidate.rebuildNetwork(); + return; + } + } + } + + T getTypeValue(); + + enum Type { + + ITEM, + FLUID, + EXTENDER, + PROXY, + ENERGY; + + public static final Type[] VALUES = values(); + } +} diff --git a/src/main/java/gregtech/api/capability/SimpleCapabilityManager.java b/src/main/java/gregtech/api/capability/SimpleCapabilityManager.java index 8aad39dc29c..f517b473bab 100644 --- a/src/main/java/gregtech/api/capability/SimpleCapabilityManager.java +++ b/src/main/java/gregtech/api/capability/SimpleCapabilityManager.java @@ -3,7 +3,6 @@ import gregtech.api.capability.impl.AbstractRecipeLogic; import gregtech.api.cover.CoverHolder; import gregtech.api.metatileentity.multiblock.IMaintenance; -import gregtech.api.terminal.hardware.HardwareProvider; import gregtech.api.worldgen.generator.GTWorldGenCapability; import gregtech.common.metatileentities.converter.ConverterTrait; @@ -48,7 +47,6 @@ public static void init() { registerCapabilityWithNoDefault(AbstractRecipeLogic.class); registerCapabilityWithNoDefault(IDataAccessHatch.class); registerCapabilityWithNoDefault(IOpticalComputationProvider.class); - registerCapabilityWithNoDefault(HardwareProvider.class); registerCapabilityWithNoDefault(ConverterTrait.class); registerCapabilityWithNoDefault(ILaserContainer.class); diff --git a/src/main/java/gregtech/api/capability/impl/AbstractRecipeLogic.java b/src/main/java/gregtech/api/capability/impl/AbstractRecipeLogic.java index c1ca110c2ef..455ae3afd47 100644 --- a/src/main/java/gregtech/api/capability/impl/AbstractRecipeLogic.java +++ b/src/main/java/gregtech/api/capability/impl/AbstractRecipeLogic.java @@ -18,9 +18,9 @@ import gregtech.api.recipes.logic.IParallelableRecipeLogic; import gregtech.api.recipes.logic.OCParams; import gregtech.api.recipes.logic.OCResult; -import gregtech.api.recipes.recipeproperties.CleanroomProperty; -import gregtech.api.recipes.recipeproperties.DimensionProperty; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; +import gregtech.api.recipes.properties.impl.CleanroomProperty; +import gregtech.api.recipes.properties.impl.DimensionProperty; import gregtech.api.util.GTLog; import gregtech.api.util.GTTransferUtils; import gregtech.api.util.GTUtility; @@ -441,9 +441,11 @@ protected boolean checkCleanroomRequirement(@NotNull Recipe recipe) { } protected boolean checkDimensionRequirement(@NotNull Recipe recipe) { - if (!recipe.hasProperty(DimensionProperty.getInstance())) return true; - return recipe.getProperty(DimensionProperty.getInstance(), DimensionProperty.DimensionPropertyList.EMPTY_LIST) - .checkDimension(this.getMetaTileEntity().getWorld().provider.getDimension()); + DimensionProperty.DimensionPropertyList list = recipe.getProperty(DimensionProperty.getInstance(), null); + if (list == null) { + return true; + } + return list.checkDimension(this.getMetaTileEntity().getWorld().provider.getDimension()); } /** @@ -682,7 +684,7 @@ protected static boolean areItemStacksEqual(@NotNull ItemStack stackA, @NotNull @NotNull IMultipleTankHandler importFluids) { calculateOverclock(recipe); - modifyOverclockPost(ocResult, recipe.getRecipePropertyStorage()); + modifyOverclockPost(ocResult, recipe.propertyStorage()); if (ocResult.parallel() > 1) { recipe = subTickOC(ocResult, recipe, importInventory, importFluids); @@ -814,7 +816,7 @@ protected boolean hasEnoughPower(long eut, int duration) { * @param ocResult The overclock result * @param storage the RecipePropertyStorage of the recipe being processed */ - protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull IRecipePropertyStorage storage) {} + protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull RecipePropertyStorage storage) {} /** * Calculates the overclocked Recipe's final duration and EU/t @@ -837,13 +839,13 @@ protected final void calculateOverclock(@NotNull Recipe recipe) { * @param ocResult the result of overclocking */ protected void performOverclocking(@NotNull Recipe recipe, @NotNull OCParams ocParams, @NotNull OCResult ocResult) { - modifyOverclockPre(ocParams, recipe.getRecipePropertyStorage()); + modifyOverclockPre(ocParams, recipe.propertyStorage()); if (ocParams.ocAmount() <= 0) { // number of OCs is <= 0, so do not overclock ocResult.init(ocParams.eut(), ocParams.duration()); } else { - runOverclockingLogic(ocParams, ocResult, recipe.getRecipePropertyStorage(), getMaximumOverclockVoltage()); + runOverclockingLogic(ocParams, ocResult, recipe.propertyStorage(), getMaximumOverclockVoltage()); } } @@ -854,7 +856,7 @@ protected void performOverclocking(@NotNull Recipe recipe, @NotNull OCParams ocP protected int getNumberOfOCs(long recipeEUt) { if (!isAllowOverclocking()) return 0; - int recipeTier = GTUtility.getTierByVoltage(recipeEUt); + int recipeTier = GTUtility.getOCTierByVoltage(recipeEUt); int maximumTier = getOverclockForTier(getMaximumOverclockVoltage()); if (maximumTier <= GTValues.LV) return 0; @@ -873,7 +875,7 @@ protected int getNumberOfOCs(long recipeEUt) { * @param ocParams an array of [recipeEUt, recipeDuration, numberOfOCs] * @param storage the RecipePropertyStorage of the recipe being processed */ - protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull IRecipePropertyStorage storage) {} + protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull RecipePropertyStorage storage) {} /** * Calls the desired overclocking logic to be run for the recipe. Performs the actual overclocking on the provided @@ -885,7 +887,7 @@ protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull IRecipePr * @param maxVoltage the maximum voltage the recipe is allowed to be run at */ protected void runOverclockingLogic(@NotNull OCParams ocParams, @NotNull OCResult ocResult, - @NotNull IRecipePropertyStorage propertyStorage, long maxVoltage) { + @NotNull RecipePropertyStorage propertyStorage, long maxVoltage) { standardOC(ocParams, ocResult, maxVoltage, getOverclockingDurationFactor(), getOverclockingVoltageFactor()); } @@ -911,7 +913,7 @@ protected double getOverclockingVoltageFactor() { * @return the highest voltage tier the machine should use to overclock with */ protected int getOverclockForTier(long voltage) { - return GTUtility.getTierByVoltage(voltage); + return GTUtility.getOCTierByVoltage(voltage); } /** diff --git a/src/main/java/gregtech/api/capability/impl/ComputationRecipeLogic.java b/src/main/java/gregtech/api/capability/impl/ComputationRecipeLogic.java index 99284729017..67c3c03fbc9 100644 --- a/src/main/java/gregtech/api/capability/impl/ComputationRecipeLogic.java +++ b/src/main/java/gregtech/api/capability/impl/ComputationRecipeLogic.java @@ -4,8 +4,8 @@ import gregtech.api.capability.IOpticalComputationReceiver; import gregtech.api.metatileentity.multiblock.RecipeMapMultiblockController; import gregtech.api.recipes.Recipe; -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 net.minecraft.nbt.NBTTagCompound; @@ -49,11 +49,12 @@ public boolean checkRecipe(@NotNull Recipe recipe) { if (!super.checkRecipe(recipe)) { return false; } - if (!recipe.hasProperty(ComputationProperty.getInstance())) { + int recipeCWUt = recipe.getProperty(ComputationProperty.getInstance(), 0); + if (recipeCWUt == 0) { return true; } + IOpticalComputationProvider provider = getComputationProvider(); - int recipeCWUt = recipe.getProperty(ComputationProperty.getInstance(), 0); return provider.requestCWUt(recipeCWUt, true) >= recipeCWUt; } diff --git a/src/main/java/gregtech/api/capability/impl/FuelRecipeLogic.java b/src/main/java/gregtech/api/capability/impl/FuelRecipeLogic.java index f70ca3fcde9..26871a55d3c 100644 --- a/src/main/java/gregtech/api/capability/impl/FuelRecipeLogic.java +++ b/src/main/java/gregtech/api/capability/impl/FuelRecipeLogic.java @@ -6,7 +6,7 @@ import gregtech.api.recipes.RecipeMap; import gregtech.api.recipes.logic.OCParams; import gregtech.api.recipes.logic.OCResult; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; import org.jetbrains.annotations.NotNull; @@ -40,7 +40,7 @@ protected boolean hasEnoughPower(long eut, int duration) { @Override protected void runOverclockingLogic(@NotNull OCParams ocParams, @NotNull OCResult ocResult, - @NotNull IRecipePropertyStorage propertyStorage, long maxVoltage) { + @NotNull RecipePropertyStorage propertyStorage, long maxVoltage) { standardOC(ocParams, ocResult, maxVoltage, getOverclockingDurationFactor(), getOverclockingVoltageFactor()); } diff --git a/src/main/java/gregtech/api/capability/impl/HeatingCoilRecipeLogic.java b/src/main/java/gregtech/api/capability/impl/HeatingCoilRecipeLogic.java index 1c97891e9bb..fc9bd216d55 100644 --- a/src/main/java/gregtech/api/capability/impl/HeatingCoilRecipeLogic.java +++ b/src/main/java/gregtech/api/capability/impl/HeatingCoilRecipeLogic.java @@ -5,8 +5,8 @@ import gregtech.api.recipes.logic.OCParams; import gregtech.api.recipes.logic.OCResult; import gregtech.api.recipes.logic.OverclockingLogic; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; -import gregtech.api.recipes.recipeproperties.TemperatureProperty; +import gregtech.api.recipes.properties.RecipePropertyStorage; +import gregtech.api.recipes.properties.impl.TemperatureProperty; import org.jetbrains.annotations.NotNull; @@ -26,18 +26,18 @@ public HeatingCoilRecipeLogic(RecipeMapMultiblockController metaTileEntity) { } @Override - protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull IRecipePropertyStorage storage) { + protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull RecipePropertyStorage storage) { super.modifyOverclockPre(ocParams, storage); // coil EU/t discount ocParams.setEut(OverclockingLogic.applyCoilEUtDiscount(ocParams.eut(), ((IHeatingCoil) metaTileEntity).getCurrentTemperature(), - storage.getRecipePropertyValue(TemperatureProperty.getInstance(), 0))); + storage.get(TemperatureProperty.getInstance(), 0))); } @Override protected void runOverclockingLogic(@NotNull OCParams ocParams, @NotNull OCResult ocResult, - @NotNull IRecipePropertyStorage propertyStorage, long maxVoltage) { + @NotNull RecipePropertyStorage propertyStorage, long maxVoltage) { heatingCoilOC(ocParams, ocResult, maxVoltage, ((IHeatingCoil) metaTileEntity).getCurrentTemperature(), - propertyStorage.getRecipePropertyValue(TemperatureProperty.getInstance(), 0)); + propertyStorage.get(TemperatureProperty.getInstance(), 0)); } } diff --git a/src/main/java/gregtech/api/capability/impl/MultiblockFuelRecipeLogic.java b/src/main/java/gregtech/api/capability/impl/MultiblockFuelRecipeLogic.java index 746593f366a..30c5e5410e3 100644 --- a/src/main/java/gregtech/api/capability/impl/MultiblockFuelRecipeLogic.java +++ b/src/main/java/gregtech/api/capability/impl/MultiblockFuelRecipeLogic.java @@ -8,7 +8,7 @@ import gregtech.api.recipes.Recipe; import gregtech.api.recipes.logic.OCParams; import gregtech.api.recipes.logic.OCResult; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; import gregtech.api.util.GTUtility; import gregtech.api.util.TextFormattingUtil; @@ -29,7 +29,7 @@ public MultiblockFuelRecipeLogic(RecipeMapMultiblockController tileEntity) { } @Override - protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull IRecipePropertyStorage storage) { + protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull RecipePropertyStorage storage) { // apply maintenance bonuses Tuple maintenanceValues = getMaintenanceValues(); @@ -40,7 +40,7 @@ protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull IRecipePr } @Override - protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull IRecipePropertyStorage storage) { + protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull RecipePropertyStorage storage) { // apply maintenance penalties Tuple maintenanceValues = getMaintenanceValues(); diff --git a/src/main/java/gregtech/api/capability/impl/MultiblockRecipeLogic.java b/src/main/java/gregtech/api/capability/impl/MultiblockRecipeLogic.java index 60960b6c55f..ff95f0fbb0c 100644 --- a/src/main/java/gregtech/api/capability/impl/MultiblockRecipeLogic.java +++ b/src/main/java/gregtech/api/capability/impl/MultiblockRecipeLogic.java @@ -12,7 +12,7 @@ import gregtech.api.recipes.RecipeMap; import gregtech.api.recipes.logic.OCParams; import gregtech.api.recipes.logic.OCResult; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; import gregtech.api.util.GTUtility; import gregtech.common.ConfigHolder; @@ -281,7 +281,7 @@ protected boolean prepareRecipeDistinct(Recipe recipe) { } @Override - protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull IRecipePropertyStorage storage) { + protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull RecipePropertyStorage storage) { super.modifyOverclockPre(ocParams, storage); // apply maintenance bonuses @@ -295,13 +295,13 @@ protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull IRecipePr @Override protected void runOverclockingLogic(@NotNull OCParams ocParams, @NotNull OCResult ocResult, - @NotNull IRecipePropertyStorage propertyStorage, long maxVoltage) { + @NotNull RecipePropertyStorage propertyStorage, long maxVoltage) { subTickParallelOC(ocParams, ocResult, maxVoltage, getOverclockingDurationFactor(), getOverclockingVoltageFactor()); } @Override - protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull IRecipePropertyStorage storage) { + protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull RecipePropertyStorage storage) { super.modifyOverclockPost(ocResult, storage); // apply maintenance penalties @@ -331,7 +331,7 @@ public long getMaximumOverclockVoltage() { // amperage is 1 when the energy is not exactly on a tier // the voltage for recipe search is always on tier, so take the closest lower tier - return GTValues.V[GTUtility.getFloorTierByVoltage(voltage)]; + return GTValues.VOC[GTUtility.getFloorTierByVoltage(voltage)]; } else { // amperage != 1 means the voltage is exactly on a tier // ignore amperage, since only the voltage is relevant for recipe search @@ -420,7 +420,7 @@ public long getMaxVoltage() { // The voltage for recipe search is always on tier, so take the closest lower tier. // List check is done because single hatches will always be a "clean voltage," no need // for any additional checks. - return GTValues.V[GTUtility.getFloorTierByVoltage(voltage)]; + return GTValues.VOC[GTUtility.getFloorTierByVoltage(voltage)]; } return voltage; } else { diff --git a/src/main/java/gregtech/api/capability/impl/PrimitiveRecipeLogic.java b/src/main/java/gregtech/api/capability/impl/PrimitiveRecipeLogic.java index d1893fa8f84..40e4f13ca43 100644 --- a/src/main/java/gregtech/api/capability/impl/PrimitiveRecipeLogic.java +++ b/src/main/java/gregtech/api/capability/impl/PrimitiveRecipeLogic.java @@ -5,7 +5,7 @@ import gregtech.api.recipes.RecipeMap; import gregtech.api.recipes.logic.OCParams; import gregtech.api.recipes.logic.OCResult; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; import org.jetbrains.annotations.NotNull; @@ -50,7 +50,7 @@ public long getMaxVoltage() { @Override protected void runOverclockingLogic(@NotNull OCParams ocParams, @NotNull OCResult ocResult, - @NotNull IRecipePropertyStorage propertyStorage, long maxVoltage) { + @NotNull RecipePropertyStorage propertyStorage, long maxVoltage) { ocParams.setEut(1L); super.runOverclockingLogic(ocParams, ocResult, propertyStorage, maxVoltage); } diff --git a/src/main/java/gregtech/api/capability/impl/RecipeLogicEnergy.java b/src/main/java/gregtech/api/capability/impl/RecipeLogicEnergy.java index 4e62346dcf2..8460b2a7aa7 100644 --- a/src/main/java/gregtech/api/capability/impl/RecipeLogicEnergy.java +++ b/src/main/java/gregtech/api/capability/impl/RecipeLogicEnergy.java @@ -5,7 +5,7 @@ import gregtech.api.recipes.RecipeMap; import gregtech.api.recipes.logic.OCParams; import gregtech.api.recipes.logic.OCResult; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; import org.jetbrains.annotations.NotNull; @@ -56,7 +56,7 @@ public long getMaxVoltage() { @Override protected void runOverclockingLogic(@NotNull OCParams ocParams, @NotNull OCResult ocResult, - @NotNull IRecipePropertyStorage propertyStorage, long maxVoltage) { + @NotNull RecipePropertyStorage propertyStorage, long maxVoltage) { subTickNonParallelOC(ocParams, ocResult, maxVoltage, getOverclockingDurationFactor(), getOverclockingVoltageFactor()); } diff --git a/src/main/java/gregtech/api/cover/CoverSaveHandler.java b/src/main/java/gregtech/api/cover/CoverSaveHandler.java index fe62aa782a9..e9041d022f3 100644 --- a/src/main/java/gregtech/api/cover/CoverSaveHandler.java +++ b/src/main/java/gregtech/api/cover/CoverSaveHandler.java @@ -1,5 +1,6 @@ package gregtech.api.cover; +import gregtech.api.metatileentity.interfaces.ISyncedTileEntity; import gregtech.api.util.GTLog; import net.minecraft.nbt.NBTTagCompound; @@ -66,6 +67,7 @@ public static void receiveInitialSyncData(@NotNull PacketBuffer buf, @NotNull Co } else { Cover cover = definition.createCover(coverHolder, facing); cover.readInitialSyncData(buf); + ISyncedTileEntity.checkInitialData(buf, cover); coverHolder.addCover(facing, cover); } } @@ -107,6 +109,7 @@ public static void readCoverPlacement(@NotNull PacketBuffer buf, @NotNull CoverH coverHolder.addCover(placementSide, cover); cover.readInitialSyncData(buf); + ISyncedTileEntity.checkInitialData(buf, cover); } coverHolder.scheduleRenderUpdate(); } diff --git a/src/main/java/gregtech/api/cover/CoverWithUI.java b/src/main/java/gregtech/api/cover/CoverWithUI.java index d1c6fa0d0c8..6c288e08137 100644 --- a/src/main/java/gregtech/api/cover/CoverWithUI.java +++ b/src/main/java/gregtech/api/cover/CoverWithUI.java @@ -22,6 +22,7 @@ import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.screen.ModularScreen; import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.utils.Color; import com.cleanroommc.modularui.utils.MouseData; import com.cleanroommc.modularui.value.BoolValue; import com.cleanroommc.modularui.value.sync.EnumSyncValue; @@ -29,7 +30,7 @@ import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widget.ParentWidget; import com.cleanroommc.modularui.widgets.ToggleButton; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import org.jetbrains.annotations.ApiStatus; public interface CoverWithUI extends Cover, IUIHolder, IGuiHolder { @@ -98,12 +99,14 @@ default void markAsDirty() { /** * Create the Title bar widget for a Cover. */ - static Row createTitleRow(ItemStack stack) { - return new Row() + static Flow createTitleRow(ItemStack stack) { + return Flow.row() .pos(4, 4) .height(16).coverChildrenWidth() .child(new ItemDrawable(stack).asWidget().size(16).marginRight(4)) - .child(IKey.str(stack.getDisplayName()).color(UI_TITLE_COLOR).asWidget().heightRel(1.0f)); + .child(IKey.str(stack.getDisplayName()) + .color(UI_TITLE_COLOR) + .asWidget().heightRel(1.0f)); } /** @@ -135,6 +138,7 @@ default IKey createAdjustOverlay(boolean increment) { scale = 0.5f; } return IKey.str(builder.toString()) + .color(Color.WHITE.main) .scale(scale); } @@ -204,8 +208,8 @@ private BoolValue.Dynamic boolValueOf(EnumSyncValue syncValue, T value) { return new BoolValue.Dynamic(() -> syncValue.getValue() == value, $ -> syncValue.setValue(value)); } - public Row build() { - var row = new Row().marginBottom(2).coverChildrenHeight().widthRel(1f); + public Flow build() { + var row = Flow.row().marginBottom(2).coverChildrenHeight().widthRel(1f); if (this.enumValue != null && this.syncValue != null) { for (var enumVal : enumValue.getEnumConstants()) { var button = new ToggleButton().size(18).marginRight(2) diff --git a/src/main/java/gregtech/api/gui/GuiTextures.java b/src/main/java/gregtech/api/gui/GuiTextures.java index e2b7afa929a..8c984b5d4ed 100644 --- a/src/main/java/gregtech/api/gui/GuiTextures.java +++ b/src/main/java/gregtech/api/gui/GuiTextures.java @@ -474,9 +474,6 @@ public class GuiTextures { .fullImage("textures/gui/terminal/icon/appearance_hover.png"); public final static TextureArea ICON_CALCULATOR = TextureArea .fullImage("textures/gui/terminal/icon/calculator_hover.png"); - public final static TextureArea UI_FRAME_SIDE_UP = TextureArea.fullImage("textures/gui/terminal/frame_side_up.png"); - public final static TextureArea UI_FRAME_SIDE_DOWN = TextureArea - .fullImage("textures/gui/terminal/frame_side_down.png"); // Texture Areas public static final TextureArea BUTTON_FLUID = TextureArea diff --git a/src/main/java/gregtech/api/gui/widgets/ClickButtonWidget.java b/src/main/java/gregtech/api/gui/widgets/ClickButtonWidget.java index a834867fd1e..d4e059d713a 100644 --- a/src/main/java/gregtech/api/gui/widgets/ClickButtonWidget.java +++ b/src/main/java/gregtech/api/gui/widgets/ClickButtonWidget.java @@ -15,7 +15,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; -import com.google.common.base.Preconditions; import org.lwjgl.input.Mouse; import java.util.Arrays; @@ -64,7 +63,6 @@ public ClickButtonWidget setDisplayFunction(Supplier displayFunction) { } public ClickButtonWidget setTooltipText(String tooltipText, Object... args) { - Preconditions.checkNotNull(tooltipText, "tooltipText"); this.tooltipText = tooltipText; this.tooltipArgs = args; return this; diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java new file mode 100644 index 00000000000..fe5625480e8 --- /dev/null +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -0,0 +1,79 @@ +package gregtech.api.items; + +import net.minecraft.block.BlockCauldron; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.common.util.Constants; + +import org.jetbrains.annotations.NotNull; + +public interface IDyeableItem { + + String COLOR_KEY = "gt_color"; + + default boolean hasColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + return nbttagcompound != null && nbttagcompound.hasKey(COLOR_KEY, Constants.NBT.TAG_INT); + } + + default int getColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound != null && nbttagcompound.hasKey(COLOR_KEY, Constants.NBT.TAG_INT)) { + return nbttagcompound.getInteger(COLOR_KEY); + } + return getDefaultColor(stack); + } + + default int getDefaultColor(ItemStack stack) { + return 0xFFFFFF; + } + + default void removeColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound != null && nbttagcompound.hasKey(COLOR_KEY)) { + nbttagcompound.removeTag(COLOR_KEY); + } + } + + default void setColor(ItemStack stack, int color) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound == null) { + nbttagcompound = new NBTTagCompound(); + stack.setTagCompound(nbttagcompound); + } + nbttagcompound.setInteger(COLOR_KEY, color); + } + + default @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, + float hitY, float hitZ, @NotNull EnumHand hand) { + ItemStack stack = player.getHeldItem(hand); + if (this.hasColor(stack)) { + IBlockState iblockstate = world.getBlockState(pos); + if (iblockstate.getBlock() instanceof BlockCauldron cauldron) { + int water = iblockstate.getValue(BlockCauldron.LEVEL); + if (water > 0) { + this.removeColor(stack); + cauldron.setWaterLevel(world, pos, iblockstate, water - 1); + return EnumActionResult.SUCCESS; + } + } + } + return EnumActionResult.PASS; + } + + /** + * Controls whether the dyeing recipe simply removes the dyeable item from the crafting grid, + * or calls {@link net.minecraftforge.common.ForgeHooks#getContainerItem(ItemStack)} on it. + */ + default boolean shouldGetContainerItem() { + return true; + } +} diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 94ae45effb9..c8d4d70b42d 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -5,15 +5,12 @@ import gregtech.api.capability.GregtechCapabilities; import gregtech.api.capability.impl.CombinedCapabilityProvider; import gregtech.api.capability.impl.ElectricItem; -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.ModularUI; -import gregtech.api.gui.widgets.ClickButtonWidget; -import gregtech.api.gui.widgets.DynamicLabelWidget; import gregtech.api.items.gui.ItemUIFactory; -import gregtech.api.items.gui.PlayerInventoryHolder; import gregtech.api.items.metaitem.ElectricStats; import gregtech.api.items.toolitem.aoe.AoESymmetrical; import gregtech.api.items.toolitem.behavior.IToolBehavior; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; import gregtech.api.recipes.ModHandler; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Material; @@ -63,6 +60,17 @@ import appeng.api.implementations.items.IAEWrench; import buildcraft.api.tools.IToolWrench; import cofh.api.item.IToolHammer; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.api.widget.IWidget; +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.factory.ItemGuiFactory; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.value.sync.IntSyncValue; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.widgets.ButtonWidget; +import com.cleanroommc.modularui.widgets.TextWidget; +import com.cleanroommc.modularui.widgets.layout.Flow; import com.enderio.core.common.interfaces.IOverlayRenderAware; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; @@ -207,7 +215,7 @@ default ItemStack get(Material material) { // Set behaviours NBTTagCompound behaviourTag = getBehaviorsTag(stack); - getToolStats().getBehaviors().forEach(behavior -> behavior.addBehaviorNBT(stack, behaviourTag)); + getBehaviors(stack).forEach(behavior -> behavior.addBehaviorNBT(stack, behaviourTag)); if (aoeDefinition != AoESymmetrical.none()) { behaviourTag.setInteger(MAX_AOE_COLUMN_KEY, aoeDefinition.column); @@ -409,14 +417,14 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { } default boolean definition$hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) { - getToolStats().getBehaviors().forEach(behavior -> behavior.hitEntity(stack, target, attacker)); + getBehaviors(stack).forEach(behavior -> behavior.hitEntity(stack, target, attacker)); damageItem(stack, attacker, getToolStats().getToolDamagePerAttack(stack)); return true; } default boolean definition$onBlockStartBreak(ItemStack stack, BlockPos pos, EntityPlayer player) { if (player.world.isRemote) return false; - getToolStats().getBehaviors().forEach(behavior -> behavior.onBlockStartBreak(stack, pos, player)); + getBehaviors(stack).forEach(behavior -> behavior.onBlockStartBreak(stack, pos, player)); if (!player.isSneaking()) { EntityPlayerMP playerMP = (EntityPlayerMP) player; @@ -458,7 +466,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default boolean definition$onBlockDestroyed(ItemStack stack, World worldIn, IBlockState state, BlockPos pos, EntityLivingBase entityLiving) { if (!worldIn.isRemote) { - getToolStats().getBehaviors() + getBehaviors(stack) .forEach(behavior -> behavior.onBlockDestroyed(stack, worldIn, state, pos, entityLiving)); if ((double) state.getBlockHardness(worldIn, pos) != 0.0D) { @@ -522,7 +530,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default boolean definition$canDisableShield(ItemStack stack, ItemStack shield, EntityLivingBase entity, EntityLivingBase attacker) { - return getToolStats().getBehaviors().stream() + return getBehaviors(stack).stream() .anyMatch(behavior -> behavior.canDisableShield(stack, shield, entity, attacker)); } @@ -570,7 +578,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { } default boolean definition$onEntitySwing(EntityLivingBase entityLiving, ItemStack stack) { - getToolStats().getBehaviors().forEach(behavior -> behavior.onEntitySwing(entityLiving, stack)); + getBehaviors(stack).forEach(behavior -> behavior.onEntitySwing(entityLiving, stack)); return false; } @@ -622,7 +630,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { if (isElectric()) { providers.add(ElectricStats.createElectricItem(0L, getElectricTier()).createProvider(stack)); } - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + for (IToolBehavior behavior : getBehaviors(stack)) { ICapabilityProvider behaviorProvider = behavior.createProvider(stack, nbt); if (behaviorProvider != null) { providers.add(behaviorProvider); @@ -633,10 +641,15 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { return new CombinedCapabilityProvider(providers); } + @NotNull + default List getBehaviors(ItemStack stack) { + return getToolStats().getBehaviors(); + } + default EnumActionResult definition$onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + for (IToolBehavior behavior : getBehaviors(player.getHeldItem(hand))) { if (behavior.onItemUseFirst(player, world, pos, facing, hitX, hitY, hitZ, hand) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; @@ -648,8 +661,9 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default EnumActionResult definition$onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { - for (IToolBehavior behavior : getToolStats().getBehaviors()) { - if (behavior.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ) == EnumActionResult.SUCCESS) { + for (IToolBehavior behavior : getBehaviors(player.getHeldItem(hand))) { + if (behavior.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ) == + EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; } } @@ -662,12 +676,12 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { if (!world.isRemote) { // TODO: relocate to keybind action when keybind PR happens if (player.isSneaking() && getMaxAoEDefinition(stack) != AoESymmetrical.none()) { - PlayerInventoryHolder.openHandItemUI(player, hand); + ItemGuiFactory.INSTANCE.open((EntityPlayerMP) player, hand); return ActionResult.newResult(EnumActionResult.SUCCESS, stack); } } - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + for (IToolBehavior behavior : getBehaviors(stack)) { if (behavior.onItemRightClick(world, player, hand).getType() == EnumActionResult.SUCCESS) { return ActionResult.newResult(EnumActionResult.SUCCESS, stack); } @@ -762,10 +776,10 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { tooltip.add(I18n.format("item.gt.tool.behavior.relocate_mining")); } - if (!addedBehaviorNewLine && !toolStats.getBehaviors().isEmpty()) { + if (!addedBehaviorNewLine && !getBehaviors(stack).isEmpty()) { tooltip.add(""); } - toolStats.getBehaviors().forEach(behavior -> behavior.addInformation(stack, world, tooltip, flag)); + getBehaviors(stack).forEach(behavior -> behavior.addInformation(stack, world, tooltip, flag)); // unique tooltip String uniqueTooltip = "item.gt.tool." + getToolId() + ".tooltip"; @@ -878,6 +892,7 @@ default ModelResourceLocation getModelLocation() { // Sound Playing default void playCraftingSound(EntityPlayer player, ItemStack stack) { + stack = toolbeltPassthrough(stack); // player null check for things like auto-crafters if (ConfigHolder.client.toolCraftingSounds && getSound() != null && player != null) { if (canPlaySound(stack)) { @@ -903,45 +918,76 @@ default void playSound(EntityPlayer player) { } } - default ModularUI createUI(PlayerInventoryHolder holder, EntityPlayer entityPlayer) { - NBTTagCompound tag = getBehaviorsTag(holder.getCurrentItem()); - AoESymmetrical defaultDefinition = getMaxAoEDefinition(holder.getCurrentItem()); - return ModularUI.builder(GuiTextures.BORDERED_BACKGROUND, 120, 80) - .label(6, 10, "item.gt.tool.aoe.columns") - .label(49, 10, "item.gt.tool.aoe.rows") - .label(79, 10, "item.gt.tool.aoe.layers") - .widget(new ClickButtonWidget(15, 24, 20, 20, "+", data -> { - AoESymmetrical.increaseColumn(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(15, 44, 20, 20, "-", data -> { - AoESymmetrical.decreaseColumn(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(50, 24, 20, 20, "+", data -> { - AoESymmetrical.increaseRow(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(50, 44, 20, 20, "-", data -> { - AoESymmetrical.decreaseRow(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(85, 24, 20, 20, "+", data -> { - AoESymmetrical.increaseLayer(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(85, 44, 20, 20, "-", data -> { - AoESymmetrical.decreaseLayer(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new DynamicLabelWidget(23, 65, () -> Integer.toString( - 1 + 2 * AoESymmetrical.getColumn(getBehaviorsTag(holder.getCurrentItem()), defaultDefinition)))) - .widget(new DynamicLabelWidget(58, 65, () -> Integer.toString( - 1 + 2 * AoESymmetrical.getRow(getBehaviorsTag(holder.getCurrentItem()), defaultDefinition)))) - .widget(new DynamicLabelWidget(93, 65, - () -> Integer.toString(1 + - AoESymmetrical.getLayer(getBehaviorsTag(holder.getCurrentItem()), defaultDefinition)))) - .build(holder, entityPlayer); + @Override + default ModularPanel buildUI(HandGuiData guiData, PanelSyncManager manager) { + final var usedStack = guiData.getUsedItemStack(); + final var behaviorsTag = getBehaviorsTag(usedStack); + final var defaultDefinition = getMaxAoEDefinition(usedStack); + + var columnValue = new IntSyncValue( + () -> AoESymmetrical.getColumn(behaviorsTag, defaultDefinition), + i -> AoESymmetrical.setColumn(behaviorsTag, i, defaultDefinition)); + var rowValue = new IntSyncValue( + () -> AoESymmetrical.getRow(behaviorsTag, defaultDefinition), + i -> AoESymmetrical.setRow(behaviorsTag, i, defaultDefinition)); + var layerValue = new IntSyncValue( + () -> AoESymmetrical.getLayer(behaviorsTag, defaultDefinition), + i -> AoESymmetrical.setLayer(behaviorsTag, i, defaultDefinition)); + + manager.syncValue("row_value", rowValue); + manager.syncValue("column_value", columnValue); + manager.syncValue("layer_value", layerValue); + + return GTGuis.createPanel(usedStack.getTranslationKey(), 120, 80) + .child(Flow.row() + .widthRel(1f) + .margin(4, 0) + .alignY(0.5f) + .coverChildrenHeight() + .mainAxisAlignment(Alignment.MainAxis.SPACE_BETWEEN) + .child(createColumn(columnValue, "columns", true, defaultDefinition.column)) + .child(createColumn(rowValue, "rows", true, defaultDefinition.row)) + .child(createColumn(layerValue, "layers", false, defaultDefinition.layer))); + } + + default Flow createColumn(IntSyncValue syncValue, String lang, boolean shouldDouble, int max) { + final var display = IKey.dynamic( + () -> String.valueOf(1 + (shouldDouble ? 2 * syncValue.getIntValue() : syncValue.getIntValue()))); + + IWidget increaseButton = new ButtonWidget<>() + .size(9, 18) + .background(GTGuiTextures.MC_BUTTON) + .overlay(GTGuiTextures.PLUS) + .disableHoverBackground() + .onMousePressed(data -> { + int val = syncValue.getIntValue(); + if (val < max) syncValue.setIntValue(++val); + return true; + }); + + IWidget decreaseButton = new ButtonWidget<>() + .size(9, 18) + .background(GTGuiTextures.MC_BUTTON) + .overlay(GTGuiTextures.MINUS) + .disableHoverBackground() + .onMousePressed(data -> { + int val = syncValue.getIntValue(); + if (val > 0) syncValue.setIntValue(--val); + return true; + }); + + return Flow.column() + .coverChildren() + .child(new TextWidget(IKey.lang("item.gt.tool.aoe." + lang)) + .marginBottom(5)) + .child(Flow.row() + .coverChildren() + .marginBottom(5) + .child(increaseButton) + .child(decreaseButton)) + .child(new TextWidget(display) + .alignment(Alignment.Center) + .widthRel(1f)); } Set getToolClasses(ItemStack stack); diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTHoe.java b/src/main/java/gregtech/api/items/toolitem/ItemGTHoe.java index 13e14e8e574..1dd69871cb4 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTHoe.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTHoe.java @@ -314,7 +314,7 @@ public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World w @Override public boolean hitEntity(@NotNull ItemStack stack, @NotNull EntityLivingBase target, @NotNull EntityLivingBase attacker) { - getToolStats().getBehaviors().forEach(behavior -> behavior.hitEntity(stack, target, attacker)); + getBehaviors(stack).forEach(behavior -> behavior.hitEntity(stack, target, attacker)); // damage by 1, as this is what vanilla does ToolHelper.damageItem(stack, attacker, 1); return true; diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java new file mode 100644 index 00000000000..2f4af5961da --- /dev/null +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -0,0 +1,772 @@ +package gregtech.api.items.toolitem; + +import gregtech.api.GregTechAPI; +import gregtech.api.items.IDyeableItem; +import gregtech.api.items.gui.ItemUIFactory; +import gregtech.api.items.toolitem.behavior.IToolBehavior; +import gregtech.api.metatileentity.MetaTileEntityHolder; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; +import gregtech.api.unification.material.Material; +import gregtech.api.unification.material.properties.PropertyKey; +import gregtech.api.unification.material.properties.ToolProperty; +import gregtech.api.util.LocalizationUtils; +import gregtech.api.util.TextFormattingUtil; +import gregtech.client.utils.TooltipHelper; +import gregtech.common.items.behaviors.ColorSprayBehaviour; +import gregtech.common.metatileentities.multi.multiblockpart.MetaTileEntityMaintenanceHatch; +import gregtech.core.network.packets.PacketToolbeltSelectionChange; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.resources.I18n; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.ai.attributes.AttributeModifier; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.EntityEquipmentSlot; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemTool; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.ICapabilityProvider; +import net.minecraftforge.common.util.INBTSerializable; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.items.CapabilityItemHandler; +import net.minecraftforge.items.ItemStackHandler; +import net.minecraftforge.oredict.OreDictionary; +import net.minecraftforge.oredict.OreIngredient; + +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.value.sync.SyncHandlers; +import com.cleanroommc.modularui.widgets.ItemSlot; +import com.cleanroommc.modularui.widgets.layout.Grid; +import com.cleanroommc.modularui.widgets.slot.SlotGroup; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Multimap; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Range; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.IntSupplier; +import java.util.function.Supplier; + +import static gregtech.api.items.toolitem.ToolHelper.MATERIAL_KEY; + +public class ItemGTToolbelt extends ItemGTTool implements IDyeableItem { + + private static final ThreadLocal lastSlot = ThreadLocal.withInitial(() -> -999); + private static final ThreadLocal lastPlayer = ThreadLocal.withInitial(() -> null); + + public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { + super(domain, id, -1, + new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), + null, false, new HashSet<>(), "toolbelt", new ArrayList<>(), + markerItem); + } + + public int getSelectedSlot(@NotNull ItemStack toolbelt) { + return getHandler(toolbelt).getSelectedSlot(); + } + + public int getSlotCount(@NotNull ItemStack toolbelt) { + return getHandler(toolbelt).getSlots(); + } + + public @NotNull ItemStack getSelectedTool(@NotNull ItemStack toolbelt) { + return getHandler(toolbelt).getSelectedStack(); + } + + @NotNull + public ItemStack getToolInSlot(@NotNull ItemStack toolbelt, int slot) { + ToolStackHandler handler = getHandler(toolbelt); + if (slot < 0 || slot >= handler.getSlots()) return ItemStack.EMPTY; + return handler.getStackInSlot(slot); + } + + @Override + public ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager) { + final var usedStack = guiData.getUsedItemStack(); + final var handler = getHandler(usedStack); + final var selected = handler.getSelectedStack(); + if (!selected.isEmpty() && selected.getItem() instanceof ItemUIFactory factory) { + return factory.buildUI(guiData, guiSyncManager); + } + + int heightBonus = (handler.getSlots() / 9) * 18; + + SlotGroup group = new SlotGroup("toolbelt_inventory", 9); + guiSyncManager.registerSlotGroup(group); + + List slots = new ArrayList<>(); + for (int i = 0; i < handler.getSlots(); i++) { + slots.add(new ItemSlot()); + } + + return GTGuis.createPanel(usedStack.getTranslationKey(), 176, 120 + heightBonus + 12) + .child(IKey.str(usedStack.getDisplayName()).asWidget() + .pos(5, 5) + .height(12)) + .child(new Grid() + .margin(0) + .leftRel(0.5f) + .top(7 + 12) + .coverChildren() + .mapTo(group.getRowSize(), slots, (index, value) -> value + .slot(SyncHandlers.itemSlot(handler, index) + .slotGroup(group) + .changeListener( + (newItem, onlyAmountChanged, client, init) -> handler + .onContentsChanged(index))) + .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) + .debugName("slot_" + index)) + .debugName("toolbelt_inventory")) + .bindPlayerInventory(); + } + + @Override + public @NotNull List getBehaviors(ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected.isEmpty()) return super.getBehaviors(stack); + else if (selected.getItem() instanceof IGTTool tool) { + return tool.getBehaviors(selected); + } else return Collections.emptyList(); + } + + @Override + public float getDestroySpeed(@NotNull ItemStack stack, @NotNull IBlockState state) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().getDestroySpeed(selected, state); + } else return definition$getDestroySpeed(stack, state); + } + + @Override + public boolean hitEntity(@NotNull ItemStack stack, @NotNull EntityLivingBase target, + @NotNull EntityLivingBase attacker) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().hitEntity(selected, target, attacker); + } else return definition$hitEntity(stack, target, attacker); + } + + @Override + public boolean onBlockStartBreak(@NotNull ItemStack itemstack, @NotNull BlockPos pos, + @NotNull EntityPlayer player) { + ItemStack selected = getHandler(itemstack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().onBlockStartBreak(selected, pos, player); + } else return definition$onBlockStartBreak(itemstack, pos, player); + } + + @Override + public boolean onBlockDestroyed(@NotNull ItemStack stack, @NotNull World worldIn, @NotNull IBlockState state, + @NotNull BlockPos pos, @NotNull EntityLivingBase entityLiving) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().onBlockDestroyed(selected, worldIn, state, pos, entityLiving); + } else return definition$onBlockDestroyed(stack, worldIn, state, pos, entityLiving); + } + + @Override + public boolean getIsRepairable(@NotNull ItemStack toRepair, @NotNull ItemStack repair) { + ItemStack selected = getHandler(toRepair).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().getIsRepairable(selected, repair); + } else return definition$getIsRepairable(toRepair, repair); + } + + @NotNull + @Override + public Multimap getAttributeModifiers(@NotNull EntityEquipmentSlot slot, + @NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().getAttributeModifiers(slot, selected); + } else return definition$getAttributeModifiers(slot, stack); + } + + @Override + public int getHarvestLevel(@NotNull ItemStack stack, @NotNull String toolClass, @Nullable EntityPlayer player, + @Nullable IBlockState blockState) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().getHarvestLevel(stack, toolClass, player, blockState); + } else return definition$getHarvestLevel(stack, toolClass, player, blockState); + } + + @NotNull + @Override + public Set getToolClasses(@NotNull ItemStack stack) { + return getHandler(stack).getToolClasses(true); + } + + @Override + public boolean canDisableShield(@NotNull ItemStack stack, @NotNull ItemStack shield, + @NotNull EntityLivingBase entity, @NotNull EntityLivingBase attacker) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().canDisableShield(selected, shield, entity, attacker); + } else return definition$canDisableShield(stack, shield, entity, attacker); + } + + @Override + public boolean doesSneakBypassUse(@NotNull ItemStack stack, @NotNull IBlockAccess world, @NotNull BlockPos pos, + @NotNull EntityPlayer player) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().doesSneakBypassUse(selected, world, pos, player); + } else return definition$doesSneakBypassUse(stack, world, pos, player); + } + + @Override + public boolean onEntitySwing(@NotNull EntityLivingBase entityLiving, @NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().onEntitySwing(entityLiving, selected); + } else return definition$onEntitySwing(entityLiving, stack); + } + + @Override + public boolean canDestroyBlockInCreative(@NotNull World world, @NotNull BlockPos pos, @NotNull ItemStack stack, + @NotNull EntityPlayer player) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().canDestroyBlockInCreative(world, pos, selected, player); + } else return definition$canDestroyBlockInCreative(world, pos, stack, player); + } + + @Override + public boolean shouldCauseReequipAnimation(@NotNull ItemStack oldStack, @NotNull ItemStack newStack, + boolean slotChanged) { + return false; + } + + @Override + public boolean isDamaged(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().isDamaged(selected); + } else return definition$isDamaged(stack); + } + + @Override + public int getDamage(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().getDamage(selected); + } else return definition$getDamage(stack); + } + + @Override + public int getMaxDamage(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().getMaxDamage(selected); + } else return definition$getMaxDamage(stack); + } + + @Override + public void setDamage(@NotNull ItemStack stack, int damage) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + selected.getItem().setDamage(selected, damage); + } else definition$setDamage(stack, damage); + } + + @Override + public double getDurabilityForDisplay(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + double dis = selected.getItem().getDurabilityForDisplay(selected); + // vanillaesque tools need to be inverted + if (selected.getItem() instanceof ItemTool) dis = 1 - dis; + return dis; + } else return definition$getDurabilityForDisplay(stack); + } + + @Override + @SideOnly(Side.CLIENT) + public void addInformation(@NotNull ItemStack stack, @Nullable World world, @NotNull List tooltip, + @NotNull ITooltipFlag flag) { + ToolStackHandler handler = getHandler(stack); + ItemStack selected = handler.getSelectedStack(); + if (!selected.isEmpty()) { + selected.getItem().addInformation(selected, world, tooltip, flag); + } else { + if (stack.getItemDamage() > 0) { + int damageRemaining = this.getTotalMaxDurability(stack) - stack.getItemDamage() + 1; + tooltip.add(I18n.format("item.gt.tool.tooltip.general_uses", + TextFormattingUtil.formatNumbers(damageRemaining))); + } + tooltip.add(I18n.format("item.gt.tool.toolbelt.size", + TextFormattingUtil.formatNumbers(handler.getSlots()))); + tooltip.add(""); + if (TooltipHelper.isShiftDown()) { + tooltip.add(I18n.format("item.gt.tool.toolbelt.tooltip")); + tooltip.add(""); + tooltip.add(I18n.format("item.gt.tool.toolbelt.paint")); + tooltip.add(""); + tooltip.add(I18n.format("item.gt.tool.toolbelt.maintenance")); + } else tooltip.add(I18n.format("gregtech.tooltip.hold_shift")); + } + if (TooltipHelper.isCtrlDown()) { + tooltip.add(""); + for (int i = 0; i < handler.getSlots(); i++) { + ItemStack tool = handler.getStackInSlot(i); + String name = tool.isEmpty() ? "x" : tool.getDisplayName(); + tooltip.add(I18n.format( + handler.selectedSlot == i ? "item.gt.tool.toolbelt.selected" : "item.gt.tool.toolbelt.tool", + i + 1, name)); + } + } else tooltip.add(I18n.format("gregtech.tooltip.hold_ctrl")); + } + + @Override + public boolean canHarvestBlock(@NotNull IBlockState state, @NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (!selected.isEmpty()) { + return selected.getItem().canHarvestBlock(state, selected); + } else return ToolHelper.isToolEffective(state, getToolClasses(stack), getTotalHarvestLevel(stack)); + } + + @Override + public void wrenchUsed(EntityPlayer player, EnumHand hand, ItemStack wrench, RayTraceResult rayTrace) { + ItemStack selected = getHandler(wrench).getSelectedStack(); + if (!selected.isEmpty() && selected.getItem() instanceof IGTTool tool) { + tool.wrenchUsed(player, hand, selected, rayTrace); + } else super.wrenchUsed(player, hand, wrench, rayTrace); + } + + @Override + public void toolUsed(ItemStack item, EntityLivingBase user, BlockPos pos) { + ItemStack selected = getHandler(item).getSelectedStack(); + if (!selected.isEmpty() && selected.getItem() instanceof IGTTool tool) { + tool.toolUsed(selected, user, pos); + } else super.toolUsed(item, user, pos); + } + + @Override + public void used(@NotNull EnumHand hand, @NotNull EntityPlayer player, @NotNull BlockPos pos) { + ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); + if (!selected.isEmpty() && selected.getItem() instanceof IGTTool tool) { + tool.used(hand, player, pos); + } else super.used(hand, player, pos); + } + + @Override + public boolean hasContainerItem(@NotNull ItemStack stack) { + return true; + } + + @Override + public @NotNull ItemStack getContainerItem(@NotNull ItemStack stack) { + if (getHandler(stack).dealCraftDamageToSelected()) { + return stack.copy(); + } + return super.getContainerItem(stack); + } + + public void setOnCraftIngredient(ItemStack stack, Ingredient ingredient) { + int match = getHandler(stack).checkIngredientAgainstTools(ingredient); + if (match != -1) { + setSelectedTool(match, stack); + PacketToolbeltSelectionChange.toClient(match, + lastSlot.get(), lastPlayer.get()); + } + } + + public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass, + @Nullable EntityPlayer entityPlayer) { + return getHandler(stack).checkMaintenanceAgainstTools(toolClass, true, entityPlayer); + } + + public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { + return getHandler(stack).checkIngredientAgainstTools(ingredient) != -1; + } + + public boolean supportsTool(ItemStack stack, ItemStack tool) { + return getHandler(stack).checkToolAgainstTools(tool) != -1; + } + + private ToolStackHandler getHandler(ItemStack stack) { + return (ToolStackHandler) stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); + } + + @Override + public ICapabilityProvider initCapabilities(@NotNull ItemStack stack, NBTTagCompound nbt) { + return new ToolbeltCapabilityProvider(stack); + } + + @SideOnly(Side.CLIENT) + public void changeSelectedToolMousewheel(int direction, ItemStack stack) { + ToolStackHandler handler = getHandler(stack); + if (direction < 0) handler.incrementSelectedSlot(); + else handler.decrementSelectedSlot(); + PacketToolbeltSelectionChange.toServer(handler.selectedSlot); + } + + @SideOnly(Side.CLIENT) + public void changeSelectedToolHotkey(int slot, ItemStack stack) { + ToolStackHandler handler = getHandler(stack); + if (slot < 0 || slot >= handler.getSlots()) handler.selectedSlot = -1; + else handler.selectedSlot = slot; + PacketToolbeltSelectionChange.toServer(handler.selectedSlot); + } + + /** + * For use by {@link PacketToolbeltSelectionChange} only! + */ + @ApiStatus.Internal + public void setSelectedTool(int slot, ItemStack stack) { + ToolStackHandler handler = getHandler(stack); + if (slot < 0 || slot >= handler.getSlots()) + handler.selectedSlot = -1; + else handler.selectedSlot = slot; + } + + @Override + public @NotNull String getItemStackDisplayName(@NotNull ItemStack stack) { + ItemStack tool = getHandler(stack).getSelectedStack(); + String selectedToolDisplay = ""; + if (!tool.isEmpty()) { + selectedToolDisplay = " (" + tool.getDisplayName() + ")"; + } + getHandler(stack).disablePassthrough(); + String name = LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), + selectedToolDisplay); + getHandler(stack).enablePassthrough(); + return name; + } + + @Override + public @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, + float hitY, float hitZ, @NotNull EnumHand hand) { + EnumActionResult result = IDyeableItem.super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + if (result == EnumActionResult.PASS) { + ItemStack stack = player.getHeldItem(hand); + ToolStackHandler handler = getHandler(stack); + if (handler.getSelectedStack().isEmpty() && + world.getTileEntity(pos) instanceof MetaTileEntityHolder holder && + holder.getMetaTileEntity() instanceof MetaTileEntityMaintenanceHatch maintenance) { + maintenance.fixMaintenanceProblemsWithToolbelt(player, this, stack); + return EnumActionResult.SUCCESS; + } + return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + } else return result; + } + + @Override + public @NotNull EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, + @NotNull EnumFacing facing, float hitX, float hitY, float hitZ) { + ToolStackHandler handler = getHandler(player.getHeldItem(hand)); + ItemStack selected = handler.getSelectedStack(); + if (!selected.isEmpty()) { + ColorSprayBehaviour spray = ColorSprayBehaviour.getBehavior(selected); + if (spray != null) { + EnumActionResult result = spray.useFromToolbelt(player, world, pos, hand, facing, hitX, hitY, hitZ, + selected); + if (result != EnumActionResult.PASS) return result; + } + } + return super.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); + } + + @Override + public int getColor(ItemStack stack, int tintIndex) { + if (tintIndex == 0) { + return this.getColor(stack); + } + getHandler(stack).disablePassthrough(); + int color = super.getColor(stack, tintIndex); + getHandler(stack).enablePassthrough(); + return color; + } + + @Override + public int getDefaultColor(ItemStack stack) { + return 0xA06540; + } + + @Override + public boolean shouldGetContainerItem() { + return false; + } + + public static boolean checkIngredientAgainstToolbelt(@NotNull ItemStack input, @NotNull OreIngredient ingredient) { + if (input.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.supportsIngredient(input, ingredient)) { + toolbelt.setOnCraftIngredient(input, ingredient); + return true; + } + } + return false; + } + + public static void setCraftingSlot(int slot, EntityPlayerMP player) { + lastSlot.set(slot); + lastPlayer.set(player); + } + + public static boolean checkToolAgainstToolbelt(@NotNull ItemStack toolbelt, @NotNull ItemStack tool) { + if (toolbelt.getItem() instanceof ItemGTToolbelt belt && ToolHelper.isUtilityItem(tool)) { + return belt.supportsTool(toolbelt, tool); + } + return false; + } + + protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { + + protected final IntSupplier slotCountSupplier; + + private @Nullable ToolStackHandler handler; + + public ToolbeltCapabilityProvider(ItemStack stack) { + slotCountSupplier = () -> { + if (!ToolHelper.hasMaterial(stack)) return 4; + NBTTagCompound toolTag = stack.getOrCreateSubCompound(ToolHelper.TOOL_TAG_KEY); + Material material = GregTechAPI.materialManager.getMaterial(toolTag.getString(MATERIAL_KEY)); + if (material == null) return 4; + ToolProperty toolProperty = material.getProperty(PropertyKey.TOOL); + return Math.min(8, 2 + toolProperty.getToolHarvestLevel()); + }; + } + + @Override + public boolean hasCapability(@NotNull Capability capability, EnumFacing facing) { + return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY; + } + + @Override + public T getCapability(@NotNull Capability capability, EnumFacing facing) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) + return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(this.getHandler()); + else return null; + } + + @Override + public NBTTagCompound serializeNBT() { + return this.getHandler().serializeNBT(); + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + // .copy() prevents double damage ticks in singleplayer + this.getHandler().deserializeNBT(nbt.copy()); + } + + protected @NotNull ToolStackHandler getHandler() { + int size = slotCountSupplier.getAsInt(); + if (handler == null) handler = new ToolStackHandler(size); + else if (handler.getSlots() != size) handler.setSize(size); + return handler; + } + } + + @Override + public NBTTagCompound getNBTShareTag(ItemStack stack) { + NBTTagCompound tag = new NBTTagCompound(); + if (stack.getTagCompound() != null) { + tag.setTag("NBT", stack.getTagCompound()); + } + tag.setTag("Cap", getHandler(stack).serializeNBT()); + return tag; + } + + @Override + public void readNBTShareTag(ItemStack stack, NBTTagCompound nbt) { + // cap syncing is handled separately, we only need it on the share tag so that changes are detected properly. + stack.setTagCompound(nbt == null ? null : (nbt.hasKey("NBT") ? nbt.getCompoundTag("NBT") : null)); + } + + protected static class ToolStackHandler extends ItemStackHandler { + + private static final Set EMPTY = ImmutableSet.of(); + + private @Range(from = -1, to = 128) int selectedSlot = -1; + + protected ItemTool[] tools; + protected IGTTool[] gtTools; + protected final Set toolClasses = new ObjectOpenHashSet<>(); + + private boolean passthrough = true; + + public ToolStackHandler(int size) { + setSize(size); + } + + public void incrementSelectedSlot() { + if ((this.selectedSlot += 1) >= this.getSlots()) this.selectedSlot = -1; + } + + public void decrementSelectedSlot() { + if ((this.selectedSlot -= 1) < -1) this.selectedSlot = this.getSlots() - 1; + } + + public int getSelectedSlot() { + if (passthrough) return selectedSlot; + else return -1; + } + + public void setSelectedSlot(int selectedSlot) { + this.selectedSlot = Math.min(getSlots() - 1, Math.max(selectedSlot, -1)); + } + + public void enablePassthrough() { + this.passthrough = true; + } + + public void disablePassthrough() { + this.passthrough = false; + } + + public @NotNull ItemStack getSelectedStack() { + if (getSelectedSlot() == -1) return ItemStack.EMPTY; + else return this.getStackInSlot(getSelectedSlot()); + } + + public Set getToolClasses(boolean defaultEmpty) { + ItemStack selectedStack = getSelectedStack(); + if (!selectedStack.isEmpty()) { + if (selectedStack.getItem() instanceof ItemTool tool) { + return tool.getToolClasses(selectedStack); + } else if (selectedStack.getItem() instanceof IGTTool tool) { + return tool.getToolClasses(selectedStack); + } + } + if (defaultEmpty) return EMPTY; + return toolClasses; + } + + @Override + public boolean isItemValid(int slot, @NotNull ItemStack stack) { + Item item = stack.getItem(); + if (item instanceof ItemGTToolbelt) return false; + return ToolHelper.isUtilityItem(stack); + } + + @Override + protected void onContentsChanged(int slot) { + if (this.selectedSlot == slot) this.selectedSlot = -1; + this.updateSlot(slot); + this.update(); + + super.onContentsChanged(slot); + } + + @Override + public NBTTagCompound serializeNBT() { + NBTTagCompound tag = super.serializeNBT(); + if (this.selectedSlot != -1) tag.setByte("SelectedSlot", (byte) this.selectedSlot); + return tag; + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + super.deserializeNBT(nbt); + if (nbt.hasKey("SelectedSlot")) this.selectedSlot = nbt.getByte("SelectedSlot"); + } + + @Override + public void setSize(int size) { + super.setSize(size); + this.gtTools = new IGTTool[size]; + this.tools = new ItemTool[size]; + } + + @Override + protected void onLoad() { + for (int i = 0; i < getSlots(); i++) { + this.updateSlot(i); + } + this.update(); + } + + protected void updateSlot(int slot) { + Item item = this.getStackInSlot(slot).getItem(); + if (item instanceof ItemTool tool) { + tools[slot] = tool; + } else { + tools[slot] = null; + } + if (item instanceof IGTTool tool) { + gtTools[slot] = tool; + } else { + gtTools[slot] = null; + } + } + + protected void update() { + this.toolClasses.clear(); + for (int i = 0; i < getSlots(); i++) { + if (tools[i] != null) this.toolClasses.addAll(tools[i].getToolClasses(stacks.get(i))); + } + } + + public boolean checkMaintenanceAgainstTools(String toolClass, boolean doCraftingDamage, + @Nullable EntityPlayer entityPlayer) { + for (int i = 0; i < this.getSlots(); i++) { + ItemStack stack = this.getStackInSlot(i); + if (ToolHelper.isTool(stack, toolClass)) { + if (doCraftingDamage) ToolHelper.damageItemWhenCrafting(stack, entityPlayer); + return true; + } + } + return false; + } + + public int checkIngredientAgainstTools(Ingredient ingredient) { + for (int i = 0; i < this.getSlots(); i++) { + ItemStack stack = this.getStackInSlot(i); + if (ingredient.test(stack)) { + return i; + } + } + return -1; + } + + public void dealCraftDamageToSlot(int slot) { + ItemStack stack = this.getStackInSlot(slot); + this.setStackInSlot(slot, stack.getItem().getContainerItem(stack)); + } + + public boolean dealCraftDamageToSelected() { + if (selectedSlot != -1) { + dealCraftDamageToSlot(selectedSlot); + return true; + } else return false; + } + + public int checkToolAgainstTools(ItemStack tool) { + for (int i = 0; i < this.getSlots(); i++) { + ItemStack stack = this.getStackInSlot(i); + if (OreDictionary.itemMatches(stack, tool, false)) { + return i; + } + } + return -1; + } + } +} diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index 23d3145ca9b..3dc2f38b11d 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -3,6 +3,8 @@ import gregtech.api.GTValues; import gregtech.api.capability.GregtechCapabilities; import gregtech.api.capability.IElectricItem; +import gregtech.api.items.metaitem.MetaItem; +import gregtech.api.items.metaitem.stats.IItemBehaviour; import gregtech.api.items.toolitem.aoe.AoESymmetrical; import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMaps; @@ -15,10 +17,17 @@ import gregtech.api.util.function.QuintFunction; import gregtech.common.ConfigHolder; import gregtech.common.items.MetaItems; +import gregtech.common.items.behaviors.ColorSprayBehaviour; import gregtech.tools.enchants.EnchantmentHardHammer; import net.minecraft.advancements.CriteriaTriggers; -import net.minecraft.block.*; +import net.minecraft.block.Block; +import net.minecraft.block.BlockCommandBlock; +import net.minecraft.block.BlockLiquid; +import net.minecraft.block.BlockPane; +import net.minecraft.block.BlockRailBase; +import net.minecraft.block.BlockStructure; +import net.minecraft.block.BlockWeb; import net.minecraft.block.state.IBlockState; import net.minecraft.enchantment.EnchantmentDurability; import net.minecraft.enchantment.EnchantmentHelper; @@ -29,6 +38,7 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Enchantments; import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemTool; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.play.server.SPacketBlockChange; import net.minecraft.stats.StatBase; @@ -57,7 +67,11 @@ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; -import java.util.*; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.Set; import java.util.function.Supplier; import static gregtech.api.GTValues.LV; @@ -184,19 +198,34 @@ public static void registerToolSymbol(Character symbol, IGTTool tool) { } public static NBTTagCompound getToolTag(ItemStack stack) { + stack = toolbeltPassthrough(stack); return stack.getOrCreateSubCompound(TOOL_TAG_KEY); } + public static ItemStack toolbeltPassthrough(ItemStack stack) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt && hasMaterial(stack)) { + ItemStack selected = toolbelt.getSelectedTool(stack); + if (!selected.isEmpty()) stack = selected; + } + return stack; + } + public static NBTTagCompound getBehaviorsTag(ItemStack stack) { + stack = toolbeltPassthrough(stack); return stack.getOrCreateSubCompound(BEHAVIOURS_TAG_KEY); } + public static void setBehaviorsTag(ItemStack stack, NBTTagCompound tag) { + stack = toolbeltPassthrough(stack); + stack.setTagInfo(BEHAVIOURS_TAG_KEY, tag); + } + public static ItemStack getAndSetToolData(IGTTool tool, Material material, int maxDurability, int harvestLevel, float toolSpeed, float attackDamage) { ItemStack stack = tool.getRaw(); GTUtility.getOrCreateNbtCompound(stack).setInteger(HIDE_FLAGS, 2); NBTTagCompound toolTag = getToolTag(stack); - toolTag.setString(MATERIAL_KEY, material.toString()); + toolTag.setString(MATERIAL_KEY, material.getRegistryName()); toolTag.setInteger(MAX_DURABILITY_KEY, maxDurability); toolTag.setInteger(HARVEST_LEVEL_KEY, harvestLevel); toolTag.setFloat(TOOL_SPEED_KEY, toolSpeed); @@ -220,6 +249,13 @@ public static ItemStack getAndSetToolData(IGTTool tool, Material material, int m * @param entity entity that has damaged this stack */ public static void damageItemWhenCrafting(@NotNull ItemStack stack, @Nullable EntityLivingBase entity) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selectedStack = toolbelt.getSelectedTool(stack); + if (!selectedStack.isEmpty()) { + damageItemWhenCrafting(selectedStack, entity); + return; + } + } int damage = 2; if (stack.getItem() instanceof IGTTool) { damage = ((IGTTool) stack.getItem()).getToolStats().getToolDamagePerCraft(stack); @@ -254,58 +290,63 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa * @param damage how much damage the stack will take */ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBase entity, int damage) { - if (!(stack.getItem() instanceof IGTTool)) { + if (!(stack.getItem() instanceof IGTTool tool)) { if (entity != null) stack.damageItem(damage, entity); - } else { - if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean(UNBREAKABLE_KEY)) { + return; + } else if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selectedStack = toolbelt.getSelectedTool(stack); + if (!selectedStack.isEmpty()) { + damageItem(selectedStack, entity, damage); return; } - IGTTool tool = (IGTTool) stack.getItem(); - if (!(entity instanceof EntityPlayer) || !((EntityPlayer) entity).capabilities.isCreativeMode) { - Random random = entity == null ? GTValues.RNG : entity.getRNG(); - if (tool.isElectric()) { - int electricDamage = damage * ConfigHolder.machines.energyUsageMultiplier; - IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, - null); - if (electricItem != null) { - electricItem.discharge(electricDamage, tool.getElectricTier(), true, false, false); - if (electricItem.getCharge() > 0 && - random.nextInt(100) >= ConfigHolder.tools.rngDamageElectricTools) { - return; - } - } else { - throw new IllegalStateException( - "Electric tool does not have an attached electric item capability."); - } - } - int unbreakingLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack); - int negated = 0; - for (int k = 0; unbreakingLevel > 0 && k < damage; k++) { - if (EnchantmentDurability.negateDamage(stack, unbreakingLevel, random)) { - negated++; + } + if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean(UNBREAKABLE_KEY)) { + return; + } + if (!(entity instanceof EntityPlayer) || !((EntityPlayer) entity).capabilities.isCreativeMode) { + Random random = entity == null ? GTValues.RNG : entity.getRNG(); + if (tool.isElectric()) { + int electricDamage = damage * ConfigHolder.machines.energyUsageMultiplier; + IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, + null); + if (electricItem != null) { + electricItem.discharge(electricDamage, tool.getElectricTier(), true, false, false); + if (electricItem.getCharge() > 0 && + random.nextInt(100) >= ConfigHolder.tools.rngDamageElectricTools) { + return; } + } else { + throw new IllegalStateException( + "Electric tool does not have an attached electric item capability."); } - damage -= negated; - if (damage <= 0) { - return; - } - int newDurability = stack.getItemDamage() + damage; - if (entity instanceof EntityPlayerMP) { - CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger((EntityPlayerMP) entity, stack, newDurability); + } + int unbreakingLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack); + int negated = 0; + for (int k = 0; unbreakingLevel > 0 && k < damage; k++) { + if (EnchantmentDurability.negateDamage(stack, unbreakingLevel, random)) { + negated++; } - stack.setItemDamage(newDurability); - if (newDurability > stack.getMaxDamage()) { - if (entity instanceof EntityPlayer) { - StatBase stat = StatList.getObjectBreakStats(stack.getItem()); - if (stat != null) { - ((EntityPlayer) entity).addStat(stat); - } - } - if (entity != null) { - entity.renderBrokenItemStack(stack); + } + damage -= negated; + if (damage <= 0) { + return; + } + int newDurability = stack.getItemDamage() + damage; + if (entity instanceof EntityPlayerMP) { + CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger((EntityPlayerMP) entity, stack, newDurability); + } + stack.setItemDamage(newDurability); + if (newDurability > stack.getMaxDamage()) { + if (entity instanceof EntityPlayer) { + StatBase stat = StatList.getObjectBreakStats(stack.getItem()); + if (stat != null) { + ((EntityPlayer) entity).addStat(stat); } - stack.shrink(1); } + if (entity != null) { + entity.renderBrokenItemStack(stack); + } + stack.shrink(1); } } } @@ -320,6 +361,7 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa */ public static void onActionDone(@NotNull EntityPlayer player, @NotNull World world, @NotNull EnumHand hand) { ItemStack stack = player.getHeldItem(hand); + stack = toolbeltPassthrough(stack); IGTTool tool = (IGTTool) stack.getItem(); ToolHelper.damageItem(stack, player); if (tool.getSound() != null) { @@ -346,6 +388,32 @@ public static boolean isTool(ItemStack tool, String... toolClasses) { return false; } + /** + * @return if the itemstack should be considered a utility item and thus can be put into toolbelts. + */ + public static boolean isUtilityItem(ItemStack utility) { + return isTool(utility) || isSpraycan(utility); + } + + /** + * @return if the itemstack should be considered a tool + */ + public static boolean isTool(ItemStack tool) { + return tool.getItem() instanceof ItemTool || tool.getItem() instanceof IGTTool; + } + + /** + * @return if the itemstack should be considered a spraycan + */ + public static boolean isSpraycan(ItemStack spraycan) { + if (spraycan.getItem() instanceof MetaItemmeta) { + for (IItemBehaviour behaviour : meta.getBehaviours(spraycan)) { + if (behaviour instanceof ColorSprayBehaviour) return true; + } + } + return false; + } + /** * Return if all the specified tool classes exists in the tool */ @@ -363,6 +431,7 @@ public static boolean areTools(ItemStack tool, String... toolClasses) { * @return The level of Fortune or Looting that the tool is enchanted with, or zero */ public static int getFortuneOrLootingLevel(ItemStack tool) { + tool = toolbeltPassthrough(tool); if (tool.getItem() instanceof ItemGTSword) { return EnchantmentHelper.getEnchantmentLevel(Enchantments.LOOTING, tool); } else if (tool.getItem() instanceof IGTTool) { @@ -384,6 +453,7 @@ public static AoESymmetrical getAoEDefinition(ItemStack stack) { * AoE Block Breaking Routine. */ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlayerMP player) { + stack = toolbeltPassthrough(stack); int currentDurability = getToolTag(stack).getInteger(DURABILITY_KEY); int maximumDurability = getToolTag(stack).getInteger(MAX_DURABILITY_KEY); int remainingUses = maximumDurability - currentDurability; @@ -400,7 +470,9 @@ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlaye return true; } // If the tool is an electric tool, catch the tool breaking and cancel the remaining AOE - else if (!player.getHeldItemMainhand().isItemEqualIgnoreDurability(stack)) { + ItemStack tool = player.getHeldItemMainhand(); + tool = toolbeltPassthrough(tool); + if (!tool.isItemEqualIgnoreDurability(stack)) { return true; } } @@ -412,6 +484,7 @@ else if (!player.getHeldItemMainhand().isItemEqualIgnoreDurability(stack)) { public static Set iterateAoE(ItemStack stack, AoESymmetrical aoeDefinition, World world, EntityPlayer player, RayTraceResult rayTraceResult, QuintFunction function) { + stack = toolbeltPassthrough(stack); if (aoeDefinition != AoESymmetrical.none() && rayTraceResult != null && rayTraceResult.typeOfHit == RayTraceResult.Type.BLOCK && rayTraceResult.sideHit != null) { int column = aoeDefinition.column; @@ -659,7 +732,6 @@ public static void applyHammerDropConversion(ItemStack tool, IBlockState state, } } - @SuppressWarnings("BooleanMethodIsAlwaysInverted") public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { // This is *not* a vanilla/forge convention, Forge never added "shears" to ItemShear's tool classes. if (isTool(tool, ToolClasses.SHEARS) && shearBlockRoutine(player, tool, pos) == 0) { @@ -710,6 +782,7 @@ public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, B */ public static int shearBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { if (!player.isCreative()) { + tool = toolbeltPassthrough(tool); World world = player.world; IBlockState state = world.getBlockState(pos); if (state.getBlock() instanceof IShearable) { @@ -768,8 +841,15 @@ public static ItemStack getSilkTouchDrop(@NotNull IBlockState state) { } public static void playToolSound(ItemStack stack, EntityPlayer player) { + stack = toolbeltPassthrough(stack); if (stack.getItem() instanceof IGTTool) { ((IGTTool) stack.getItem()).playSound(player); } } + + public static boolean hasMaterial(ItemStack stack) { + var tag = stack.getTagCompound(); + if (tag == null || !tag.hasKey(TOOL_TAG_KEY)) return false; + return tag.getCompoundTag(TOOL_TAG_KEY).hasKey(MATERIAL_KEY); + } } diff --git a/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java b/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java index a1dfc249012..8f3276f6212 100644 --- a/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java +++ b/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java @@ -3,6 +3,7 @@ import gregtech.api.items.toolitem.ToolHelper; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.math.MathHelper; import net.minecraftforge.common.util.Constants; import com.google.common.base.Preconditions; @@ -73,70 +74,46 @@ public static int getLayer(NBTTagCompound tag, AoESymmetrical defaultDefinition) return defaultDefinition.layer; } + public static void setColumn(NBTTagCompound tag, int i, AoESymmetrical defaultDefinition) { + tag.setInteger(ToolHelper.AOE_COLUMN_KEY, MathHelper.clamp(i, 0, defaultDefinition.column)); + } + + public static void setRow(NBTTagCompound tag, int i, AoESymmetrical defaultDefinition) { + tag.setInteger(ToolHelper.AOE_ROW_KEY, MathHelper.clamp(i, 0, defaultDefinition.row)); + } + + public static void setLayer(NBTTagCompound tag, int i, AoESymmetrical defaultDefinition) { + tag.setInteger(ToolHelper.AOE_LAYER_KEY, MathHelper.clamp(i, 0, defaultDefinition.layer)); + } + public static void increaseColumn(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_COLUMN_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_COLUMN_KEY, defaultDefinition.column); - } else { - int currentColumn = tag.getInteger(ToolHelper.AOE_COLUMN_KEY); - if (currentColumn < defaultDefinition.column) { - tag.setInteger(ToolHelper.AOE_COLUMN_KEY, currentColumn + 1); - } - } + int currentColumn = getColumn(tag, defaultDefinition); + setColumn(tag, currentColumn + 1, defaultDefinition); } public static void increaseRow(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_ROW_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_ROW_KEY, defaultDefinition.row); - } else { - int currentRow = tag.getInteger(ToolHelper.AOE_ROW_KEY); - if (currentRow < defaultDefinition.row) { - tag.setInteger(ToolHelper.AOE_ROW_KEY, currentRow + 1); - } - } + int currentRow = getRow(tag, defaultDefinition); + setRow(tag, currentRow + 1, defaultDefinition); } public static void increaseLayer(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_LAYER_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_LAYER_KEY, defaultDefinition.layer); - } else { - int currentLayer = tag.getInteger(ToolHelper.AOE_LAYER_KEY); - if (currentLayer < defaultDefinition.layer) { - tag.setInteger(ToolHelper.AOE_LAYER_KEY, currentLayer + 1); - } - } + int currentLayer = getLayer(tag, defaultDefinition); + setLayer(tag, currentLayer + 1, defaultDefinition); } public static void decreaseColumn(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_COLUMN_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_COLUMN_KEY, defaultDefinition.column); - } else { - int currentColumn = tag.getInteger(ToolHelper.AOE_COLUMN_KEY); - if (currentColumn > 0) { - tag.setInteger(ToolHelper.AOE_COLUMN_KEY, currentColumn - 1); - } - } + int currentColumn = getColumn(tag, defaultDefinition); + setColumn(tag, currentColumn - 1, defaultDefinition); } public static void decreaseRow(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_ROW_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_ROW_KEY, defaultDefinition.row); - } else { - int currentRow = tag.getInteger(ToolHelper.AOE_ROW_KEY); - if (currentRow > 0) { - tag.setInteger(ToolHelper.AOE_ROW_KEY, currentRow - 1); - } - } + int currentRow = getRow(tag, defaultDefinition); + setRow(tag, currentRow - 1, defaultDefinition); } public static void decreaseLayer(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_LAYER_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_LAYER_KEY, defaultDefinition.layer); - } else { - int currentLayer = tag.getInteger(ToolHelper.AOE_LAYER_KEY); - if (currentLayer > 0) { - tag.setInteger(ToolHelper.AOE_LAYER_KEY, currentLayer - 1); - } - } + int currentLayer = getLayer(tag, defaultDefinition); + setLayer(tag, currentLayer - 1, defaultDefinition); } public static AoESymmetrical none() { diff --git a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java index 4131cf59218..77dd5679b68 100644 --- a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java +++ b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java @@ -79,7 +79,10 @@ default boolean canDisableShield(ItemStack stack, ItemStack shield, EntityLiving } /** - * Called when a Block is right-clicked with this Item, but before the block is activated + * Called when a Block is right-clicked with this Item, but before the block is activated. + * If actions not going through {@link gregtech.api.items.toolitem.ToolHelper} are performed, such as + * {@link ItemStack#shrink(int)}, don't forget to perform toolbelt passthrough via + * {@link gregtech.api.items.toolitem.ToolHelper#toolbeltPassthrough(ItemStack)} * * @param player the player clicking with the item * @param world the world in which the block is clicked @@ -97,7 +100,10 @@ default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull W } /** - * Called when a Block is right-clicked with this Item + * Called when a Block is right-clicked with this Item. + * If actions not going through {@link gregtech.api.items.toolitem.ToolHelper} are performed, such as + * {@link ItemStack#shrink(int)}, don't forget to perform toolbelt passthrough via + * {@link gregtech.api.items.toolitem.ToolHelper#toolbeltPassthrough(ItemStack)} * * @param player the player clicking with the item * @param world the world in which the block is clicked @@ -117,6 +123,9 @@ default EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World /** * Called when the equipped item is right-clicked. + * If actions not going through {@link gregtech.api.items.toolitem.ToolHelper} are performed, such as + * {@link ItemStack#shrink(int)}, don't forget to perform toolbelt passthrough via + * {@link gregtech.api.items.toolitem.ToolHelper#toolbeltPassthrough(ItemStack)} * * @param world the world in which the click happened * @param player the player clicking the item diff --git a/src/main/java/gregtech/api/metatileentity/MetaTileEntity.java b/src/main/java/gregtech/api/metatileentity/MetaTileEntity.java index 435281e015a..c2f54e16422 100644 --- a/src/main/java/gregtech/api/metatileentity/MetaTileEntity.java +++ b/src/main/java/gregtech/api/metatileentity/MetaTileEntity.java @@ -35,6 +35,8 @@ import gregtech.api.util.Mods; import gregtech.client.renderer.texture.Textures; import gregtech.client.utils.BloomEffectUtil; +import gregtech.client.utils.RenderUtil; +import gregtech.client.utils.TooltipHelper; import gregtech.common.ConfigHolder; import gregtech.common.creativetab.GTCreativeTabs; import gregtech.common.items.MetaItems; @@ -45,6 +47,7 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.I18n; import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; @@ -86,7 +89,6 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.ColourMultiplier; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; import com.cleanroommc.modularui.api.IGuiHolder; @@ -98,6 +100,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArraySet; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.ApiStatus; @@ -105,10 +108,12 @@ import org.jetbrains.annotations.Nullable; import java.util.ArrayList; +import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.UUID; import java.util.function.BiConsumer; import java.util.function.Consumer; @@ -160,6 +165,16 @@ public abstract class MetaTileEntity implements ISyncedTileEntity, CoverHolder, private int playSoundCooldown = 0; private int lastTick = 0; + @Nullable + private UUID owner = null; + + private final Set creativeTabs = new ObjectArraySet<>(); + + { + creativeTabs.add(CreativeTabs.SEARCH); + creativeTabs.add(GTCreativeTabs.TAB_GREGTECH_MACHINES); + } + protected MetaTileEntity(@NotNull ResourceLocation metaTileEntityId) { this.metaTileEntityId = metaTileEntityId; this.registry = GregTechAPI.mteManager.getRegistry(metaTileEntityId.getNamespace()); @@ -229,7 +244,10 @@ public void addDebugInfo(List list) {} @SideOnly(Side.CLIENT) public void addInformation(ItemStack stack, @Nullable World world, @NotNull List tooltip, - boolean advanced) {} + boolean advanced) { + if (ConfigHolder.machines.doTerrainExplosion && getIsWeatherOrTerrainResistant()) + tooltip.add(I18n.format("gregtech.universal.tooltip.terrain_resist")); + } /** * Override this to add extended tool information to the "Hold SHIFT to show Tool Info" tooltip section. @@ -264,7 +282,7 @@ public boolean showToolUsages() { @SideOnly(Side.CLIENT) public Pair getParticleTexture() { - return Pair.of(TextureUtils.getMissingSprite(), 0xFFFFFF); + return Pair.of(RenderUtil.getMissingSprite(), 0xFFFFFF); } /** @@ -290,7 +308,7 @@ public void setRenderContextStack(ItemStack itemStack) { */ @SideOnly(Side.CLIENT) public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline) { - TextureAtlasSprite atlasSprite = TextureUtils.getMissingSprite(); + TextureAtlasSprite atlasSprite = RenderUtil.getMissingSprite(); IVertexOperation[] renderPipeline = ArrayUtils.add(pipeline, new ColourMultiplier(GTUtility.convertRGBtoOpaqueRGBA_CL(getPaintingColorForRendering()))); for (EnumFacing face : EnumFacing.VALUES) { @@ -356,7 +374,7 @@ public void getSubItems(CreativeTabs creativeTab, NonNullList subItem * MachineItemBlock#addCreativeTab(CreativeTabs) */ public boolean isInCreativeTab(CreativeTabs creativeTab) { - return creativeTab == CreativeTabs.SEARCH || creativeTab == GTCreativeTabs.TAB_GREGTECH_MACHINES; + return creativeTabs.contains(creativeTab); } public String getItemSubTypeId(ItemStack itemStack) { @@ -509,6 +527,10 @@ public boolean onRightClick(EntityPlayer playerIn, EnumHand hand, EnumFacing fac } else { MetaTileEntityUIFactory.INSTANCE.openUI(getHolder(), (EntityPlayerMP) playerIn); } + + if (getOwner() == null) { + this.owner = playerIn.getUniqueID(); + } } return true; } else { @@ -577,6 +599,9 @@ public final boolean onToolClick(EntityPlayer playerIn, @NotNull Set 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 MetaItemmetaItem) { + 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 RecipePropertythat)) 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 node) { - if (node.isLeaf()) return; - for (TreeNode 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 key - * @param leaf - */ -public class TreeNode { - - public final int dimension; - protected final T key; - protected K content; - protected List> children; - - public TreeNode(int dimension, T key) { - this.dimension = dimension; - this.key = key; - } - - public boolean isLeaf() { - return getChildren() == null || getChildren().isEmpty(); - } - - public TreeNode getOrCreateChild(T childKey) { - TreeNode result; - if (getChildren() != null) { - result = getChildren().stream().filter(child -> child.key.equals(childKey)).findFirst().orElseGet(() -> { - TreeNode newNode = new TreeNode<>(dimension + 1, childKey); - getChildren().add(newNode); - return newNode; - }); - } else { - children = new ArrayList<>(); - result = new TreeNode<>(dimension + 1, childKey); - getChildren().add(result); - } - return result; - } - - public TreeNode getChild(T key) { - if (getChildren() != null) { - for (TreeNode child : getChildren()) { - if (child.key.equals(key)) { - return child; - } - } - } - return null; - } - - public void addContent(T key, K content) { - getOrCreateChild(key).content = content; - } - - public T getKey() { - return key; - } - - public K getContent() { - return content; - } - - public List> getChildren() { - return children; - } - - @Override - public String toString() { - return key.toString(); - } -} diff --git a/src/main/java/gregtech/api/unification/material/Material.java b/src/main/java/gregtech/api/unification/material/Material.java index 18770e5325c..29c4c9fd9e4 100644 --- a/src/main/java/gregtech/api/unification/material/Material.java +++ b/src/main/java/gregtech/api/unification/material/Material.java @@ -10,7 +10,22 @@ import gregtech.api.unification.material.info.MaterialFlag; import gregtech.api.unification.material.info.MaterialFlags; import gregtech.api.unification.material.info.MaterialIconSet; -import gregtech.api.unification.material.properties.*; +import gregtech.api.unification.material.properties.BlastProperty; +import gregtech.api.unification.material.properties.DustProperty; +import gregtech.api.unification.material.properties.FluidPipeProperties; +import gregtech.api.unification.material.properties.FluidProperty; +import gregtech.api.unification.material.properties.GemProperty; +import gregtech.api.unification.material.properties.IMaterialProperty; +import gregtech.api.unification.material.properties.IngotProperty; +import gregtech.api.unification.material.properties.ItemPipeProperties; +import gregtech.api.unification.material.properties.MaterialProperties; +import gregtech.api.unification.material.properties.OreProperty; +import gregtech.api.unification.material.properties.PolymerProperty; +import gregtech.api.unification.material.properties.PropertyKey; +import gregtech.api.unification.material.properties.RotorProperty; +import gregtech.api.unification.material.properties.ToolProperty; +import gregtech.api.unification.material.properties.WireProperties; +import gregtech.api.unification.material.properties.WoodProperty; import gregtech.api.unification.material.registry.MaterialRegistry; import gregtech.api.unification.stack.MaterialStack; import gregtech.api.util.FluidTooltipUtil; @@ -35,7 +50,11 @@ import stanhebben.zenscript.annotations.ZenMethod; import stanhebben.zenscript.annotations.ZenOperator; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Objects; import java.util.function.Consumer; import java.util.function.UnaryOperator; @@ -110,6 +129,14 @@ public Material setFormula(String formula, boolean withFormatting) { return this; } + @ZenMethod + public Material setComponents(MaterialStack... components) { + this.materialInfo.setComponents(components); + this.chemicalFormula = null; + this.chemicalFormula = calculateChemicalFormula(); + return this; + } + public ImmutableList getMaterialComponents() { return materialInfo.componentList; } @@ -1172,5 +1199,10 @@ private void verifyInfo(MaterialProperties p, boolean averageRGB) { } } } + + public MaterialInfo setComponents(MaterialStack... components) { + this.componentList = ImmutableList.copyOf(Arrays.asList(components)); + return this; + } } } diff --git a/src/main/java/gregtech/api/unification/material/materials/FirstDegreeMaterials.java b/src/main/java/gregtech/api/unification/material/materials/FirstDegreeMaterials.java index ff2806d31d5..2863f07c1a9 100644 --- a/src/main/java/gregtech/api/unification/material/materials/FirstDegreeMaterials.java +++ b/src/main/java/gregtech/api/unification/material/materials/FirstDegreeMaterials.java @@ -241,7 +241,6 @@ public static void register() { Galena = new Material.Builder(279, gregtechId("galena")) .dust(3).ore() .color(0x643C64) - .flags(NO_SMELTING) .components(Lead, 1, Sulfur, 1) .build(); diff --git a/src/main/java/gregtech/api/unification/material/materials/HigherDegreeMaterials.java b/src/main/java/gregtech/api/unification/material/materials/HigherDegreeMaterials.java index eae825e44d3..8646df2403f 100644 --- a/src/main/java/gregtech/api/unification/material/materials/HigherDegreeMaterials.java +++ b/src/main/java/gregtech/api/unification/material/materials/HigherDegreeMaterials.java @@ -38,20 +38,20 @@ public static void register() { .ingot(3).fluid() .color(0x8C6464).iconSet(METALLIC) .flags(EXT_METAL, GENERATE_GEAR) - .components(SterlingSilver, 1, BismuthBronze, 1, Steel, 2, BlackSteel, 4) + .components(RoseGold, 1, Brass, 1, Steel, 2, BlackSteel, 4) .toolStats(ToolProperty.Builder.of(7.0F, 6.0F, 2560, 3) .attackSpeed(0.1F).enchantability(21).build()) - .blast(b -> b.temp(1300, GasTier.LOW).blastStats(VA[HV], 1000)) + .blast(b -> b.temp(1813, GasTier.LOW).blastStats(VA[HV], 1000)) .build(); BlueSteel = new Material.Builder(2511, gregtechId("blue_steel")) .ingot(3).fluid() .color(0x64648C).iconSet(METALLIC) .flags(EXT_METAL, GENERATE_FRAME, GENERATE_GEAR) - .components(RoseGold, 1, Brass, 1, Steel, 2, BlackSteel, 4) + .components(SterlingSilver, 1, BismuthBronze, 1, Steel, 2, BlackSteel, 4) .toolStats(ToolProperty.Builder.of(15.0F, 6.0F, 1024, 3) .attackSpeed(0.1F).enchantability(33).build()) - .blast(b -> b.temp(1400, GasTier.LOW).blastStats(VA[HV], 1000)) + .blast(b -> b.temp(1813, GasTier.LOW).blastStats(VA[HV], 1000)) .build(); Basalt = new Material.Builder(2512, gregtechId("basalt")) diff --git a/src/main/java/gregtech/api/unification/material/materials/SecondDegreeMaterials.java b/src/main/java/gregtech/api/unification/material/materials/SecondDegreeMaterials.java index aff4da9ac1f..218e3d043d4 100644 --- a/src/main/java/gregtech/api/unification/material/materials/SecondDegreeMaterials.java +++ b/src/main/java/gregtech/api/unification/material/materials/SecondDegreeMaterials.java @@ -98,7 +98,7 @@ public static void register() { .flags(EXT_METAL, GENERATE_FINE_WIRE, GENERATE_GEAR, GENERATE_FRAME) .components(Nickel, 1, BlackBronze, 1, Steel, 3) .cableProperties(V[EV], 3, 2) - .blast(1200, GasTier.LOW) + .blast(1758, GasTier.LOW) .build(); DamascusSteel = new Material.Builder(2012, gregtechId("damascus_steel")) diff --git a/src/main/java/gregtech/api/util/AssemblyLineManager.java b/src/main/java/gregtech/api/util/AssemblyLineManager.java index a2652acfa84..7601c0e73cd 100644 --- a/src/main/java/gregtech/api/util/AssemblyLineManager.java +++ b/src/main/java/gregtech/api/util/AssemblyLineManager.java @@ -11,7 +11,7 @@ import gregtech.api.recipes.ingredients.nbtmatch.NBTMatcher; import gregtech.api.recipes.machines.IScannerRecipeMap; import gregtech.api.recipes.machines.RecipeMapScanner; -import gregtech.api.recipes.recipeproperties.ScanProperty; +import gregtech.api.recipes.properties.impl.ScanProperty; import gregtech.common.ConfigHolder; import gregtech.common.items.MetaItems; diff --git a/src/main/java/gregtech/api/util/FluidTankSwitchShim.java b/src/main/java/gregtech/api/util/FluidTankSwitchShim.java index e0210eee145..0e4c556da3a 100644 --- a/src/main/java/gregtech/api/util/FluidTankSwitchShim.java +++ b/src/main/java/gregtech/api/util/FluidTankSwitchShim.java @@ -11,14 +11,17 @@ // probably causes problems public class FluidTankSwitchShim implements IFluidTank, IFluidHandler { - IFluidTank tank; + @Nullable + private IFluidTank tank; + private static final FluidTankInfo NO_INFO = new FluidTankInfo(null, 0); + private static final IFluidTankProperties[] NO_PROPS = new IFluidTankProperties[0]; public FluidTankSwitchShim(IFluidTank tank) { changeTank(tank); } public void changeTank(IFluidTank tank) { - if (!(tank instanceof IFluidHandler)) { + if (tank != null && !(tank instanceof IFluidHandler)) { throw new IllegalArgumentException("Shim tank must be both IFluidTank and IFluidHandler!"); } this.tank = tank; @@ -27,43 +30,49 @@ public void changeTank(IFluidTank tank) { @Nullable @Override public FluidStack getFluid() { - return tank.getFluid(); + return tank == null ? null : tank.getFluid(); } @Override public int getFluidAmount() { - return tank.getFluidAmount(); + return tank == null ? 0 : tank.getFluidAmount(); } @Override public int getCapacity() { - return tank.getCapacity(); + return tank == null ? 0 : tank.getCapacity(); } @Override public FluidTankInfo getInfo() { - return tank.getInfo(); + return tank == null ? NO_INFO : tank.getInfo(); } @Override public IFluidTankProperties[] getTankProperties() { + if (tank == null) + return NO_PROPS; + return ((IFluidHandler) tank).getTankProperties(); } @Override public int fill(FluidStack resource, boolean doFill) { + if (tank == null) return 0; return ((IFluidHandler) tank).fill(resource, doFill); } @Nullable @Override public FluidStack drain(FluidStack resource, boolean doDrain) { + if (tank == null) return null; return ((IFluidHandler) tank).drain(resource, doDrain); } @Nullable @Override public FluidStack drain(int maxDrain, boolean doDrain) { + if (tank == null) return null; return tank.drain(maxDrain, doDrain); } } diff --git a/src/main/java/gregtech/api/util/GTTransferUtils.java b/src/main/java/gregtech/api/util/GTTransferUtils.java index 2e3c3655a49..d79024f844b 100644 --- a/src/main/java/gregtech/api/util/GTTransferUtils.java +++ b/src/main/java/gregtech/api/util/GTTransferUtils.java @@ -175,9 +175,6 @@ public static ItemStack insertItem(IItemHandler handler, ItemStack stack, boolea if (handler == null || stack.isEmpty()) { return stack; } - if (!stack.isStackable()) { - return insertToEmpty(handler, stack, simulate); - } IntList emptySlots = new IntArrayList(); int slots = handler.getSlots(); diff --git a/src/main/java/gregtech/api/util/GTUtility.java b/src/main/java/gregtech/api/util/GTUtility.java index cc54a5a2d49..39b4a6a0d65 100644 --- a/src/main/java/gregtech/api/util/GTUtility.java +++ b/src/main/java/gregtech/api/util/GTUtility.java @@ -75,8 +75,6 @@ import java.util.function.Function; import java.util.function.Predicate; -import static gregtech.api.GTValues.V; - public class GTUtility { public static String[] mapToString(T[] array, Function mapper) { @@ -256,7 +254,22 @@ public static int nearestLesser(@NotNull long[] array, long value) { * tier that can handle it, {@code MAX} is returned. */ public static byte getTierByVoltage(long voltage) { - return (byte) Math.min(GTValues.MAX, nearestLesser(V, voltage) + 1); + if (voltage >= GTValues.V[GTValues.MAX]) { + return GTValues.MAX; + } + return getOCTierByVoltage(voltage); + } + + /** + * @return Lowest tier of the voltage that can handle {@code voltage}, extended up to max long value; that is, + * a voltage with value greater than equal than {@code voltage}. If there's no + * tier that can handle it, {@code MAX_TRUE} is returned. + */ + public static byte getOCTierByVoltage(long voltage) { + if (voltage <= GTValues.V[GTValues.ULV]) { + return GTValues.ULV; + } + return (byte) ((62 - Long.numberOfLeadingZeros(voltage - 1)) >> 1); } /** @@ -266,7 +279,14 @@ public static byte getTierByVoltage(long voltage) { * {@code ULV} if there's no tier below */ public static byte getFloorTierByVoltage(long voltage) { - return (byte) Math.max(GTValues.ULV, nearestLesserOrEqual(V, voltage)); + if (voltage < GTValues.V[GTValues.LV]) { + return GTValues.ULV; + } + if (voltage == GTValues.VOC[GTValues.MAX_TRUE]) { + return GTValues.MAX_TRUE; + } + + return (byte) ((60 - Long.numberOfLeadingZeros(voltage)) >> 1); } @SuppressWarnings("deprecation") diff --git a/src/main/java/gregtech/api/util/OverlayedItemHandler.java b/src/main/java/gregtech/api/util/OverlayedItemHandler.java index 83c63422930..dcd73ddb281 100644 --- a/src/main/java/gregtech/api/util/OverlayedItemHandler.java +++ b/src/main/java/gregtech/api/util/OverlayedItemHandler.java @@ -58,7 +58,8 @@ public int insertStackedItemStack(@NotNull ItemStack stack, int amountToInsert) ItemStack slotKey = this.slots[i].getItemStack(); if (slotKey.isEmpty() || ItemStackHashStrategy.comparingAllButCount().equals(slotKey, stack)) { // if the slot is not full - int canInsertUpTo = this.slots[i].getSlotLimit() - this.slots[i].getCount(); + int canInsertUpTo = Math.min(this.slots[i].getSlotLimit() - this.slots[i].getCount(), + stack.getMaxStackSize()); if (canInsertUpTo > 0) { int insertedAmount = Math.min(canInsertUpTo, amountToInsert); this.slots[i].setItemStack(stack.copy()); // this copy may not be need, needs further tests diff --git a/src/main/java/gregtech/api/util/VirtualTankRegistry.java b/src/main/java/gregtech/api/util/VirtualTankRegistry.java deleted file mode 100644 index f43809d7eb3..00000000000 --- a/src/main/java/gregtech/api/util/VirtualTankRegistry.java +++ /dev/null @@ -1,338 +0,0 @@ -package gregtech.api.util; - -import gregtech.api.GTValues; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; -import net.minecraft.world.storage.MapStorage; -import net.minecraft.world.storage.WorldSavedData; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidTankProperties; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -public class VirtualTankRegistry extends WorldSavedData { - - private static final int DEFAULT_CAPACITY = 64000; // 64B - private static final String DATA_ID = GTValues.MODID + ".vtank_data"; - - protected static Map> tankMap = new HashMap<>(); - - public VirtualTankRegistry() { - super(DATA_ID); - } - - // for some reason, MapStorage throws an error if this constructor is not present - @SuppressWarnings("unused") - public VirtualTankRegistry(String name) { - super(name); - } - - /** - * Retrieves a tank from the registry - * - * @param key The name of the tank - * @param uuid The uuid of the player the tank is private to, or null if the tank is public - * @return The tank object - */ - public static IFluidTank getTank(String key, UUID uuid) { - return tankMap.get(uuid).get(key); - } - - /** - * @return the internal Map of tanks. - * Do not use to modify the map! - */ - public static Map> getTankMap() { - return tankMap; - } - - /** - * Retrieves a tank from the registry, creating it if it does not exist - * - * @param key The name of the tank - * @param uuid The uuid of the player the tank is private to, or null if the tank is public - * @param capacity The initial capacity of the tank - * @return The tank object - */ - public static IFluidTank getTankCreate(String key, UUID uuid, int capacity) { - if (!tankMap.containsKey(uuid) || !tankMap.get(uuid).containsKey(key)) { - addTank(key, uuid, capacity); - } - return getTank(key, uuid); - } - - /** - * Retrieves a tank from the registry, creating it with {@link #DEFAULT_CAPACITY the default capacity} if it does - * not exist - * - * @param key The name of the tank - * @param uuid The uuid of the player the tank is private to, or null if the tank is public - * @return The tank object - */ - public static IFluidTank getTankCreate(String key, UUID uuid) { - return getTankCreate(key, uuid, DEFAULT_CAPACITY); - } - - /** - * Adds a tank to the registry - * - * @param key The name of the tank - * @param uuid The uuid of the player the tank is private to, or null if the tank is public - * @param capacity The initial capacity of the tank - */ - public static void addTank(String key, UUID uuid, int capacity) { - if (tankMap.containsKey(uuid) && tankMap.get(uuid).containsKey(key)) { - GTLog.logger.warn("Overwriting virtual tank " + key + "/" + (uuid == null ? "null" : uuid.toString()) + - ", this might cause fluid loss!"); - } else if (!tankMap.containsKey(uuid)) { - tankMap.put(uuid, new HashMap<>()); - } - tankMap.get(uuid).put(key, new VirtualTank(capacity)); - } - - /** - * Adds a tank to the registry with {@link #DEFAULT_CAPACITY the default capacity} - * - * @param key The name of the tank - * @param uuid The uuid of the player the tank is private to, or null if the tank is public - */ - public static void addTank(String key, UUID uuid) { - addTank(key, uuid, DEFAULT_CAPACITY); - } - - /** - * Removes a tank from the registry. Use with caution! - * - * @param key The name of the tank - * @param uuid The uuid of the player the tank is private to, or null if the tank is public - * @param removeFluid Whether to remove the tank if it has fluid in it - */ - public static void delTank(String key, UUID uuid, boolean removeFluid) { - if (tankMap.containsKey(uuid) && tankMap.get(uuid).containsKey(key)) { - if (removeFluid || tankMap.get(uuid).get(key).getFluidAmount() <= 0) { - tankMap.get(uuid).remove(key); - if (tankMap.get(uuid).size() == 0) { - tankMap.remove(uuid); - } - } - } else { - GTLog.logger.warn("Attempted to delete tank " + key + "/" + (uuid == null ? "null" : uuid.toString()) + - ", which does not exist!"); - } - } - - /** - * To be called on server stopped event - */ - public static void clearMaps() { - tankMap.clear(); - } - - @Override - public void readFromNBT(NBTTagCompound nbt) { - if (nbt.hasKey("Public")) { - NBTTagCompound publicTanks = nbt.getCompoundTag("Public"); - for (String key : publicTanks.getKeySet()) { - NBTTagCompound tankCompound = publicTanks.getCompoundTag(key); - VirtualTankRegistry.addTank(key, null, tankCompound.getInteger("Capacity")); - if (!tankCompound.hasKey("Empty")) { - VirtualTankRegistry.getTank(key, null).fill(FluidStack.loadFluidStackFromNBT(tankCompound), true); - } - } - } - if (nbt.hasKey("Private")) { - NBTTagCompound privateTankUUIDs = nbt.getCompoundTag("Private"); - for (String uuidStr : privateTankUUIDs.getKeySet()) { - UUID uuid = UUID.fromString(uuidStr); - NBTTagCompound privateTanks = privateTankUUIDs.getCompoundTag(uuidStr); - for (String key : privateTanks.getKeySet()) { - NBTTagCompound tankCompound = privateTanks.getCompoundTag(key); - VirtualTankRegistry.addTank(key, uuid, tankCompound.getInteger("Capacity")); - if (!tankCompound.hasKey("Empty")) { - VirtualTankRegistry.getTank(key, uuid).fill(FluidStack.loadFluidStackFromNBT(tankCompound), - true); - } - } - } - } - } - - @NotNull - @Override - public NBTTagCompound writeToNBT(NBTTagCompound compound) { - compound.setTag("Private", new NBTTagCompound()); - tankMap.forEach((uuid, map) -> { - NBTTagCompound mapCompound = new NBTTagCompound(); - map.forEach((key, tank) -> { - if (tank.getFluid() != null || tank.getCapacity() != DEFAULT_CAPACITY) { - NBTTagCompound tankCompound = new NBTTagCompound(); - tankCompound.setInteger("Capacity", tank.getCapacity()); - if (tank.getFluid() != null) { - tank.getFluid().writeToNBT(tankCompound); - } else { - tankCompound.setString("Empty", ""); - } - mapCompound.setTag(key, tankCompound); - } - }); - if (mapCompound.getSize() > 0) { - if (uuid == null) { - compound.setTag("Public", mapCompound); - } else { - compound.getCompoundTag("Private").setTag(uuid.toString(), mapCompound); - } - } - }); - return compound; - } - - @Override - public boolean isDirty() { - // can't think of a good way to mark dirty other than always - return true; - } - - /** - * To be called on world load event - */ - public static void initializeStorage(World world) { - MapStorage storage = world.getMapStorage(); - VirtualTankRegistry instance = (VirtualTankRegistry) storage.getOrLoadData(VirtualTankRegistry.class, DATA_ID); - - if (instance == null) { - instance = new VirtualTankRegistry(); - storage.setData(DATA_ID, instance); - } - } - - private static class VirtualTank implements IFluidTank, IFluidHandler { - - @Nullable - protected FluidStack fluid; - protected int capacity; - protected IFluidTankProperties[] tankProperties; - - public VirtualTank(int capacity) { - this.capacity = capacity; - } - - @Nullable - @Override - public FluidStack getFluid() { - return this.fluid; - } - - @Override - public int getFluidAmount() { - return this.fluid == null ? 0 : this.fluid.amount; - } - - @Override - public int getCapacity() { - return this.capacity; - } - - @Override - public FluidTankInfo getInfo() { - return new FluidTankInfo(this); - } - - @Override - public IFluidTankProperties[] getTankProperties() { - if (this.tankProperties == null) { - this.tankProperties = new IFluidTankProperties[] { new VirtualTankProperties(this) }; - } - return this.tankProperties; - } - - @Override - public int fill(FluidStack fluidStack, boolean doFill) { - if (fluidStack == null || fluidStack.amount <= 0 || - (this.fluid != null && !fluidStack.isFluidEqual(this.fluid))) - return 0; - - int fillAmt = Math.min(fluidStack.amount, this.capacity - this.getFluidAmount()); - if (doFill) { - if (this.fluid == null) { - this.fluid = new FluidStack(fluidStack, fillAmt); - } else { - this.fluid.amount += fillAmt; - } - } - return fillAmt; - } - - @Nullable - @Override - public FluidStack drain(FluidStack resource, boolean doDrain) { - return resource == null || !resource.isFluidEqual(this.fluid) ? null : drain(resource.amount, doDrain); - } - - @Nullable - @Override - public FluidStack drain(int amount, boolean doDrain) { - if (this.fluid == null || amount <= 0) - return null; - - int drainAmt = Math.min(this.getFluidAmount(), amount); - FluidStack drainedFluid = new FluidStack(fluid, drainAmt); - if (doDrain) { - this.fluid.amount -= drainAmt; - if (this.fluid.amount <= 0) { - this.fluid = null; - } - } - return drainedFluid; - } - - private static class VirtualTankProperties implements IFluidTankProperties { - - protected final VirtualTank tank; - - private VirtualTankProperties(VirtualTank tank) { - this.tank = tank; - } - - @Nullable - @Override - public FluidStack getContents() { - FluidStack contents = tank.getFluid(); - return contents == null ? null : contents.copy(); - } - - @Override - public int getCapacity() { - return tank.getCapacity(); - } - - @Override - public boolean canFill() { - return true; - } - - @Override - public boolean canDrain() { - return true; - } - - @Override - public boolean canFillFluidType(FluidStack fluidStack) { - return true; - } - - @Override - public boolean canDrainFluidType(FluidStack fluidStack) { - return true; - } - } - } -} diff --git a/src/main/java/gregtech/api/util/virtualregistry/EntryTypes.java b/src/main/java/gregtech/api/util/virtualregistry/EntryTypes.java new file mode 100644 index 00000000000..6324958b8c7 --- /dev/null +++ b/src/main/java/gregtech/api/util/virtualregistry/EntryTypes.java @@ -0,0 +1,66 @@ +package gregtech.api.util.virtualregistry; + +import gregtech.api.util.GTLog; +import gregtech.api.util.virtualregistry.entries.VirtualTank; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.function.Supplier; + +import static gregtech.api.util.GTUtility.gregtechId; + +public final class EntryTypes { + + private static final Map> TYPES_MAP = new Object2ObjectOpenHashMap<>(); + public static final EntryTypes ENDER_FLUID = addEntryType(gregtechId("ender_fluid"), VirtualTank::new); + // ENDER_ITEM("ender_item", null), + // ENDER_ENERGY("ender_energy", null), + // ENDER_REDSTONE("ender_redstone", null); + private final ResourceLocation location; + private final Supplier factory; + + private EntryTypes(ResourceLocation location, Supplier supplier) { + this.location = location; + this.factory = supplier; + } + + public T createInstance(NBTTagCompound nbt) { + var entry = createInstance(); + entry.deserializeNBT(nbt); + return entry; + } + + public T createInstance() { + return factory.get(); + } + + @Override + public String toString() { + return this.location.toString(); + } + + @Nullable + public static EntryTypes fromString(String name) { + return TYPES_MAP.getOrDefault(gregtechId(name), null); + } + + @Nullable + public static EntryTypes fromLocation(String location) { + return TYPES_MAP.getOrDefault(new ResourceLocation(location), null); + } + + public static EntryTypes addEntryType(ResourceLocation location, Supplier supplier) { + var type = new EntryTypes<>(location, supplier); + if (!TYPES_MAP.containsKey(location)) { + TYPES_MAP.put(location, type); + } else { + GTLog.logger.warn("Entry \"{}\" is already registered!", location); + } + return type; + } +} diff --git a/src/main/java/gregtech/api/util/virtualregistry/VirtualEnderRegistry.java b/src/main/java/gregtech/api/util/virtualregistry/VirtualEnderRegistry.java new file mode 100644 index 00000000000..3d8ccd78224 --- /dev/null +++ b/src/main/java/gregtech/api/util/virtualregistry/VirtualEnderRegistry.java @@ -0,0 +1,175 @@ +package gregtech.api.util.virtualregistry; + +import gregtech.api.GTValues; +import gregtech.api.util.GTLog; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraft.world.storage.MapStorage; +import net.minecraft.world.storage.WorldSavedData; +import net.minecraftforge.fluids.IFluidTank; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; + +@SuppressWarnings("SameParameterValue") +public class VirtualEnderRegistry extends WorldSavedData { + + private static final String DATA_ID = GTValues.MODID + ".virtual_entry_data"; + private static final String OLD_DATA_ID = GTValues.MODID + ".vtank_data"; + private static final String PUBLIC_KEY = "Public"; + private static final String PRIVATE_KEY = "Private"; + private static final Map VIRTUAL_REGISTRIES = new HashMap<>(); + + public VirtualEnderRegistry(String name) { + super(name); + } + + public static T getEntry(@Nullable UUID owner, EntryTypes type, String name) { + return getRegistry(owner).getEntry(type, name); + } + + public static void addEntry(@Nullable UUID owner, String name, VirtualEntry entry) { + getRegistry(owner).addEntry(name, entry); + } + + public static boolean hasEntry(@Nullable UUID owner, EntryTypes type, String name) { + return getRegistry(owner).contains(type, name); + } + + public static @NotNull T getOrCreateEntry(@Nullable UUID owner, EntryTypes type, + String name) { + if (!hasEntry(owner, type, name)) + addEntry(owner, name, type.createInstance()); + + return getEntry(owner, type, name); + } + + /** + * Removes an entry from the registry. Use with caution! + * + * @param owner The uuid of the player the entry is private to, or null if the entry is public + * @param type Type of the registry to remove from + * @param name The name of the entry + */ + public static void deleteEntry(@Nullable UUID owner, EntryTypes type, String name) { + var registry = getRegistry(owner); + if (registry.contains(type, name)) { + registry.deleteEntry(type, name); + return; + } + GTLog.logger.warn("Attempted to delete {} entry {} of type {}, which does not exist", + owner == null ? "public" : String.format("private [%s]", owner), name, type); + } + + public static void deleteEntry(@Nullable UUID owner, EntryTypes type, String name, + Predicate shouldDelete) { + T entry = getEntry(owner, type, name); + if (entry != null && shouldDelete.test(entry)) + deleteEntry(owner, type, name); + } + + public static Set getEntryNames(UUID owner, EntryTypes type) { + return getRegistry(owner).getEntryNames(type); + } + + /** + * To be called on server stopped event + */ + public static void clearMaps() { + VIRTUAL_REGISTRIES.clear(); + } + + private static VirtualRegistryMap getRegistry(UUID owner) { + return VIRTUAL_REGISTRIES.computeIfAbsent(owner, key -> new VirtualRegistryMap()); + } + + // remove if tank app is removed + public static Map> createTankMap() { + Map> map = new HashMap<>(); + for (var uuid : VIRTUAL_REGISTRIES.keySet()) { + map.put(uuid, new HashMap<>()); + for (var name : getEntryNames(uuid, EntryTypes.ENDER_FLUID)) { + map.get(uuid).put(name, getEntry(uuid, EntryTypes.ENDER_FLUID, name)); + } + } + return map; + } + + @Override + public final void readFromNBT(NBTTagCompound nbt) { + if (nbt.hasKey(PUBLIC_KEY)) { + VIRTUAL_REGISTRIES.put(null, new VirtualRegistryMap(nbt.getCompoundTag(PUBLIC_KEY))); + } + if (nbt.hasKey(PRIVATE_KEY)) { + NBTTagCompound privateEntries = nbt.getCompoundTag(PRIVATE_KEY); + for (String owner : privateEntries.getKeySet()) { + var privateMap = privateEntries.getCompoundTag(owner); + VIRTUAL_REGISTRIES.put(UUID.fromString(owner), new VirtualRegistryMap(privateMap)); + } + } + } + + @NotNull + @Override + public final NBTTagCompound writeToNBT(@NotNull NBTTagCompound tag) { + var privateTag = new NBTTagCompound(); + for (var owner : VIRTUAL_REGISTRIES.keySet()) { + var mapTag = VIRTUAL_REGISTRIES.get(owner).serializeNBT(); + if (owner != null) { + privateTag.setTag(owner.toString(), mapTag); + } else { + tag.setTag(PUBLIC_KEY, mapTag); + } + } + tag.setTag(PRIVATE_KEY, privateTag); + return tag; + } + + @Override + public boolean isDirty() { + // can't think of a good way to mark dirty other than always + return true; + } + + /** + * To be called on world load event + */ + @SuppressWarnings("DataFlowIssue") + public static void initializeStorage(World world) { + MapStorage storage = world.getMapStorage(); + + VirtualEnderRegistry instance = (VirtualEnderRegistry) storage.getOrLoadData(VirtualEnderRegistry.class, + DATA_ID); + VirtualEnderRegistry old = (VirtualEnderRegistry) storage.getOrLoadData(VirtualEnderRegistry.class, + OLD_DATA_ID); + + if (instance == null) { + instance = new VirtualEnderRegistry(DATA_ID); + storage.setData(DATA_ID, instance); + } + + if (old != null) { + instance.readFromNBT(old.serializeNBT()); + var file = world.getSaveHandler().getMapFileFromName(OLD_DATA_ID); + var split = file.getName().split("\\."); + var stringBuilder = new StringBuilder(split[0]) + .append('.') + .append(split[1]) + .append(".backup") + .append('.') + .append(split[2]); + if (file.renameTo(new File(file.getParent(), stringBuilder.toString()))) { + file.deleteOnExit(); + GTLog.logger.warn("Moved Virtual Tank Data to new format, created backup!"); + } + } + } +} diff --git a/src/main/java/gregtech/api/util/virtualregistry/VirtualEntry.java b/src/main/java/gregtech/api/util/virtualregistry/VirtualEntry.java new file mode 100644 index 00000000000..2775069f0e3 --- /dev/null +++ b/src/main/java/gregtech/api/util/virtualregistry/VirtualEntry.java @@ -0,0 +1,79 @@ +package gregtech.api.util.virtualregistry; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.INBTSerializable; + +import org.jetbrains.annotations.NotNull; + +public abstract class VirtualEntry implements INBTSerializable { + + public static final String DEFAULT_COLOR = "FFFFFFFF"; + protected static final String COLOR_KEY = "color"; + protected static final String DESC_KEY = "description"; + + private int color = 0xFFFFFFFF; + private String colorStr = DEFAULT_COLOR; + private @NotNull String description = ""; + + public abstract EntryTypes getType(); + + public String getColorStr() { + return colorStr; + } + + public int getColor() { + return this.color; + } + + public void setColor(String color) { + this.color = parseColor(color); + this.colorStr = color.toUpperCase(); + } + + public void setColor(int color) { + setColor(Integer.toHexString(color)); + } + + private int parseColor(String s) { + // stupid java not having actual unsigned ints + long tmp = Long.parseLong(s, 16); + if (tmp > 0x7FFFFFFF) { + tmp -= 0x100000000L; + } + return (int) tmp; + } + + public @NotNull String getDescription() { + return this.description; + } + + public void setDescription(@NotNull String desc) { + this.description = desc; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof VirtualEntry other)) return false; + return this.getType() == other.getType() && + this.color == other.color; + } + + @Override + public NBTTagCompound serializeNBT() { + var tag = new NBTTagCompound(); + tag.setString(COLOR_KEY, this.colorStr); + + if (description != null && !description.isEmpty()) + tag.setString(DESC_KEY, this.description); + + return tag; + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + setColor(nbt.getString(COLOR_KEY)); + + if (nbt.hasKey(DESC_KEY)) + setDescription(nbt.getString(DESC_KEY)); + } +} diff --git a/src/main/java/gregtech/api/util/virtualregistry/VirtualRegistryMap.java b/src/main/java/gregtech/api/util/virtualregistry/VirtualRegistryMap.java new file mode 100644 index 00000000000..18a2b9a81e8 --- /dev/null +++ b/src/main/java/gregtech/api/util/virtualregistry/VirtualRegistryMap.java @@ -0,0 +1,87 @@ +package gregtech.api.util.virtualregistry; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.INBTSerializable; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class VirtualRegistryMap implements INBTSerializable { + + private final Map, Map> registryMap = new HashMap<>(); + + public VirtualRegistryMap(NBTTagCompound tag) { + deserializeNBT(tag); + } + + public VirtualRegistryMap() {} + + @SuppressWarnings("unchecked") + public @Nullable T getEntry(EntryTypes type, String name) { + if (!contains(type, name)) + return null; + + return (T) registryMap.get(type).get(name); + } + + public void addEntry(String name, VirtualEntry entry) { + registryMap.computeIfAbsent(entry.getType(), k -> new HashMap<>()) + .put(name, entry); + } + + public boolean contains(EntryTypes type, String name) { + if (!registryMap.containsKey(type)) + return false; + + return registryMap.get(type).containsKey(name); + } + + public void deleteEntry(EntryTypes type, String name) { + registryMap.get(type).remove(name); + } + + public void clear() { + registryMap.clear(); + } + + public Set getEntryNames(EntryTypes type) { + return registryMap.get(type).keySet(); + } + + @Override + public @NotNull NBTTagCompound serializeNBT() { + var tag = new NBTTagCompound(); + for (var type : registryMap.keySet()) { + var entriesTag = new NBTTagCompound(); + var entries = registryMap.get(type); + for (var name : entries.keySet()) { + entriesTag.setTag(name, entries.get(name).serializeNBT()); + } + tag.setTag(type.toString(), entriesTag); + } + return tag; + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + for (var entryType : nbt.getKeySet()) { + EntryTypes type; + if (entryType.contains(":")) { + type = EntryTypes.fromLocation(entryType); + } else { + type = EntryTypes.fromString(entryType); + } + if (type == null) continue; + + var virtualEntries = nbt.getCompoundTag(entryType); + for (var name : virtualEntries.getKeySet()) { + var entry = virtualEntries.getCompoundTag(name); + addEntry(name, type.createInstance(entry)); + } + } + } +} diff --git a/src/main/java/gregtech/api/util/virtualregistry/entries/VirtualTank.java b/src/main/java/gregtech/api/util/virtualregistry/entries/VirtualTank.java new file mode 100644 index 00000000000..3ad02e5969c --- /dev/null +++ b/src/main/java/gregtech/api/util/virtualregistry/entries/VirtualTank.java @@ -0,0 +1,180 @@ +package gregtech.api.util.virtualregistry.entries; + +import gregtech.api.util.virtualregistry.EntryTypes; +import gregtech.api.util.virtualregistry.VirtualEntry; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidTank; +import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.fluids.capability.IFluidTankProperties; + +import org.jetbrains.annotations.Nullable; + +public class VirtualTank extends VirtualEntry implements IFluidTank, IFluidHandler { + + protected static final String CAPACITY_KEY = "capacity"; + protected static final String FLUID_KEY = "fluid"; + private static final int DEFAULT_CAPACITY = 64000; // 64B + + @Nullable + private FluidStack fluidStack = null; + private int capacity; + private final IFluidTankProperties[] props = new IFluidTankProperties[] { + createProperty(this) + }; + + public VirtualTank(int capacity) { + this.capacity = capacity; + } + + public VirtualTank() { + this(DEFAULT_CAPACITY); + } + + @Override + public EntryTypes getType() { + return EntryTypes.ENDER_FLUID; + } + + @Override + public FluidStack getFluid() { + return this.fluidStack; + } + + public void setFluid(FluidStack fluid) { + this.fluidStack = fluid; + } + + @Override + public int getFluidAmount() { + return fluidStack == null ? 0 : fluidStack.amount; + } + + @Override + public int getCapacity() { + return this.capacity; + } + + @Override + public FluidTankInfo getInfo() { + return new FluidTankInfo(this); + } + + @Override + public IFluidTankProperties[] getTankProperties() { + return this.props; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof VirtualTank other)) return false; + if (this.fluidStack == null && other.fluidStack == null) + return super.equals(o); + if (this.fluidStack == null || other.fluidStack == null) + return false; + if (this.fluidStack.isFluidStackIdentical(other.fluidStack)) + return super.equals(o); + + return false; + } + + @Override + public NBTTagCompound serializeNBT() { + var tag = super.serializeNBT(); + tag.setInteger(CAPACITY_KEY, this.capacity); + + if (this.fluidStack != null) + tag.setTag(FLUID_KEY, this.fluidStack.writeToNBT(new NBTTagCompound())); + + return tag; + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + super.deserializeNBT(nbt); + this.capacity = nbt.getInteger(CAPACITY_KEY); + + if (nbt.hasKey(FLUID_KEY)) + setFluid(FluidStack.loadFluidStackFromNBT(nbt.getCompoundTag(FLUID_KEY))); + } + + @Override + public int fill(FluidStack fluidStack, boolean doFill) { + if (fluidStack == null || fluidStack.amount <= 0 || + (this.fluidStack != null && !fluidStack.isFluidEqual(this.fluidStack))) + return 0; + + int fillAmt = Math.min(fluidStack.amount, getCapacity() - this.getFluidAmount()); + + if (doFill) { + if (this.fluidStack == null) { + this.fluidStack = new FluidStack(fluidStack, fillAmt); + } else { + this.fluidStack.amount += fillAmt; + } + } + return fillAmt; + } + + @Nullable + @Override + public FluidStack drain(FluidStack resource, boolean doDrain) { + return resource == null || !resource.isFluidEqual(this.fluidStack) ? null : drain(resource.amount, doDrain); + } + + @Nullable + @Override + public FluidStack drain(int amount, boolean doDrain) { + if (this.fluidStack == null || amount <= 0) + return null; + + int drainAmt = Math.min(this.getFluidAmount(), amount); + FluidStack drainedFluid = new FluidStack(this.fluidStack, drainAmt); + if (doDrain) { + this.fluidStack.amount -= drainAmt; + if (this.fluidStack.amount <= 0) { + this.fluidStack = null; + } + } + return drainedFluid; + } + + private static IFluidTankProperties createProperty(VirtualTank tank) { + return new IFluidTankProperties() { + + @Nullable + @Override + public FluidStack getContents() { + FluidStack contents = tank.getFluid(); + return contents == null ? null : contents.copy(); + } + + @Override + public int getCapacity() { + return tank.getCapacity(); + } + + @Override + public boolean canFill() { + return true; + } + + @Override + public boolean canDrain() { + return true; + } + + @Override + public boolean canFillFluidType(FluidStack fluidStack) { + return true; + } + + @Override + public boolean canDrainFluidType(FluidStack fluidStack) { + return true; + } + }; + } +} diff --git a/src/main/java/gregtech/asm/GregTechTransformer.java b/src/main/java/gregtech/asm/GregTechTransformer.java index 9a13badeaf5..c3b906dd4ae 100644 --- a/src/main/java/gregtech/asm/GregTechTransformer.java +++ b/src/main/java/gregtech/asm/GregTechTransformer.java @@ -222,17 +222,24 @@ public byte[] transform(String name, String transformedName, byte[] basicClass) // 0); // return classWriter.toByteArray(); // } + // case OreIngredientVisitor.TARGET_CLASS_NAME: { + // ClassReader classReader = new ClassReader(basicClass); + // ClassWriter classWriter = new ClassWriter(0); + // classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, + // OreIngredientVisitor::new), 0); + // return classWriter.toByteArray(); + // } + /* + * if (EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.containsKey(internalName)) { + * ObfMapping methodMapping = EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.get(internalName); + * ClassReader classReader = new ClassReader(basicClass); + * ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + * classReader.accept(new TargetClassVisitor(classWriter, methodMapping, + * mv -> new EnchantmentCanApplyVisitor(mv, methodMapping)), ClassReader.EXPAND_FRAMES); + * return classWriter.toByteArray(); + * } + */ } - /* - * if (EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.containsKey(internalName)) { - * ObfMapping methodMapping = EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.get(internalName); - * ClassReader classReader = new ClassReader(basicClass); - * ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - * classReader.accept(new TargetClassVisitor(classWriter, methodMapping, - * mv -> new EnchantmentCanApplyVisitor(mv, methodMapping)), ClassReader.EXPAND_FRAMES); - * return classWriter.toByteArray(); - * } - */ return basicClass; } } diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index 7fb4773d478..03783021f60 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -4,11 +4,12 @@ import gregtech.api.fluids.GTFluidRegistration; import gregtech.api.items.metaitem.MetaOreDictItem; import gregtech.api.items.toolitem.IGTTool; -import gregtech.api.terminal.TerminalRegistry; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; import gregtech.api.unification.stack.UnificationEntry; import gregtech.api.util.FluidTooltipUtil; +import gregtech.api.util.GTLog; import gregtech.api.util.IBlockOre; import gregtech.api.util.Mods; import gregtech.client.model.customtexture.CustomTextureModelHandler; @@ -21,6 +22,7 @@ import gregtech.client.renderer.pipe.LaserPipeRenderer; import gregtech.client.renderer.pipe.OpticalPipeRenderer; import gregtech.client.renderer.pipe.PipeRenderer; +import gregtech.client.renderer.texture.Textures; import gregtech.client.utils.ItemRenderCompat; import gregtech.client.utils.TooltipHelper; import gregtech.common.CommonProxy; @@ -34,9 +36,16 @@ import net.minecraft.block.Block; import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.gui.GuiIngame; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.SimpleReloadableResourceManager; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; import net.minecraft.inventory.ContainerPlayer; import net.minecraft.inventory.ContainerWorkbench; @@ -46,7 +55,12 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.client.GuiIngameForge; +import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.event.ModelRegistryEvent; +import net.minecraftforge.client.event.MouseEvent; +import net.minecraftforge.client.event.RenderGameOverlayEvent; +import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.Constants; import net.minecraftforge.event.entity.player.ItemTooltipEvent; @@ -60,7 +74,6 @@ import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.oredict.OreDictionary; -import codechicken.lib.texture.TextureUtils; import org.jetbrains.annotations.NotNull; import paulscode.sound.SoundSystemConfig; @@ -92,8 +105,6 @@ public void onPreLoad() { OpticalPipeRenderer.INSTANCE.preInit(); LaserPipeRenderer.INSTANCE.preInit(); MetaEntities.initRenderers(); - TextureUtils.addIconRegister(GTFluidRegistration.INSTANCE::registerSprites); - TextureUtils.addIconRegister(PipeRenderer::initializeRestrictor); } @Override @@ -105,7 +116,6 @@ public void onLoad() { @Override public void onPostLoad() { super.onPostLoad(); - TerminalRegistry.initTerminalFiles(); ItemRenderCompat.init(); FacadeRenderer.init(); } @@ -116,6 +126,19 @@ public static void registerColors() { ToolItems.registerColors(); } + @SubscribeEvent + public static void textureStitchPre(@NotNull TextureStitchEvent.Pre event) { + TextureMap map = event.getMap(); + GTFluidRegistration.INSTANCE.registerSprites(map); + PipeRenderer.initializeRestrictor(map); + Textures.register(map); + CableRenderer.INSTANCE.registerIcons(map); + FluidPipeRenderer.INSTANCE.registerIcons(map); + ItemPipeRenderer.INSTANCE.registerIcons(map); + OpticalPipeRenderer.INSTANCE.registerIcons(map); + LaserPipeRenderer.INSTANCE.registerIcons(map); + } + @SubscribeEvent public static void registerModels(ModelRegistryEvent event) { MetaBlocks.registerStateMappers(); @@ -124,6 +147,14 @@ public static void registerModels(ModelRegistryEvent event) { ToolItems.registerModels(); } + @SubscribeEvent + @SideOnly(Side.CLIENT) + public static void registerBakedModels(ModelBakeEvent event) { + GTLog.logger.info("Registering special item models"); + MetaItems.registerBakedModels(event); + ToolItems.registerBakedModels(event); + } + @SubscribeEvent public static void addMaterialFormulaHandler(@NotNull ItemTooltipEvent event) { ItemStack itemStack = event.getItemStack(); @@ -315,4 +346,83 @@ private static boolean hasActuallyAdvancedInfo(List tooltip) { public boolean isFancyGraphics() { return Minecraft.getMinecraft().gameSettings.fancyGraphics; } + + @SubscribeEvent(priority = EventPriority.HIGH) + public static void onMouseEvent(@NotNull MouseEvent event) { + if (!ConfigHolder.client.toolbeltConfig.enableToolbeltScrollingCapture) return; + EntityPlayerSP player = Minecraft.getMinecraft().player; + if (event.getDwheel() != 0 && player.isSneaking()) { + ItemStack stack = player.getHeldItemMainhand(); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + // vanilla code in GuiIngame line 1235 does not copy the stack before storing it in the highlighting + // item stack, so unless we copy the stack the tool highlight will not refresh. + stack = stack.copy(); + toolbelt.changeSelectedToolMousewheel(event.getDwheel(), stack); + InventoryPlayer inv = Minecraft.getMinecraft().player.inventory; + inv.mainInventory.set(inv.currentItem, stack); + event.setCanceled(true); + } + } + } + + @SubscribeEvent + public static void onRenderGameOverlayPostEvent(RenderGameOverlayEvent.Post event) { + if (!ConfigHolder.client.toolbeltConfig.enableToolbeltHotbarDisplay) return; + if (event.getType() == RenderGameOverlayEvent.ElementType.HOTBAR) { + if (Minecraft.getMinecraft().ingameGUI instanceof GuiIngameForge gui) { + ItemStack stack = Minecraft.getMinecraft().player.getHeldItemMainhand(); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + renderToolbeltHotbar(gui, stack, toolbelt, event.getResolution(), event.getPartialTicks()); + } + } + } + } + + private static void renderToolbeltHotbar(GuiIngameForge gui, ItemStack stack, ItemGTToolbelt toolbelt, + ScaledResolution sr, float partialTicks) { + Minecraft mc = Minecraft.getMinecraft(); + int offset = 31; + int slots = Math.min(9, toolbelt.getSlotCount(stack)); + GuiIngameForge.left_height += offset - 6; + if (slots > 4) { + GuiIngameForge.right_height += offset - 6; + } + if (mc.getRenderViewEntity() instanceof EntityPlayer entityplayer) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + mc.getTextureManager().bindTexture(GuiIngame.WIDGETS_TEX_PATH); + int i = sr.getScaledWidth() / 2; + float f = gui.zLevel; + gui.zLevel = -90.0F; + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, + GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, + GlStateManager.DestFactor.ZERO); + // draw the left side of the hotbar + gui.drawTexturedModalRect(i - 91, sr.getScaledHeight() - 22 - offset, 0, 0, slots * 20 - 18, 22); + // draw the endpiece to the hotbar + gui.drawTexturedModalRect(i - 91 + slots * 20 - 18, sr.getScaledHeight() - 22 - offset, 162, 0, 20, 22); + int selected = toolbelt.getSelectedSlot(stack); + if (selected != -1) { + gui.drawTexturedModalRect(i - 91 - 1 + selected * 20, sr.getScaledHeight() - 22 - 1 - offset, 0, 22, 24, + 24); + } + gui.zLevel = -80f; + GlStateManager.enableRescaleNormal(); + RenderHelper.enableGUIStandardItemLighting(); + + for (int l = 0; l < slots; ++l) { + ItemStack stack1 = toolbelt.getToolInSlot(stack, l); + if (stack1.isEmpty()) continue; + int i1 = i - 90 + l * 20 + 2; + int j1 = sr.getScaledHeight() - 16 - 3 - offset; + gui.renderHotbarItem(i1, j1, partialTicks, entityplayer, stack1); + } + + gui.zLevel = f; + + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableRescaleNormal(); + GlStateManager.disableBlend(); + } + } } diff --git a/src/main/java/gregtech/client/event/ClientEventHandler.java b/src/main/java/gregtech/client/event/ClientEventHandler.java index f4ac14d8bfd..57c79a3afb7 100644 --- a/src/main/java/gregtech/client/event/ClientEventHandler.java +++ b/src/main/java/gregtech/client/event/ClientEventHandler.java @@ -10,7 +10,6 @@ import gregtech.client.particle.GTParticleManager; import gregtech.client.renderer.handler.BlockPosHighlightRenderer; import gregtech.client.renderer.handler.MultiblockPreviewRenderer; -import gregtech.client.renderer.handler.TerminalARRenderer; import gregtech.client.utils.BloomEffectUtil; import gregtech.client.utils.DepthTextureUtil; import gregtech.client.utils.TooltipHelper; @@ -69,7 +68,6 @@ public static void onPreWorldRender(TickEvent.RenderTickEvent event) { @SubscribeEvent public static void onClientTick(TickEvent.ClientTickEvent event) { GTParticleManager.clientTick(event); - TerminalARRenderer.onClientTick(event); TooltipHelper.onClientTick(event); if (event.phase == TickEvent.Phase.END) { CLIENT_TIME++; @@ -81,23 +79,16 @@ public static void onRenderWorldLast(RenderWorldLastEvent event) { DepthTextureUtil.renderWorld(event); MultiblockPreviewRenderer.renderWorldLastEvent(event); BlockPosHighlightRenderer.renderWorldLastEvent(event); - TerminalARRenderer.renderWorldLastEvent(event); GTParticleManager.renderWorld(event); } @SubscribeEvent public static void onRenderGameOverlayPre(RenderGameOverlayEvent.Pre event) { - TerminalARRenderer.renderGameOverlayEvent(event); if (ConfigHolder.misc.debug && event instanceof RenderGameOverlayEvent.Text text) { GTParticleManager.debugOverlay(text); } } - @SubscribeEvent - public static void onRenderSpecificHand(RenderSpecificHandEvent event) { - TerminalARRenderer.renderHandEvent(event); - } - private static final Map DEFAULT_CAPES = new Object2ObjectOpenHashMap<>(); @SubscribeEvent diff --git a/src/main/java/gregtech/client/model/modelfactories/BakedModelHandler.java b/src/main/java/gregtech/client/model/modelfactories/BakedModelHandler.java index 3aa4d37f038..7506494a04b 100644 --- a/src/main/java/gregtech/client/model/modelfactories/BakedModelHandler.java +++ b/src/main/java/gregtech/client/model/modelfactories/BakedModelHandler.java @@ -1,24 +1,16 @@ package gregtech.client.model.modelfactories; +import gregtech.client.utils.RenderUtil; + import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.ItemMeshDefinition; -import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; -import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType; -import net.minecraft.client.renderer.block.model.ItemOverrideList; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.block.statemap.StateMapperBase; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.Tuple; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.model.ModelFluid; import net.minecraftforge.client.model.ModelLoader; -import net.minecraftforge.client.model.PerspectiveMapWrapper; import net.minecraftforge.fluids.BlockFluidBase; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; @@ -26,19 +18,9 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import codechicken.lib.render.item.CCRenderItem; -import codechicken.lib.texture.TextureUtils; -import codechicken.lib.util.TransformUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import javax.vecmath.Matrix4f; - @SideOnly(Side.CLIENT) public class BakedModelHandler { @@ -49,25 +31,13 @@ protected ModelResourceLocation getModelResourceLocation(IBlockState state) { return getSimpleModelLocation(state.getBlock()); } }; - private static final ItemMeshDefinition SIMPLE_MESH_DEFINITION = (stack) -> getSimpleModelLocation( - Block.getBlockFromItem(stack.getItem())); private static ModelResourceLocation getSimpleModelLocation(Block block) { return new ModelResourceLocation(Block.REGISTRY.getNameForObject(block), ""); } - private final List> builtInBlocks = new ArrayList<>(); private final List fluidBlocks = new ArrayList<>(); - public void addBuiltInBlock(Block block, String particleTexture) { - this.builtInBlocks.add(new Tuple<>(block, particleTexture)); - ModelLoader.setCustomStateMapper(block, SIMPLE_STATE_MAPPER); - Item itemFromBlock = Item.getItemFromBlock(block); - if (itemFromBlock != Items.AIR) { - ModelLoader.setCustomMeshDefinition(itemFromBlock, SIMPLE_MESH_DEFINITION); - } - } - public void addFluidBlock(BlockFluidBase fluidBase) { this.fluidBlocks.add(fluidBase); ModelLoader.setCustomStateMapper(fluidBase, SIMPLE_STATE_MAPPER); @@ -79,63 +49,9 @@ public void onModelsBake(ModelBakeEvent event) { Fluid fluid = ObfuscationReflectionHelper.getPrivateValue(BlockFluidBase.class, fluidBlock, "definedFluid"); ModelFluid modelFluid = new ModelFluid(fluid); IBakedModel bakedModel = modelFluid.bake(modelFluid.getDefaultState(), DefaultVertexFormats.ITEM, - TextureUtils::getTexture); + RenderUtil::getTexture); ModelResourceLocation resourceLocation = getSimpleModelLocation(fluidBlock); event.getModelRegistry().putObject(resourceLocation, bakedModel); } - for (Tuple tuple : builtInBlocks) { - ModelResourceLocation resourceLocation = getSimpleModelLocation(tuple.getFirst()); - ModelBuiltInRenderer bakedModel = new ModelBuiltInRenderer(tuple.getSecond()); - event.getModelRegistry().putObject(resourceLocation, bakedModel); - } - } - - private static class ModelBuiltInRenderer implements IBakedModel { - - private final String particleTexture; - - public ModelBuiltInRenderer(String particleTexture) { - this.particleTexture = particleTexture; - } - - @NotNull - @Override - public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { - return Collections.emptyList(); - } - - @Override - public boolean isAmbientOcclusion() { - return true; - } - - @Override - public boolean isGui3d() { - return true; - } - - @Override - public boolean isBuiltInRenderer() { - return true; - } - - @NotNull - @Override - public TextureAtlasSprite getParticleTexture() { - return TextureUtils.getBlockTexture(particleTexture); - } - - @NotNull - @Override - public ItemOverrideList getOverrides() { - return ItemOverrideList.NONE; - } - - @NotNull - @Override - public Pair handlePerspective(@NotNull TransformType cameraTransformType) { - CCRenderItem.notifyTransform(cameraTransformType); - return PerspectiveMapWrapper.handlePerspective(this, TransformUtils.DEFAULT_BLOCK, cameraTransformType); - } } } diff --git a/src/main/java/gregtech/client/renderer/ICCLBlockRenderer.java b/src/main/java/gregtech/client/renderer/ICCLBlockRenderer.java deleted file mode 100644 index f1d70220390..00000000000 --- a/src/main/java/gregtech/client/renderer/ICCLBlockRenderer.java +++ /dev/null @@ -1,19 +0,0 @@ -package gregtech.client.renderer; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.BufferBuilder; -import net.minecraft.client.renderer.block.model.ItemCameraTransforms; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -public interface ICCLBlockRenderer { - - @SideOnly(Side.CLIENT) - void renderItem(ItemStack rawStack, ItemCameraTransforms.TransformType transformType); - - @SideOnly(Side.CLIENT) - void renderBlock(IBlockAccess world, BlockPos pos, IBlockState state, BufferBuilder buffer); -} diff --git a/src/main/java/gregtech/client/renderer/ICubeRenderer.java b/src/main/java/gregtech/client/renderer/ICubeRenderer.java index 5fb0a866a42..1830ecad570 100644 --- a/src/main/java/gregtech/client/renderer/ICubeRenderer.java +++ b/src/main/java/gregtech/client/renderer/ICubeRenderer.java @@ -1,6 +1,7 @@ package gregtech.client.renderer; import gregtech.api.gui.resources.ResourceHelper; +import gregtech.client.texture.IconRegistrar; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; @@ -11,13 +12,12 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils.IIconRegister; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public interface ICubeRenderer extends IIconRegister { +public interface ICubeRenderer extends IconRegistrar { String EMISSIVE = "_emissive"; diff --git a/src/main/java/gregtech/client/renderer/handler/BlockPosHighlightRenderer.java b/src/main/java/gregtech/client/renderer/handler/BlockPosHighlightRenderer.java index df5f186744f..c4b1254beb2 100644 --- a/src/main/java/gregtech/client/renderer/handler/BlockPosHighlightRenderer.java +++ b/src/main/java/gregtech/client/renderer/handler/BlockPosHighlightRenderer.java @@ -19,22 +19,33 @@ public class BlockPosHighlightRenderer { private static BlockPos posHighLight; - private static long hlEndTime; + private static long duration; + private static long offset; + private static long start; public static void renderBlockBoxHighLight(BlockPos blockpos, long durTimeMillis) { posHighLight = blockpos; - hlEndTime = System.currentTimeMillis() + durTimeMillis; + duration = durTimeMillis; + offset = 1500; + start = System.currentTimeMillis(); + } + + public static void renderBlockBoxHighLight(BlockPos blockpos, long durTimeMillis, long offsetTimeMillis) { + posHighLight = blockpos; + duration = durTimeMillis; + offset = offsetTimeMillis; + start = System.currentTimeMillis(); } public static void renderWorldLastEvent(RenderWorldLastEvent evt) { if (posHighLight != null) { long time = System.currentTimeMillis(); - if (time > hlEndTime) { + if (time > duration + start) { posHighLight = null; - hlEndTime = 0; + duration = 0; return; } - if (((time / 500) & 1) == 0) { + if (time % offset >= offset / 2) { return; } EntityPlayerSP p = Minecraft.getMinecraft().player; diff --git a/src/main/java/gregtech/client/renderer/handler/CCLBlockRenderer.java b/src/main/java/gregtech/client/renderer/handler/CCLBlockRenderer.java deleted file mode 100644 index e2046685f86..00000000000 --- a/src/main/java/gregtech/client/renderer/handler/CCLBlockRenderer.java +++ /dev/null @@ -1,122 +0,0 @@ -package gregtech.client.renderer.handler; - -import gregtech.api.util.GTLog; -import gregtech.api.util.GTUtility; -import gregtech.client.renderer.ICCLBlockRenderer; -import gregtech.client.renderer.texture.Textures; -import gregtech.client.utils.ItemRenderCompat; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.BufferBuilder; -import net.minecraft.client.renderer.block.model.ItemCameraTransforms; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumBlockRenderType; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.IBlockAccess; -import net.minecraftforge.client.event.ModelBakeEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.model.IModelState; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import codechicken.lib.render.CCRenderState; -import codechicken.lib.render.block.BlockRenderingRegistry; -import codechicken.lib.render.block.ICCBlockRenderer; -import codechicken.lib.render.item.IItemRenderer; -import codechicken.lib.texture.TextureUtils; -import codechicken.lib.util.TransformUtils; -import codechicken.lib.vec.Cuboid6; -import codechicken.lib.vec.Vector3; -import codechicken.lib.vec.uv.IconTransformation; - -@SideOnly(Side.CLIENT) -public class CCLBlockRenderer implements ICCBlockRenderer, IItemRenderer { - - public static final ModelResourceLocation MODEL_LOCATION = new ModelResourceLocation( - GTUtility.gregtechId("ccl_block"), "normal"); - public static final CCLBlockRenderer INSTANCE = new CCLBlockRenderer(); - public static EnumBlockRenderType BLOCK_RENDER_TYPE; - public static Minecraft mc = Minecraft.getMinecraft(); - - public static void preInit() { - BLOCK_RENDER_TYPE = BlockRenderingRegistry.createRenderType("gregtech_ccl_block"); - BlockRenderingRegistry.registerRenderer(BLOCK_RENDER_TYPE, INSTANCE); - MinecraftForge.EVENT_BUS.register(INSTANCE); - TextureUtils.addIconRegister(Textures::register); - } - - @SubscribeEvent - public void onModelsBake(ModelBakeEvent event) { - GTLog.logger.info("Injected ccl block render model"); - event.getModelRegistry().putObject(MODEL_LOCATION, this); - } - - @Override - public void renderItem(ItemStack rawStack, ItemCameraTransforms.TransformType transformType) { - ItemStack stack = ItemRenderCompat.getRepresentedStack(rawStack); - if (stack.getItem() instanceof ItemBlock itemBlock && - itemBlock.getBlock() instanceof ICCLBlockRenderer renderer) { - renderer.renderItem(stack, transformType); - } - } - - @Override - public boolean renderBlock(IBlockAccess world, BlockPos pos, IBlockState state, BufferBuilder buffer) { - if (state != null && (state.getBlock() instanceof ICCLBlockRenderer)) { - ((ICCLBlockRenderer) state.getBlock()).renderBlock(world, pos, state, buffer); - return true; - } - return false; - } - - @Override - public IModelState getTransforms() { - return TransformUtils.DEFAULT_BLOCK; - } - - @Override - public boolean isBuiltInRenderer() { - return true; - } - - @Override - public void renderBrightness(IBlockState state, float brightness) {} - - @Override - public void handleRenderBlockDamage(IBlockAccess world, BlockPos pos, IBlockState state, TextureAtlasSprite sprite, - BufferBuilder buffer) { - if (state == null || !(state.getBlock() instanceof ICCLBlockRenderer)) { - return; - } - CCRenderState renderState = CCRenderState.instance(); - renderState.reset(); - renderState.bind(buffer); - renderState.setPipeline(new Vector3(new Vec3d(pos)).translation(), new IconTransformation(sprite)); - codechicken.lib.render.BlockRenderer.renderCuboid(renderState, Cuboid6.full, 0); - } - - @Override - public TextureAtlasSprite getParticleTexture() { - return TextureUtils.getMissingSprite(); - } - - @Override - public void registerTextures(TextureMap map) {} - - @Override - public boolean isAmbientOcclusion() { - return true; - } - - @Override - public boolean isGui3d() { - return true; - } -} diff --git a/src/main/java/gregtech/client/renderer/handler/MetaTileEntityRenderer.java b/src/main/java/gregtech/client/renderer/handler/MetaTileEntityRenderer.java index 8e0fe1f6962..80db7976e18 100644 --- a/src/main/java/gregtech/client/renderer/handler/MetaTileEntityRenderer.java +++ b/src/main/java/gregtech/client/renderer/handler/MetaTileEntityRenderer.java @@ -7,6 +7,7 @@ import gregtech.client.renderer.CubeRendererState; import gregtech.client.renderer.texture.Textures; import gregtech.client.utils.ItemRenderCompat; +import gregtech.client.utils.RenderUtil; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.BufferBuilder; @@ -38,7 +39,6 @@ import codechicken.lib.render.block.ICCBlockRenderer; import codechicken.lib.render.item.IItemRenderer; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils; import codechicken.lib.util.TransformUtils; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; @@ -61,7 +61,6 @@ public static void preInit() { BLOCK_RENDER_TYPE = BlockRenderingRegistry.createRenderType("meta_tile_entity"); BlockRenderingRegistry.registerRenderer(BLOCK_RENDER_TYPE, INSTANCE); MinecraftForge.EVENT_BUS.register(INSTANCE); - TextureUtils.addIconRegister(Textures::register); } @SubscribeEvent @@ -153,17 +152,12 @@ public void handleRenderBlockDamage(IBlockAccess world, BlockPos pos, IBlockStat public static Pair getParticleTexture(IBlockAccess world, BlockPos pos) { MetaTileEntity metaTileEntity = GTUtility.getMetaTileEntity(world, pos); if (metaTileEntity == null) { - return Pair.of(TextureUtils.getMissingSprite(), 0xFFFFFF); + return Pair.of(RenderUtil.getMissingSprite(), 0xFFFFFF); } else { return metaTileEntity.getParticleTexture(); } } - @Override - public TextureAtlasSprite getParticleTexture() { - return TextureUtils.getMissingSprite(); - } - @Override public void registerTextures(TextureMap map) {} diff --git a/src/main/java/gregtech/client/renderer/handler/TerminalARRenderer.java b/src/main/java/gregtech/client/renderer/handler/TerminalARRenderer.java deleted file mode 100644 index 1bc5e61a13e..00000000000 --- a/src/main/java/gregtech/client/renderer/handler/TerminalARRenderer.java +++ /dev/null @@ -1,99 +0,0 @@ -package gregtech.client.renderer.handler; - -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.app.ARApplication; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.client.utils.RenderUtil; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumHand; -import net.minecraftforge.client.event.RenderGameOverlayEvent; -import net.minecraftforge.client.event.RenderSpecificHandEvent; -import net.minecraftforge.client.event.RenderWorldLastEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -/** - * Created with IntelliJ IDEA. - * - * @Author: KilaBash - * @Date: 2021/09/13 - * @Description: Renderer for AR applications. - * Please don't render your stuff here, it's just a handler - */ -@SideOnly(Side.CLIENT) -public class TerminalARRenderer { - - public static ARApplication APP; - public static int x, y, width, height; - public static EnumHand HELD_HAND; - - public static void renderHandEvent(RenderSpecificHandEvent event) { - if (APP != null && event.getHand() == HELD_HAND) { - event.setCanceled(true); - } - } - - public static void renderGameOverlayEvent(RenderGameOverlayEvent.Pre event) { - if (APP != null && event.getType() == RenderGameOverlayEvent.ElementType.ALL) { - int sWidth = event.getResolution().getScaledWidth(); - int sHeight = event.getResolution().getScaledHeight(); - width = (int) (380 * 0.8 * sHeight / 256); - height = (int) (0.8 * sHeight); - x = (sWidth - width) / 2; - y = (sHeight - height) / 2; - GlStateManager.enableBlend(); - TerminalOSWidget.TERMINAL_FRAME.draw(x, y, width, height); - GlStateManager.disableBlend(); - } - } - - public static void renderWorldLastEvent(RenderWorldLastEvent event) { - if (APP != null) { - RenderUtil.useScissor(x, y, width, height, () -> APP.drawARScreen(event)); - } - } - - public static void onClientTick(TickEvent.ClientTickEvent event) { - if (event.phase == TickEvent.Phase.END) { - EntityPlayer player = Minecraft.getMinecraft().player; - if (player == null) { - if (APP != null) { - APP.onARClosed(); - APP = null; - } - return; - } - HELD_HAND = EnumHand.MAIN_HAND; - NBTTagCompound tag = player.getHeldItem(EnumHand.MAIN_HAND).getSubCompound("terminal"); - if (tag == null) { - tag = player.getHeldItem(EnumHand.OFF_HAND).getSubCompound("terminal"); - HELD_HAND = EnumHand.OFF_HAND; - } - if (tag != null && tag.hasKey("_ar")) { - AbstractApplication app = TerminalRegistry.getApplication(tag.getString("_ar")); - if (app instanceof ARApplication) { - if (APP != app) { - if (APP != null) { - APP.onARClosed(); - } - APP = (ARApplication) app; - APP.setAROpened(player.getHeldItem(HELD_HAND)); - APP.onAROpened(); - } - APP.tickAR(player); - return; - } - } - if (APP != null) { - APP.onARClosed(); - APP = null; - } - } - } -} diff --git a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java new file mode 100644 index 00000000000..bdeacb59ff8 --- /dev/null +++ b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java @@ -0,0 +1,60 @@ +package gregtech.client.renderer.handler; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderItem; +import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.model.IModelState; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import codechicken.lib.render.item.IItemRenderer; +import codechicken.lib.util.TransformUtils; + +@SideOnly(Side.CLIENT) +public class ToolbeltRenderer implements IItemRenderer { + + private final IBakedModel toolbeltModel; + + public ToolbeltRenderer(IBakedModel toolbeltModel) { + this.toolbeltModel = toolbeltModel; + } + + @Override + public void renderItem(ItemStack stack, ItemCameraTransforms.TransformType transformType) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + GlStateManager.pushMatrix(); + GlStateManager.translate(0.5F, 0.5F, 0.5F); + + RenderItem renderItem = Minecraft.getMinecraft().getRenderItem(); + + ItemStack selected = toolbelt.getSelectedTool(stack); + if (!selected.isEmpty()) { + IBakedModel selectedModel = renderItem.getItemModelWithOverrides(selected, null, null); + renderItem.renderItem(selected, selectedModel); + } + renderItem.renderItem(stack, toolbeltModel); + + GlStateManager.popMatrix(); + } + } + + @Override + public IModelState getTransforms() { + return TransformUtils.DEFAULT_TOOL; + } + + @Override + public boolean isAmbientOcclusion() { + return false; + } + + @Override + public boolean isGui3d() { + return false; + } +} diff --git a/src/main/java/gregtech/client/renderer/pipe/CableRenderer.java b/src/main/java/gregtech/client/renderer/pipe/CableRenderer.java index 17edbcd501d..5c91a2f44cc 100644 --- a/src/main/java/gregtech/client/renderer/pipe/CableRenderer.java +++ b/src/main/java/gregtech/client/renderer/pipe/CableRenderer.java @@ -6,6 +6,7 @@ import gregtech.api.pipenet.tile.IPipeTile; import gregtech.api.unification.material.Material; import gregtech.api.util.GTUtility; +import gregtech.client.utils.RenderUtil; import gregtech.common.pipelike.cable.Insulation; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -14,7 +15,6 @@ import codechicken.lib.render.pipeline.ColourMultiplier; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils; import codechicken.lib.vec.uv.IconTransformation; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; @@ -84,11 +84,11 @@ public TextureAtlasSprite getParticleTexture(IPipeType pipeType, @Nullable Ma @Override public Pair getParticleTexture(IPipeTile pipeTile) { if (pipeTile == null) { - return Pair.of(TextureUtils.getMissingSprite(), 0xFFFFFF); + return Pair.of(RenderUtil.getMissingSprite(), 0xFFFFFF); } IPipeType pipeType = pipeTile.getPipeType(); if (!(pipeType instanceof Insulation)) { - return Pair.of(TextureUtils.getMissingSprite(), 0xFFFFFF); + return Pair.of(RenderUtil.getMissingSprite(), 0xFFFFFF); } Material material = pipeTile instanceof TileEntityMaterialPipeBase ? ((TileEntityMaterialPipeBase) pipeTile).getPipeMaterial() : null; diff --git a/src/main/java/gregtech/client/renderer/pipe/PipeRenderer.java b/src/main/java/gregtech/client/renderer/pipe/PipeRenderer.java index e3195dba22c..563f780c26a 100644 --- a/src/main/java/gregtech/client/renderer/pipe/PipeRenderer.java +++ b/src/main/java/gregtech/client/renderer/pipe/PipeRenderer.java @@ -14,6 +14,7 @@ import gregtech.client.renderer.CubeRendererState; import gregtech.client.renderer.texture.Textures; import gregtech.client.utils.ItemRenderCompat; +import gregtech.client.utils.RenderUtil; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -48,7 +49,6 @@ import codechicken.lib.render.item.IItemRenderer; import codechicken.lib.render.pipeline.ColourMultiplier; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils; import codechicken.lib.util.TransformUtils; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; @@ -126,7 +126,6 @@ public void preInit() { blockRenderType = BlockRenderingRegistry.createRenderType(name); BlockRenderingRegistry.registerRenderer(blockRenderType, this); MinecraftForge.EVENT_BUS.register(this); - TextureUtils.addIconRegister(this::registerIcons); } public ModelResourceLocation getModelLocation() { @@ -406,11 +405,6 @@ public IModelState getTransforms() { return TransformUtils.DEFAULT_BLOCK; } - @Override - public TextureAtlasSprite getParticleTexture() { - return TextureUtils.getMissingSprite(); - } - @Override public boolean isBuiltInRenderer() { return true; @@ -428,13 +422,13 @@ public boolean isGui3d() { public Pair getParticleTexture(IPipeTile pipeTile) { if (pipeTile == null) { - return Pair.of(TextureUtils.getMissingSprite(), 0xFFFFFF); + return Pair.of(RenderUtil.getMissingSprite(), 0xFFFFFF); } IPipeType pipeType = pipeTile.getPipeType(); Material material = pipeTile instanceof TileEntityMaterialPipeBase ? ((TileEntityMaterialPipeBase) pipeTile).getPipeMaterial() : null; if (pipeType == null) { - return Pair.of(TextureUtils.getMissingSprite(), 0xFFFFFF); + return Pair.of(RenderUtil.getMissingSprite(), 0xFFFFFF); } TextureAtlasSprite atlasSprite = getParticleTexture(pipeType, material); int pipeColor = getPipeColor(material, pipeTile.getPaintingColor()); diff --git a/src/main/java/gregtech/client/renderer/texture/Textures.java b/src/main/java/gregtech/client/renderer/texture/Textures.java index 8615691ba87..76f91891093 100644 --- a/src/main/java/gregtech/client/renderer/texture/Textures.java +++ b/src/main/java/gregtech/client/renderer/texture/Textures.java @@ -20,6 +20,7 @@ import gregtech.client.renderer.texture.custom.FireboxActiveRenderer; import gregtech.client.renderer.texture.custom.LargeTurbineRenderer; import gregtech.client.renderer.texture.custom.QuantumStorageRenderer; +import gregtech.client.texture.IconRegistrar; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; @@ -32,7 +33,6 @@ import codechicken.lib.render.BlockRenderer.BlockFace; import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils.IIconRegister; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; import codechicken.lib.vec.TransformationList; @@ -52,7 +52,7 @@ public class Textures { public static final Map CUBE_RENDERER_REGISTRY = new HashMap<>(); private static final ThreadLocal blockFaces = ThreadLocal.withInitial(BlockFace::new); - public static final List iconRegisters = new ArrayList<>(); + public static final List iconRegisters = new ArrayList<>(); // Custom Renderers public static final ClipboardRenderer CLIPBOARD_RENDERER = new ClipboardRenderer(); @@ -97,6 +97,32 @@ public class Textures { "casings/pipe/machine_casing_grate"); public static final SimpleOverlayRenderer HIGH_POWER_CASING = new SimpleOverlayRenderer( "casings/computer/high_power_casing"); + public static final SimpleOverlayRenderer QUANTUM_CASING = new SimpleOverlayRenderer( + "casings/quantum/quantum_casing"); + public static final SimpleOverlayRenderer QUANTUM_CONTROLLER_FRONT_INACTIVE = new SimpleOverlayRenderer( + "casings/quantum/controller_front_inactive"); + public static final SimpleOverlayRenderer QUANTUM_CONTROLLER_FRONT_ACTIVE = new SimpleOverlayRenderer( + "casings/quantum/controller_front_active"); + public static final SimpleOverlayRenderer QUANTUM_CONTROLLER_ACTIVE = new SimpleOverlayRenderer( + "casings/quantum/controller_active"); + public static final SimpleOverlayRenderer QUANTUM_CONTROLLER_INACTIVE = new SimpleOverlayRenderer( + "casings/quantum/controller_inactive"); + public static final SimpleOverlayRenderer QUANTUM_PROXY_INACTIVE = new SimpleOverlayRenderer( + "casings/quantum/proxy_inactive"); + public static final SimpleOverlayRenderer QUANTUM_PROXY_ACTIVE = new SimpleOverlayRenderer( + "casings/quantum/proxy_active"); + public static final SimpleOverlayRenderer QUANTUM_EXTENDER = new SimpleOverlayRenderer("casings/quantum/extender"); + public static final SimpleOverlayRenderer QUANTUM_EXTENDER_ACTIVE = new SimpleOverlayRenderer( + "casings/quantum/extender_active"); + + public static final SimpleOverlayRenderer QUANTUM_INDICATOR = new SimpleOverlayRenderer( + "casings/quantum/quantum_indicator_disconnected"); + + public static final SimpleOverlayRenderer QUANTUM_INDICATOR_CONNECTED = new SimpleOverlayRenderer( + "casings/quantum/quantum_indicator_connected"); + + public static final SimpleOverlayRenderer QUANTUM_INDICATOR_POWERED = new SimpleOverlayRenderer( + "casings/quantum/quantum_indicator_powered"); // Simple Sided Cube Renderers public static final SimpleSidedCubeRenderer STEAM_CASING_BRONZE = new SimpleSidedCubeRenderer( @@ -622,8 +648,8 @@ public class Textures { @SideOnly(Side.CLIENT) public static void register(TextureMap textureMap) { GTLog.logger.info("Loading meta tile entity texture sprites..."); - for (IIconRegister iconRegister : iconRegisters) { - iconRegister.registerIcons(textureMap); + for (IconRegistrar registrar : iconRegisters) { + registrar.registerIcons(textureMap); } RESTRICTIVE_OVERLAY = textureMap.registerSprite(gregtechId("blocks/pipe/pipe_restrictive")); diff --git a/src/main/java/gregtech/client/renderer/texture/custom/ClipboardRenderer.java b/src/main/java/gregtech/client/renderer/texture/custom/ClipboardRenderer.java index 107200e2989..319fe32b325 100644 --- a/src/main/java/gregtech/client/renderer/texture/custom/ClipboardRenderer.java +++ b/src/main/java/gregtech/client/renderer/texture/custom/ClipboardRenderer.java @@ -1,6 +1,7 @@ package gregtech.client.renderer.texture.custom; import gregtech.client.renderer.texture.Textures; +import gregtech.client.texture.IconRegistrar; import gregtech.common.metatileentities.MetaTileEntityClipboard; import net.minecraft.client.Minecraft; @@ -17,17 +18,17 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils.IIconRegister; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; import codechicken.lib.vec.Rotation; import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.HashMap; import java.util.List; -public class ClipboardRenderer implements IIconRegister { +public class ClipboardRenderer implements IconRegistrar { private static final Cuboid6 pageBox = new Cuboid6(3 / 16.0, 0.25 / 16.0, 0.25 / 16.0, 13 / 16.0, 14.25 / 16.0, 0.3 / 16.0); @@ -57,7 +58,7 @@ public ClipboardRenderer() { @Override @SideOnly(Side.CLIENT) - public void registerIcons(TextureMap textureMap) { + public void registerIcons(@NotNull TextureMap textureMap) { this.textures[0] = textureMap.registerSprite(new ResourceLocation("gregtech:blocks/clipboard/wood")); boxTextureMap.put(boardBox, this.textures[0]); this.textures[1] = textureMap.registerSprite(new ResourceLocation("gregtech:blocks/clipboard/clip")); diff --git a/src/main/java/gregtech/client/renderer/texture/custom/CrateRenderer.java b/src/main/java/gregtech/client/renderer/texture/custom/CrateRenderer.java index 0f999dd687d..78558aaa1aa 100644 --- a/src/main/java/gregtech/client/renderer/texture/custom/CrateRenderer.java +++ b/src/main/java/gregtech/client/renderer/texture/custom/CrateRenderer.java @@ -2,6 +2,7 @@ import gregtech.api.util.GTUtility; import gregtech.client.renderer.texture.Textures; +import gregtech.client.texture.IconRegistrar; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; @@ -13,12 +14,12 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.ColourMultiplier; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils.IIconRegister; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; import org.apache.commons.lang3.ArrayUtils; +import org.jetbrains.annotations.NotNull; -public class CrateRenderer implements IIconRegister { +public class CrateRenderer implements IconRegistrar { private final String basePath; @@ -32,7 +33,7 @@ public CrateRenderer(String basePath) { @Override @SideOnly(Side.CLIENT) - public void registerIcons(TextureMap textureMap) { + public void registerIcons(@NotNull TextureMap textureMap) { this.sideSprite = textureMap.registerSprite(GTUtility.gregtechId("blocks/" + basePath)); } diff --git a/src/main/java/gregtech/client/renderer/texture/custom/DrumRenderer.java b/src/main/java/gregtech/client/renderer/texture/custom/DrumRenderer.java index d02d824d280..f2fd93de8ba 100644 --- a/src/main/java/gregtech/client/renderer/texture/custom/DrumRenderer.java +++ b/src/main/java/gregtech/client/renderer/texture/custom/DrumRenderer.java @@ -2,6 +2,7 @@ import gregtech.api.GTValues; import gregtech.client.renderer.texture.Textures; +import gregtech.client.texture.IconRegistrar; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; @@ -13,11 +14,11 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils.IIconRegister; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; +import org.jetbrains.annotations.NotNull; -public class DrumRenderer implements IIconRegister { +public class DrumRenderer implements IconRegistrar { private final String basePath; @@ -31,7 +32,7 @@ public DrumRenderer(String basePath) { @Override @SideOnly(Side.CLIENT) - public void registerIcons(TextureMap textureMap) { + public void registerIcons(@NotNull TextureMap textureMap) { String formattedBase = GTValues.MODID + ":blocks/" + basePath; this.textures = new TextureAtlasSprite[3]; this.textures[0] = textureMap.registerSprite(new ResourceLocation(formattedBase + "/top")); diff --git a/src/main/java/gregtech/client/renderer/texture/custom/LargeTurbineRenderer.java b/src/main/java/gregtech/client/renderer/texture/custom/LargeTurbineRenderer.java index f2f2e063d82..27545d1a47a 100644 --- a/src/main/java/gregtech/client/renderer/texture/custom/LargeTurbineRenderer.java +++ b/src/main/java/gregtech/client/renderer/texture/custom/LargeTurbineRenderer.java @@ -4,6 +4,7 @@ import gregtech.client.renderer.cclop.ColourOperation; import gregtech.client.renderer.cclop.LightMapOperation; import gregtech.client.renderer.texture.Textures; +import gregtech.client.texture.IconRegistrar; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; @@ -15,12 +16,12 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.ColourMultiplier; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils.IIconRegister; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; import org.apache.commons.lang3.ArrayUtils; +import org.jetbrains.annotations.NotNull; -public class LargeTurbineRenderer implements IIconRegister { +public class LargeTurbineRenderer implements IconRegistrar { @SideOnly(Side.CLIENT) private TextureAtlasSprite baseRingSprite; @@ -37,7 +38,7 @@ public LargeTurbineRenderer() { @Override @SideOnly(Side.CLIENT) - public void registerIcons(TextureMap textureMap) { + public void registerIcons(@NotNull TextureMap textureMap) { this.baseRingSprite = textureMap .registerSprite(GTUtility.gregtechId("blocks/multiblock/large_turbine/base_ring")); this.baseBackgroundSprite = textureMap diff --git a/src/main/java/gregtech/client/renderer/texture/custom/QuantumStorageRenderer.java b/src/main/java/gregtech/client/renderer/texture/custom/QuantumStorageRenderer.java index 03c0dd5656c..893cfa843ee 100644 --- a/src/main/java/gregtech/client/renderer/texture/custom/QuantumStorageRenderer.java +++ b/src/main/java/gregtech/client/renderer/texture/custom/QuantumStorageRenderer.java @@ -2,13 +2,14 @@ import gregtech.api.gui.resources.TextTexture; import gregtech.api.metatileentity.ITieredMetaTileEntity; -import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.util.TextFormattingUtil; import gregtech.client.renderer.texture.Textures; import gregtech.client.renderer.texture.cube.SimpleSidedCubeRenderer.RenderSide; +import gregtech.client.texture.IconRegistrar; import gregtech.client.utils.RenderUtil; import gregtech.common.ConfigHolder; import gregtech.common.metatileentities.storage.MetaTileEntityQuantumChest; +import gregtech.common.metatileentities.storage.MetaTileEntityQuantumStorage; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; @@ -33,13 +34,13 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.texture.TextureUtils; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; +import org.jetbrains.annotations.NotNull; import java.util.EnumMap; -public class QuantumStorageRenderer implements TextureUtils.IIconRegister { +public class QuantumStorageRenderer implements IconRegistrar { private static final Cuboid6 glassBox = new Cuboid6(1 / 16.0, 1 / 16.0, 1 / 16.0, 15 / 16.0, 15 / 16.0, 15 / 16.0); @@ -64,15 +65,15 @@ public QuantumStorageRenderer() { } @Override - public void registerIcons(TextureMap textureMap) { + public void registerIcons(@NotNull TextureMap textureMap) { this.glassTexture = textureMap .registerSprite(new ResourceLocation("gregtech:blocks/overlay/machine/overlay_screen_glass")); } - public void renderMachine(CCRenderState renderState, - Matrix4 translation, - IVertexOperation[] pipeline, - T mte) { + public & ITieredMetaTileEntity> void renderMachine(CCRenderState renderState, + Matrix4 translation, + IVertexOperation[] pipeline, + T mte) { EnumFacing frontFacing = mte.getFrontFacing(); int tier = mte.getTier(); Textures.renderFace(renderState, translation, pipeline, frontFacing, glassBox, glassTexture, @@ -81,6 +82,10 @@ public void renderMachine(CCR TextureAtlasSprite hullTexture = Textures.VOLTAGE_CASINGS[tier] .getSpriteOnSide(RenderSide.bySide(EnumFacing.NORTH)); + if (mte.isConnected()) { + hullTexture = Textures.QUANTUM_CASING.getParticleSprite(); + } + for (var facing : boxFacingMap.keySet()) { // do not render the box at the front face when "facing" is "frontFacing" if (facing == frontFacing) continue; diff --git a/src/main/java/gregtech/client/shader/Shaders.java b/src/main/java/gregtech/client/shader/Shaders.java index 1d20438bbbb..409818af327 100644 --- a/src/main/java/gregtech/client/shader/Shaders.java +++ b/src/main/java/gregtech/client/shader/Shaders.java @@ -148,6 +148,7 @@ public static Framebuffer renderFullImageInFBO(Framebuffer fbo, ShaderObject fra // GlStateManager.viewport(0, 0, mc.displayWidth, mc.displayHeight); // OpenGlHelper.glBindFramebuffer(OpenGlHelper.GL_FRAMEBUFFER, lastID); + fbo.bindFramebuffer(false); return fbo; } } diff --git a/src/main/java/gregtech/client/texture/IconRegistrar.java b/src/main/java/gregtech/client/texture/IconRegistrar.java new file mode 100644 index 00000000000..6e6ec35ea65 --- /dev/null +++ b/src/main/java/gregtech/client/texture/IconRegistrar.java @@ -0,0 +1,22 @@ +package gregtech.client.texture; + +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.jetbrains.annotations.NotNull; + +/** + * Functional Interface for registering ResourceLocations to a TextureMap. + *

+ * Called during {@link net.minecraftforge.client.event.TextureStitchEvent.Pre} + */ +@FunctionalInterface +public interface IconRegistrar { + + /** + * @param map the map to register textures to + */ + @SideOnly(Side.CLIENT) + void registerIcons(@NotNull TextureMap map); +} diff --git a/src/main/java/gregtech/client/utils/BloomEffectUtil.java b/src/main/java/gregtech/client/utils/BloomEffectUtil.java index c4a4e0548ee..36671852320 100644 --- a/src/main/java/gregtech/client/utils/BloomEffectUtil.java +++ b/src/main/java/gregtech/client/utils/BloomEffectUtil.java @@ -18,23 +18,19 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.shader.Framebuffer; import net.minecraft.entity.Entity; -import net.minecraft.launchwrapper.Launch; import net.minecraft.util.BlockRenderLayer; import net.minecraft.world.World; -import net.minecraftforge.common.util.EnumHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import com.github.bsideup.jabel.Desugar; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import org.apache.commons.lang3.reflect.FieldUtils; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; -import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -336,24 +332,9 @@ public boolean test(BloomRenderTicket bloomRenderTicket) { }, validityChecker); } - @SuppressWarnings({ "rawtypes", "unchecked" }) public static void init() { - bloom = EnumHelper.addEnum(BlockRenderLayer.class, "BLOOM", new Class[] { String.class }, "Bloom"); + bloom = BlockRenderLayer.valueOf("BLOOM"); BLOOM = bloom; - if (Mods.Nothirium.isModLoaded()) { - try { - // Nothirium hard copies the BlockRenderLayer enum into a ChunkRenderPass enum. Add our BLOOM layer to - // that too. - Class crp = Class.forName("meldexun.nothirium.api.renderer.chunk.ChunkRenderPass", false, - Launch.classLoader); - EnumHelper.addEnum(crp, "BLOOM", new Class[] {}); - Field all = FieldUtils.getField(crp, "ALL", false); - FieldUtils.removeFinalModifier(all); - FieldUtils.writeStaticField(all, crp.getEnumConstants()); - } catch (ClassNotFoundException | IllegalAccessException e) { - throw new RuntimeException(e); - } - } } // Calls injected via ASM diff --git a/src/main/java/gregtech/client/utils/BloomEffectVintagiumUtil.java b/src/main/java/gregtech/client/utils/BloomEffectVintagiumUtil.java index 0d63f22a2d4..68bd1469c38 100644 --- a/src/main/java/gregtech/client/utils/BloomEffectVintagiumUtil.java +++ b/src/main/java/gregtech/client/utils/BloomEffectVintagiumUtil.java @@ -11,14 +11,12 @@ @SideOnly(Side.CLIENT) public class BloomEffectVintagiumUtil { - public static BlockRenderPass bloom; - /** * @return {@link BlockRenderPass} instance for the bloom render layer. */ @NotNull @SuppressWarnings("unused") public static BlockRenderPass getBloomPass() { - return Objects.requireNonNull(bloom, "Bloom effect is not initialized yet"); + return Objects.requireNonNull(BlockRenderPass.valueOf("BLOOM"), "Bloom effect is not initialized yet"); } } diff --git a/src/main/java/gregtech/client/utils/RenderUtil.java b/src/main/java/gregtech/client/utils/RenderUtil.java index 070ff054c10..f38d5cee0d4 100644 --- a/src/main/java/gregtech/client/utils/RenderUtil.java +++ b/src/main/java/gregtech/client/utils/RenderUtil.java @@ -25,7 +25,6 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import codechicken.lib.texture.TextureUtils; import codechicken.lib.vec.Matrix4; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -392,7 +391,7 @@ public static void renderFluidOverLay(float x, float y, float width, float heigh float r = (color >> 16 & 255) / 255.0f; float g = (color >> 8 & 255) / 255.0f; float b = (color & 255) / 255.0f; - TextureAtlasSprite sprite = TextureUtils.getTexture(fluidStack.getFluid().getStill(fluidStack)); + TextureAtlasSprite sprite = getTexture(fluidStack.getFluid().getStill(fluidStack)); GlStateManager.enableBlend(); GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); @@ -530,8 +529,7 @@ public static void drawFluidForGui(FluidStack contents, int tankCapacity, int st heightT--; Fluid fluid = contents.getFluid(); ResourceLocation fluidStill = fluid.getStill(contents); - TextureAtlasSprite fluidStillSprite = Minecraft.getMinecraft().getTextureMapBlocks() - .getAtlasSprite(fluidStill.toString()); + TextureAtlasSprite fluidStillSprite = getTexture(fluidStill); int fluidColor = fluid.getColor(contents); int scaledAmount; if (contents.amount == tankCapacity) { @@ -667,4 +665,31 @@ public void put(int element, float @NotNull... data) { builder.setApplyDiffuseLighting(false); return builder.build(); } + + /** + * @return the block texture map + */ + public static @NotNull TextureMap getTextureMap() { + return Minecraft.getMinecraft().getTextureMapBlocks(); + } + + /** + * @param location the location of the texture in the Block Texture Map + * @return the texture at the location + * @throws IllegalArgumentException if the texture does not exist in the atlas + */ + public static @NotNull TextureAtlasSprite getTexture(@NotNull ResourceLocation location) { + TextureAtlasSprite sprite = getTextureMap().getTextureExtry(location.toString()); + if (sprite == null) { + throw new IllegalArgumentException("Texture does not exist at " + location); + } + return sprite; + } + + /** + * @return the missing texture atlas sprite + */ + public static @NotNull TextureAtlasSprite getMissingSprite() { + return getTextureMap().getMissingSprite(); + } } diff --git a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java index de982d07450..c8ffd11b817 100644 --- a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java +++ b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java @@ -5,6 +5,7 @@ import gregtech.api.items.metaitem.MetaItem; import gregtech.api.items.metaitem.stats.IItemDurabilityManager; import gregtech.api.items.toolitem.IGTTool; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolHelper; import gregtech.api.util.GTUtility; @@ -113,6 +114,13 @@ private static void overpaintVanillaRenderBug(BufferBuilder worldrenderer, int x } public static void renderBarsTool(IGTTool tool, ItemStack stack, int xPosition, int yPosition) { + if (tool instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedTool(stack); + if (!selected.isEmpty() && selected.getItem() instanceof IGTTool toool) { + tool = toool; + stack = selected; + } + } boolean renderedDurability = false; NBTTagCompound tag = GTUtility.getOrCreateNbtCompound(stack); if (!tag.getBoolean(ToolHelper.UNBREAKABLE_KEY)) { diff --git a/src/main/java/gregtech/common/CommonProxy.java b/src/main/java/gregtech/common/CommonProxy.java index 6817aaa7ce5..59055bb74e1 100644 --- a/src/main/java/gregtech/common/CommonProxy.java +++ b/src/main/java/gregtech/common/CommonProxy.java @@ -10,8 +10,7 @@ import gregtech.api.recipes.GTRecipeInputCache; import gregtech.api.recipes.ModHandler; import gregtech.api.recipes.ingredients.GTRecipeOreInput; -import gregtech.api.recipes.recipeproperties.FusionEUToStartProperty; -import gregtech.api.terminal.TerminalRegistry; +import gregtech.api.recipes.properties.impl.FusionEUToStartProperty; import gregtech.api.unification.material.Material; import gregtech.api.unification.material.info.MaterialFlags; import gregtech.api.unification.material.properties.DustProperty; @@ -410,8 +409,6 @@ public void onLoad() { } public void onPostLoad() { - TerminalRegistry.init(); - if (ConfigHolder.compat.removeSmeltingForEBFMetals) { ModHandler.removeSmeltingEBFMetals(); } diff --git a/src/main/java/gregtech/common/ConfigHolder.java b/src/main/java/gregtech/common/ConfigHolder.java index caf04defc48..5ecec7ab1b0 100644 --- a/src/main/java/gregtech/common/ConfigHolder.java +++ b/src/main/java/gregtech/common/ConfigHolder.java @@ -35,7 +35,6 @@ public class ConfigHolder { // TODO move to ToolsModule config @Config.Comment("Config options for Tools and Armor") @Config.Name("Tool and Armor Options") - @Config.RequiresMcRestart public static ToolOptions tools = new ToolOptions(); @Config.Comment("Config options for World Generation features") @@ -382,6 +381,9 @@ public static class ClientOptions { @Config.Name("Shader Options") public ShaderOptions shader = new ShaderOptions(); + @Config.Name("Toolbelt Config") + public ToolbeltConfig toolbeltConfig = new ToolbeltConfig(); + @Config.Comment({ "Terminal root path.", "Default: {.../config}/gregtech/terminal" }) @Config.RequiresMcRestart public String terminalRootPath = "gregtech/terminal"; @@ -555,6 +557,22 @@ public static class ShaderOptions { @Config.RangeDouble(min = 0) public double step = 1; } + + public static class ToolbeltConfig { + + @Config.Comment({ "Enable the capturing of hotbar scroll while sneaking by a selected toolbelt.", + "Default: true" }) + public boolean enableToolbeltScrollingCapture = true; + + @Config.Comment({ "Enable the capturing of hotbar keypresses while sneaking by a selected toolbelt.", + "Default: true" }) + public boolean enableToolbeltKeypressCapture = true; + + @Config.Comment({ + "Enable the display of a second hotbar representing the toolbelt's inventory when one is selected.", + "Default: true" }) + public boolean enableToolbeltHotbarDisplay = true; + } } public static class FusionBloom { @@ -641,34 +659,42 @@ public static class HeatEffectBloom { public static class ToolOptions { + @Config.RequiresMcRestart @Config.Name("NanoSaber Options") public NanoSaber nanoSaber = new NanoSaber(); + @Config.RequiresMcRestart @Config.Comment("NightVision Goggles Voltage Tier. Default: 1 (LV)") @Config.RangeInt(min = 0, max = 14) public int voltageTierNightVision = 1; + @Config.RequiresMcRestart @Config.Comment("NanoSuit Voltage Tier. Default: 3 (HV)") @Config.RangeInt(min = 0, max = 14) public int voltageTierNanoSuit = 3; + @Config.RequiresMcRestart @Config.Comment({ "Advanced NanoSuit Chestplate Voltage Tier.", "Default: 3 (HV)" }) @Config.RangeInt(min = 0, max = 14) public int voltageTierAdvNanoSuit = 3; + @Config.RequiresMcRestart @Config.Comment({ "QuarkTech Suit Voltage Tier.", "Default: 5 (IV)" }) @Config.RangeInt(min = 0, max = 14) @Config.SlidingOption public int voltageTierQuarkTech = 5; + @Config.RequiresMcRestart @Config.Comment({ "Advanced QuarkTech Suit Chestplate Voltage Tier.", "Default: 5 (LuV)" }) @Config.RangeInt(min = 0, max = 14) public int voltageTierAdvQuarkTech = 6; + @Config.RequiresMcRestart @Config.Comment({ "Electric Impeller Jetpack Voltage Tier.", "Default: 2 (MV)" }) @Config.RangeInt(min = 0, max = 14) public int voltageTierImpeller = 2; + @Config.RequiresMcRestart @Config.Comment({ "Advanced Electric Jetpack Voltage Tier.", "Default: 3 (HV)" }) @Config.RangeInt(min = 0, max = 14) public int voltageTierAdvImpeller = 3; @@ -680,6 +706,11 @@ public static class ToolOptions { @Config.Comment("Armor HUD Location") public ArmorHud armorHud = new ArmorHud(); + + @Config.Comment({ "How often items should be moved by a magnet", "Default: 10 ticks" }) + @Config.RangeInt(min = 1, max = 100) + @Config.SlidingOption + public int magnetDelay = 10; } public static class ArmorHud { diff --git a/src/main/java/gregtech/common/EventHandlers.java b/src/main/java/gregtech/common/EventHandlers.java index 8fa23091b99..ecbe6b16097 100644 --- a/src/main/java/gregtech/common/EventHandlers.java +++ b/src/main/java/gregtech/common/EventHandlers.java @@ -13,7 +13,7 @@ import gregtech.api.util.CapesRegistry; import gregtech.api.util.GTUtility; import gregtech.api.util.Mods; -import gregtech.api.util.VirtualTankRegistry; +import gregtech.api.util.virtualregistry.VirtualEnderRegistry; import gregtech.api.worldgen.bedrockFluids.BedrockFluidVeinSaveData; import gregtech.common.entities.EntityGTExplosive; import gregtech.common.items.MetaItems; @@ -327,7 +327,7 @@ public static void onPlayerTickClient(TickEvent.PlayerTickEvent event) { @SubscribeEvent public static void onWorldLoadEvent(WorldEvent.Load event) { - VirtualTankRegistry.initializeStorage(event.getWorld()); + VirtualEnderRegistry.initializeStorage(event.getWorld()); CapesRegistry.checkAdvancements(event.getWorld()); } diff --git a/src/main/java/gregtech/common/ToolEventHandlers.java b/src/main/java/gregtech/common/ToolEventHandlers.java index 62195e49791..e503b539547 100644 --- a/src/main/java/gregtech/common/ToolEventHandlers.java +++ b/src/main/java/gregtech/common/ToolEventHandlers.java @@ -165,6 +165,7 @@ public static void onHarvestDrops(@NotNull BlockEvent.HarvestDropsEvent event) { // only try once, so future water placement does not get eaten too return false; }); + stack = ToolHelper.toolbeltPassthrough(stack); ((IGTTool) stack.getItem()).playSound(player); } } diff --git a/src/main/java/gregtech/common/covers/CoverBehaviors.java b/src/main/java/gregtech/common/covers/CoverBehaviors.java index 78413327163..355fe3b0dff 100644 --- a/src/main/java/gregtech/common/covers/CoverBehaviors.java +++ b/src/main/java/gregtech/common/covers/CoverBehaviors.java @@ -8,6 +8,7 @@ import gregtech.api.util.GTLog; import gregtech.client.renderer.texture.Textures; import gregtech.common.covers.detector.*; +import gregtech.common.covers.ender.CoverEnderFluidLink; import gregtech.common.items.MetaItems; import gregtech.common.items.behaviors.CoverDigitalInterfaceWirelessPlaceBehaviour; diff --git a/src/main/java/gregtech/common/covers/CoverConveyor.java b/src/main/java/gregtech/common/covers/CoverConveyor.java index 798c0000e8c..1fa4e43dffe 100644 --- a/src/main/java/gregtech/common/covers/CoverConveyor.java +++ b/src/main/java/gregtech/common/covers/CoverConveyor.java @@ -45,6 +45,7 @@ import com.cleanroommc.modularui.api.drawable.IDrawable; import com.cleanroommc.modularui.api.widget.Interactable; import com.cleanroommc.modularui.drawable.DynamicDrawable; +import com.cleanroommc.modularui.factory.GuiData; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Color; @@ -55,8 +56,7 @@ import com.cleanroommc.modularui.value.sync.StringSyncValue; import com.cleanroommc.modularui.widget.ParentWidget; import com.cleanroommc.modularui.widgets.ButtonWidget; -import com.cleanroommc.modularui.widgets.layout.Column; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import com.cleanroommc.modularui.widgets.textfield.TextFieldWidget; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; @@ -510,12 +510,12 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan getItemFilterContainer().setMaxTransferSize(getMaxStackSize()); return panel.child(CoverWithUI.createTitleRow(getPickItem())) - .child(createUI(panel, guiSyncManager)) + .child(createUI(guiData, guiSyncManager)) .bindPlayerInventory(); } - protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager guiSyncManager) { - var column = new Column().top(24).margin(7, 0) + protected ParentWidget createUI(GuiData data, PanelSyncManager guiSyncManager) { + var column = Flow.column().top(24).margin(7, 0) .widthRel(1f).coverChildrenHeight(); EnumSyncValue manualIOmode = new EnumSyncValue<>(ManualImportExportMode.class, @@ -525,7 +525,6 @@ protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager this::getConveyorMode, this::setConveyorMode); IntSyncValue throughput = new IntSyncValue(this::getTransferRate, this::setTransferRate); - throughput.updateCacheFromSource(true); StringSyncValue formattedThroughput = new StringSyncValue(throughput::getStringValue, throughput::setStringValue); @@ -539,7 +538,7 @@ protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager guiSyncManager.syncValue("throughput", throughput); if (createThroughputRow()) - column.child(new Row().coverChildrenHeight() + column.child(Flow.row().coverChildrenHeight() .marginBottom(2).widthRel(1f) .child(new ButtonWidget<>() .left(0).width(18) @@ -567,7 +566,7 @@ protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager .onUpdateListener(w -> w.overlay(createAdjustOverlay(true))))); if (createFilterRow()) - column.child(getItemFilterContainer().initUI(mainPanel, guiSyncManager)); + column.child(getItemFilterContainer().initUI(data, guiSyncManager)); if (createManualIOModeRow()) column.child(new EnumRowBuilder<>(ManualImportExportMode.class) diff --git a/src/main/java/gregtech/common/covers/CoverDigitalInterface.java b/src/main/java/gregtech/common/covers/CoverDigitalInterface.java index d4950ca4ac7..0063a113faa 100644 --- a/src/main/java/gregtech/common/covers/CoverDigitalInterface.java +++ b/src/main/java/gregtech/common/covers/CoverDigitalInterface.java @@ -19,8 +19,8 @@ import gregtech.api.util.TextFormattingUtil; import gregtech.client.renderer.texture.Textures; import gregtech.client.utils.RenderUtil; +import gregtech.common.gui.widget.prospector.widget.WidgetOreList; import gregtech.common.metatileentities.multi.electric.MetaTileEntityPowerSubstation; -import gregtech.common.terminal.app.prospector.widget.WidgetOreList; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; diff --git a/src/main/java/gregtech/common/covers/CoverEnderFluidLink.java b/src/main/java/gregtech/common/covers/CoverEnderFluidLink.java deleted file mode 100644 index a674b6fbd54..00000000000 --- a/src/main/java/gregtech/common/covers/CoverEnderFluidLink.java +++ /dev/null @@ -1,348 +0,0 @@ -package gregtech.common.covers; - -import gregtech.api.capability.GregtechTileCapabilities; -import gregtech.api.capability.IControllable; -import gregtech.api.cover.CoverBase; -import gregtech.api.cover.CoverDefinition; -import gregtech.api.cover.CoverWithUI; -import gregtech.api.cover.CoverableView; -import gregtech.api.mui.GTGuiTextures; -import gregtech.api.mui.GTGuis; -import gregtech.api.util.FluidTankSwitchShim; -import gregtech.api.util.GTTransferUtils; -import gregtech.api.util.VirtualTankRegistry; -import gregtech.client.renderer.texture.Textures; -import gregtech.common.covers.filter.FluidFilterContainer; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.BlockRenderLayer; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.ITickable; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandler; - -import codechicken.lib.raytracer.CuboidRayTraceResult; -import codechicken.lib.render.CCRenderState; -import codechicken.lib.render.pipeline.IVertexOperation; -import codechicken.lib.vec.Cuboid6; -import codechicken.lib.vec.Matrix4; -import com.cleanroommc.modularui.api.drawable.IKey; -import com.cleanroommc.modularui.drawable.DynamicDrawable; -import com.cleanroommc.modularui.drawable.Rectangle; -import com.cleanroommc.modularui.factory.SidedPosGuiData; -import com.cleanroommc.modularui.screen.ModularPanel; -import com.cleanroommc.modularui.utils.Color; -import com.cleanroommc.modularui.value.sync.BooleanSyncValue; -import com.cleanroommc.modularui.value.sync.EnumSyncValue; -import com.cleanroommc.modularui.value.sync.FluidSlotSyncHandler; -import com.cleanroommc.modularui.value.sync.PanelSyncManager; -import com.cleanroommc.modularui.value.sync.StringSyncValue; -import com.cleanroommc.modularui.widgets.FluidSlot; -import com.cleanroommc.modularui.widgets.ToggleButton; -import com.cleanroommc.modularui.widgets.layout.Column; -import com.cleanroommc.modularui.widgets.layout.Row; -import com.cleanroommc.modularui.widgets.textfield.TextFieldWidget; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.UUID; -import java.util.regex.Pattern; - -public class CoverEnderFluidLink extends CoverBase implements CoverWithUI, ITickable, IControllable { - - public static final int TRANSFER_RATE = 8000; // mB/t - private static final Pattern COLOR_INPUT_PATTERN = Pattern.compile("[0-9a-fA-F]*"); - - protected CoverPump.PumpMode pumpMode = CoverPump.PumpMode.IMPORT; - private int color = 0xFFFFFFFF; - private UUID playerUUID = null; - private boolean isPrivate = false; - private boolean workingEnabled = true; - private boolean ioEnabled = false; - private String tempColorStr; - private boolean isColorTemp; - private final FluidTankSwitchShim linkedTank; - protected final FluidFilterContainer fluidFilter; - - protected CoverEnderFluidLink(@NotNull CoverDefinition definition, @NotNull CoverableView coverableView, - @NotNull EnumFacing attachedSide) { - super(definition, coverableView, attachedSide); - this.linkedTank = new FluidTankSwitchShim(VirtualTankRegistry.getTankCreate(makeTankName(), null)); - this.fluidFilter = new FluidFilterContainer(this); - } - - private String makeTankName() { - return "EFLink#" + Integer.toHexString(this.color).toUpperCase(); - } - - private UUID getTankUUID() { - return isPrivate ? playerUUID : null; - } - - public FluidFilterContainer getFluidFilterContainer() { - return this.fluidFilter; - } - - public boolean isIOEnabled() { - return this.ioEnabled; - } - - @Override - public boolean canAttach(@NotNull CoverableView coverable, @NotNull EnumFacing side) { - return coverable.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side); - } - - @Override - public void renderCover(@NotNull CCRenderState renderState, @NotNull Matrix4 translation, - IVertexOperation[] pipeline, @NotNull Cuboid6 plateBox, @NotNull BlockRenderLayer layer) { - Textures.ENDER_FLUID_LINK.renderSided(getAttachedSide(), plateBox, renderState, pipeline, translation); - } - - @Override - public @NotNull EnumActionResult onScrewdriverClick(@NotNull EntityPlayer playerIn, @NotNull EnumHand hand, - @NotNull CuboidRayTraceResult hitResult) { - if (!getWorld().isRemote) { - openUI((EntityPlayerMP) playerIn); - } - return EnumActionResult.SUCCESS; - } - - @Override - public void onAttachment(@NotNull CoverableView coverableView, @NotNull EnumFacing side, - @Nullable EntityPlayer player, @NotNull ItemStack itemStack) { - super.onAttachment(coverableView, side, player, itemStack); - if (player != null) { - this.playerUUID = player.getUniqueID(); - } - } - - @Override - public void onRemoval() { - dropInventoryContents(fluidFilter); - } - - @Override - public void update() { - if (workingEnabled && ioEnabled) { - transferFluids(); - } - } - - protected void transferFluids() { - IFluidHandler fluidHandler = getCoverableView().getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, - getAttachedSide()); - if (fluidHandler == null) return; - if (pumpMode == CoverPump.PumpMode.IMPORT) { - GTTransferUtils.transferFluids(fluidHandler, linkedTank, TRANSFER_RATE, fluidFilter::test); - } else if (pumpMode == CoverPump.PumpMode.EXPORT) { - GTTransferUtils.transferFluids(linkedTank, fluidHandler, TRANSFER_RATE, fluidFilter::test); - } - } - - public void setPumpMode(CoverPump.PumpMode pumpMode) { - this.pumpMode = pumpMode; - markDirty(); - } - - public CoverPump.PumpMode getPumpMode() { - return pumpMode; - } - - @Override - public void openUI(EntityPlayerMP player) { - CoverWithUI.super.openUI(player); - isColorTemp = false; - } - - @Override - public boolean usesMui2() { - return true; - } - - @Override - public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncManager) { - var panel = GTGuis.createPanel(this, 176, 192); - - getFluidFilterContainer().setMaxTransferSize(1); - - return panel.child(CoverWithUI.createTitleRow(getPickItem())) - .child(createWidgets(panel, guiSyncManager)) - .bindPlayerInventory(); - } - - protected Column createWidgets(ModularPanel panel, PanelSyncManager syncManager) { - var isPrivate = new BooleanSyncValue(this::isPrivate, this::setPrivate); - isPrivate.updateCacheFromSource(true); - - var color = new StringSyncValue(this::getColorStr, this::updateColor); - color.updateCacheFromSource(true); - - var pumpMode = new EnumSyncValue<>(CoverPump.PumpMode.class, this::getPumpMode, this::setPumpMode); - syncManager.syncValue("pump_mode", pumpMode); - pumpMode.updateCacheFromSource(true); - - var ioEnabled = new BooleanSyncValue(this::isIOEnabled, this::setIoEnabled); - - var fluidTank = new FluidSlotSyncHandler(this.linkedTank); - fluidTank.updateCacheFromSource(true); - - return new Column().coverChildrenHeight().top(24) - .margin(7, 0).widthRel(1f) - .child(new Row().marginBottom(2) - .coverChildrenHeight() - .child(new ToggleButton() - .tooltip(tooltip -> tooltip.setAutoUpdate(true)) - .background(GTGuiTextures.PRIVATE_MODE_BUTTON[0]) - .hoverBackground(GTGuiTextures.PRIVATE_MODE_BUTTON[0]) - .selectedBackground(GTGuiTextures.PRIVATE_MODE_BUTTON[1]) - .selectedHoverBackground(GTGuiTextures.PRIVATE_MODE_BUTTON[1]) - .tooltipBuilder(tooltip -> tooltip.addLine(IKey.lang(this.isPrivate ? - "cover.ender_fluid_link.private.tooltip.enabled" : - "cover.ender_fluid_link.private.tooltip.disabled"))) - .marginRight(2) - .value(isPrivate)) - .child(new DynamicDrawable(() -> new Rectangle() - .setColor(this.color) - .asIcon().size(16)) - .asWidget() - .background(GTGuiTextures.SLOT) - .size(18).marginRight(2)) - .child(new TextFieldWidget().height(18) - .value(color) - .setValidator(s -> { - if (s.length() != 8) { - return color.getStringValue(); - } - return s; - }) - .setPattern(COLOR_INPUT_PATTERN) - .widthRel(0.5f).marginRight(2)) - .child(new FluidSlot().size(18) - .syncHandler(fluidTank))) - .child(new Row().marginBottom(2) - .coverChildrenHeight() - .child(new ToggleButton() - .value(ioEnabled) - .overlay(IKey.dynamic(() -> IKey.lang(this.ioEnabled ? - "behaviour.soft_hammer.enabled" : - "behaviour.soft_hammer.disabled").get()) - .color(Color.WHITE.darker(1))) - .widthRel(0.6f) - .left(0))) - .child(getFluidFilterContainer().initUI(panel, syncManager)) - .child(new EnumRowBuilder<>(CoverPump.PumpMode.class) - .value(pumpMode) - .overlay(GTGuiTextures.CONVEYOR_MODE_OVERLAY) - .lang("cover.pump.mode") - .build()); - } - - public void updateColor(String str) { - if (str.length() == 8) { - isColorTemp = false; - // stupid java not having actual unsigned ints - long tmp = Long.parseLong(str, 16); - if (tmp > 0x7FFFFFFF) { - tmp -= 0x100000000L; - } - this.color = (int) tmp; - updateTankLink(); - } else { - tempColorStr = str; - isColorTemp = true; - } - } - - public String getColorStr() { - return isColorTemp ? tempColorStr : Integer.toHexString(this.color).toUpperCase(); - } - - public void updateTankLink() { - this.linkedTank.changeTank(VirtualTankRegistry.getTankCreate(makeTankName(), getTankUUID())); - markDirty(); - } - - @Override - public void writeToNBT(NBTTagCompound tagCompound) { - super.writeToNBT(tagCompound); - tagCompound.setInteger("Frequency", color); - tagCompound.setInteger("PumpMode", pumpMode.ordinal()); - tagCompound.setBoolean("WorkingAllowed", workingEnabled); - tagCompound.setBoolean("IOAllowed", ioEnabled); - tagCompound.setBoolean("Private", isPrivate); - tagCompound.setString("PlacedUUID", playerUUID.toString()); - tagCompound.setTag("Filter", fluidFilter.serializeNBT()); - } - - @Override - public void readFromNBT(NBTTagCompound tagCompound) { - super.readFromNBT(tagCompound); - this.color = tagCompound.getInteger("Frequency"); - this.pumpMode = CoverPump.PumpMode.values()[tagCompound.getInteger("PumpMode")]; - this.workingEnabled = tagCompound.getBoolean("WorkingAllowed"); - this.ioEnabled = tagCompound.getBoolean("IOAllowed"); - this.isPrivate = tagCompound.getBoolean("Private"); - this.playerUUID = UUID.fromString(tagCompound.getString("PlacedUUID")); - this.fluidFilter.deserializeNBT(tagCompound.getCompoundTag("Filter")); - updateTankLink(); - } - - @Override - public void writeInitialSyncData(PacketBuffer packetBuffer) { - packetBuffer.writeInt(this.color); - packetBuffer.writeString(this.playerUUID == null ? "null" : this.playerUUID.toString()); - } - - @Override - public void readInitialSyncData(PacketBuffer packetBuffer) { - this.color = packetBuffer.readInt(); - // does client even need uuid info? just in case - String uuidStr = packetBuffer.readString(36); - this.playerUUID = uuidStr.equals("null") ? null : UUID.fromString(uuidStr); - // client does not need the actual tank reference, the default one will do just fine - } - - @Override - public boolean isWorkingEnabled() { - return workingEnabled; - } - - @Override - public void setWorkingEnabled(boolean isActivationAllowed) { - this.workingEnabled = isActivationAllowed; - } - - public T getCapability(Capability capability, T defaultValue) { - if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { - return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(linkedTank); - } - if (capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE) { - return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this); - } - return defaultValue; - } - - private boolean isIoEnabled() { - return ioEnabled; - } - - private void setIoEnabled(boolean ioEnabled) { - this.ioEnabled = ioEnabled; - } - - private boolean isPrivate() { - return isPrivate; - } - - private void setPrivate(boolean isPrivate) { - this.isPrivate = isPrivate; - updateTankLink(); - } -} diff --git a/src/main/java/gregtech/common/covers/CoverFluidFilter.java b/src/main/java/gregtech/common/covers/CoverFluidFilter.java index c8763119b57..a0b6585ebd7 100644 --- a/src/main/java/gregtech/common/covers/CoverFluidFilter.java +++ b/src/main/java/gregtech/common/covers/CoverFluidFilter.java @@ -9,8 +9,8 @@ import gregtech.api.util.GTLog; import gregtech.api.util.GTUtility; import gregtech.client.renderer.texture.cube.SimpleOverlayRenderer; -import gregtech.client.utils.TooltipHelper; import gregtech.common.covers.filter.BaseFilter; +import gregtech.common.covers.filter.BaseFilterContainer; import gregtech.common.covers.filter.FluidFilterContainer; import net.minecraft.entity.player.EntityPlayer; @@ -32,14 +32,18 @@ import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; +import com.cleanroommc.modularui.api.drawable.IKey; import com.cleanroommc.modularui.drawable.Rectangle; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.utils.Color; +import com.cleanroommc.modularui.value.sync.BooleanSyncValue; import com.cleanroommc.modularui.value.sync.EnumSyncValue; import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widgets.SlotGroupWidget; -import com.cleanroommc.modularui.widgets.layout.Column; +import com.cleanroommc.modularui.widgets.ToggleButton; +import com.cleanroommc.modularui.widgets.layout.Flow; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -51,7 +55,8 @@ public class CoverFluidFilter extends CoverBase implements CoverWithUI { protected final SimpleOverlayRenderer texture; protected final FluidFilterContainer fluidFilterContainer; protected FluidFilterMode filterMode; - protected FluidHandlerFiltered fluidHandler; + protected boolean allowFlow = false; + protected FluidHandlerDelegate fluidHandler; public CoverFluidFilter(@NotNull CoverDefinition definition, @NotNull CoverableView coverableView, @NotNull EnumFacing attachedSide, String titleLocale, SimpleOverlayRenderer texture) { @@ -77,9 +82,6 @@ public void onAttachment(@NotNull CoverableView coverableView, @NotNull EnumFaci @Override public @NotNull ItemStack getPickItem() { - if (TooltipHelper.isCtrlDown()) - return getCoverableView().getStackForm(); - return this.fluidFilterContainer.getFilterStack(); } @@ -107,11 +109,15 @@ public FluidFilterMode getFilterMode() { return filterMode; } - @SuppressWarnings("DataFlowIssue") // this cover always has a filter public @NotNull BaseFilter getFilter() { - return this.fluidFilterContainer.hasFilter() ? - this.fluidFilterContainer.getFilter() : - BaseFilter.ERROR_FILTER; + var filter = getFilterContainer().getFilter(); + if (filter == null) return BaseFilter.ERROR_FILTER; + + return filter; + } + + public @NotNull BaseFilterContainer getFilterContainer() { + return this.fluidFilterContainer; } @Override @@ -143,17 +149,34 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan guiSyncManager.syncValue("filtering_mode", filteringMode); this.fluidFilterContainer.setMaxTransferSize(1); - getFilter().getFilterReader().readStack(this.fluidFilterContainer.getFilterStack()); return getFilter().createPanel(guiSyncManager) - .size(176, 194).padding(7) - .child(CoverWithUI.createTitleRow(getPickItem())) - .child(new Column().widthRel(1f).align(Alignment.TopLeft).top(22).coverChildrenHeight() + .size(176, 212).padding(7) + .child(CoverWithUI.createTitleRow(getFilterContainer().getFilterStack())) + .child(Flow.column().widthRel(1f).align(Alignment.TopLeft).top(22).coverChildrenHeight() .child(new EnumRowBuilder<>(FluidFilterMode.class) .value(filteringMode) .lang("cover.filter.mode.title") .overlay(16, GTGuiTextures.FILTER_MODE_OVERLAY) .build()) + .child(Flow.row() + .marginBottom(2) + .widthRel(1f) + .coverChildrenHeight() + .setEnabledIf(b -> getFilterMode() != FluidFilterMode.FILTER_BOTH) + .child(new ToggleButton() + .overlay(IKey.dynamic(() -> IKey.lang(allowFlow ? + "cover.generic.enabled" : + "cover.generic.disabled").get()) + .color(Color.WHITE.main).shadow(false)) + .tooltip(tooltip -> tooltip + .addLine(IKey.lang("cover.filter.allow_flow.tooltip"))) + .size(72, 18) + .value(new BooleanSyncValue(() -> allowFlow, b -> allowFlow = b))) + .child(IKey.lang("cover.filter.allow_flow.label") + .asWidget() + .height(18) + .alignX(1f))) .child(new Rectangle().setColor(UI_TEXT_COLOR).asWidget() .height(1).widthRel(0.95f).margin(0, 4)) .child(getFilter().createWidgets(guiSyncManager))) @@ -207,30 +230,36 @@ public FluidHandlerFiltered(@NotNull IFluidHandler delegate) { } public int fill(FluidStack resource, boolean doFill) { - if (getFilterMode() == FluidFilterMode.FILTER_DRAIN || !fluidFilterContainer.test(resource)) { - return 0; - } - return super.fill(resource, doFill); + // set to drain, but filling is allowed + if (getFilterMode() == FluidFilterMode.FILTER_DRAIN && allowFlow) + return super.fill(resource, doFill); + + // if set to insert or both, test the stack + if (getFilterMode() != FluidFilterMode.FILTER_DRAIN && fluidFilterContainer.test(resource)) + return super.fill(resource, doFill); + + // otherwise fail + return 0; } @Nullable public FluidStack drain(FluidStack resource, boolean doDrain) { - if (getFilterMode() == FluidFilterMode.FILTER_FILL || !fluidFilterContainer.test(resource)) { - return null; - } - return super.drain(resource, doDrain); + // set to fill, draining is allowed + if (getFilterMode() == FluidFilterMode.FILTER_FILL && allowFlow) + return super.drain(resource, doDrain); + + // if set to extract or both, test stack + if (getFilterMode() != FluidFilterMode.FILTER_FILL && fluidFilterContainer.test(resource)) + return super.drain(resource, doDrain); + + // otherwise fail + return null; } @Nullable public FluidStack drain(int maxDrain, boolean doDrain) { - if (getFilterMode() != FluidFilterMode.FILTER_FILL) { - FluidStack result = super.drain(maxDrain, false); - if (result == null || result.amount <= 0 || !fluidFilterContainer.test(result)) { - return null; - } - return doDrain ? super.drain(maxDrain, true) : result; - } - return super.drain(maxDrain, doDrain); + var f = super.drain(maxDrain, false); + return drain(f, doDrain); } } } diff --git a/src/main/java/gregtech/common/covers/CoverFluidRegulator.java b/src/main/java/gregtech/common/covers/CoverFluidRegulator.java index 27122cdfa7a..141b51e0552 100644 --- a/src/main/java/gregtech/common/covers/CoverFluidRegulator.java +++ b/src/main/java/gregtech/common/covers/CoverFluidRegulator.java @@ -20,6 +20,7 @@ import net.minecraftforge.fml.relauncher.SideOnly; import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.GuiData; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Color; @@ -247,7 +248,7 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan } @Override - protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager syncManager) { + protected ParentWidget createUI(GuiData data, PanelSyncManager syncManager) { var transferMode = new EnumSyncValue<>(TransferMode.class, this::getTransferMode, this::setTransferMode); transferMode.updateCacheFromSource(true); syncManager.syncValue("transfer_mode", transferMode); @@ -259,7 +260,7 @@ protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager sync var filterTransferSize = new StringSyncValue(this::getStringTransferRate, this::setStringTransferRate); filterTransferSize.updateCacheFromSource(true); - return super.createUI(mainPanel, syncManager) + return super.createUI(data, syncManager) .child(new EnumRowBuilder<>(TransferMode.class) .value(transferMode) .lang("cover.generic.transfer_mode") diff --git a/src/main/java/gregtech/common/covers/CoverFluidVoiding.java b/src/main/java/gregtech/common/covers/CoverFluidVoiding.java index c6aa519660c..4bd8472b55f 100644 --- a/src/main/java/gregtech/common/covers/CoverFluidVoiding.java +++ b/src/main/java/gregtech/common/covers/CoverFluidVoiding.java @@ -25,6 +25,7 @@ import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.GuiData; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Color; @@ -32,7 +33,7 @@ import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widget.ParentWidget; import com.cleanroommc.modularui.widgets.ToggleButton; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import org.jetbrains.annotations.NotNull; public class CoverFluidVoiding extends CoverPump { @@ -76,11 +77,11 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan } @Override - protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager syncManager) { + protected ParentWidget createUI(GuiData data, PanelSyncManager syncManager) { var isWorking = new BooleanSyncValue(this::isWorkingEnabled, this::setWorkingEnabled); - return super.createUI(mainPanel, syncManager) - .child(new Row().height(18).widthRel(1f) + return super.createUI(data, syncManager) + .child(Flow.row().height(18).widthRel(1f) .marginBottom(2) .child(new ToggleButton() .value(isWorking) diff --git a/src/main/java/gregtech/common/covers/CoverFluidVoidingAdvanced.java b/src/main/java/gregtech/common/covers/CoverFluidVoidingAdvanced.java index 80b7bb45564..b6a9e1cd1e5 100644 --- a/src/main/java/gregtech/common/covers/CoverFluidVoidingAdvanced.java +++ b/src/main/java/gregtech/common/covers/CoverFluidVoidingAdvanced.java @@ -20,6 +20,7 @@ import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.GuiData; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Color; @@ -105,7 +106,7 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan } @Override - protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager syncManager) { + protected ParentWidget createUI(GuiData data, PanelSyncManager syncManager) { var voidingMode = new EnumSyncValue<>(VoidingMode.class, this::getVoidingMode, this::setVoidingMode); syncManager.syncValue("voiding_mode", voidingMode); @@ -118,7 +119,7 @@ protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager sync transferTextField.setEnabled(this.fluidFilterContainer.showGlobalTransferLimitSlider() && this.voidingMode == VoidingMode.VOID_OVERFLOW); - return super.createUI(mainPanel, syncManager) + return super.createUI(data, syncManager) .child(new EnumRowBuilder<>(VoidingMode.class) .value(voidingMode) .lang("cover.voiding.voiding_mode") diff --git a/src/main/java/gregtech/common/covers/CoverItemFilter.java b/src/main/java/gregtech/common/covers/CoverItemFilter.java index 5267d23469d..8c667ad8ce7 100644 --- a/src/main/java/gregtech/common/covers/CoverItemFilter.java +++ b/src/main/java/gregtech/common/covers/CoverItemFilter.java @@ -9,8 +9,8 @@ import gregtech.api.util.GTLog; import gregtech.api.util.GTUtility; import gregtech.client.renderer.texture.cube.SimpleOverlayRenderer; -import gregtech.client.utils.TooltipHelper; import gregtech.common.covers.filter.BaseFilter; +import gregtech.common.covers.filter.BaseFilterContainer; import gregtech.common.covers.filter.ItemFilterContainer; import net.minecraft.entity.player.EntityPlayer; @@ -31,14 +31,18 @@ import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; +import com.cleanroommc.modularui.api.drawable.IKey; import com.cleanroommc.modularui.drawable.Rectangle; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.utils.Color; +import com.cleanroommc.modularui.value.sync.BooleanSyncValue; import com.cleanroommc.modularui.value.sync.EnumSyncValue; import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widgets.SlotGroupWidget; -import com.cleanroommc.modularui.widgets.layout.Column; +import com.cleanroommc.modularui.widgets.ToggleButton; +import com.cleanroommc.modularui.widgets.layout.Flow; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -50,7 +54,8 @@ public class CoverItemFilter extends CoverBase implements CoverWithUI { protected final SimpleOverlayRenderer texture; protected final ItemFilterContainer itemFilterContainer; protected ItemFilterMode filterMode = ItemFilterMode.FILTER_INSERT; - protected ItemHandlerFiltered itemHandler; + protected boolean allowFlow = false; + protected ItemHandlerDelegate itemHandler; public CoverItemFilter(@NotNull CoverDefinition definition, @NotNull CoverableView coverableView, @NotNull EnumFacing attachedSide, String titleLocale, SimpleOverlayRenderer texture) { @@ -70,9 +75,6 @@ public void onAttachment(@NotNull CoverableView coverableView, @NotNull EnumFaci @Override public @NotNull ItemStack getPickItem() { - if (TooltipHelper.isCtrlDown()) - return getCoverableView().getStackForm(); - return this.itemFilterContainer.getFilterStack(); } @@ -105,11 +107,15 @@ public ItemFilterMode getFilterMode() { return filterMode; } - @SuppressWarnings("DataFlowIssue") // this cover should always have a filter public @NotNull BaseFilter getFilter() { - return this.itemFilterContainer.hasFilter() ? - this.itemFilterContainer.getFilter() : - BaseFilter.ERROR_FILTER; + var filter = getFilterContainer().getFilter(); + if (filter == null) return BaseFilter.ERROR_FILTER; + + return filter; + } + + public @NotNull BaseFilterContainer getFilterContainer() { + return this.itemFilterContainer; } @Override @@ -145,17 +151,34 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan var filteringMode = new EnumSyncValue<>(ItemFilterMode.class, this::getFilterMode, this::setFilterMode); guiSyncManager.syncValue("filtering_mode", filteringMode); - getFilter().getFilterReader().readStack(this.itemFilterContainer.getFilterStack()); return getFilter().createPanel(guiSyncManager) - .size(176, 194).padding(7) - .child(CoverWithUI.createTitleRow(getPickItem()).left(4)) - .child(new Column().widthRel(1f).align(Alignment.TopLeft).top(22).coverChildrenHeight() + .size(176, 212).padding(7) + .child(CoverWithUI.createTitleRow(getFilterContainer().getFilterStack()).left(4)) + .child(Flow.column().widthRel(1f).align(Alignment.TopLeft).top(22).coverChildrenHeight() .child(new EnumRowBuilder<>(ItemFilterMode.class) .value(filteringMode) .lang("cover.filter.mode.title") .overlay(16, GTGuiTextures.FILTER_MODE_OVERLAY) .build()) + .child(Flow.row() + .marginBottom(2) + .widthRel(1f) + .coverChildrenHeight() + .setEnabledIf(b -> getFilterMode() != ItemFilterMode.FILTER_BOTH) + .child(new ToggleButton() + .overlay(IKey.dynamic(() -> IKey.lang(allowFlow ? + "cover.generic.enabled" : + "cover.generic.disabled").get()) + .color(Color.WHITE.main).shadow(false)) + .tooltip(tooltip -> tooltip + .addLine(IKey.lang("cover.filter.allow_flow.tooltip"))) + .size(72, 18) + .value(new BooleanSyncValue(() -> allowFlow, b -> allowFlow = b))) + .child(IKey.lang("cover.filter.allow_flow.label") + .asWidget() + .height(18) + .alignX(1f))) .child(new Rectangle().setColor(UI_TEXT_COLOR).asWidget() .height(1).widthRel(0.95f).margin(0, 4)) .child(getFilter().createWidgets(guiSyncManager).left(0))) @@ -212,23 +235,31 @@ public ItemHandlerFiltered(IItemHandler delegate) { @NotNull @Override public ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) { - if (getFilterMode() == ItemFilterMode.FILTER_EXTRACT || !itemFilterContainer.test(stack)) { - return stack; - } - return super.insertItem(slot, stack, simulate); + // set to extract, but insertion is allowed + if (getFilterMode() == ItemFilterMode.FILTER_EXTRACT && allowFlow) + return super.insertItem(slot, stack, simulate); + + // if set to insert or both, test the stack + if (getFilterMode() != ItemFilterMode.FILTER_EXTRACT && itemFilterContainer.test(stack)) + return super.insertItem(slot, stack, simulate); + + // otherwise fail + return stack; } @NotNull @Override public ItemStack extractItem(int slot, int amount, boolean simulate) { - if (getFilterMode() != ItemFilterMode.FILTER_INSERT) { - ItemStack result = super.extractItem(slot, amount, true); - if (result.isEmpty() || !itemFilterContainer.test(result)) { - return ItemStack.EMPTY; - } - return simulate ? result : super.extractItem(slot, amount, false); - } - return super.extractItem(slot, amount, simulate); + // set to insert, but extraction is allowed + if (getFilterMode() == ItemFilterMode.FILTER_INSERT && allowFlow) + return super.extractItem(slot, amount, simulate); + + // if set to extract or both, test stack + if (getFilterMode() != ItemFilterMode.FILTER_INSERT && itemFilterContainer.test(getStackInSlot(slot))) + return super.extractItem(slot, amount, simulate); + + // otherwise fail + return ItemStack.EMPTY; } } } diff --git a/src/main/java/gregtech/common/covers/CoverItemVoiding.java b/src/main/java/gregtech/common/covers/CoverItemVoiding.java index 35a64252725..e8129ec11f3 100644 --- a/src/main/java/gregtech/common/covers/CoverItemVoiding.java +++ b/src/main/java/gregtech/common/covers/CoverItemVoiding.java @@ -22,6 +22,7 @@ import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.GuiData; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Color; @@ -29,8 +30,7 @@ import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widget.ParentWidget; import com.cleanroommc.modularui.widgets.ToggleButton; -import com.cleanroommc.modularui.widgets.layout.Column; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import org.jetbrains.annotations.NotNull; public class CoverItemVoiding extends CoverConveyor { @@ -78,11 +78,11 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan } @Override - protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager guiSyncManager) { + protected ParentWidget createUI(GuiData data, PanelSyncManager guiSyncManager) { var isWorking = new BooleanSyncValue(this::isWorkingEnabled, this::setWorkingEnabled); - return super.createUI(mainPanel, guiSyncManager) - .child(new Row().height(18).widthRel(1f) + return super.createUI(data, guiSyncManager) + .child(Flow.row().height(18).widthRel(1f) .marginBottom(2) .child(new ToggleButton() .value(isWorking) diff --git a/src/main/java/gregtech/common/covers/CoverItemVoidingAdvanced.java b/src/main/java/gregtech/common/covers/CoverItemVoidingAdvanced.java index 4a062735ae3..b739e7e6e1f 100644 --- a/src/main/java/gregtech/common/covers/CoverItemVoidingAdvanced.java +++ b/src/main/java/gregtech/common/covers/CoverItemVoidingAdvanced.java @@ -17,6 +17,7 @@ import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; +import com.cleanroommc.modularui.factory.GuiData; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Color; @@ -24,8 +25,7 @@ import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.value.sync.StringSyncValue; import com.cleanroommc.modularui.widget.ParentWidget; -import com.cleanroommc.modularui.widgets.layout.Column; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import com.cleanroommc.modularui.widgets.textfield.TextFieldWidget; import org.jetbrains.annotations.NotNull; @@ -94,7 +94,7 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan } @Override - protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager guiSyncManager) { + protected ParentWidget createUI(GuiData data, PanelSyncManager guiSyncManager) { var voidingMode = new EnumSyncValue<>(VoidingMode.class, this::getVoidingMode, this::setVoidingMode); guiSyncManager.syncValue("voiding_mode", voidingMode); @@ -106,13 +106,13 @@ protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager transferTextField.setEnabled(this.itemFilterContainer.showGlobalTransferLimitSlider() && this.voidingMode == VoidingMode.VOID_OVERFLOW); - return super.createUI(mainPanel, guiSyncManager) + return super.createUI(data, guiSyncManager) .child(new EnumRowBuilder<>(VoidingMode.class) .value(voidingMode) .lang("cover.voiding.voiding_mode") .overlay(16, GTGuiTextures.VOIDING_MODE_OVERLAY) .build()) - .child(new Row().right(0).coverChildrenHeight() + .child(Flow.row().right(0).coverChildrenHeight() .child(transferTextField .setEnabledIf(w -> this.itemFilterContainer.showGlobalTransferLimitSlider() && this.voidingMode == VoidingMode.VOID_OVERFLOW) diff --git a/src/main/java/gregtech/common/covers/CoverMachineController.java b/src/main/java/gregtech/common/covers/CoverMachineController.java index 2626d8f3acd..545f3cde52e 100644 --- a/src/main/java/gregtech/common/covers/CoverMachineController.java +++ b/src/main/java/gregtech/common/covers/CoverMachineController.java @@ -32,7 +32,7 @@ import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widget.Widget; import com.cleanroommc.modularui.widgets.ToggleButton; -import com.cleanroommc.modularui.widgets.layout.Column; +import com.cleanroommc.modularui.widgets.layout.Flow; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -121,7 +121,7 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan return GTGuis.createPanel(this, 176, 112) .child(CoverWithUI.createTitleRow(getPickItem())) - .child(new Column() + .child(Flow.column() .widthRel(1.0f).margin(7, 0) .top(24).coverChildrenHeight() @@ -151,7 +151,7 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan // Controlling selector .child(createSettingsRow().height(16 + 2 + 16) - .child(new Column().heightRel(1.0f).coverChildrenWidth() + .child(Flow.column().heightRel(1.0f).coverChildrenWidth() .child(IKey.lang("cover.machine_controller.control").asWidget() .left(0).height(16).marginBottom(2)) .child(modeButton(controllerModeValue, ControllerMode.MACHINE).left(0))) @@ -169,8 +169,8 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan .right(0)))); } - private Column modeColumn(EnumSyncValue syncValue, ControllerMode mode, IKey title) { - return new Column().coverChildrenHeight().width(18) + private Flow modeColumn(EnumSyncValue syncValue, ControllerMode mode, IKey title) { + return Flow.column().coverChildrenHeight().width(18) .child(title.asWidget().size(16).marginBottom(2).alignment(Alignment.Center)) .child(modeButton(syncValue, mode)); } diff --git a/src/main/java/gregtech/common/covers/CoverPump.java b/src/main/java/gregtech/common/covers/CoverPump.java index 2fdb55e2cdd..b57e5a33545 100644 --- a/src/main/java/gregtech/common/covers/CoverPump.java +++ b/src/main/java/gregtech/common/covers/CoverPump.java @@ -43,6 +43,7 @@ import com.cleanroommc.modularui.api.drawable.IDrawable; import com.cleanroommc.modularui.api.widget.Interactable; import com.cleanroommc.modularui.drawable.DynamicDrawable; +import com.cleanroommc.modularui.factory.GuiData; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Color; @@ -53,8 +54,7 @@ import com.cleanroommc.modularui.value.sync.StringSyncValue; import com.cleanroommc.modularui.widget.ParentWidget; import com.cleanroommc.modularui.widgets.ButtonWidget; -import com.cleanroommc.modularui.widgets.layout.Column; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import com.cleanroommc.modularui.widgets.textfield.TextFieldWidget; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -196,41 +196,36 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan getFluidFilterContainer().setMaxTransferSize(getMaxTransferRate()); return panel.child(CoverWithUI.createTitleRow(getPickItem())) - .child(createUI(panel, guiSyncManager)) + .child(createUI(guiData, guiSyncManager)) .bindPlayerInventory(); } - protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager syncManager) { + protected ParentWidget createUI(GuiData data, PanelSyncManager syncManager) { var manualIOmode = new EnumSyncValue<>(ManualImportExportMode.class, this::getManualImportExportMode, this::setManualImportExportMode); - manualIOmode.updateCacheFromSource(true); var throughput = new IntSyncValue(this::getTransferRate, this::setTransferRate); - throughput.updateCacheFromSource(true); var throughputString = new StringSyncValue( - throughput::getStringValue, - throughput::setStringValue); - throughputString.updateCacheFromSource(true); + throughput::getStringValue, throughput::setStringValue); var pumpMode = new EnumSyncValue<>(PumpMode.class, this::getPumpMode, this::setPumpMode); - pumpMode.updateCacheFromSource(true); syncManager.syncValue("manual_io", manualIOmode); syncManager.syncValue("pump_mode", pumpMode); syncManager.syncValue("throughput", throughput); - var column = new Column().top(24).margin(7, 0) + var column = Flow.column().top(24).margin(7, 0) .widthRel(1f).coverChildrenHeight(); if (createThroughputRow()) - column.child(new Row().coverChildrenHeight() + column.child(Flow.row().coverChildrenHeight() .marginBottom(2).widthRel(1f) .child(new ButtonWidget<>() .left(0).width(18) .onMousePressed(mouseButton -> { int val = throughput.getValue() - getIncrementValue(MouseData.create(mouseButton)); - throughput.setValue(val, true, true); + throughput.setValue(val); Interactable.playButtonClickSound(); return true; }) @@ -245,15 +240,14 @@ protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager sync .right(0).width(18) .onMousePressed(mouseButton -> { int val = throughput.getValue() + getIncrementValue(MouseData.create(mouseButton)); - throughput.setValue(val, true, true); + throughput.setValue(val); Interactable.playButtonClickSound(); return true; }) .onUpdateListener(w -> w.overlay(createAdjustOverlay(true))))); if (createFilterRow()) - column.child(getFluidFilterContainer() - .initUI(mainPanel, syncManager)); + column.child(getFluidFilterContainer().initUI(data, syncManager)); if (createManualIOModeRow()) column.child(new EnumRowBuilder<>(ManualImportExportMode.class) diff --git a/src/main/java/gregtech/common/covers/CoverRoboticArm.java b/src/main/java/gregtech/common/covers/CoverRoboticArm.java index 22047e6db2e..b1b99657adf 100644 --- a/src/main/java/gregtech/common/covers/CoverRoboticArm.java +++ b/src/main/java/gregtech/common/covers/CoverRoboticArm.java @@ -19,6 +19,7 @@ import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Matrix4; +import com.cleanroommc.modularui.factory.GuiData; import com.cleanroommc.modularui.factory.SidedPosGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.utils.Color; @@ -26,8 +27,7 @@ import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.value.sync.StringSyncValue; import com.cleanroommc.modularui.widget.ParentWidget; -import com.cleanroommc.modularui.widgets.layout.Column; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import com.cleanroommc.modularui.widgets.textfield.TextFieldWidget; import org.jetbrains.annotations.NotNull; @@ -197,7 +197,7 @@ public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncMan } @Override - protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager guiSyncManager) { + protected ParentWidget createUI(GuiData data, PanelSyncManager guiSyncManager) { EnumSyncValue transferMode = new EnumSyncValue<>(TransferMode.class, this::getTransferMode, this::setTransferMode); guiSyncManager.syncValue("transfer_mode", transferMode); @@ -207,13 +207,13 @@ protected ParentWidget createUI(ModularPanel mainPanel, PanelSyncManager s -> this.itemFilterContainer.setTransferSize(Integer.parseInt(s))); filterTransferSize.updateCacheFromSource(true); - return super.createUI(mainPanel, guiSyncManager) + return super.createUI(data, guiSyncManager) .child(new EnumRowBuilder<>(TransferMode.class) .value(transferMode) .lang("cover.generic.transfer_mode") .overlay(GTGuiTextures.TRANSFER_MODE_OVERLAY) .build()) - .child(new Row().right(0).coverChildrenHeight() + .child(Flow.row().right(0).coverChildrenHeight() .child(new TextFieldWidget().widthRel(0.5f).right(0) .setEnabledIf(w -> shouldDisplayAmountSlider()) .setNumbers(0, Integer.MAX_VALUE) diff --git a/src/main/java/gregtech/common/covers/ender/CoverAbstractEnderLink.java b/src/main/java/gregtech/common/covers/ender/CoverAbstractEnderLink.java new file mode 100644 index 00000000000..4ed97afcc0e --- /dev/null +++ b/src/main/java/gregtech/common/covers/ender/CoverAbstractEnderLink.java @@ -0,0 +1,420 @@ +package gregtech.common.covers.ender; + +import gregtech.api.capability.GregtechDataCodes; +import gregtech.api.capability.IControllable; +import gregtech.api.cover.CoverBase; +import gregtech.api.cover.CoverDefinition; +import gregtech.api.cover.CoverWithUI; +import gregtech.api.cover.CoverableView; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; +import gregtech.api.util.virtualregistry.EntryTypes; +import gregtech.api.util.virtualregistry.VirtualEnderRegistry; +import gregtech.api.util.virtualregistry.VirtualEntry; +import gregtech.common.mui.widget.InteractableText; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.ITickable; + +import codechicken.lib.raytracer.CuboidRayTraceResult; +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.DynamicDrawable; +import com.cleanroommc.modularui.drawable.GuiTextures; +import com.cleanroommc.modularui.drawable.Rectangle; +import com.cleanroommc.modularui.factory.GuiData; +import com.cleanroommc.modularui.factory.SidedPosGuiData; +import com.cleanroommc.modularui.network.NetworkUtils; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.utils.Color; +import com.cleanroommc.modularui.value.sync.BooleanSyncValue; +import com.cleanroommc.modularui.value.sync.PanelSyncHandler; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.value.sync.StringSyncValue; +import com.cleanroommc.modularui.value.sync.SyncHandler; +import com.cleanroommc.modularui.widgets.ButtonWidget; +import com.cleanroommc.modularui.widgets.ListWidget; +import com.cleanroommc.modularui.widgets.ToggleButton; +import com.cleanroommc.modularui.widgets.layout.Flow; +import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.textfield.TextFieldWidget; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.input.Keyboard; + +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +@SuppressWarnings("SameParameterValue") +public abstract class CoverAbstractEnderLink extends CoverBase + implements CoverWithUI, ITickable, IControllable { + + protected static final Pattern COLOR_INPUT_PATTERN = Pattern.compile("[0-9a-fA-F]*"); + + protected T activeEntry = null; + protected String color = VirtualEntry.DEFAULT_COLOR; + protected UUID playerUUID = null; + private boolean isPrivate = false; + private boolean workingEnabled = true; + private boolean ioEnabled = false; + + public CoverAbstractEnderLink(@NotNull CoverDefinition definition, @NotNull CoverableView coverableView, + @NotNull EnumFacing attachedSide) { + super(definition, coverableView, attachedSide); + updateLink(); + } + + protected void updateLink() { + this.activeEntry = VirtualEnderRegistry.getOrCreateEntry(getOwner(), getType(), createName()); + this.activeEntry.setColor(this.color); + markDirty(); + } + + protected abstract EntryTypes getType(); + + public String getColorStr() { + return this.color; + } + + protected final String createName() { + return identifier() + this.color; + } + + protected abstract String identifier(); + + protected final UUID getOwner() { + return isPrivate ? playerUUID : null; + } + + @Override + public void readCustomData(int discriminator, @NotNull PacketBuffer buf) { + super.readCustomData(discriminator, buf); + if (discriminator == GregtechDataCodes.UPDATE_PRIVATE) { + setPrivate(buf.readBoolean()); + updateLink(); + } + } + + @Override + public @NotNull EnumActionResult onScrewdriverClick(@NotNull EntityPlayer playerIn, @NotNull EnumHand hand, + @NotNull CuboidRayTraceResult hitResult) { + if (!getWorld().isRemote) { + openUI((EntityPlayerMP) playerIn); + } + return EnumActionResult.SUCCESS; + } + + @Override + public void onAttachment(@NotNull CoverableView coverableView, @NotNull EnumFacing side, + @Nullable EntityPlayer player, @NotNull ItemStack itemStack) { + super.onAttachment(coverableView, side, player, itemStack); + if (player != null) { + this.playerUUID = player.getUniqueID(); + } + } + + public void updateColor(String str) { + if (str.length() == 8) { + this.color = str.toUpperCase(); + updateLink(); + } + } + + @Override + public boolean usesMui2() { + return true; + } + + @Override + public ModularPanel buildUI(SidedPosGuiData guiData, PanelSyncManager guiSyncManager) { + var panel = GTGuis.createPanel(this, 176, 192); + + this.playerUUID = guiData.getPlayer().getUniqueID(); + + return panel.child(CoverWithUI.createTitleRow(getPickItem())) + .child(createWidgets(guiData, guiSyncManager)) + .bindPlayerInventory(); + } + + protected Flow createWidgets(GuiData data, PanelSyncManager syncManager) { + var name = new StringSyncValue(this::getColorStr, this::updateColor); + + // todo unneeded cast in mui2 rc3 + var entrySelectorSH = (PanelSyncHandler) syncManager.panel("entry_selector", entrySelector(getType()), true); + + return Flow.column().coverChildrenHeight().top(24) + .margin(7, 0).widthRel(1f) + .child(new Row().marginBottom(2) + .coverChildrenHeight() + .child(createPrivateButton()) + .child(createColorIcon()) + .child(new TextFieldWidget() + .height(18) + .value(name) + .setPattern(COLOR_INPUT_PATTERN) + .widthRel(0.5f) + .marginRight(2)) + .child(createEntrySlot()) + .child(new ButtonWidget<>() + .overlay(GTGuiTextures.MENU_OVERLAY) + .background(GTGuiTextures.MC_BUTTON) + .disableHoverBackground() + .addTooltipLine(IKey.lang("cover.generic.ender.open_selector")) + .onMousePressed(i -> { + if (entrySelectorSH.isPanelOpen()) { + entrySelectorSH.closePanel(); + } else { + entrySelectorSH.openPanel(); + } + return true; + }))) + .child(createIoRow()); + } + + protected abstract IWidget createEntrySlot(); + + protected IWidget createColorIcon() { + return new DynamicDrawable(() -> new Rectangle() + .setColor(this.activeEntry.getColor()) + .asIcon().size(16)) + .asWidget() + .background(GTGuiTextures.SLOT) + .size(18) + .marginRight(2); + } + + protected IWidget createPrivateButton() { + return new ToggleButton() + .value(new BooleanSyncValue(this::isPrivate, this::setPrivate)) + .tooltip(tooltip -> tooltip.setAutoUpdate(true)) + .background(GTGuiTextures.PRIVATE_MODE_BUTTON[0]) + .hoverBackground(GTGuiTextures.PRIVATE_MODE_BUTTON[0]) + .selectedBackground(GTGuiTextures.PRIVATE_MODE_BUTTON[1]) + .selectedHoverBackground(GTGuiTextures.PRIVATE_MODE_BUTTON[1]) + .tooltipBuilder(tooltip -> tooltip.addLine(IKey.lang(this.isPrivate ? + "cover.ender_fluid_link.private.tooltip.enabled" : + "cover.ender_fluid_link.private.tooltip.disabled"))) + .marginRight(2); + } + + protected IWidget createIoRow() { + return Flow.row().marginBottom(2) + .coverChildrenHeight() + .child(new ToggleButton() + .value(new BooleanSyncValue(this::isIoEnabled, this::setIoEnabled)) + .overlay(IKey.dynamic(() -> IKey.lang(this.ioEnabled ? + "behaviour.soft_hammer.enabled" : + "behaviour.soft_hammer.disabled").get()) + .color(Color.WHITE.darker(1))) + .widthRel(0.6f) + .left(0)); + } + + @Override + public boolean isWorkingEnabled() { + return workingEnabled; + } + + @Override + public void setWorkingEnabled(boolean isActivationAllowed) { + this.workingEnabled = isActivationAllowed; + } + + public boolean isIoEnabled() { + return ioEnabled; + } + + protected void setIoEnabled(boolean ioEnabled) { + this.ioEnabled = ioEnabled; + } + + private boolean isPrivate() { + return isPrivate; + } + + private void setPrivate(boolean isPrivate) { + this.isPrivate = isPrivate; + updateLink(); + writeCustomData(GregtechDataCodes.UPDATE_PRIVATE, buffer -> buffer.writeBoolean(this.isPrivate)); + } + + @Override + public void writeInitialSyncData(PacketBuffer packetBuffer) { + packetBuffer.writeString(this.playerUUID == null ? "null" : this.playerUUID.toString()); + } + + @Override + public void readInitialSyncData(PacketBuffer packetBuffer) { + // does client even need uuid info? just in case + String uuidStr = packetBuffer.readString(36); + this.playerUUID = uuidStr.equals("null") ? null : UUID.fromString(uuidStr); + } + + @Override + public void readFromNBT(@NotNull NBTTagCompound nbt) { + super.readFromNBT(nbt); + this.ioEnabled = nbt.getBoolean("IOAllowed"); + this.isPrivate = nbt.getBoolean("Private"); + this.workingEnabled = nbt.getBoolean("WorkingAllowed"); + this.playerUUID = UUID.fromString(nbt.getString("PlacedUUID")); + int color = nbt.getInteger("Frequency"); + this.color = Integer.toHexString(color).toUpperCase(); + updateLink(); + } + + @Override + public void writeToNBT(@NotNull NBTTagCompound nbt) { + super.writeToNBT(nbt); + nbt.setBoolean("IOAllowed", ioEnabled); + nbt.setBoolean("Private", isPrivate); + nbt.setBoolean("WorkingAllowed", workingEnabled); + nbt.setString("PlacedUUID", playerUUID.toString()); + nbt.setInteger("Frequency", activeEntry.getColor()); + } + + protected PanelSyncHandler.IPanelBuilder entrySelector(EntryTypes type) { + return (syncManager, syncHandler) -> { + Set names = VirtualEnderRegistry.getEntryNames(getOwner(), type); + return GTGuis.createPopupPanel("entry_selector", 168, 112) + .child(IKey.lang("cover.generic.ender.known_channels") + .color(UI_TITLE_COLOR) + .asWidget() + .top(6) + .left(4)) + .child(ListWidget.builder(names, name -> createRow(name, syncManager, type)) + .background(GTGuiTextures.DISPLAY.asIcon() + .width(168 - 8) + .height(112 - 20)) + .paddingTop(1) + .size(168 - 12, 112 - 24) + .left(4) + .bottom(6)); + }; + } + + protected PanelSyncHandler.IPanelBuilder entryDescription(String key, T entry) { + return (syncManager, syncHandler) -> { + var sync = new StringSyncValue(entry::getDescription, entry::setDescription); + return GTGuis.createPopupPanel(key, 168, 36 + 6) + .child(IKey.lang("cover.generic.ender.set_description.title", entry.getColorStr()) + .color(UI_TITLE_COLOR) + .asWidget() + .left(4) + .top(6)) + .child(new TextFieldWidget() { + + // todo move this to new class? + @Override + public @NotNull Result onKeyPressed(char character, int keyCode) { + var result = super.onKeyPressed(character, keyCode); + if (result == Result.SUCCESS && keyCode == Keyboard.KEY_RETURN) { + sync.setStringValue(getText()); + if (syncHandler.isPanelOpen()) { + syncHandler.closePanel(); + } + } + return result; + } + }.setTextColor(Color.WHITE.darker(1)) + .value(sync) + .widthRel(0.95f) + .height(18) + .alignX(0.5f) + .bottom(6)); + }; + } + + protected IWidget createRow(final String name, final PanelSyncManager syncManager, final EntryTypes type) { + final T entry = VirtualEnderRegistry.getEntry(getOwner(), type, name); + var key = String.format("entry#%s_description", entry.getColorStr()); + var syncKey = PanelSyncManager.makeSyncKey(key, isPrivate ? 1 : 0); + final var panelHandler = (PanelSyncHandler) syncManager.panel(syncKey, + entryDescription(key, entry), true); + final var syncHandler = new EnderCoverSyncHandler(); + syncManager.syncValue(key + "_handler", syncHandler); + + return Flow.row() + .left(4) + .marginBottom(2) + .height(18) + .widthRel(0.98f) + .setEnabledIf(row -> VirtualEnderRegistry.hasEntry(getOwner(), type, name)) + .child(new Rectangle() + .setColor(entry.getColor()) + .asWidget() + .marginRight(4) + .size(16) + .background(GTGuiTextures.SLOT.asIcon().size(18)) + .top(1)) + .child(new InteractableText<>(entry, this::updateColor) + .tooltip(tooltip -> tooltip.setAutoUpdate(true)) + .tooltipBuilder(tooltip -> { + String desc = entry.getDescription(); + if (!desc.isEmpty()) tooltip.add(desc); + }) + .width(64) + .height(16) + .top(1) + .marginRight(4)) + .child(new ButtonWidget<>() + .overlay(GuiTextures.GEAR) + .addTooltipLine(IKey.lang("cover.generic.ender.set_description.tooltip")) + .onMousePressed(i -> { + // open entry settings + if (panelHandler.isPanelOpen()) { + panelHandler.closePanel(); + } else { + panelHandler.openPanel(); + } + return true; + })) + .child(createSlotWidget(entry)) + .child(new ButtonWidget<>() + .overlay(GTGuiTextures.BUTTON_CROSS) + .setEnabledIf(w -> !Objects.equals(entry.getColor(), activeEntry.getColor())) + .addTooltipLine(IKey.lang("cover.generic.ender.delete_entry")) + .onMousePressed(i -> { + // todo option to force delete, maybe as a popup? + deleteEntry(getOwner(), name); + syncHandler.syncToServer(1, buffer -> { + NetworkUtils.writeStringSafe(buffer, + getOwner() == null ? "null" : getOwner().toString()); + NetworkUtils.writeStringSafe(buffer, name); + }); + Interactable.playButtonClickSound(); + return true; + })); + } + + protected abstract IWidget createSlotWidget(T entry); + + protected abstract void deleteEntry(UUID player, String name); + + private final class EnderCoverSyncHandler extends SyncHandler { + + private static final int DELETE_ENTRY = 1; + + @Override + public void readOnClient(int i, PacketBuffer packetBuffer) {} + + @Override + public void readOnServer(int i, PacketBuffer packetBuffer) { + if (i == DELETE_ENTRY) { + var s = NetworkUtils.readStringSafe(packetBuffer); + UUID uuid = "null".equals(s) ? null : UUID.fromString(s); + String name = NetworkUtils.readStringSafe(packetBuffer); + deleteEntry(uuid, name); + } + } + } +} diff --git a/src/main/java/gregtech/common/covers/ender/CoverEnderFluidLink.java b/src/main/java/gregtech/common/covers/ender/CoverEnderFluidLink.java new file mode 100644 index 00000000000..4c373dfd41c --- /dev/null +++ b/src/main/java/gregtech/common/covers/ender/CoverEnderFluidLink.java @@ -0,0 +1,185 @@ +package gregtech.common.covers.ender; + +import gregtech.api.capability.GregtechTileCapabilities; +import gregtech.api.capability.IControllable; +import gregtech.api.cover.CoverDefinition; +import gregtech.api.cover.CoverWithUI; +import gregtech.api.cover.CoverableView; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.util.FluidTankSwitchShim; +import gregtech.api.util.GTTransferUtils; +import gregtech.api.util.virtualregistry.EntryTypes; +import gregtech.api.util.virtualregistry.VirtualEnderRegistry; +import gregtech.api.util.virtualregistry.entries.VirtualTank; +import gregtech.client.renderer.texture.Textures; +import gregtech.common.covers.CoverPump; +import gregtech.common.covers.filter.FluidFilterContainer; +import gregtech.common.mui.widget.GTFluidSlot; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.BlockRenderLayer; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.ITickable; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.fluids.capability.IFluidHandler; + +import codechicken.lib.render.CCRenderState; +import codechicken.lib.render.pipeline.IVertexOperation; +import codechicken.lib.vec.Cuboid6; +import codechicken.lib.vec.Matrix4; +import com.cleanroommc.modularui.api.widget.IWidget; +import com.cleanroommc.modularui.factory.GuiData; +import com.cleanroommc.modularui.value.sync.EnumSyncValue; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.widgets.layout.Flow; +import org.jetbrains.annotations.NotNull; + +import java.util.UUID; + +public class CoverEnderFluidLink extends CoverAbstractEnderLink + implements CoverWithUI, ITickable, IControllable { + + public static final int TRANSFER_RATE = 8000; // mB/t + + protected CoverPump.PumpMode pumpMode = CoverPump.PumpMode.IMPORT; + private final FluidTankSwitchShim linkedTank; + protected final FluidFilterContainer fluidFilter; + + public CoverEnderFluidLink(@NotNull CoverDefinition definition, @NotNull CoverableView coverableView, + @NotNull EnumFacing attachedSide) { + super(definition, coverableView, attachedSide); + this.linkedTank = new FluidTankSwitchShim(this.activeEntry); + this.fluidFilter = new FluidFilterContainer(this); + } + + @Override + protected void updateLink() { + super.updateLink(); + if (this.linkedTank != null) + this.linkedTank.changeTank(this.activeEntry); + } + + @Override + protected EntryTypes getType() { + return EntryTypes.ENDER_FLUID; + } + + @Override + protected String identifier() { + return "EFLink#"; + } + + public FluidFilterContainer getFluidFilterContainer() { + return this.fluidFilter; + } + + @Override + public boolean canAttach(@NotNull CoverableView coverable, @NotNull EnumFacing side) { + return coverable.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side); + } + + @Override + public void renderCover(@NotNull CCRenderState renderState, @NotNull Matrix4 translation, + IVertexOperation[] pipeline, @NotNull Cuboid6 plateBox, @NotNull BlockRenderLayer layer) { + Textures.ENDER_FLUID_LINK.renderSided(getAttachedSide(), plateBox, renderState, pipeline, translation); + } + + @Override + public void onRemoval() { + dropInventoryContents(fluidFilter); + } + + @Override + public void update() { + if (isWorkingEnabled() && isIoEnabled()) { + transferFluids(); + } + } + + protected void transferFluids() { + IFluidHandler fluidHandler = getCoverableView().getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, + getAttachedSide()); + if (fluidHandler == null) return; + if (pumpMode == CoverPump.PumpMode.IMPORT) { + GTTransferUtils.transferFluids(fluidHandler, activeEntry, TRANSFER_RATE, fluidFilter::test); + } else if (pumpMode == CoverPump.PumpMode.EXPORT) { + GTTransferUtils.transferFluids(activeEntry, fluidHandler, TRANSFER_RATE, fluidFilter::test); + } + } + + public void setPumpMode(CoverPump.PumpMode pumpMode) { + this.pumpMode = pumpMode; + markDirty(); + } + + public CoverPump.PumpMode getPumpMode() { + return pumpMode; + } + + @Override + protected IWidget createSlotWidget(VirtualTank entry) { + var fluidTank = GTFluidSlot.sync(entry) + .accessibility(false, false); + + return new GTFluidSlot() + .size(18) + .background(GTGuiTextures.FLUID_SLOT) + .syncHandler(fluidTank) + .marginRight(2); + } + + @Override + protected void deleteEntry(UUID uuid, String name) { + VirtualEnderRegistry.deleteEntry(uuid, getType(), name, tank -> tank.getFluidAmount() == 0); + } + + @Override + protected IWidget createEntrySlot() { + return new GTFluidSlot() + .size(18) + .background(GTGuiTextures.FLUID_SLOT) + .syncHandler(this.linkedTank) + .marginRight(2); + } + + protected Flow createWidgets(GuiData data, PanelSyncManager syncManager) { + getFluidFilterContainer().setMaxTransferSize(1); + + var pumpMode = new EnumSyncValue<>(CoverPump.PumpMode.class, this::getPumpMode, this::setPumpMode); + syncManager.syncValue("pump_mode", pumpMode); + pumpMode.updateCacheFromSource(true); + + return super.createWidgets(data, syncManager) + .child(getFluidFilterContainer().initUI(data, syncManager)) + .child(new EnumRowBuilder<>(CoverPump.PumpMode.class) + .value(pumpMode) + .overlay(GTGuiTextures.CONVEYOR_MODE_OVERLAY) + .lang("cover.pump.mode") + .build()); + } + + @Override + public void writeToNBT(NBTTagCompound tagCompound) { + super.writeToNBT(tagCompound); + tagCompound.setInteger("PumpMode", pumpMode.ordinal()); + tagCompound.setTag("Filter", fluidFilter.serializeNBT()); + } + + @Override + public void readFromNBT(NBTTagCompound tagCompound) { + super.readFromNBT(tagCompound); + this.pumpMode = CoverPump.PumpMode.values()[tagCompound.getInteger("PumpMode")]; + this.fluidFilter.deserializeNBT(tagCompound.getCompoundTag("Filter")); + } + + public T getCapability(Capability capability, T defaultValue) { + if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { + return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(this.activeEntry); + } + if (capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE) { + return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this); + } + return defaultValue; + } +} diff --git a/src/main/java/gregtech/common/covers/filter/BaseFilter.java b/src/main/java/gregtech/common/covers/filter/BaseFilter.java index 27f6a56bccb..b0a312b6e1e 100644 --- a/src/main/java/gregtech/common/covers/filter/BaseFilter.java +++ b/src/main/java/gregtech/common/covers/filter/BaseFilter.java @@ -144,7 +144,8 @@ public IWidget createBlacklistUI() { .value(new BooleanSyncValue( this::isBlacklistFilter, this::setBlacklistFilter)) - .textureGetter(state -> GTGuiTextures.BUTTON_BLACKLIST[state]) + .stateBackground(0, GTGuiTextures.BUTTON_BLACKLIST[0]) + .stateBackground(1, GTGuiTextures.BUTTON_BLACKLIST[1]) .addTooltip(0, IKey.lang("cover.filter.blacklist.disabled")) .addTooltip(1, IKey.lang("cover.filter.blacklist.enabled"))); } diff --git a/src/main/java/gregtech/common/covers/filter/BaseFilterContainer.java b/src/main/java/gregtech/common/covers/filter/BaseFilterContainer.java index 38867b542bf..7bb6c7473e3 100644 --- a/src/main/java/gregtech/common/covers/filter/BaseFilterContainer.java +++ b/src/main/java/gregtech/common/covers/filter/BaseFilterContainer.java @@ -1,5 +1,6 @@ package gregtech.common.covers.filter; +import gregtech.api.cover.CoverWithUI; import gregtech.api.mui.GTGuiTextures; import gregtech.api.util.IDirtyNotifiable; @@ -11,16 +12,15 @@ 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.GuiTextures; -import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.factory.GuiData; import com.cleanroommc.modularui.utils.Alignment; import com.cleanroommc.modularui.value.sync.PanelSyncHandler; import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.value.sync.SyncHandlers; import com.cleanroommc.modularui.widgets.ButtonWidget; import com.cleanroommc.modularui.widgets.ItemSlot; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -212,17 +212,14 @@ public void handleLegacyNBT(NBTTagCompound nbt) { } /** Uses Cleanroom MUI */ - public IWidget initUI(ModularPanel main, PanelSyncManager manager) { - PanelSyncHandler panel = manager.panel("filter_panel", main, (syncManager, syncHandler) -> { + public IWidget initUI(GuiData data, PanelSyncManager manager) { + PanelSyncHandler panel = (PanelSyncHandler) manager.panel("filter_panel", (syncManager, syncHandler) -> { var filter = hasFilter() ? getFilter() : BaseFilter.ERROR_FILTER; filter.setMaxTransferSize(getMaxTransferSize()); return filter.createPopupPanel(syncManager); - }); + }, true); - var filterButton = new ButtonWidget<>(); - filterButton.setEnabled(hasFilter()); - - return new Row().coverChildrenHeight() + return Flow.row().coverChildrenHeight() .marginBottom(2).widthRel(1f) .child(new ItemSlot() .slot(SyncHandlers.itemSlot(this, 0) @@ -235,7 +232,7 @@ public IWidget initUI(ModularPanel main, PanelSyncManager manager) { })) .size(18).marginRight(2) .background(GTGuiTextures.SLOT, GTGuiTextures.FILTER_SLOT_OVERLAY.asIcon().size(16))) - .child(filterButton + .child(new ButtonWidget<>() .background(GTGuiTextures.MC_BUTTON, GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) .hoverBackground(GuiTextures.MC_BUTTON_HOVERED, GTGuiTextures.FILTER_SETTINGS_OVERLAY.asIcon().size(16)) @@ -246,10 +243,11 @@ public IWidget initUI(ModularPanel main, PanelSyncManager manager) { } else { panel.closePanel(); } - Interactable.playButtonClickSound(); return true; })) .child(IKey.dynamic(this::getFilterName) + .color(CoverWithUI.UI_TEXT_COLOR) + .shadow(false) .alignment(Alignment.CenterRight).asWidget() .left(36).right(0).height(18)); } diff --git a/src/main/java/gregtech/common/covers/filter/OreDictionaryItemFilter.java b/src/main/java/gregtech/common/covers/filter/OreDictionaryItemFilter.java index 0eec589f555..0d91fd97cf8 100644 --- a/src/main/java/gregtech/common/covers/filter/OreDictionaryItemFilter.java +++ b/src/main/java/gregtech/common/covers/filter/OreDictionaryItemFilter.java @@ -20,7 +20,7 @@ import com.cleanroommc.modularui.api.drawable.IKey; import com.cleanroommc.modularui.drawable.UITexture; import com.cleanroommc.modularui.screen.ModularPanel; -import com.cleanroommc.modularui.screen.Tooltip; +import com.cleanroommc.modularui.screen.RichTooltip; import com.cleanroommc.modularui.utils.BooleanConsumer; import com.cleanroommc.modularui.utils.Color; import com.cleanroommc.modularui.value.sync.BooleanSyncValue; @@ -29,8 +29,7 @@ import com.cleanroommc.modularui.widget.Widget; import com.cleanroommc.modularui.widgets.CycleButtonWidget; import com.cleanroommc.modularui.widgets.SlotGroupWidget; -import com.cleanroommc.modularui.widgets.layout.Column; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.jetbrains.annotations.NotNull; @@ -112,7 +111,7 @@ public void initUI(Consumer widgetGroup) {} var caseSensitive = new BooleanSyncValue(this.filterReader::isCaseSensitive, setCaseSensitive); var matchAll = new BooleanSyncValue(this.filterReader::shouldMatchAll, setMatchAll); - return new Column().widthRel(1f).coverChildrenHeight() + return Flow.column().widthRel(1f).coverChildrenHeight() .child(new HighlightedTextField() .setHighlightRule(this::highlightRule) .onUnfocus(() -> { @@ -123,9 +122,9 @@ public void initUI(Consumer widgetGroup) {} .setTextColor(Color.WHITE.darker(1)) .value(expression).marginBottom(4) .height(18).widthRel(1f)) - .child(new Row().coverChildrenHeight() + .child(Flow.row().coverChildrenHeight() .widthRel(1f) - .child(new Column().height(18) + .child(Flow.column().height(18) .coverChildrenWidth().marginRight(2) .child(GTGuiTextures.OREDICT_INFO.asWidget() .size(8).top(0) @@ -148,7 +147,8 @@ public void initUI(Consumer widgetGroup) {} .child(new CycleButtonWidget() .size(18).value(caseSensitive) .marginRight(2) - .textureGetter(state -> GTGuiTextures.BUTTON_CASE_SENSITIVE[state]) + .stateBackground(0, GTGuiTextures.BUTTON_CASE_SENSITIVE[0]) + .stateBackground(1, GTGuiTextures.BUTTON_CASE_SENSITIVE[1]) .addTooltip(0, IKey.lang("cover.ore_dictionary_filter.button.case_sensitive.disabled")) .addTooltip(1, @@ -156,7 +156,8 @@ public void initUI(Consumer widgetGroup) {} .child(new CycleButtonWidget() .size(18).value(matchAll) .marginRight(2) - .textureGetter(state -> GTGuiTextures.BUTTON_MATCH_ALL[state]) + .stateBackground(0, GTGuiTextures.BUTTON_MATCH_ALL[0]) + .stateBackground(1, GTGuiTextures.BUTTON_MATCH_ALL[1]) .addTooltip(0, IKey.lang("cover.ore_dictionary_filter.button.match_all.disabled")) .addTooltip(1, @@ -180,7 +181,7 @@ protected void getStatusIcon(Widget widget) { widget.background(texture); } - protected void createStatusTooltip(Tooltip tooltip) { + protected void createStatusTooltip(RichTooltip tooltip) { var result = this.filterReader.getResult(); if (result == null) return; List list = new ArrayList<>(); diff --git a/src/main/java/gregtech/common/covers/filter/SimpleFluidFilter.java b/src/main/java/gregtech/common/covers/filter/SimpleFluidFilter.java index ed2b3a40eaf..b36acc61283 100644 --- a/src/main/java/gregtech/common/covers/filter/SimpleFluidFilter.java +++ b/src/main/java/gregtech/common/covers/filter/SimpleFluidFilter.java @@ -2,8 +2,8 @@ import gregtech.api.cover.CoverWithUI; import gregtech.api.mui.GTGuis; -import gregtech.api.mui.sync.FixedFluidSlotSH; import gregtech.common.covers.filter.readers.SimpleFluidFilterReader; +import gregtech.common.mui.widget.GTFluidSlot; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; @@ -11,9 +11,8 @@ import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widget.Widget; -import com.cleanroommc.modularui.widgets.FluidSlot; import com.cleanroommc.modularui.widgets.SlotGroupWidget; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import org.jetbrains.annotations.NotNull; import java.util.function.Consumer; @@ -53,13 +52,15 @@ public void configureFilterTanks(int amount) { @Override public @NotNull Widget createWidgets(PanelSyncManager syncManager) { - return new Row().coverChildrenHeight().widthRel(1f) + return Flow.row().coverChildrenHeight().widthRel(1f) .child(SlotGroupWidget.builder() .matrix("FFF", "FFF", "FFF") - .key('F', i -> new FluidSlot() - .syncHandler(new FixedFluidSlotSH(filterReader.getFluidTank(i)).phantom(true))) + .key('F', i -> new GTFluidSlot() + .syncHandler(GTFluidSlot.sync(filterReader.getFluidTank(i)) + .phantom(true) + .showAmount(getFilterReader()::shouldShowAmount))) .build().marginRight(4)) .child(createBlacklistUI()); } diff --git a/src/main/java/gregtech/common/covers/filter/SimpleItemFilter.java b/src/main/java/gregtech/common/covers/filter/SimpleItemFilter.java index 4eaf4ffc865..d69e6de7649 100644 --- a/src/main/java/gregtech/common/covers/filter/SimpleItemFilter.java +++ b/src/main/java/gregtech/common/covers/filter/SimpleItemFilter.java @@ -26,8 +26,7 @@ import com.cleanroommc.modularui.widgets.CycleButtonWidget; import com.cleanroommc.modularui.widgets.ItemSlot; import com.cleanroommc.modularui.widgets.SlotGroupWidget; -import com.cleanroommc.modularui.widgets.layout.Column; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import com.cleanroommc.modularui.widgets.slot.SlotGroup; import org.jetbrains.annotations.NotNull; @@ -114,7 +113,7 @@ public void initUI(Consumer widgetGroup) { syncManager.registerSlotGroup(filterInventory); - return new Row().coverChildren() + return Flow.row().coverChildren() .child(SlotGroupWidget.builder() .matrix("XXX", "XXX", @@ -134,7 +133,7 @@ public void initUI(Consumer widgetGroup) { .getInteger(SimpleItemFilterReader.COUNT); if (count > 0) tooltip.addLine( - IKey.format("Count: %s", TextFormattingUtil.formatNumbers(count))); + IKey.str("Count: %s", TextFormattingUtil.formatNumbers(count))); } }) .slot(SyncHandlers.phantomItemSlot(this.filterReader, index) @@ -146,16 +145,18 @@ public void initUI(Consumer widgetGroup) { } }))) .build().marginRight(4)) - .child(new Column().width(18).coverChildren() + .child(Flow.column().width(18).coverChildren() .child(createBlacklistUI()) .child(new CycleButtonWidget() .value(ignoreDamage) - .textureGetter(state -> GTGuiTextures.BUTTON_IGNORE_DAMAGE[state]) + .stateBackground(0, GTGuiTextures.BUTTON_IGNORE_DAMAGE[0]) + .stateBackground(1, GTGuiTextures.BUTTON_IGNORE_DAMAGE[1]) .addTooltip(0, IKey.lang("cover.item_filter.ignore_damage.disabled")) .addTooltip(1, IKey.lang("cover.item_filter.ignore_damage.enabled"))) .child(new CycleButtonWidget() .value(ignoreNBT) - .textureGetter(state -> GTGuiTextures.BUTTON_IGNORE_NBT[state]) + .stateBackground(0, GTGuiTextures.BUTTON_IGNORE_NBT[0]) + .stateBackground(1, GTGuiTextures.BUTTON_IGNORE_NBT[1]) .addTooltip(0, IKey.lang("cover.item_filter.ignore_nbt.disabled")) .addTooltip(1, IKey.lang("cover.item_filter.ignore_nbt.enabled")))); } diff --git a/src/main/java/gregtech/common/covers/filter/SmartItemFilter.java b/src/main/java/gregtech/common/covers/filter/SmartItemFilter.java index 425189b7de2..d7cbf29c463 100644 --- a/src/main/java/gregtech/common/covers/filter/SmartItemFilter.java +++ b/src/main/java/gregtech/common/covers/filter/SmartItemFilter.java @@ -22,8 +22,7 @@ import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widget.Widget; import com.cleanroommc.modularui.widgets.ToggleButton; -import com.cleanroommc.modularui.widgets.layout.Column; -import com.cleanroommc.modularui.widgets.layout.Row; +import com.cleanroommc.modularui.widgets.layout.Flow; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import org.jetbrains.annotations.NotNull; @@ -115,8 +114,8 @@ public void initUI(Consumer widgetGroup) { filterReader::setFilteringMode); syncManager.syncValue("filter_mode", filterMode); - return new Row().coverChildren() - .child(new Column().coverChildren().marginRight(4) + return Flow.row().coverChildren() + .child(Flow.column().coverChildren().marginRight(4) .child(createFilterModeButton(filterMode, SmartFilteringMode.ELECTROLYZER)) .child(createFilterModeButton(filterMode, SmartFilteringMode.CENTRIFUGE)) .child(createFilterModeButton(filterMode, SmartFilteringMode.SIFTER))) diff --git a/src/main/java/gregtech/common/crafting/DyeableRecipes.java b/src/main/java/gregtech/common/crafting/DyeableRecipes.java new file mode 100644 index 00000000000..fa975fd4197 --- /dev/null +++ b/src/main/java/gregtech/common/crafting/DyeableRecipes.java @@ -0,0 +1,142 @@ +package gregtech.common.crafting; + +import gregtech.api.items.IDyeableItem; + +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.RecipesArmorDyes; +import net.minecraft.util.NonNullList; +import net.minecraft.world.World; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * Composed almost entirely of code taken from {@link RecipesArmorDyes} and modified to apply to {@link IDyeableItem} + * instead of just leather armor. Thus, will be difficult to parse. + */ +public final class DyeableRecipes extends RecipesArmorDyes { + + @ApiStatus.Internal + public DyeableRecipes() { + this.setRegistryName("gt_dyeable_dyeing"); + } + + /** + * Used to check if a recipe matches current crafting inventory + */ + @Override + public boolean matches(InventoryCrafting inv, @NotNull World worldIn) { + ItemStack itemstack = ItemStack.EMPTY; + List list = new ObjectArrayList<>(); + + for (int i = 0; i < inv.getSizeInventory(); ++i) { + ItemStack itemstack1 = inv.getStackInSlot(i); + + if (!itemstack1.isEmpty()) { + if (itemstack1.getItem() instanceof IDyeableItem) { + if (!itemstack.isEmpty()) { + return false; + } + + itemstack = itemstack1; + } else { + if (!net.minecraftforge.oredict.DyeUtils.isDye(itemstack1)) { + return false; + } + + list.add(itemstack1); + } + } + } + + return !itemstack.isEmpty() && !list.isEmpty(); + } + + /** + * Returns an Item that is the result of this recipe + */ + @Override + public @NotNull ItemStack getCraftingResult(InventoryCrafting inv) { + ItemStack itemstack = ItemStack.EMPTY; + int[] aint = new int[3]; + int i = 0; + int j = 0; + IDyeableItem dyeable = null; + + for (int k = 0; k < inv.getSizeInventory(); ++k) { + ItemStack itemstack1 = inv.getStackInSlot(k); + + if (!itemstack1.isEmpty()) { + if (itemstack1.getItem() instanceof IDyeableItem) { + dyeable = (IDyeableItem) itemstack1.getItem(); + + itemstack = itemstack1.copy(); + itemstack.setCount(1); + + if (dyeable.hasColor(itemstack1)) { + int l = dyeable.getColor(itemstack); + float f = (float) (l >> 16 & 255) / 255.0F; + float f1 = (float) (l >> 8 & 255) / 255.0F; + float f2 = (float) (l & 255) / 255.0F; + i = (int) ((float) i + Math.max(f, Math.max(f1, f2)) * 255.0F); + aint[0] = (int) ((float) aint[0] + f * 255.0F); + aint[1] = (int) ((float) aint[1] + f1 * 255.0F); + aint[2] = (int) ((float) aint[2] + f2 * 255.0F); + ++j; + } + } else { + if (!net.minecraftforge.oredict.DyeUtils.isDye(itemstack1)) { + return ItemStack.EMPTY; + } + + float[] afloat = net.minecraftforge.oredict.DyeUtils.colorFromStack(itemstack1).get() + .getColorComponentValues(); + int l1 = (int) (afloat[0] * 255.0F); + int i2 = (int) (afloat[1] * 255.0F); + int j2 = (int) (afloat[2] * 255.0F); + i += Math.max(l1, Math.max(i2, j2)); + aint[0] += l1; + aint[1] += i2; + aint[2] += j2; + ++j; + } + } + } + + if (dyeable == null) { + return ItemStack.EMPTY; + } else { + int i1 = aint[0] / j; + int j1 = aint[1] / j; + int k1 = aint[2] / j; + float f3 = (float) i / (float) j; + float f4 = (float) Math.max(i1, Math.max(j1, k1)); + i1 = (int) ((float) i1 * f3 / f4); + j1 = (int) ((float) j1 * f3 / f4); + k1 = (int) ((float) k1 * f3 / f4); + int k2 = (i1 << 8) + j1; + k2 = (k2 << 8) + k1; + // prevent consuming dye when the color would not change + if (dyeable.hasColor(itemstack) && dyeable.getColor(itemstack) == k2) return ItemStack.EMPTY; + dyeable.setColor(itemstack, k2); + return itemstack; + } + } + + @Override + public @NotNull NonNullList getRemainingItems(InventoryCrafting inv) { + NonNullList nonnulllist = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); + + for (int i = 0; i < nonnulllist.size(); ++i) { + ItemStack itemstack = inv.getStackInSlot(i); + if (!(itemstack.getItem() instanceof IDyeableItem item && !item.shouldGetContainerItem())) + nonnulllist.set(i, net.minecraftforge.common.ForgeHooks.getContainerItem(itemstack)); + } + + return nonnulllist; + } +} diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index a014bd89292..fce807d0f04 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -43,9 +43,10 @@ public GTShapedOreRecipe(boolean isClearing, ResourceLocation group, @NotNull It } // a copy of the CraftingHelper.ShapedPrimer.parseShaped method. - // the on difference is calling getIngredient of this class. + // the only difference is calling getIngredient of this class. - public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object... recipe) { + public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, + Object... recipe) { CraftingHelper.ShapedPrimer ret = new CraftingHelper.ShapedPrimer(); StringBuilder shape = new StringBuilder(); int idx = 0; @@ -126,23 +127,19 @@ public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object return ret; } - // a copy of the CraftingHelper getIngredient method. - // the only difference is checking for a filled bucket and making - // it an GTFluidCraftingIngredient protected static Ingredient getIngredient(boolean isClearing, Object obj) { - if (obj instanceof Ingredient) return (Ingredient) obj; - else if (obj instanceof ItemStack) { - ItemStack ing = (ItemStack) obj; - if (ing.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { - IFluidHandlerItem handler = ing.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, + if (obj instanceof Ingredient ing) return ing; + else if (obj instanceof ItemStack stk) { + if (stk.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { + IFluidHandlerItem handler = stk.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); if (handler != null) { FluidStack drained = handler.drain(Integer.MAX_VALUE, false); if (drained != null && drained.amount > 0) { - return new GTFluidCraftingIngredient(((ItemStack) obj).copy()); + return new GTFluidCraftingIngredient(stk.copy()); } if (!isClearing) { - ItemStack i = ((ItemStack) obj).copy(); + ItemStack i = (stk).copy(); try { return ingredientNBT.newInstance(i); } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { @@ -152,12 +149,13 @@ else if (obj instanceof ItemStack) { } } } - return Ingredient.fromStacks(((ItemStack) obj).copy()); - } else if (obj instanceof Item) return Ingredient.fromItem((Item) obj); - else if (obj instanceof Block) - return Ingredient.fromStacks(new ItemStack((Block) obj, 1, OreDictionary.WILDCARD_VALUE)); - else if (obj instanceof String) return new OreIngredient((String) obj); - else if (obj instanceof JsonElement) + return Ingredient.fromStacks(stk.copy()); + } else if (obj instanceof Item itm) return Ingredient.fromItem(itm); + else if (obj instanceof Block blk) + return Ingredient.fromStacks(new ItemStack(blk, 1, OreDictionary.WILDCARD_VALUE)); + else if (obj instanceof String str) { + return new OreIngredient(str); + } else if (obj instanceof JsonElement) throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); return null; diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index 6d0ee689b32..c2f92e47c41 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -1,42 +1,24 @@ package gregtech.common.crafting; -import gregtech.api.util.GTLog; -import gregtech.api.util.GTStringUtils; - -import net.minecraft.block.Block; import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.crafting.IngredientNBT; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; -import net.minecraftforge.fml.relauncher.ReflectionHelper; -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.OreIngredient; import net.minecraftforge.oredict.ShapelessOreRecipe; -import com.google.gson.JsonElement; import org.jetbrains.annotations.NotNull; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - public class GTShapelessOreRecipe extends ShapelessOreRecipe { boolean isClearing; - public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, - ItemStack.class); public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(group, result); this.isClearing = isClearing; for (Object in : recipe) { - Ingredient ing = getIngredient(isClearing, in); + Ingredient ing = GTShapedOreRecipe.getIngredient(isClearing, in); if (ing != null) { input.add(ing); this.isSimple = this.isSimple && ing.isSimple(); @@ -51,43 +33,6 @@ public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull } } - // a copy of the CraftingHelper getIngredient method. - // the only difference is checking for a filled bucket and making - // it an GTFluidCraftingIngredient - private static Ingredient getIngredient(boolean isClearing, Object obj) { - if (obj instanceof Ingredient) return (Ingredient) obj; - else if (obj instanceof ItemStack) { - ItemStack ing = (ItemStack) obj; - if (ing.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { - IFluidHandlerItem handler = ing.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, - null); - if (handler != null) { - FluidStack drained = handler.drain(Integer.MAX_VALUE, false); - if (drained != null && drained.amount > 0) { - return new GTFluidCraftingIngredient(((ItemStack) obj).copy()); - } - if (!isClearing) { - ItemStack i = ((ItemStack) obj).copy(); - try { - return ingredientNBT.newInstance(i); - } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { - GTLog.logger.error("Failure to instantiate an IngredientNBT of item {}", - GTStringUtils.prettyPrintItemStack(i)); - } - } - } - } - return Ingredient.fromStacks(((ItemStack) obj).copy()); - } else if (obj instanceof Item) return Ingredient.fromItem((Item) obj); - else if (obj instanceof Block) - return Ingredient.fromStacks(new ItemStack((Block) obj, 1, OreDictionary.WILDCARD_VALUE)); - else if (obj instanceof String) return new OreIngredient((String) obj); - else if (obj instanceof JsonElement) - throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); - - return null; - } - @Override public @NotNull NonNullList getRemainingItems(@NotNull InventoryCrafting inv) { if (isClearing) { diff --git a/src/main/java/gregtech/common/terminal/app/prospector/ProspectingTexture.java b/src/main/java/gregtech/common/gui/widget/prospector/ProspectingTexture.java similarity index 99% rename from src/main/java/gregtech/common/terminal/app/prospector/ProspectingTexture.java rename to src/main/java/gregtech/common/gui/widget/prospector/ProspectingTexture.java index 4f0070524ec..d0313daf95b 100644 --- a/src/main/java/gregtech/common/terminal/app/prospector/ProspectingTexture.java +++ b/src/main/java/gregtech/common/gui/widget/prospector/ProspectingTexture.java @@ -1,4 +1,4 @@ -package gregtech.common.terminal.app.prospector; +package gregtech.common.gui.widget.prospector; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.stack.MaterialStack; diff --git a/src/main/java/gregtech/common/terminal/app/prospector/ProspectorMode.java b/src/main/java/gregtech/common/gui/widget/prospector/ProspectorMode.java similarity index 93% rename from src/main/java/gregtech/common/terminal/app/prospector/ProspectorMode.java rename to src/main/java/gregtech/common/gui/widget/prospector/ProspectorMode.java index 5de3b24ec9b..0867c6d2a3f 100644 --- a/src/main/java/gregtech/common/terminal/app/prospector/ProspectorMode.java +++ b/src/main/java/gregtech/common/gui/widget/prospector/ProspectorMode.java @@ -1,4 +1,4 @@ -package gregtech.common.terminal.app.prospector; +package gregtech.common.gui.widget.prospector; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/gregtech/common/terminal/app/prospector/widget/WidgetOreList.java b/src/main/java/gregtech/common/gui/widget/prospector/widget/WidgetOreList.java similarity index 91% rename from src/main/java/gregtech/common/terminal/app/prospector/widget/WidgetOreList.java rename to src/main/java/gregtech/common/gui/widget/prospector/widget/WidgetOreList.java index 40435e51b5e..2e774351517 100644 --- a/src/main/java/gregtech/common/terminal/app/prospector/widget/WidgetOreList.java +++ b/src/main/java/gregtech/common/gui/widget/prospector/widget/WidgetOreList.java @@ -1,15 +1,19 @@ -package gregtech.common.terminal.app.prospector.widget; +package gregtech.common.gui.widget.prospector.widget; import gregtech.api.gui.GuiTextures; import gregtech.api.gui.IRenderContext; import gregtech.api.gui.Widget; -import gregtech.api.gui.widgets.*; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.os.TerminalTheme; +import gregtech.api.gui.resources.ColorRectTexture; +import gregtech.api.gui.widgets.ImageWidget; +import gregtech.api.gui.widgets.LabelWidget; +import gregtech.api.gui.widgets.SlotWidget; +import gregtech.api.gui.widgets.TankWidget; +import gregtech.api.gui.widgets.WidgetGroup; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.stack.MaterialStack; import gregtech.api.util.Position; -import gregtech.common.terminal.app.prospector.ProspectorMode; +import gregtech.common.gui.widget.prospector.ProspectorMode; +import gregtech.common.gui.widget.terminal.gui.widgets.DraggableScrollableWidgetGroup; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.item.ItemStack; @@ -23,7 +27,12 @@ import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; -import java.util.*; +import java.awt.*; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.function.Consumer; public class WidgetOreList extends DraggableScrollableWidgetGroup { @@ -39,7 +48,7 @@ public WidgetOreList(int xPosition, int yPosition, int width, int slotSize) { widgetMap = HashBiMap.create(); ores = new HashMap<>(); this.setYScrollBarWidth(5); - this.setYBarStyle(null, TerminalTheme.COLOR_F_1); + this.setYBarStyle(null, new ColorRectTexture(new Color(148, 226, 193))); clear(); } diff --git a/src/main/java/gregtech/common/terminal/app/prospector/widget/WidgetProspectingMap.java b/src/main/java/gregtech/common/gui/widget/prospector/widget/WidgetProspectingMap.java similarity index 99% rename from src/main/java/gregtech/common/terminal/app/prospector/widget/WidgetProspectingMap.java rename to src/main/java/gregtech/common/gui/widget/prospector/widget/WidgetProspectingMap.java index ba42b1a29cc..f203e1af020 100644 --- a/src/main/java/gregtech/common/terminal/app/prospector/widget/WidgetProspectingMap.java +++ b/src/main/java/gregtech/common/gui/widget/prospector/widget/WidgetProspectingMap.java @@ -1,4 +1,4 @@ -package gregtech.common.terminal.app.prospector.widget; +package gregtech.common.gui.widget.prospector.widget; import gregtech.api.gui.IRenderContext; import gregtech.api.gui.Widget; @@ -11,8 +11,8 @@ import gregtech.api.worldgen.config.OreDepositDefinition; import gregtech.api.worldgen.config.WorldGenRegistry; import gregtech.api.worldgen.filler.FillerEntry; -import gregtech.common.terminal.app.prospector.ProspectingTexture; -import gregtech.common.terminal.app.prospector.ProspectorMode; +import gregtech.common.gui.widget.prospector.ProspectingTexture; +import gregtech.common.gui.widget.prospector.ProspectorMode; import gregtech.core.network.packets.PacketProspecting; import gregtech.integration.xaero.ColorUtility; diff --git a/src/main/java/gregtech/common/terminal/component/SearchComponent.java b/src/main/java/gregtech/common/gui/widget/terminal/SearchComponent.java similarity index 94% rename from src/main/java/gregtech/common/terminal/component/SearchComponent.java rename to src/main/java/gregtech/common/gui/widget/terminal/SearchComponent.java index b0b99d8f154..b06bb1ce2f8 100644 --- a/src/main/java/gregtech/common/terminal/component/SearchComponent.java +++ b/src/main/java/gregtech/common/gui/widget/terminal/SearchComponent.java @@ -1,4 +1,4 @@ -package gregtech.common.terminal.component; +package gregtech.common.gui.widget.terminal; import gregtech.api.gui.IRenderContext; import gregtech.api.gui.resources.ColorRectTexture; @@ -6,9 +6,9 @@ import gregtech.api.gui.resources.TextureArea; import gregtech.api.gui.widgets.TextFieldWidget; import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.os.menu.IMenuComponent; -import gregtech.api.terminal.util.ISearch; -import gregtech.api.terminal.util.SearchEngine; +import gregtech.common.gui.widget.terminal.menu.IMenuComponent; +import gregtech.common.gui.widget.terminal.util.ISearch; +import gregtech.common.gui.widget.terminal.util.SearchEngine; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; diff --git a/src/main/java/gregtech/api/terminal/gui/IDraggable.java b/src/main/java/gregtech/common/gui/widget/terminal/gui/IDraggable.java similarity index 86% rename from src/main/java/gregtech/api/terminal/gui/IDraggable.java rename to src/main/java/gregtech/common/gui/widget/terminal/gui/IDraggable.java index 33b6cf41719..c93e7491f2c 100644 --- a/src/main/java/gregtech/api/terminal/gui/IDraggable.java +++ b/src/main/java/gregtech/common/gui/widget/terminal/gui/IDraggable.java @@ -1,4 +1,4 @@ -package gregtech.api.terminal.gui; +package gregtech.common.gui.widget.terminal.gui; public interface IDraggable { diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/CircleButtonWidget.java b/src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/CircleButtonWidget.java similarity index 98% rename from src/main/java/gregtech/api/terminal/gui/widgets/CircleButtonWidget.java rename to src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/CircleButtonWidget.java index 98d6b27b5ab..953bf457f1b 100644 --- a/src/main/java/gregtech/api/terminal/gui/widgets/CircleButtonWidget.java +++ b/src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/CircleButtonWidget.java @@ -1,4 +1,4 @@ -package gregtech.api.terminal.gui.widgets; +package gregtech.common.gui.widget.terminal.gui.widgets; import gregtech.api.gui.IRenderContext; import gregtech.api.gui.Widget; diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/DraggableScrollableWidgetGroup.java b/src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/DraggableScrollableWidgetGroup.java similarity index 99% rename from src/main/java/gregtech/api/terminal/gui/widgets/DraggableScrollableWidgetGroup.java rename to src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/DraggableScrollableWidgetGroup.java index 7adb35a9e56..339a7f7cdfa 100644 --- a/src/main/java/gregtech/api/terminal/gui/widgets/DraggableScrollableWidgetGroup.java +++ b/src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/DraggableScrollableWidgetGroup.java @@ -1,14 +1,14 @@ -package gregtech.api.terminal.gui.widgets; +package gregtech.common.gui.widget.terminal.gui.widgets; 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.gui.IDraggable; import gregtech.api.util.Position; import gregtech.api.util.Size; import gregtech.client.utils.RenderUtil; import gregtech.common.ConfigHolder; +import gregtech.common.gui.widget.terminal.gui.IDraggable; import net.minecraft.util.math.MathHelper; diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/RectButtonWidget.java b/src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/RectButtonWidget.java similarity index 98% rename from src/main/java/gregtech/api/terminal/gui/widgets/RectButtonWidget.java rename to src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/RectButtonWidget.java index d49b5a3c25d..e4f134ff851 100644 --- a/src/main/java/gregtech/api/terminal/gui/widgets/RectButtonWidget.java +++ b/src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/RectButtonWidget.java @@ -1,4 +1,4 @@ -package gregtech.api.terminal.gui.widgets; +package gregtech.common.gui.widget.terminal.gui.widgets; import gregtech.api.gui.IRenderContext; import gregtech.api.gui.resources.IGuiTexture; diff --git a/src/main/java/gregtech/api/terminal/gui/widgets/SelectorWidget.java b/src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/SelectorWidget.java similarity index 98% rename from src/main/java/gregtech/api/terminal/gui/widgets/SelectorWidget.java rename to src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/SelectorWidget.java index c5f35429f01..20e0bf030b5 100644 --- a/src/main/java/gregtech/api/terminal/gui/widgets/SelectorWidget.java +++ b/src/main/java/gregtech/common/gui/widget/terminal/gui/widgets/SelectorWidget.java @@ -1,4 +1,4 @@ -package gregtech.api.terminal.gui.widgets; +package gregtech.common.gui.widget.terminal.gui.widgets; import gregtech.api.gui.resources.IGuiTexture; import gregtech.api.gui.widgets.SimpleTextWidget; diff --git a/src/main/java/gregtech/api/terminal/os/menu/IMenuComponent.java b/src/main/java/gregtech/common/gui/widget/terminal/menu/IMenuComponent.java similarity index 91% rename from src/main/java/gregtech/api/terminal/os/menu/IMenuComponent.java rename to src/main/java/gregtech/common/gui/widget/terminal/menu/IMenuComponent.java index 519d09b2231..6996f8888d5 100644 --- a/src/main/java/gregtech/api/terminal/os/menu/IMenuComponent.java +++ b/src/main/java/gregtech/common/gui/widget/terminal/menu/IMenuComponent.java @@ -1,4 +1,4 @@ -package gregtech.api.terminal.os.menu; +package gregtech.common.gui.widget.terminal.menu; import gregtech.api.gui.Widget; import gregtech.api.gui.resources.ColorRectTexture; diff --git a/src/main/java/gregtech/api/terminal/util/ISearch.java b/src/main/java/gregtech/common/gui/widget/terminal/util/ISearch.java similarity index 79% rename from src/main/java/gregtech/api/terminal/util/ISearch.java rename to src/main/java/gregtech/common/gui/widget/terminal/util/ISearch.java index 2ae8c26569b..0f256ab62c0 100644 --- a/src/main/java/gregtech/api/terminal/util/ISearch.java +++ b/src/main/java/gregtech/common/gui/widget/terminal/util/ISearch.java @@ -1,4 +1,4 @@ -package gregtech.api.terminal.util; +package gregtech.common.gui.widget.terminal.util; import java.util.function.Consumer; diff --git a/src/main/java/gregtech/api/terminal/util/SearchEngine.java b/src/main/java/gregtech/common/gui/widget/terminal/util/SearchEngine.java similarity index 94% rename from src/main/java/gregtech/api/terminal/util/SearchEngine.java rename to src/main/java/gregtech/common/gui/widget/terminal/util/SearchEngine.java index deaff75d2fd..e810dfaca34 100644 --- a/src/main/java/gregtech/api/terminal/util/SearchEngine.java +++ b/src/main/java/gregtech/common/gui/widget/terminal/util/SearchEngine.java @@ -1,4 +1,4 @@ -package gregtech.api.terminal.util; +package gregtech.common.gui.widget.terminal.util; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/gregtech/common/items/MetaItem1.java b/src/main/java/gregtech/common/items/MetaItem1.java index 378b7c12849..3cf94c8a5b5 100644 --- a/src/main/java/gregtech/common/items/MetaItem1.java +++ b/src/main/java/gregtech/common/items/MetaItem1.java @@ -11,7 +11,6 @@ import gregtech.api.items.metaitem.stats.IItemComponent; import gregtech.api.items.metaitem.stats.IItemContainerItemProvider; import gregtech.api.items.metaitem.stats.ItemFluidContainer; -import gregtech.api.terminal.hardware.HardwareProvider; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.MarkerMaterial; import gregtech.api.unification.material.MarkerMaterials; @@ -48,7 +47,6 @@ import gregtech.common.items.behaviors.MultiblockBuilderBehavior; import gregtech.common.items.behaviors.NanoSaberBehavior; import gregtech.common.items.behaviors.ProspectorScannerBehavior; -import gregtech.common.items.behaviors.TerminalBehaviour; import gregtech.common.items.behaviors.TooltipBehavior; import gregtech.common.items.behaviors.TricorderBehavior; import gregtech.common.items.behaviors.TurbineRotorBehavior; @@ -792,7 +790,6 @@ public void registerSubItems() { .setMaxStackSize(1) .setCreativeTabs(GTCreativeTabs.TAB_GREGTECH_TOOLS); TERMINAL = addItem(465, "terminal") - .addComponents(new HardwareProvider(), new TerminalBehaviour()) .setMaxStackSize(1) .setCreativeTabs(GTCreativeTabs.TAB_GREGTECH_TOOLS); PROSPECTOR_LV = addItem(466, "prospector.lv") @@ -1000,11 +997,11 @@ public void registerSubItems() { BATTERY_HULL_HV = addItem(719, "battery.hull.hv") .setMaterialInfo(new ItemMaterialInfo(new MaterialStack(Materials.BatteryAlloy, M * 9))); // plate * 9 BATTERY_HULL_SMALL_VANADIUM = addItem(720, "battery.hull.ev") - .setMaterialInfo(new ItemMaterialInfo(new MaterialStack(Materials.BlueSteel, M * 2))); + .setMaterialInfo(new ItemMaterialInfo(new MaterialStack(Materials.RedSteel, M * 2))); BATTERY_HULL_MEDIUM_VANADIUM = addItem(721, "battery.hull.iv") .setMaterialInfo(new ItemMaterialInfo(new MaterialStack(Materials.RoseGold, M * 6))); BATTERY_HULL_LARGE_VANADIUM = addItem(722, "battery.hull.luv") - .setMaterialInfo(new ItemMaterialInfo(new MaterialStack(Materials.RedSteel, M * 18))); + .setMaterialInfo(new ItemMaterialInfo(new MaterialStack(Materials.BlueSteel, M * 18))); BATTERY_HULL_MEDIUM_NAQUADRIA = addItem(723, "battery.hull.zpm") .setMaterialInfo(new ItemMaterialInfo(new MaterialStack(Materials.Europium, M * 6))); BATTERY_HULL_LARGE_NAQUADRIA = addItem(724, "battery.hull.uv") diff --git a/src/main/java/gregtech/common/items/MetaItems.java b/src/main/java/gregtech/common/items/MetaItems.java index 303588e6dc8..eaa75bc932f 100644 --- a/src/main/java/gregtech/common/items/MetaItems.java +++ b/src/main/java/gregtech/common/items/MetaItems.java @@ -19,7 +19,6 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -653,7 +652,6 @@ public static void registerColors() { } } - @SubscribeEvent @SideOnly(Side.CLIENT) public static void registerBakedModels(ModelBakeEvent event) { GTLog.logger.info("Registering special item models"); diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 5545387ef7c..a7003d8f4c3 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -4,17 +4,22 @@ import gregtech.api.items.toolitem.*; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; +import gregtech.client.renderer.handler.ToolbeltRenderer; import gregtech.common.items.tool.*; import gregtech.core.sound.GTSoundEvents; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.entity.monster.EntityGolem; import net.minecraft.entity.monster.EntitySpider; import net.minecraft.init.Enchantments; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; +import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.model.ModelLoader; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; import org.jetbrains.annotations.NotNull; @@ -58,6 +63,7 @@ public final class ToolItems { public static IGTTool WIRECUTTER_LV; public static IGTTool WIRECUTTER_HV; public static IGTTool WIRECUTTER_IV; + public static ItemGTToolbelt TOOLBELT; private ToolItems() {/**/} @@ -66,6 +72,8 @@ public static List getAllTools() { } public static void init() { + TOOLBELT = (ItemGTToolbelt) register(new ItemGTToolbelt(GTValues.MODID, "toolbelt", + null, OpenGUIBehavior.INSTANCE)); SWORD = register(ItemGTSword.Builder.of(GTValues.MODID, "sword") .toolStats(b -> b.attacking() .attackDamage(3.0F).attackSpeed(-2.4F)) @@ -369,6 +377,12 @@ public static void registerModels() { TOOLS.forEach(tool -> ModelLoader.setCustomModelResourceLocation(tool.get(), 0, tool.getModelLocation())); } + @SideOnly(Side.CLIENT) + public static void registerBakedModels(ModelBakeEvent event) { + ModelResourceLocation loc = TOOLBELT.getModelLocation(); + event.getModelRegistry().putObject(loc, new ToolbeltRenderer(event.getModelRegistry().getObject(loc))); + } + public static void registerColors() { TOOLS.forEach( tool -> Minecraft.getMinecraft().getItemColors().registerItemColorHandler(tool::getColor, tool.get())); @@ -380,7 +394,9 @@ public static void registerOreDict() { if (tool.getOreDictName() != null) { OreDictUnifier.registerOre(stack, tool.getOreDictName()); } - tool.getSecondaryOreDicts().forEach(oreDict -> OreDictUnifier.registerOre(stack, oreDict)); + tool.getSecondaryOreDicts().forEach(oreDict -> { + OreDictUnifier.registerOre(stack, oreDict); + }); }); } } diff --git a/src/main/java/gregtech/common/items/behaviors/ColorSprayBehaviour.java b/src/main/java/gregtech/common/items/behaviors/ColorSprayBehaviour.java index a52777f70d6..72d164afd19 100644 --- a/src/main/java/gregtech/common/items/behaviors/ColorSprayBehaviour.java +++ b/src/main/java/gregtech/common/items/behaviors/ColorSprayBehaviour.java @@ -1,5 +1,7 @@ package gregtech.common.items.behaviors; +import gregtech.api.items.metaitem.MetaItem; +import gregtech.api.items.metaitem.stats.IItemBehaviour; import gregtech.api.items.metaitem.stats.IItemDurabilityManager; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; @@ -68,6 +70,29 @@ public ActionResult onItemUse(EntityPlayer player, World world, Block return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); } + @Nullable + public static ColorSprayBehaviour getBehavior(ItemStack spraycan) { + if (!(spraycan.getItem() instanceof MetaItemmeta)) return null; + for (IItemBehaviour behaviour : meta.getBehaviours(spraycan)) { + if (behaviour instanceof ColorSprayBehaviour spray) return spray; + } + return null; + } + + public EnumActionResult useFromToolbelt(EntityPlayer player, World world, BlockPos pos, EnumHand hand, + EnumFacing facing, float hitX, float hitY, float hitZ, ItemStack spraycan) { + if (!player.canPlayerEdit(pos, facing, spraycan)) { + return EnumActionResult.FAIL; + } + if (!tryPaintBlock(player, world, pos, facing)) { + return EnumActionResult.PASS; + } + useItemDurability(player, hand, spraycan, empty.copy()); + world.playSound(null, player.posX, player.posY, player.posZ, GTSoundEvents.SPRAY_CAN_TOOL, + SoundCategory.PLAYERS, 1.0f, 1.0f); + return EnumActionResult.SUCCESS; + } + private boolean tryPaintBlock(EntityPlayer player, World world, BlockPos pos, EnumFacing side) { IBlockState blockState = world.getBlockState(pos); Block block = blockState.getBlock(); diff --git a/src/main/java/gregtech/common/items/behaviors/IntCircuitBehaviour.java b/src/main/java/gregtech/common/items/behaviors/IntCircuitBehaviour.java index 5a7091e838e..f7523d976d1 100644 --- a/src/main/java/gregtech/common/items/behaviors/IntCircuitBehaviour.java +++ b/src/main/java/gregtech/common/items/behaviors/IntCircuitBehaviour.java @@ -21,6 +21,7 @@ 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.factory.HandGuiData; import com.cleanroommc.modularui.screen.ModularPanel; @@ -65,6 +66,7 @@ public ActionResult onItemRightClick(World world, EntityPlayer player @Override public ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager) { + var panel = GTGuis.createPanel(guiData.getUsedItemStack(), 176, 120); ItemDrawable circuitPreview = new ItemDrawable(guiData.getUsedItemStack()); for (int i = 0; i <= 32; i++) { int finalI = i; @@ -73,6 +75,7 @@ public ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager ItemStack item = IntCircuitIngredient.getIntegratedCircuit(finalI); item.setCount(guiData.getUsedItemStack().getCount()); circuitPreview.setItem(item); + if (Interactable.hasShiftDown()) panel.animateClose(); guiData.getPlayer().setHeldItem(guiData.getHand(), item); })); } @@ -91,8 +94,7 @@ public ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager .syncHandler("config", index)); } } - return GTGuis.createPanel(guiData.getUsedItemStack(), 176, 120) - .child(IKey.lang("metaitem.circuit.integrated.gui").asWidget().pos(5, 5)) + 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) diff --git a/src/main/java/gregtech/common/items/behaviors/ItemMagnetBehavior.java b/src/main/java/gregtech/common/items/behaviors/ItemMagnetBehavior.java index f5ce22ba925..bd0adea08e7 100644 --- a/src/main/java/gregtech/common/items/behaviors/ItemMagnetBehavior.java +++ b/src/main/java/gregtech/common/items/behaviors/ItemMagnetBehavior.java @@ -6,6 +6,7 @@ import gregtech.api.items.metaitem.MetaItem; import gregtech.api.items.metaitem.stats.IItemBehaviour; import gregtech.api.util.Mods; +import gregtech.common.ConfigHolder; import gregtech.integration.baubles.BaublesModule; import net.minecraft.client.resources.I18n; @@ -81,7 +82,7 @@ private static boolean toggleActive(ItemStack stack) { public void onUpdate(ItemStack stack, Entity entity) { // Adapted logic from Draconic Evolution // https://github.com/Draconic-Inc/Draconic-Evolution/blob/1.12.2/src/main/java/com/brandon3055/draconicevolution/items/tools/Magnet.java - if (!entity.isSneaking() && entity.ticksExisted % 10 == 0 && isActive(stack) && + if (!entity.isSneaking() && entity.ticksExisted % ConfigHolder.tools.magnetDelay == 0 && isActive(stack) && entity instanceof EntityPlayer player) { World world = entity.getEntityWorld(); if (!drainEnergy(true, stack, energyDraw)) { diff --git a/src/main/java/gregtech/common/items/behaviors/ProspectorScannerBehavior.java b/src/main/java/gregtech/common/items/behaviors/ProspectorScannerBehavior.java index ac1e91f3615..eaad7dd7bc2 100644 --- a/src/main/java/gregtech/common/items/behaviors/ProspectorScannerBehavior.java +++ b/src/main/java/gregtech/common/items/behaviors/ProspectorScannerBehavior.java @@ -11,10 +11,10 @@ import gregtech.api.items.gui.PlayerInventoryHolder; import gregtech.api.items.metaitem.stats.IItemBehaviour; import gregtech.api.util.GTUtility; -import gregtech.common.terminal.app.prospector.ProspectorMode; -import gregtech.common.terminal.app.prospector.widget.WidgetOreList; -import gregtech.common.terminal.app.prospector.widget.WidgetProspectingMap; -import gregtech.common.terminal.component.SearchComponent; +import gregtech.common.gui.widget.prospector.ProspectorMode; +import gregtech.common.gui.widget.prospector.widget.WidgetOreList; +import gregtech.common.gui.widget.prospector.widget.WidgetProspectingMap; +import gregtech.common.gui.widget.terminal.SearchComponent; import net.minecraft.client.resources.I18n; import net.minecraft.entity.Entity; diff --git a/src/main/java/gregtech/common/items/behaviors/TerminalBehaviour.java b/src/main/java/gregtech/common/items/behaviors/TerminalBehaviour.java deleted file mode 100644 index 6ffc8919a40..00000000000 --- a/src/main/java/gregtech/common/items/behaviors/TerminalBehaviour.java +++ /dev/null @@ -1,144 +0,0 @@ -package gregtech.common.items.behaviors; - -import gregtech.api.capability.GregtechCapabilities; -import gregtech.api.capability.IElectricItem; -import gregtech.api.gui.ModularUI; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.items.gui.ItemUIFactory; -import gregtech.api.items.gui.PlayerInventoryHolder; -import gregtech.api.items.metaitem.stats.IItemBehaviour; -import gregtech.api.items.metaitem.stats.ISubItemHandler; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.hardware.Hardware; -import gregtech.api.terminal.hardware.HardwareProvider; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.common.terminal.hardware.BatteryHardware; - -import net.minecraft.client.resources.I18n; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.util.*; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import java.util.List; - -public class TerminalBehaviour implements IItemBehaviour, ItemUIFactory, ISubItemHandler { - - @Override - public EnumActionResult onItemUseFirst(EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, - float hitY, float hitZ, EnumHand hand) { - if (player.isSneaking()) { - ItemStack itemStack = player.getHeldItem(hand); - itemStack.getOrCreateSubCompound("terminal").removeTag("_click"); - if (pos != null) { - itemStack.getOrCreateSubCompound("terminal").setTag("_click", NBTUtil.createPosTag(pos)); - if (!world.isRemote) { - PlayerInventoryHolder holder = new PlayerInventoryHolder(player, hand); - holder.openUI(); - } - return EnumActionResult.SUCCESS; - } - } - return EnumActionResult.PASS; - } - - @Override - public ActionResult onItemRightClick(World world, EntityPlayer player, EnumHand hand) { - ItemStack itemStack = player.getHeldItem(hand); - itemStack.getOrCreateSubCompound("terminal").removeTag("_click"); - if (!world.isRemote) { - PlayerInventoryHolder holder = new PlayerInventoryHolder(player, hand); - holder.openUI(); - } - return ActionResult.newResult(EnumActionResult.SUCCESS, itemStack); - } - - @Override - public void onUpdate(ItemStack itemStack, Entity entity) { - NBTTagCompound tabletNBT = itemStack.getOrCreateSubCompound("terminal"); - if (entity.ticksExisted % 20 == 0 && tabletNBT.hasKey("_ar")) { - if (entity instanceof EntityLivingBase) { - EntityLivingBase livingBase = (EntityLivingBase) entity; - if (!livingBase.getHeldItemMainhand().isItemEqual(itemStack) && - !livingBase.getHeldItemOffhand().isItemEqual(itemStack)) { - return; - } - } - - String appName = tabletNBT.getString("_ar"); - int tier = TerminalRegistry.getApplication(appName).getMaxTier(); - if (!TerminalBehaviour.isCreative(itemStack)) { - tier = Math.min(tabletNBT.getCompoundTag(appName).getInteger("_tier"), tier); - } - long cost = 0; - for (Hardware hardware : TerminalRegistry.getAppHardwareDemand(appName, tier)) { - if (hardware instanceof BatteryHardware) { - cost = ((BatteryHardware) hardware).getCharge(); - break; - } - } - if (cost > 0) { - IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, - null); - if (electricItem != null) { - long back = electricItem.discharge(cost, 999, true, false, false); - if (back != cost) { - tabletNBT.removeTag("_ar"); - } - } else { - tabletNBT.removeTag("_ar"); - } - } - } - } - - @Override - public void addInformation(ItemStack itemStack, List lines) { - HardwareProvider provider = itemStack.getCapability(GregtechCapabilities.CAPABILITY_HARDWARE_PROVIDER, null); - if (isCreative(itemStack)) { - lines.add(I18n.format("metaitem.terminal.tooltip.creative")); - } - if (provider != null) { - List hardware = provider.getHardware(); - lines.add(I18n.format("metaitem.terminal.tooltip.hardware", hardware.size())); - for (Hardware hw : hardware) { - String info = hw.addInformation(); - if (info == null) { - lines.add(hw.getLocalizedName()); - } else { - lines.add(String.format("%s (%s)", hw.getLocalizedName(), info)); - } - } - } - } - - @Override - public ModularUI createUI(PlayerInventoryHolder holder, EntityPlayer entityPlayer) { - return ModularUI.builder(IGuiTexture.EMPTY, 380, 256) - .widget(new TerminalOSWidget(12, 11, holder.getCurrentItem())) - .shouldColor(false) - .build(holder, entityPlayer); - } - - public static boolean isCreative(ItemStack itemStack) { - return itemStack != null && itemStack.getOrCreateSubCompound("terminal").getBoolean("_creative"); - } - - @Override - public String getItemSubType(ItemStack itemStack) { - return ""; - } - - @Override - public void getSubItems(ItemStack itemStack, CreativeTabs creativeTab, NonNullList subItems) { - ItemStack copy = itemStack.copy(); - copy.getOrCreateSubCompound("terminal").setBoolean("_creative", true); - subItems.add(copy); - } -} diff --git a/src/main/java/gregtech/common/items/behaviors/TricorderBehavior.java b/src/main/java/gregtech/common/items/behaviors/TricorderBehavior.java index 8e86e967a7c..1045603125a 100644 --- a/src/main/java/gregtech/common/items/behaviors/TricorderBehavior.java +++ b/src/main/java/gregtech/common/items/behaviors/TricorderBehavior.java @@ -5,6 +5,8 @@ import gregtech.api.capability.GregtechTileCapabilities; import gregtech.api.capability.IElectricItem; import gregtech.api.capability.IEnergyContainer; +import gregtech.api.capability.IQuantumController; +import gregtech.api.capability.IQuantumStorage; import gregtech.api.capability.IWorkable; import gregtech.api.capability.impl.FluidTankList; import gregtech.api.items.metaitem.stats.IItemBehaviour; @@ -49,6 +51,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; public class TricorderBehavior implements IItemBehaviour { @@ -141,13 +144,29 @@ public List getScannerInfo(EntityPlayer player, World world, Blo // name of the machine list.add(new TextComponentTranslation("behavior.tricorder.block_name", - new TextComponentTranslation(LocalizationUtils.format(metaTileEntity.getMetaFullName())) + new TextComponentTranslation(metaTileEntity.getMetaFullName()) .setStyle(new Style().setColor(TextFormatting.BLUE)), new TextComponentTranslation(TextFormattingUtil .formatNumbers( metaTileEntity.getRegistry().getIdByObjectName(metaTileEntity.metaTileEntityId))) .setStyle(new Style().setColor(TextFormatting.BLUE)))); + UUID owner = metaTileEntity.getOwner(); + if (owner != null) { + EntityPlayer ownerEntity = metaTileEntity.getWorld().getPlayerEntityByUUID(owner); + if (ownerEntity != null) { + list.add(new TextComponentTranslation("behavior.tricorder.mte_owner", + new TextComponentTranslation(ownerEntity.getName()) + .setStyle(new Style().setColor(TextFormatting.AQUA)))); + } else { + list.add(new TextComponentTranslation("behavior.tricorder.mte_owner_offline") + .setStyle(new Style().setColor(TextFormatting.YELLOW))); + } + } else { + list.add(new TextComponentTranslation("behavior.tricorder.mte_owner_null") + .setStyle(new Style().setColor(TextFormatting.RED))); + } + list.add(new TextComponentTranslation("behavior.tricorder.divider")); // fluid tanks @@ -267,6 +286,30 @@ else if (metaTileEntity instanceof IDataInfoProvider) list.addAll(provider.getDataInfo()); } + // quantum storage + if (metaTileEntity instanceof IQuantumController quantumController) { + list.add(new TextComponentTranslation("behavior.tricorder.divider")); + long eut = quantumController.getEnergyUsage(); // eu per 10 ticks + int tier = GTUtility.getTierByVoltage(eut / 10); + list.add(new TextComponentTranslation("behavior.tricorder.quantum_controller.usage", + TextFormatting.RED + String.format("%.1f", eut / 10d) + TextFormatting.RESET, + GTValues.VNF[tier])); + var handler = quantumController.getHandler(); + list.add(new TextComponentTranslation("behavior.tricorder.quantum_controller.connected_items", + TextFormatting.RED.toString() + handler.getItemHandlers().getSlots())); + list.add(new TextComponentTranslation("behavior.tricorder.quantum_controller.connected_fluids", + TextFormatting.RED.toString() + handler.getFluidTanks().getTanks())); + } else if (metaTileEntity instanceof IQuantumStoragestorage) { + var qcontrollor = storage.getQuantumController(); + if (qcontrollor != null) { + long eut = qcontrollor.getTypeEnergy(storage); + + list.add(new TextComponentTranslation("behavior.tricorder.divider")); + list.add(new TextComponentTranslation("behavior.tricorder.quantum_storage.usage", + TextFormatting.RED + String.format("%.1f", eut / 10d))); + } + } + } else if (tileEntity instanceof IPipeTile) { // pipes need special name handling IPipeTile pipeTile = (IPipeTile) tileEntity; diff --git a/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java b/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java index 4dc960a6a3f..cdb694fbb44 100644 --- a/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java +++ b/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java @@ -40,6 +40,7 @@ public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World w if (facing == EnumFacing.DOWN) return EnumActionResult.PASS; ItemStack stack = player.getHeldItem(hand); + AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); Set blocks; diff --git a/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java b/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java index d1ac7a4be93..519b275192e 100644 --- a/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java +++ b/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java @@ -42,6 +42,7 @@ public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World w if (world.isRemote) { return EnumActionResult.PASS; } + ItemStack stack = player.getHeldItem(hand); AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); diff --git a/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java b/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java index 36477d16801..9fef46e5e5d 100644 --- a/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java +++ b/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java @@ -47,6 +47,7 @@ public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World w if (facing == EnumFacing.DOWN) return EnumActionResult.PASS; ItemStack stack = player.getHeldItem(hand); + AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); Set blocks; diff --git a/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java new file mode 100644 index 00000000000..ce975ede743 --- /dev/null +++ b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java @@ -0,0 +1,30 @@ +package gregtech.common.items.tool; + +import gregtech.api.items.toolitem.behavior.IToolBehavior; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumHand; +import net.minecraft.world.World; + +import com.cleanroommc.modularui.factory.ItemGuiFactory; +import org.jetbrains.annotations.NotNull; + +public class OpenGUIBehavior implements IToolBehavior { + + public static final OpenGUIBehavior INSTANCE = new OpenGUIBehavior(); + + protected OpenGUIBehavior() {} + + @Override + public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, + @NotNull EnumHand hand) { + if (!world.isRemote) { + ItemGuiFactory.INSTANCE.open((EntityPlayerMP) player, hand); + } + return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } +} diff --git a/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java b/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java index d9d5f86ef69..8edee2b537b 100644 --- a/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java +++ b/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java @@ -40,8 +40,7 @@ protected TorchPlaceBehavior() {/**/} public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ) { - ItemStack stack = player.getHeldItem(hand); - NBTTagCompound behaviourTag = ToolHelper.getBehaviorsTag(stack); + NBTTagCompound behaviourTag = ToolHelper.getBehaviorsTag(player.getHeldItem(hand)); if (behaviourTag.getBoolean(ToolHelper.TORCH_PLACING_KEY)) { int cachedTorchSlot; ItemStack slotStack; diff --git a/src/main/java/gregtech/common/metatileentities/MetaTileEntities.java b/src/main/java/gregtech/common/metatileentities/MetaTileEntities.java index e2e2624f8cd..dbe94985456 100644 --- a/src/main/java/gregtech/common/metatileentities/MetaTileEntities.java +++ b/src/main/java/gregtech/common/metatileentities/MetaTileEntities.java @@ -124,6 +124,9 @@ import gregtech.common.metatileentities.storage.MetaTileEntityCreativeTank; import gregtech.common.metatileentities.storage.MetaTileEntityDrum; import gregtech.common.metatileentities.storage.MetaTileEntityQuantumChest; +import gregtech.common.metatileentities.storage.MetaTileEntityQuantumExtender; +import gregtech.common.metatileentities.storage.MetaTileEntityQuantumProxy; +import gregtech.common.metatileentities.storage.MetaTileEntityQuantumStorageController; import gregtech.common.metatileentities.storage.MetaTileEntityQuantumTank; import gregtech.common.metatileentities.storage.MetaTileEntityWorkbench; import gregtech.common.pipelike.fluidpipe.longdistance.MetaTileEntityLDFluidEndpoint; @@ -222,6 +225,9 @@ public class MetaTileEntities { public static final MetaTileEntityRotorHolder[] ROTOR_HOLDER = new MetaTileEntityRotorHolder[6]; // HV, EV, IV, LuV, ZPM, UV public static final MetaTileEntityMufflerHatch[] MUFFLER_HATCH = new MetaTileEntityMufflerHatch[GTValues.UV + 1]; // LV-UV public static final MetaTileEntityFusionReactor[] FUSION_REACTOR = new MetaTileEntityFusionReactor[3]; + public static MetaTileEntityQuantumStorageController QUANTUM_STORAGE_CONTROLLER; + public static MetaTileEntityQuantumProxy QUANTUM_STORAGE_PROXY; + public static MetaTileEntityQuantumExtender QUANTUM_STORAGE_EXTENDER; public static final MetaTileEntityQuantumChest[] QUANTUM_CHEST = new MetaTileEntityQuantumChest[10]; public static final MetaTileEntityQuantumTank[] QUANTUM_TANK = new MetaTileEntityQuantumTank[10]; public static final MetaTileEntityBuffer[] BUFFER = new MetaTileEntityBuffer[3]; @@ -977,6 +983,14 @@ public static void init() { PUMP[2] = registerMetaTileEntity(1532, new MetaTileEntityPump(gregtechId("pump.hv"), 3)); PUMP[3] = registerMetaTileEntity(1533, new MetaTileEntityPump(gregtechId("pump.ev"), 4)); + // Quantum Storage Network 1757 - 1759 + QUANTUM_STORAGE_CONTROLLER = registerMetaTileEntity(1757, + new MetaTileEntityQuantumStorageController(gregtechId("quantum_storage_controller"))); + QUANTUM_STORAGE_PROXY = registerMetaTileEntity(1758, + new MetaTileEntityQuantumProxy(gregtechId("quantum_storage_proxy"))); + QUANTUM_STORAGE_EXTENDER = registerMetaTileEntity(1759, + new MetaTileEntityQuantumExtender(gregtechId("quantum_storage_extender"))); + // Super / Quantum Chests, IDs 1560-1574 for (int i = 0; i < 5; i++) { String voltageName = GTValues.VN[i + 1].toLowerCase(); diff --git a/src/main/java/gregtech/common/metatileentities/MetaTileEntityClipboard.java b/src/main/java/gregtech/common/metatileentities/MetaTileEntityClipboard.java index 36942d2d51c..a50a2978aae 100644 --- a/src/main/java/gregtech/common/metatileentities/MetaTileEntityClipboard.java +++ b/src/main/java/gregtech/common/metatileentities/MetaTileEntityClipboard.java @@ -190,7 +190,7 @@ public void createFakeGui() { this.guiContainerCache = fakeModularUIContainer; if (getWorld().isRemote) this.guiCache = new FakeModularGui(ui, fakeModularUIContainer); - this.writeCustomData(CREATE_FAKE_UI, buffer -> {}); + this.writeCustomData(CREATE_FAKE_UI); } catch (Exception e) { GTLog.logger.error(e); } diff --git a/src/main/java/gregtech/common/metatileentities/converter/MetaTileEntityConverter.java b/src/main/java/gregtech/common/metatileentities/converter/MetaTileEntityConverter.java index bbf2039b094..0f4f7defa7b 100644 --- a/src/main/java/gregtech/common/metatileentities/converter/MetaTileEntityConverter.java +++ b/src/main/java/gregtech/common/metatileentities/converter/MetaTileEntityConverter.java @@ -3,7 +3,6 @@ import gregtech.api.GTValues; import gregtech.api.capability.FeCompat; import gregtech.api.capability.GregtechCapabilities; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.TieredMetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; @@ -167,11 +166,6 @@ protected boolean openGUIOnRightClick() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public T getCapability(Capability capability, EnumFacing side) { if (capability == GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER) { diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityAlarm.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityAlarm.java index 67751f893e9..8e0518fb935 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityAlarm.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityAlarm.java @@ -11,9 +11,9 @@ import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.TieredMetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; -import gregtech.api.terminal.gui.widgets.SelectorWidget; import gregtech.client.renderer.texture.Textures; import gregtech.common.ConfigHolder; +import gregtech.common.gui.widget.terminal.gui.widgets.SelectorWidget; import gregtech.core.sound.GTSoundEvents; import net.minecraft.client.resources.I18n; diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityBatteryBuffer.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityBatteryBuffer.java index 8a56af22c35..22060a1716b 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityBatteryBuffer.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityBatteryBuffer.java @@ -175,6 +175,7 @@ public void addInformation(ItemStack stack, @Nullable World player, List public void addToolUsages(ItemStack stack, @Nullable World world, List tooltip, boolean advanced) { tooltip.add(I18n.format("gregtech.tool_action.screwdriver.access_covers")); tooltip.add(I18n.format("gregtech.tool_action.wrench.set_facing")); + tooltip.add(I18n.format("gregtech.tool_action.soft_mallet.reset")); super.addToolUsages(stack, world, tooltip, advanced); } diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityBlockBreaker.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityBlockBreaker.java index b88ca1418d3..52855de6e03 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityBlockBreaker.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityBlockBreaker.java @@ -270,6 +270,7 @@ public boolean getIsWeatherOrTerrainResistant() { @Override public void addInformation(ItemStack stack, @Nullable World player, List tooltip, boolean advanced) { + super.addInformation(stack, player, tooltip, advanced); tooltip.add(I18n.format("gregtech.machine.block_breaker.tooltip")); tooltip.add(I18n.format("gregtech.universal.tooltip.uses_per_op", getEnergyPerBlockBreak())); tooltip.add(I18n.format("gregtech.universal.tooltip.voltage_in", energyContainer.getInputVoltage(), @@ -279,7 +280,6 @@ public void addInformation(ItemStack stack, @Nullable World player, List tooltip.add(I18n.format("gregtech.universal.tooltip.item_storage_capacity", getInventorySize())); tooltip.add(I18n.format("gregtech.machine.block_breaker.speed_bonus", (int) (getEfficiencyMultiplier() * 100))); tooltip.add(I18n.format("gregtech.universal.tooltip.requires_redstone")); - super.addInformation(stack, player, tooltip, advanced); } @Override diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityDiode.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityDiode.java index 61b53052962..c19b1797f96 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityDiode.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityDiode.java @@ -1,9 +1,12 @@ package gregtech.common.metatileentities.electric; import gregtech.api.GTValues; +import gregtech.api.capability.GregtechDataCodes; +import gregtech.api.capability.GregtechTileCapabilities; +import gregtech.api.capability.IControllable; import gregtech.api.capability.IEnergyContainer; import gregtech.api.capability.impl.EnergyContainerHandler; -import gregtech.api.gui.ModularUI; +import gregtech.api.metatileentity.MTETrait; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; @@ -23,6 +26,7 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.World; +import net.minecraftforge.common.capabilities.Capability; import codechicken.lib.raytracer.CuboidRayTraceResult; import codechicken.lib.render.CCRenderState; @@ -35,19 +39,23 @@ import java.util.List; import static gregtech.api.capability.GregtechDataCodes.AMP_INDEX; +import static gregtech.api.capability.GregtechDataCodes.WORKING_ENABLED; public class MetaTileEntityDiode extends MetaTileEntityMultiblockPart - implements IPassthroughHatch, IMultiblockAbilityPart { + implements IPassthroughHatch, IMultiblockAbilityPart, + IControllable { protected IEnergyContainer energyContainer; private static final String AMP_NBT_KEY = "amp_mode"; private int amps; + private boolean isWorkingEnabled; public MetaTileEntityDiode(ResourceLocation metaTileEntityId, int tier) { super(metaTileEntityId, tier); amps = 1; reinitializeEnergyContainer(); + isWorkingEnabled = true; } @Override @@ -59,6 +67,7 @@ public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { public NBTTagCompound writeToNBT(NBTTagCompound data) { super.writeToNBT(data); data.setInteger(AMP_NBT_KEY, amps); + data.setBoolean("IsWorkingEnabled", isWorkingEnabled); return data; } @@ -66,6 +75,9 @@ public NBTTagCompound writeToNBT(NBTTagCompound data) { public void readFromNBT(NBTTagCompound data) { super.readFromNBT(data); this.amps = data.getInteger(AMP_NBT_KEY); + if (data.hasKey("IsWorkingEnabled")) { + this.isWorkingEnabled = data.getBoolean("IsWorkingEnabled"); + } reinitializeEnergyContainer(); } @@ -73,12 +85,14 @@ public void readFromNBT(NBTTagCompound data) { public void writeInitialSyncData(PacketBuffer buf) { super.writeInitialSyncData(buf); buf.writeInt(amps); + buf.writeBoolean(isWorkingEnabled); } @Override public void receiveInitialSyncData(PacketBuffer buf) { super.receiveInitialSyncData(buf); this.amps = buf.readInt(); + this.isWorkingEnabled = buf.readBoolean(); } @Override @@ -86,6 +100,8 @@ public void receiveCustomData(int dataId, PacketBuffer buf) { super.receiveCustomData(dataId, buf); if (dataId == AMP_INDEX) { this.amps = buf.readInt(); + } else if (dataId == WORKING_ENABLED) { + this.isWorkingEnabled = buf.readBoolean(); } } @@ -121,13 +137,8 @@ public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, } @Override - public boolean isValidFrontFacing(EnumFacing facing) { - return true; - } - - @Override - public boolean onSoftMalletClick(EntityPlayer playerIn, EnumHand hand, EnumFacing facing, - CuboidRayTraceResult hitResult) { + public boolean onScrewdriverClick(EntityPlayer playerIn, EnumHand hand, EnumFacing facing, + CuboidRayTraceResult hitResult) { if (getWorld().isRemote) { scheduleRenderUpdate(); return true; @@ -142,11 +153,6 @@ protected boolean openGUIOnRightClick() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public void addInformation(ItemStack stack, @Nullable World player, @NotNull List tooltip, boolean advanced) { @@ -159,9 +165,9 @@ public void addInformation(ItemStack stack, @Nullable World player, @NotNull Lis @Override public void addToolUsages(ItemStack stack, @Nullable World world, List tooltip, boolean advanced) { - tooltip.add(I18n.format("gregtech.tool_action.screwdriver.access_covers")); + tooltip.add(I18n.format("gregtech.machine.diode.tooltip_tool_usage_screwdriver")); tooltip.add(I18n.format("gregtech.tool_action.wrench.set_facing")); - tooltip.add(I18n.format("gregtech.tool_action.soft_mallet.toggle_mode")); + tooltip.add(I18n.format("gregtech.tool_action.soft_mallet.reset")); super.addToolUsages(stack, world, tooltip, advanced); } @@ -180,4 +186,31 @@ public void registerAbilities(@NotNull List abilityList) { public Class getPassthroughType() { return IEnergyContainer.class; } + + @Override + protected boolean shouldUpdate(MTETrait trait) { + return !(trait instanceof EnergyContainerHandler) || isWorkingEnabled; + } + + @Override + public T getCapability(Capability capability, EnumFacing side) { + if (capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE) { + return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this); + } + + return super.getCapability(capability, side); + } + + @Override + public boolean isWorkingEnabled() { + return isWorkingEnabled; + } + + @Override + public void setWorkingEnabled(boolean isWorkingAllowed) { + this.isWorkingEnabled = isWorkingAllowed; + if (getWorld().isRemote) { + writeCustomData(GregtechDataCodes.WORKING_ENABLED, buf -> buf.writeBoolean(isWorkingAllowed)); + } + } } diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityFisher.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityFisher.java index 076cc395674..d0c2f925a81 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityFisher.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityFisher.java @@ -142,6 +142,7 @@ public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, @Override public void addInformation(ItemStack stack, @Nullable World player, List tooltip, boolean advanced) { + super.addInformation(stack, player, tooltip, advanced); tooltip.add(I18n.format("gregtech.machine.fisher.tooltip")); tooltip.add(I18n.format("gregtech.machine.fisher.speed", fishingTicks)); tooltip.add(I18n.format("gregtech.machine.fisher.requirement", (int) Math.sqrt(WATER_CHECK_SIZE), @@ -150,7 +151,6 @@ public void addInformation(ItemStack stack, @Nullable World player, List GTValues.VNF[getTier()])); tooltip.add( I18n.format("gregtech.universal.tooltip.energy_storage_capacity", energyContainer.getEnergyCapacity())); - super.addInformation(stack, player, tooltip, advanced); } @Override diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityHull.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityHull.java index f953dff1b4e..328c9d08884 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityHull.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityHull.java @@ -3,7 +3,6 @@ import gregtech.api.GTValues; import gregtech.api.capability.IEnergyContainer; import gregtech.api.capability.impl.EnergyContainerHandler; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntityHolder; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; @@ -15,7 +14,6 @@ import gregtech.common.metatileentities.multi.multiblockpart.MetaTileEntityMultiblockPart; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; @@ -72,11 +70,6 @@ protected boolean openGUIOnRightClick() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public void addInformation(ItemStack stack, @Nullable World player, List tooltip, boolean advanced) { String tierName = GTValues.VNF[getTier()]; diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityMagicEnergyAbsorber.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityMagicEnergyAbsorber.java index 80d49f2219e..1f8de9fa85b 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityMagicEnergyAbsorber.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityMagicEnergyAbsorber.java @@ -1,7 +1,6 @@ package gregtech.common.metatileentities.electric; import gregtech.api.GTValues; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.TieredMetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; @@ -18,7 +17,6 @@ import net.minecraft.entity.boss.dragon.phase.PhaseChargingPlayer; import net.minecraft.entity.boss.dragon.phase.PhaseList; import net.minecraft.entity.item.EntityEnderCrystal; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; import net.minecraft.util.DamageSource; @@ -221,11 +219,6 @@ protected boolean openGUIOnRightClick() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @SideOnly(Side.CLIENT) @Override public void randomDisplayTick() { diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityPump.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityPump.java index 454c29bb848..d268521db3c 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityPump.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityPump.java @@ -11,7 +11,6 @@ import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.util.GTUtility; import gregtech.client.renderer.texture.Textures; -import gregtech.common.ConfigHolder; import net.minecraft.block.BlockLiquid; import net.minecraft.block.state.IBlockState; @@ -398,9 +397,8 @@ public void readFromNBT(NBTTagCompound data) { @Override public void addInformation(ItemStack stack, @Nullable World player, List tooltip, boolean advanced) { + super.addInformation(stack, player, tooltip, advanced); tooltip.add(I18n.format("gregtech.machine.pump.tooltip")); - if (ConfigHolder.machines.doTerrainExplosion) - tooltip.add(I18n.format("gregtech.universal.tooltip.terrain_resist")); tooltip.add( I18n.format("gregtech.universal.tooltip.uses_per_op", GTValues.V[getTier()] * 2) + TextFormatting.GRAY + ", " + I18n.format("gregtech.machine.pump.tooltip_buckets", getPumpingCycleLength())); diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityTransformer.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityTransformer.java index d54d7c46f46..2ea4f9e8ce1 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityTransformer.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityTransformer.java @@ -2,7 +2,6 @@ import gregtech.api.GTValues; import gregtech.api.capability.impl.EnergyContainerHandler; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.TieredMetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; @@ -250,11 +249,6 @@ protected boolean openGUIOnRightClick() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public void addInformation(ItemStack stack, @Nullable World player, List tooltip, boolean advanced) { String lowerTierName = GTValues.VNF[getTier()]; diff --git a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityWorldAccelerator.java b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityWorldAccelerator.java index 861cdd4c9e9..30928bf7a92 100644 --- a/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityWorldAccelerator.java +++ b/src/main/java/gregtech/common/metatileentities/electric/MetaTileEntityWorldAccelerator.java @@ -4,7 +4,6 @@ import gregtech.api.capability.GregtechTileCapabilities; import gregtech.api.capability.IControllable; import gregtech.api.capability.impl.EnergyContainerHandler; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.TieredMetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; @@ -228,11 +227,6 @@ protected boolean openGUIOnRightClick() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public boolean onScrewdriverClick(EntityPlayer playerIn, EnumHand hand, EnumFacing facing, CuboidRayTraceResult hitResult) { diff --git a/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityCokeOvenHatch.java b/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityCokeOvenHatch.java index 4484f5b9840..acb83429697 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityCokeOvenHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityCokeOvenHatch.java @@ -3,7 +3,6 @@ import gregtech.api.capability.impl.FluidHandlerProxy; import gregtech.api.capability.impl.FluidTankList; import gregtech.api.capability.impl.ItemHandlerProxy; -import gregtech.api.gui.ModularUI; import gregtech.api.items.itemhandlers.GTItemStackHandler; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; @@ -96,11 +95,6 @@ public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { return new MetaTileEntityCokeOvenHatch(metaTileEntityId); } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override protected boolean openGUIOnRightClick() { return false; diff --git a/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityPrimitiveWaterPump.java b/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityPrimitiveWaterPump.java index 43cee2ccb2f..0017c750d94 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityPrimitiveWaterPump.java +++ b/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityPrimitiveWaterPump.java @@ -1,6 +1,5 @@ package gregtech.common.metatileentities.multi; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockPart; @@ -19,7 +18,6 @@ import gregtech.common.metatileentities.MetaTileEntities; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; @@ -97,11 +95,6 @@ private int getAmount() { return 100; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override protected boolean openGUIOnRightClick() { return false; diff --git a/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityTankValve.java b/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityTankValve.java index a645fc753e1..13f9c9657f3 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityTankValve.java +++ b/src/main/java/gregtech/common/metatileentities/multi/MetaTileEntityTankValve.java @@ -2,7 +2,6 @@ import gregtech.api.capability.impl.FluidHandlerProxy; import gregtech.api.capability.impl.FluidTankList; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; @@ -14,7 +13,6 @@ import gregtech.common.metatileentities.multi.multiblockpart.MetaTileEntityMultiblockPart; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; @@ -108,11 +106,6 @@ public void removeFromMultiBlock(MultiblockControllerBase controllerBase) { initializeDummyInventory(); } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override protected boolean openGUIOnRightClick() { return false; diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityActiveTransformer.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityActiveTransformer.java index 059ec0264a7..d22e681fad3 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityActiveTransformer.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityActiveTransformer.java @@ -15,6 +15,8 @@ import gregtech.api.pattern.FactoryBlockPattern; import gregtech.api.pattern.PatternMatchContext; import gregtech.api.pattern.TraceabilityPredicate; +import gregtech.api.util.TextComponentUtil; +import gregtech.api.util.TextFormattingUtil; import gregtech.client.renderer.ICubeRenderer; import gregtech.client.renderer.texture.Textures; import gregtech.client.utils.TooltipHelper; @@ -30,6 +32,7 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fml.relauncher.Side; @@ -50,6 +53,8 @@ public class MetaTileEntityActiveTransformer extends MultiblockWithDisplayBase i private IEnergyContainer powerOutput; private IEnergyContainer powerInput; private boolean isActive = false; + private long averageIOLastSec; + private long netIOLastSec; public MetaTileEntityActiveTransformer(ResourceLocation metaTileEntityId) { super(metaTileEntityId); @@ -64,10 +69,18 @@ public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { @Override protected void updateFormedValid() { - if (isWorkingEnabled()) { - long canDrain = powerInput.getEnergyStored(); - long totalDrained = powerOutput.changeEnergy(canDrain); - powerInput.removeEnergy(totalDrained); + if (!getWorld().isRemote) { + if ((getOffsetTimer() % 20) == 0) { + averageIOLastSec = netIOLastSec / 20; + netIOLastSec = 0; + } + + if (isWorkingEnabled()) { + long canDrain = powerInput.getEnergyStored(); + long totalDrained = powerOutput.changeEnergy(canDrain); + powerInput.removeEnergy(totalDrained); + netIOLastSec += totalDrained; + } } } @@ -159,7 +172,39 @@ protected void addDisplayText(List textList) { "gregtech.multiblock.idling", "gregtech.multiblock.idling", "gregtech.machine.active_transformer.routing") - .addWorkingStatusLine(); + .addWorkingStatusLine() + .addCustom(tl -> { + if (isStructureFormed()) { + // Max input line + ITextComponent maxInputFormatted = TextComponentUtil.stringWithColor( + TextFormatting.WHITE, + TextFormattingUtil.formatNumbers( + powerInput.getInputVoltage() * powerInput.getInputAmperage()) + " EU/t"); + tl.add(TextComponentUtil.translationWithColor( + TextFormatting.GREEN, + "gregtech.multiblock.active_transformer.max_in", + maxInputFormatted)); + + // Max output line + ITextComponent maxOutputFormatted = TextComponentUtil.stringWithColor( + TextFormatting.WHITE, + TextFormattingUtil.formatNumbers( + powerOutput.getOutputVoltage() * powerOutput.getOutputAmperage()) + " EU/t"); + tl.add(TextComponentUtil.translationWithColor( + TextFormatting.RED, + "gregtech.multiblock.active_transformer.max_out", + maxOutputFormatted)); + + // Average I/O line + ITextComponent avgInputFormatted = TextComponentUtil.stringWithColor( + TextFormatting.WHITE, + TextFormattingUtil.formatNumbers(averageIOLastSec) + " EU/t"); + tl.add(TextComponentUtil.translationWithColor( + TextFormatting.AQUA, + "gregtech.multiblock.active_transformer.average_io", + avgInputFormatted)); + } + }); } @Override @@ -255,4 +300,8 @@ public void addInformation(ItemStack stack, @Nullable World world, @NotNull List tooltip.add(I18n.format("gregtech.machine.active_transformer.tooltip3") + TooltipHelper.RAINBOW_SLOW + I18n.format("gregtech.machine.active_transformer.tooltip3.5")); } + + public long getAverageIOLastSec() { + return this.averageIOLastSec; + } } diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityAssemblyLine.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityAssemblyLine.java index fb2de88df33..69b648b41cb 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityAssemblyLine.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityAssemblyLine.java @@ -14,7 +14,7 @@ import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMaps; import gregtech.api.recipes.ingredients.GTRecipeInput; -import gregtech.api.recipes.recipeproperties.ResearchProperty; +import gregtech.api.recipes.properties.impl.ResearchProperty; import gregtech.api.util.GTUtility; import gregtech.api.util.RelativeDirection; import gregtech.client.particle.GTLaserBeamParticle; diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityCleanroom.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityCleanroom.java index 73163307e2a..22c6909ca35 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityCleanroom.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityCleanroom.java @@ -635,7 +635,8 @@ public int getProgressPercent() { @Override public int getEnergyTier() { if (energyContainer == null) return GTValues.LV; - return Math.max(GTValues.LV, GTUtility.getFloorTierByVoltage(energyContainer.getInputVoltage())); + return Math.min(GTValues.MAX, + Math.max(GTValues.LV, GTUtility.getFloorTierByVoltage(energyContainer.getInputVoltage()))); } @Override diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityCrackingUnit.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityCrackingUnit.java index d71dca8cd0d..b1bd30b8574 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityCrackingUnit.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityCrackingUnit.java @@ -12,7 +12,7 @@ import gregtech.api.pattern.PatternMatchContext; import gregtech.api.recipes.RecipeMaps; import gregtech.api.recipes.logic.OCResult; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; import gregtech.api.util.GTUtility; import gregtech.api.util.TextComponentUtil; import gregtech.client.renderer.ICubeRenderer; @@ -150,7 +150,7 @@ public CrackingUnitWorkableHandler(RecipeMapMultiblockController tileEntity) { } @Override - protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull IRecipePropertyStorage storage) { + protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull RecipePropertyStorage storage) { super.modifyOverclockPost(ocResult, storage); int coilTier = ((MetaTileEntityCrackingUnit) metaTileEntity).getCoilTier(); diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityDistillationTower.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityDistillationTower.java index 2c7eea8410a..886cd35353d 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityDistillationTower.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityDistillationTower.java @@ -15,9 +15,7 @@ import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMaps; import gregtech.api.util.GTTransferUtils; -import gregtech.api.util.GTUtility; import gregtech.api.util.RelativeDirection; -import gregtech.api.util.TextComponentUtil; import gregtech.client.renderer.ICubeRenderer; import gregtech.client.renderer.texture.Textures; import gregtech.common.blocks.BlockMetalCasing.MetalCasingType; @@ -28,15 +26,11 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TextFormatting; -import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.jetbrains.annotations.NotNull; -import java.util.List; import java.util.function.Function; import static gregtech.api.util.RelativeDirection.*; @@ -86,22 +80,6 @@ public boolean allowsExtendedFacing() { return false; } - @Override - protected void addDisplayText(List textList) { - if (isStructureFormed()) { - FluidStack stackInTank = importFluids.drain(Integer.MAX_VALUE, false); - if (stackInTank != null && stackInTank.amount > 0) { - ITextComponent fluidName = TextComponentUtil.setColor(GTUtility.getFluidTranslation(stackInTank), - TextFormatting.AQUA); - textList.add(TextComponentUtil.translationWithColor( - TextFormatting.GRAY, - "gregtech.multiblock.distillation_tower.distilling_fluid", - fluidName)); - } - } - super.addDisplayText(textList); - } - @Override protected void formStructure(PatternMatchContext context) { super.formStructure(context); diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityElectricBlastFurnace.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityElectricBlastFurnace.java index 78d9449eaf2..89c277d7c8d 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityElectricBlastFurnace.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityElectricBlastFurnace.java @@ -17,7 +17,7 @@ import gregtech.api.pattern.PatternMatchContext; import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMaps; -import gregtech.api.recipes.recipeproperties.TemperatureProperty; +import gregtech.api.recipes.properties.impl.TemperatureProperty; import gregtech.api.util.GTUtility; import gregtech.api.util.TextComponentUtil; import gregtech.api.util.TextFormattingUtil; diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityFusionReactor.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityFusionReactor.java index 4b6b9db00d5..b9a918639f3 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityFusionReactor.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityFusionReactor.java @@ -30,8 +30,8 @@ import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMaps; import gregtech.api.recipes.logic.OCParams; -import gregtech.api.recipes.recipeproperties.FusionEUToStartProperty; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; +import gregtech.api.recipes.properties.impl.FusionEUToStartProperty; import gregtech.api.util.RelativeDirection; import gregtech.api.util.TextComponentUtil; import gregtech.api.util.TextFormattingUtil; @@ -637,13 +637,13 @@ public boolean checkRecipe(@NotNull Recipe recipe) { } @Override - protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull IRecipePropertyStorage storage) { + protected void modifyOverclockPre(@NotNull OCParams ocParams, @NotNull RecipePropertyStorage storage) { super.modifyOverclockPre(ocParams, storage); // Limit the number of OCs to the difference in fusion reactor MK. // I.e., a MK2 reactor can overclock a MK1 recipe once, and a // MK3 reactor can overclock a MK2 recipe once, or a MK1 recipe twice. - long euToStart = storage.getRecipePropertyValue(FusionEUToStartProperty.getInstance(), 0L); + long euToStart = storage.get(FusionEUToStartProperty.getInstance(), 0L); int fusionTier = FusionEUToStartProperty.getFusionTier(euToStart); if (fusionTier != 0) fusionTier = MetaTileEntityFusionReactor.this.tier - fusionTier; ocParams.setOcAmount(Math.min(fusionTier, ocParams.ocAmount())); diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityMultiSmelter.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityMultiSmelter.java index d25c923630d..71fca7ba8d4 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityMultiSmelter.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityMultiSmelter.java @@ -17,7 +17,7 @@ import gregtech.api.recipes.logic.OCParams; import gregtech.api.recipes.logic.OCResult; import gregtech.api.recipes.machines.RecipeMapFurnace; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; import gregtech.api.util.GTUtility; import gregtech.api.util.TextComponentUtil; import gregtech.api.util.TextFormattingUtil; @@ -208,7 +208,7 @@ public ParallelLogicType getParallelLogicType() { @Override protected void runOverclockingLogic(@NotNull OCParams ocParams, @NotNull OCResult ocResult, - @NotNull IRecipePropertyStorage propertyStorage, long maxVoltage) { + @NotNull RecipePropertyStorage propertyStorage, long maxVoltage) { standardOC(ocParams, ocResult, maxVoltage, getOverclockingDurationFactor(), getOverclockingVoltageFactor()); } diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityProcessingArray.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityProcessingArray.java index 7a8fd7a9162..4759bb1dec7 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityProcessingArray.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityProcessingArray.java @@ -24,7 +24,7 @@ import gregtech.api.recipes.RecipeMap; import gregtech.api.recipes.logic.OCParams; import gregtech.api.recipes.logic.OCResult; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; import gregtech.api.util.GTUtility; import gregtech.api.util.TextComponentUtil; import gregtech.api.util.TextFormattingUtil; @@ -417,7 +417,7 @@ protected int getNumberOfOCs(long recipeEUt) { @Override protected void runOverclockingLogic(@NotNull OCParams ocParams, @NotNull OCResult ocResult, - @NotNull IRecipePropertyStorage propertyStorage, long maxVoltage) { + @NotNull RecipePropertyStorage propertyStorage, long maxVoltage) { subTickNonParallelOC(ocParams, ocResult, maxVoltage, getOverclockingDurationFactor(), getOverclockingVoltageFactor()); } diff --git a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityPyrolyseOven.java b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityPyrolyseOven.java index efda75b7dc6..b4715563582 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityPyrolyseOven.java +++ b/src/main/java/gregtech/common/metatileentities/multi/electric/MetaTileEntityPyrolyseOven.java @@ -12,7 +12,7 @@ import gregtech.api.pattern.PatternMatchContext; import gregtech.api.recipes.RecipeMaps; import gregtech.api.recipes.logic.OCResult; -import gregtech.api.recipes.recipeproperties.IRecipePropertyStorage; +import gregtech.api.recipes.properties.RecipePropertyStorage; import gregtech.api.util.GTUtility; import gregtech.api.util.TextComponentUtil; import gregtech.client.renderer.ICubeRenderer; @@ -173,7 +173,7 @@ public PyrolyseOvenWorkableHandler(RecipeMapMultiblockController tileEntity) { } @Override - protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull IRecipePropertyStorage storage) { + protected void modifyOverclockPost(@NotNull OCResult ocResult, @NotNull RecipePropertyStorage storage) { super.modifyOverclockPost(ocResult, storage); int coilTier = ((MetaTileEntityPyrolyseOven) metaTileEntity).getCoilTier(); diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityAutoMaintenanceHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityAutoMaintenanceHatch.java index 7743303c4ec..c1ac8373b43 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityAutoMaintenanceHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityAutoMaintenanceHatch.java @@ -1,7 +1,6 @@ package gregtech.common.metatileentities.multi.multiblockpart; import gregtech.api.capability.IMaintenanceHatch; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; @@ -12,7 +11,6 @@ import net.minecraft.client.resources.I18n; import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; @@ -95,11 +93,6 @@ public boolean startWithoutProblems() { return true; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override protected boolean openGUIOnRightClick() { return false; diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityComputationHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityComputationHatch.java index ae41352ceb2..85c2bc25173 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityComputationHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityComputationHatch.java @@ -4,7 +4,6 @@ import gregtech.api.capability.GregtechTileCapabilities; import gregtech.api.capability.IOpticalComputationHatch; import gregtech.api.capability.IOpticalComputationProvider; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; @@ -14,7 +13,6 @@ import gregtech.common.pipelike.optical.tile.TileEntityOpticalPipe; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; @@ -132,11 +130,6 @@ protected boolean openGUIOnRightClick() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public boolean canPartShare() { return false; diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityEnergyHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityEnergyHatch.java index 1440514f90e..fd79fc8811d 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityEnergyHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityEnergyHatch.java @@ -1,13 +1,17 @@ package gregtech.common.metatileentities.multi.multiblockpart; import gregtech.api.GTValues; +import gregtech.api.capability.GregtechDataCodes; import gregtech.api.capability.IEnergyContainer; +import gregtech.api.capability.IQuantumController; +import gregtech.api.capability.IQuantumStorage; import gregtech.api.capability.impl.EnergyContainerHandler; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; import gregtech.api.metatileentity.multiblock.MultiblockAbility; +import gregtech.api.util.GTUtility; +import gregtech.client.renderer.ICubeRenderer; import gregtech.client.renderer.texture.Textures; import gregtech.client.renderer.texture.cube.SimpleOverlayRenderer; import gregtech.client.utils.PipelineUtil; @@ -15,10 +19,13 @@ import net.minecraft.client.resources.I18n; import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.PacketBuffer; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import codechicken.lib.render.CCRenderState; @@ -27,15 +34,23 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.lang.ref.WeakReference; import java.util.List; public class MetaTileEntityEnergyHatch extends MetaTileEntityMultiblockPart - implements IMultiblockAbilityPart { + implements IMultiblockAbilityPart, + IQuantumStorage { protected final boolean isExportHatch; protected final int amperage; protected final IEnergyContainer energyContainer; + /** not synced, server only. lazily initialized from pos */ + private WeakReference controller = new WeakReference<>(null); + + /** synced, server and client */ + private BlockPos controllerPos; + public MetaTileEntityEnergyHatch(ResourceLocation metaTileEntityId, int tier, int amperage, boolean isExportHatch) { super(metaTileEntityId, tier); this.isExportHatch = isExportHatch; @@ -110,11 +125,6 @@ protected boolean openGUIOnRightClick() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public void addInformation(ItemStack stack, @Nullable World world, List tooltip, boolean advanced) { String tierName = GTValues.VNF[getTier()]; @@ -204,4 +214,137 @@ public void doExplosion(float explosionPower) { super.doExplosion(explosionPower); } } + + @Override + public void onRemoval() { + if (!getWorld().isRemote && isConnected()) { + IQuantumController controller = getQuantumController(); + if (controller != null) controller.rebuildNetwork(); + } + } + + @Override + public void onPlacement(@Nullable EntityLivingBase placer) { + super.onPlacement(placer); + if (getWorld() == null || getWorld().isRemote || isExportHatch) + return; + + // add to the network if an adjacent block is part of a network + // use whatever we find first, merging networks is not supported + tryFindNetwork(); + } + + @Override + public Type getType() { + return Type.ENERGY; + } + + @Override + public ICubeRenderer getBaseTexture() { + if (isConnected()) { + return Textures.QUANTUM_CASING; + } + return super.getBaseTexture(); + } + + @Override + public void setConnected(IQuantumController controller) { + if (getWorld().isRemote) return; + if (isExportHatch) return; + + if (!controller.getPos().equals(controllerPos)) { + this.controller = new WeakReference<>(controller); + this.controllerPos = controller.getPos(); + writeCustomData(GregtechDataCodes.UPDATE_CONTROLLER_POS, buf -> buf.writeBlockPos(controllerPos)); + markDirty(); + } + } + + @Override + public void setDisconnected() { + if (getWorld().isRemote) return; + + controller.clear(); + controllerPos = null; + writeCustomData(GregtechDataCodes.REMOVE_CONTROLLER, buf -> {}); + markDirty(); + } + + @Override + public void receiveCustomData(int dataId, PacketBuffer buf) { + super.receiveCustomData(dataId, buf); + if (dataId == GregtechDataCodes.UPDATE_CONTROLLER_POS) { + this.controllerPos = buf.readBlockPos(); + this.controller.clear(); + scheduleRenderUpdate(); + } else if (dataId == GregtechDataCodes.REMOVE_CONTROLLER) { + this.controllerPos = null; + this.controller.clear(); + scheduleRenderUpdate(); + } + } + + @Override + public void writeInitialSyncData(PacketBuffer buf) { + super.writeInitialSyncData(buf); + buf.writeBoolean(controllerPos != null); + if (controllerPos != null) { + buf.writeBlockPos(controllerPos); + } + } + + @Override + public void receiveInitialSyncData(PacketBuffer buf) { + super.receiveInitialSyncData(buf); + if (buf.readBoolean()) { + controllerPos = buf.readBlockPos(); + scheduleRenderUpdate(); + } + } + + // use this to make sure controller is properly initialized + @Override + public final IQuantumController getQuantumController() { + if (isConnected()) { + if (controller.get() != null) return controller.get(); + MetaTileEntity mte = GTUtility.getMetaTileEntity(getWorld(), controllerPos); + if (mte instanceof IQuantumController quantumController) { + controller = new WeakReference<>(quantumController); + return quantumController; + } else { + // controller is no longer there for some reason, need to disconnect + setDisconnected(); + tryFindNetwork(); + } + } + return null; + } + + @Override + public BlockPos getControllerPos() { + return controllerPos; + } + + @Override + public IEnergyContainer getTypeValue() { + return this.energyContainer; + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound data) { + NBTTagCompound tagCompound = super.writeToNBT(data); + tagCompound.setBoolean("HasController", controllerPos != null); + if (controllerPos != null) { + tagCompound.setLong("ControllerPos", controllerPos.toLong()); + } + return tagCompound; + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + if (data.getBoolean("HasController")) { + this.controllerPos = BlockPos.fromLong(data.getLong("ControllerPos")); + } + } } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityFluidHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityFluidHatch.java index 8eca7ca9111..153c93bdb12 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityFluidHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityFluidHatch.java @@ -4,33 +4,28 @@ import gregtech.api.capability.impl.FilteredItemHandler; import gregtech.api.capability.impl.FluidTankList; import gregtech.api.capability.impl.NotifiableFluidTank; -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.ModularUI; -import gregtech.api.gui.ModularUI.Builder; -import gregtech.api.gui.widgets.*; import gregtech.api.items.itemhandlers.GTItemStackHandler; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; import gregtech.api.metatileentity.multiblock.MultiblockAbility; -import gregtech.api.util.GTUtility; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; import gregtech.client.renderer.texture.Textures; import gregtech.client.renderer.texture.cube.SimpleOverlayRenderer; import gregtech.common.metatileentities.storage.MetaTileEntityQuantumTank; +import gregtech.common.mui.widget.GTFluidSlot; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.IFluidTank; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.items.IItemHandlerModifiable; @@ -38,25 +33,36 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Matrix4; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.PosGuiData; +import com.cleanroommc.modularui.network.NetworkUtils; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.utils.Color; +import com.cleanroommc.modularui.value.sync.BooleanSyncValue; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.widgets.ItemSlot; +import com.cleanroommc.modularui.widgets.RichTextWidget; +import com.cleanroommc.modularui.widgets.ToggleButton; +import com.cleanroommc.modularui.widgets.slot.ModularSlot; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; -import java.util.function.Consumer; public class MetaTileEntityFluidHatch extends MetaTileEntityMultiblockNotifiablePart implements IMultiblockAbilityPart, IControllable { - private static final int INITIAL_INVENTORY_SIZE = 8000; + public static final int INITIAL_INVENTORY_SIZE = 8000; // only holding this for convenience - private final HatchFluidTank fluidTank; - private boolean workingEnabled; + protected final HatchFluidTank fluidTank; + protected boolean workingEnabled; // export hatch-only fields - private boolean locked; + protected boolean locked; @Nullable - private FluidStack lockedFluid; + protected FluidStack lockedFluid; public MetaTileEntityFluidHatch(ResourceLocation metaTileEntityId, int tier, boolean isExportHatch) { super(metaTileEntityId, tier, isExportHatch); @@ -161,6 +167,8 @@ public void receiveCustomData(int dataId, PacketBuffer buf) { super.receiveCustomData(dataId, buf); if (dataId == GregtechDataCodes.WORKING_ENABLED) { this.workingEnabled = buf.readBoolean(); + } else if (dataId == GregtechDataCodes.LOCK_FILL) { + this.lockedFluid = NetworkUtils.readFluidStack(buf); } } @@ -176,7 +184,7 @@ public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, } } - private int getInventorySize() { + protected int getInventorySize() { return INITIAL_INVENTORY_SIZE * (1 << Math.min(9, getTier())); } @@ -212,93 +220,85 @@ public void registerAbilities(List abilityList) { } @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return createTankUI(fluidTank, getMetaFullName(), entityPlayer).build(getHolder(), entityPlayer); + public boolean usesMui2() { + return true; } - public ModularUI.Builder createTankUI(IFluidTank fluidTank, String title, EntityPlayer entityPlayer) { - // Create base builder/widget references - Builder builder = ModularUI.defaultBuilder(); - TankWidget tankWidget; - - // Add input/output-specific widgets - if (isExportHatch) { - tankWidget = new PhantomTankWidget(fluidTank, 69, 43, 18, 18, - () -> this.lockedFluid, - f -> { - if (this.fluidTank.getFluidAmount() != 0) { - return; - } - if (f == null) { - this.setLocked(false); - this.lockedFluid = null; - } else { - this.setLocked(true); - this.lockedFluid = f.copy(); - this.lockedFluid.amount = 1; - } - }) - .setAlwaysShowFull(true).setDrawHoveringText(false); - - builder.image(7, 16, 81, 46, GuiTextures.DISPLAY) - .widget(new SlotWidget(exportItems, 0, 90, 44, true, false) - .setBackgroundTexture(GuiTextures.SLOT, GuiTextures.OUT_SLOT_OVERLAY)) - .widget(new ToggleButtonWidget(7, 64, 18, 18, - GuiTextures.BUTTON_LOCK, this::isLocked, this::setLocked) - .setTooltipText("gregtech.gui.fluid_lock.tooltip") - .shouldUseBaseBackground()); - } else { - tankWidget = new TankWidget(fluidTank, 69, 52, 18, 18) - .setAlwaysShowFull(true).setDrawHoveringText(false); - - builder.image(7, 16, 81, 55, GuiTextures.DISPLAY) - .widget(new ImageWidget(91, 36, 14, 15, GuiTextures.TANK_ICON)) - .widget(new SlotWidget(exportItems, 0, 90, 53, true, false) - .setBackgroundTexture(GuiTextures.SLOT, GuiTextures.OUT_SLOT_OVERLAY)); - } - - // Add general widgets - return builder.label(6, 6, title) - .label(11, 20, "gregtech.gui.fluid_amount", 0xFFFFFF) - .widget(new AdvancedTextWidget(11, 30, getFluidAmountText(tankWidget), 0xFFFFFF)) - .widget(new AdvancedTextWidget(11, 40, getFluidNameText(tankWidget), 0xFFFFFF)) - .widget(tankWidget) - .widget(new FluidContainerSlotWidget(importItems, 0, 90, 16, false) - .setBackgroundTexture(GuiTextures.SLOT, GuiTextures.IN_SLOT_OVERLAY)) - .bindPlayerInventory(entityPlayer.inventory); - } - - private Consumer> getFluidNameText(TankWidget tankWidget) { - return (list) -> { - TextComponentTranslation translation = tankWidget.getFluidTextComponent(); - // If there is no fluid in the tank, but there is a locked fluid - if (translation == null) { - translation = GTUtility.getFluidTranslation(this.lockedFluid); - } - - if (translation != null) { - list.add(translation); - } - }; - } - - private Consumer> getFluidAmountText(TankWidget tankWidget) { - return (list) -> { - String fluidAmount = ""; - - // Nothing in the tank - if (tankWidget.getFormattedFluidAmount().equals("0")) { - // Display Zero to show information about the locked fluid - if (this.lockedFluid != null) { - fluidAmount = "0"; - } - } else { - fluidAmount = tankWidget.getFormattedFluidAmount(); - } - if (!fluidAmount.isEmpty()) { - list.add(new TextComponentString(fluidAmount)); - } - }; + @Override + public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager guiSyncManager) { + var fluidSyncHandler = GTFluidSlot.sync(fluidTank) + .showAmount(false) + .accessibility(true, !isExportHatch) + .handleLocking(() -> this.lockedFluid, fluidStack -> { + setLocked(fluidStack != null); + this.lockedFluid = fluidStack; + this.fluidTank.onContentsChanged(); + }, this::setLocked); + + return GTGuis.createPanel(this, 176, 166) + .child(IKey.lang(getMetaFullName()).asWidget().pos(6, 6)) + + // export specific + .childIf(isExportHatch, new ItemSlot() + .pos(90, 44) + .background(GTGuiTextures.SLOT, GTGuiTextures.OUT_SLOT_OVERLAY) + .slot(new ModularSlot(exportItems, 0) + .accessibility(false, true))) + .childIf(isExportHatch, new ToggleButton() + .pos(7, 63) + .overlay(GTGuiTextures.BUTTON_LOCK) + // todo doing things this way causes flickering if it fails + // due to sync value cache + .value(new BooleanSyncValue(this::isLocked, b -> fluidSyncHandler.lockFluid(b, false))) + .addTooltip(true, IKey.lang("gregtech.gui.fluid_lock.tooltip.enabled")) + .addTooltip(false, IKey.lang("gregtech.gui.fluid_lock.tooltip.disabled"))) + + // import specific + .childIf(!isExportHatch, GTGuiTextures.TANK_ICON.asWidget() + .pos(91, 36) + .size(14, 15)) + .childIf(!isExportHatch, new ItemSlot() + .pos(90, 53) + .background(GTGuiTextures.SLOT, GTGuiTextures.OUT_SLOT_OVERLAY) + .slot(new ModularSlot(exportItems, 0) + .accessibility(false, true))) + + // common ui + .child(new RichTextWidget() + .size(81 - 6, (isExportHatch ? 46 : 55) - 8) + // .padding(3, 4) + .background(GTGuiTextures.DISPLAY.asIcon().size(81, isExportHatch ? 46 : 55)) + .pos(7 + 3, 16 + 4) + .textColor(Color.WHITE.main) + .alignment(Alignment.TopLeft) + .autoUpdate(true) + .textBuilder(richText -> { + richText.addLine(IKey.lang("gregtech.gui.fluid_amount")); + String name = fluidSyncHandler.getFluidLocalizedName(); + if (name == null) return; + if (name.length() > 25) name = name.substring(0, 25) + "..."; + + richText.addLine(IKey.str(name)); + richText.addLine(IKey.str(fluidSyncHandler.getFormattedFluidAmount())); + })) + .child(new GTFluidSlot() + .disableBackground() + .pos(69, isExportHatch ? 43 : 52) + .size(18) + .syncHandler(fluidSyncHandler)) + .child(new ItemSlot() + .pos(90, 16) + .background(GTGuiTextures.SLOT, GTGuiTextures.IN_SLOT_OVERLAY) + .slot(new ModularSlot(importItems, 0) + .singletonSlotGroup() + .filter(stack -> { + if (!isExportHatch) return true; + var h = FluidUtil.getFluidHandler(stack); + if (h == null) return false; + return h.getTankProperties()[0].getContents() == null; + }) + .accessibility(true, true))) + .bindPlayerInventory(); } @Override @@ -324,11 +324,10 @@ private boolean isLocked() { } private void setLocked(boolean locked) { - if (this.locked == locked) return; + if (!isExportHatch || this.locked == locked) return; this.locked = locked; - if (!getWorld().isRemote) { - markDirty(); - } + + if (!getWorld().isRemote) markDirty(); if (locked && fluidTank.getFluid() != null) { this.lockedFluid = fluidTank.getFluid().copy(); this.lockedFluid.amount = 1; @@ -339,7 +338,7 @@ private void setLocked(boolean locked) { fluidTank.onContentsChanged(); } - private class HatchFluidTank extends NotifiableFluidTank implements IFilteredFluidContainer, IFilter { + protected class HatchFluidTank extends NotifiableFluidTank implements IFilteredFluidContainer, IFilter { public HatchFluidTank(int capacity, MetaTileEntity entityToNotify, boolean isExport) { super(capacity, entityToNotify, isExport); @@ -352,6 +351,8 @@ public int fillInternal(FluidStack resource, boolean doFill) { if (doFill && locked && lockedFluid == null) { lockedFluid = resource.copy(); lockedFluid.amount = 1; + writeCustomData(GregtechDataCodes.LOCK_FILL, + buffer -> NetworkUtils.writeFluidStack(buffer, lockedFluid)); } return accepted; } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityItemBus.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityItemBus.java index 50435231a3b..a549ccbf81f 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityItemBus.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityItemBus.java @@ -47,7 +47,7 @@ import com.cleanroommc.modularui.widgets.ItemSlot; import com.cleanroommc.modularui.widgets.SlotGroupWidget; import com.cleanroommc.modularui.widgets.ToggleButton; -import com.cleanroommc.modularui.widgets.layout.Column; +import com.cleanroommc.modularui.widgets.layout.Flow; import com.cleanroommc.modularui.widgets.layout.Grid; import it.unimi.dsi.fastutil.objects.Object2IntMap; import org.jetbrains.annotations.NotNull; @@ -310,7 +310,7 @@ public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager guiSyncManager) .minColWidth(18).minRowHeight(18) .alignX(0.5f) .matrix(widgets)) - .child(new Column() + .child(Flow.column() .pos(backgroundWidth - 7 - 18, backgroundHeight - 18 * 4 - 7 - 5) .width(18).height(18 * 4 + 5) .child(GTGuiTextures.getLogo(getUITheme()).asWidget().size(17).top(18 * 3 + 5)) diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityLaserHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityLaserHatch.java index 76acce75c33..f47d35c0377 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityLaserHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityLaserHatch.java @@ -3,7 +3,6 @@ import gregtech.api.GTValues; import gregtech.api.capability.ILaserContainer; import gregtech.api.capability.impl.LaserContainerHandler; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.IDataInfoProvider; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; @@ -12,7 +11,6 @@ import gregtech.client.renderer.texture.Textures; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; @@ -62,11 +60,6 @@ public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { return new MetaTileEntityLaserHatch(metaTileEntityId, isOutput, tier, amperage); } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override protected boolean openGUIOnRightClick() { return false; diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMachineHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMachineHatch.java index 47b88bb6ef0..312f7cb9d56 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMachineHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMachineHatch.java @@ -97,6 +97,7 @@ private int getMachineLimit() { public void addInformation(ItemStack stack, @Nullable World player, List tooltip, boolean advanced) { super.addInformation(stack, player, tooltip, advanced); tooltip.add(I18n.format("gregtech.machine.machine_hatch.processing_array")); + tooltip.add(I18n.format("gregtech.universal.disabled")); } @Override diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java index 31c87a58251..6c8e3cd2e97 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java @@ -9,6 +9,7 @@ import gregtech.api.gui.widgets.ClickButtonWidget; import gregtech.api.gui.widgets.SlotWidget; import gregtech.api.items.itemhandlers.GTItemStackHandler; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolClasses; import gregtech.api.items.toolitem.ToolHelper; import gregtech.api.metatileentity.MetaTileEntity; @@ -45,6 +46,7 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Matrix4; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -260,24 +262,12 @@ private void fixProblemsWithTools(byte problems, EntityPlayer entityPlayer) { if (((problems >> index) & 1) == 0) { proceed = true; switch (index) { - case 0: - toolsToMatch.set(0, ToolClasses.WRENCH); - break; - case 1: - toolsToMatch.set(1, ToolClasses.SCREWDRIVER); - break; - case 2: - toolsToMatch.set(2, ToolClasses.SOFT_MALLET); - break; - case 3: - toolsToMatch.set(3, ToolClasses.HARD_HAMMER); - break; - case 4: - toolsToMatch.set(4, ToolClasses.WIRE_CUTTER); - break; - case 5: - toolsToMatch.set(5, ToolClasses.CROWBAR); - break; + case 0 -> toolsToMatch.set(0, ToolClasses.WRENCH); + case 1 -> toolsToMatch.set(1, ToolClasses.SCREWDRIVER); + case 2 -> toolsToMatch.set(2, ToolClasses.SOFT_MALLET); + case 3 -> toolsToMatch.set(3, ToolClasses.HARD_HAMMER); + case 4 -> toolsToMatch.set(4, ToolClasses.WIRE_CUTTER); + case 5 -> toolsToMatch.set(5, ToolClasses.CROWBAR); } } } @@ -285,38 +275,66 @@ private void fixProblemsWithTools(byte problems, EntityPlayer entityPlayer) { return; } + mainfor: for (int i = 0; i < toolsToMatch.size(); i++) { String toolToMatch = toolsToMatch.get(i); if (toolToMatch != null) { // Try to use the item in the player's "hand" (under the cursor) ItemStack heldItem = entityPlayer.inventory.getItemStack(); - if (ToolHelper.isTool(heldItem, toolToMatch)) { + if (heldItem.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.damageAgainstMaintenanceProblem(heldItem, toolToMatch, entityPlayer)) { + ((IMaintenance) getController()).setMaintenanceFixed(i); + setTaped(false); + continue; + } + } else if (ToolHelper.isTool(heldItem, toolToMatch)) { fixProblemWithTool(i, heldItem, entityPlayer); if (toolsToMatch.stream().allMatch(Objects::isNull)) { return; } + continue; } // Then try all the remaining inventory slots for (ItemStack itemStack : entityPlayer.inventory.mainInventory) { - if (ToolHelper.isTool(itemStack, toolToMatch)) { + if (itemStack.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.damageAgainstMaintenanceProblem(itemStack, toolToMatch, entityPlayer)) { + ((IMaintenance) getController()).setMaintenanceFixed(i); + setTaped(false); + continue mainfor; + } + } else if (ToolHelper.isTool(itemStack, toolToMatch)) { fixProblemWithTool(i, itemStack, entityPlayer); if (toolsToMatch.stream().allMatch(Objects::isNull)) { return; } + continue mainfor; } } + } + } + } - for (ItemStack stack : entityPlayer.inventory.mainInventory) { - if (ToolHelper.isTool(stack, toolToMatch)) { - ((IMaintenance) this.getController()).setMaintenanceFixed(i); - ToolHelper.damageItemWhenCrafting(stack, entityPlayer); - if (toolsToMatch.stream().allMatch(Objects::isNull)) { - return; - } - } + @ApiStatus.Internal + public void fixMaintenanceProblemsWithToolbelt(@NotNull EntityPlayer entityPlayer, ItemGTToolbelt toolbelt, + ItemStack toolbeltStack) { + byte problems = ((IMaintenance) this.getController()).getMaintenanceProblems(); + for (byte index = 0; index < 6; index++) { + if (((problems >> index) & 1) == 0) { + String toolToMatch = switch (index) { + case 0 -> ToolClasses.WRENCH; + case 1 -> ToolClasses.SCREWDRIVER; + case 2 -> ToolClasses.SOFT_MALLET; + case 3 -> ToolClasses.HARD_HAMMER; + case 4 -> ToolClasses.WIRE_CUTTER; + case 5 -> ToolClasses.CROWBAR; + default -> null; + }; + if (toolbelt.damageAgainstMaintenanceProblem(toolbeltStack, toolToMatch, entityPlayer)) { + ((IMaintenance) getController()).setMaintenanceFixed(index); + setTaped(false); } } } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMultiFluidHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMultiFluidHatch.java index cf053eb8500..6ac0ad4ee05 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMultiFluidHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMultiFluidHatch.java @@ -6,18 +6,16 @@ import gregtech.api.capability.IControllable; import gregtech.api.capability.impl.FluidTankList; import gregtech.api.capability.impl.NotifiableFluidTank; -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.ModularUI; -import gregtech.api.gui.widgets.TankWidget; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; import gregtech.api.metatileentity.multiblock.MultiblockAbility; +import gregtech.api.mui.GTGuis; import gregtech.client.renderer.texture.Textures; import gregtech.client.renderer.texture.cube.SimpleOverlayRenderer; +import gregtech.common.mui.widget.GTFluidSlot; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; @@ -31,8 +29,15 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Matrix4; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.PosGuiData; +import com.cleanroommc.modularui.network.NetworkUtils; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.widgets.layout.Grid; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.List; public class MetaTileEntityMultiFluidHatch extends MetaTileEntityMultiblockNotifiablePart @@ -114,12 +119,19 @@ public T getCapability(Capability capability, EnumFacing side) { public void writeInitialSyncData(PacketBuffer buf) { super.writeInitialSyncData(buf); buf.writeBoolean(workingEnabled); + for (var tank : fluidTankList.getFluidTanks()) { + NetworkUtils.writeFluidStack(buf, tank.getFluid()); + } } @Override public void receiveInitialSyncData(PacketBuffer buf) { super.receiveInitialSyncData(buf); this.workingEnabled = buf.readBoolean(); + for (var tank : fluidTankList.getFluidTanks()) { + var fluid = NetworkUtils.readFluidStack(buf); + tank.fill(fluid, true); + } } @Override @@ -190,23 +202,29 @@ public void registerAbilities(List abilityList) { } @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { + public boolean usesMui2() { + return true; + } + + @Override + public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager guiSyncManager) { int rowSize = (int) Math.sqrt(numSlots); - ModularUI.Builder builder = ModularUI.builder(GuiTextures.BACKGROUND, 176, - 18 + 18 * rowSize + 94) - .label(10, 5, getMetaFullName()); - - for (int y = 0; y < rowSize; y++) { - for (int x = 0; x < rowSize; x++) { - int index = y * rowSize + x; - builder.widget( - new TankWidget(fluidTankList.getTankAt(index), 89 - rowSize * 9 + x * 18, 18 + y * 18, 18, 18) - .setBackgroundTexture(GuiTextures.FLUID_SLOT) - .setContainerClicking(true, !isExportHatch) - .setAlwaysShowFull(true)); - } + + List fluidSlots = new ArrayList<>(); + for (int i = 0; i < numSlots; i++) { + fluidSlots.add(new GTFluidSlot()); } - builder.bindPlayerInventory(entityPlayer.inventory, GuiTextures.SLOT, 7, 18 + 18 * rowSize + 12); - return builder.build(getHolder(), entityPlayer); + + return GTGuis.createPanel(this, 176, 18 + 18 * rowSize + 94) + .child(IKey.lang(getMetaFullName()).asWidget().pos(5, 5)) + .child(new Grid() + .margin(0) + .leftRel(0.5f) + .top(17) + .mapTo(rowSize, fluidSlots, + (i, slot) -> slot.syncHandler(GTFluidSlot.sync(fluidTankList.getTankAt(i)) + .accessibility(true, !isExportHatch))) + .coverChildren()) + .bindPlayerInventory(); } } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityOpticalDataHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityOpticalDataHatch.java index 054cbccfd19..b86782957d2 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityOpticalDataHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityOpticalDataHatch.java @@ -4,7 +4,6 @@ import gregtech.api.capability.GregtechTileCapabilities; import gregtech.api.capability.IDataAccessHatch; import gregtech.api.capability.IOpticalDataAccessHatch; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; @@ -15,7 +14,6 @@ import gregtech.common.pipelike.optical.tile.TileEntityOpticalPipe; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; @@ -47,11 +45,6 @@ public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { return new MetaTileEntityOpticalDataHatch(metaTileEntityId, this.isTransmitter); } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override protected boolean openGUIOnRightClick() { return false; diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityPassthroughHatchFluid.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityPassthroughHatchFluid.java index 84c388dece1..5305afee5e5 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityPassthroughHatchFluid.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityPassthroughHatchFluid.java @@ -1,23 +1,26 @@ package gregtech.common.metatileentities.multi.multiblockpart; +import gregtech.api.capability.GregtechDataCodes; +import gregtech.api.capability.GregtechTileCapabilities; +import gregtech.api.capability.IControllable; import gregtech.api.capability.impl.FilteredFluidHandler; import gregtech.api.capability.impl.FluidHandlerProxy; import gregtech.api.capability.impl.FluidTankList; import gregtech.api.capability.impl.NotifiableItemStackHandler; -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.ModularUI; -import gregtech.api.gui.widgets.TankWidget; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; import gregtech.api.metatileentity.multiblock.IPassthroughHatch; import gregtech.api.metatileentity.multiblock.MultiblockAbility; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; import gregtech.client.renderer.texture.Textures; +import gregtech.common.mui.widget.GTFluidSlot; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.PacketBuffer; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; @@ -29,13 +32,24 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Matrix4; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.api.widget.IWidget; +import com.cleanroommc.modularui.factory.PosGuiData; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.BooleanSyncValue; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.widgets.SlotGroupWidget; +import com.cleanroommc.modularui.widgets.ToggleButton; +import com.cleanroommc.modularui.widgets.layout.Grid; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.List; public class MetaTileEntityPassthroughHatchFluid extends MetaTileEntityMultiblockPart implements IPassthroughHatch, - IMultiblockAbilityPart { + IMultiblockAbilityPart, + IControllable { private static final int TANK_SIZE = 16_000; @@ -44,8 +58,11 @@ public class MetaTileEntityPassthroughHatchFluid extends MetaTileEntityMultibloc private IFluidHandler importHandler; private IFluidHandler exportHandler; + private boolean workingEnabled; + public MetaTileEntityPassthroughHatchFluid(ResourceLocation metaTileEntityId, int tier) { super(metaTileEntityId, tier); + this.workingEnabled = true; initializeInventory(); } @@ -70,11 +87,25 @@ protected void initializeInventory() { public void update() { super.update(); if (!getWorld().isRemote && getOffsetTimer() % 5 == 0) { - pushFluidsIntoNearbyHandlers(getFrontFacing().getOpposite()); // outputs to back - pullFluidsFromNearbyHandlers(getFrontFacing()); // inputs from front + if (workingEnabled) { + pushFluidsIntoNearbyHandlers(getFrontFacing().getOpposite()); // outputs to back + pullFluidsFromNearbyHandlers(getFrontFacing()); // inputs from front + } + } + } + + public void setWorkingEnabled(boolean workingEnabled) { + this.workingEnabled = workingEnabled; + World world = getWorld(); + if (world != null && !world.isRemote) { + writeCustomData(GregtechDataCodes.WORKING_ENABLED, buf -> buf.writeBoolean(workingEnabled)); } } + public boolean isWorkingEnabled() { + return this.workingEnabled; + } + @Override public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline) { super.renderMetaTileEntity(renderState, translation, pipeline); @@ -101,33 +132,51 @@ protected IItemHandlerModifiable createImportItemHandler() { } @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { + public boolean usesMui2() { + return true; + } + + @Override + public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager guiSyncManager) { int rowSize = (int) Math.sqrt(getTier() + 1); - return createUITemplate(entityPlayer, rowSize) - .build(getHolder(), entityPlayer); - } - - private ModularUI.Builder createUITemplate(EntityPlayer player, int rowSize) { - ModularUI.Builder builder = ModularUI.builder(GuiTextures.BACKGROUND, 176, 18 + 18 * rowSize + 94) - .label(6, 6, getMetaFullName()); - - for (int y = 0; y < rowSize; y++) { - for (int x = 0; x < rowSize; x++) { - int index = y * rowSize + x; - builder.widget( - new TankWidget(fluidTankList.getTankAt(index), 89 - rowSize * 9 + x * 18, 18 + y * 18, 18, 18) - .setBackgroundTexture(GuiTextures.FLUID_SLOT) - .setContainerClicking(true, true) - .setAlwaysShowFull(true)); + + int backgroundWidth = 9 * 18 + 14; + int backgroundHeight = 18 + 18 * rowSize + 94; + + List> widgets = new ArrayList<>(); + for (int i = 0; i < rowSize; i++) { + widgets.add(new ArrayList<>()); + for (int j = 0; j < rowSize; j++) { + widgets.get(i).add(new GTFluidSlot().syncHandler(fluidTankList.getTankAt(i * rowSize + j)) + .background(GTGuiTextures.FLUID_SLOT)); } } - return builder.bindPlayerInventory(player.inventory, GuiTextures.SLOT, 7, 18 + 18 * rowSize + 12); + + BooleanSyncValue workingStateValue = new BooleanSyncValue(() -> workingEnabled, val -> workingEnabled = val); + return GTGuis.createPanel(this, backgroundWidth, backgroundHeight) + .child(IKey.lang(getMetaFullName()).asWidget().pos(5, 5)) + .child(SlotGroupWidget.playerInventory().left(7).bottom(7)) + .child(new Grid() + .top(18).height(rowSize * 18) + .minElementMargin(0, 0) + .minColWidth(18).minRowHeight(18) + .alignX(0.5f) + .matrix(widgets)) + .child(new ToggleButton() + .top(18 * 2).left(18 * 8 + 7) + .value(workingStateValue) + .overlay(GTGuiTextures.BUTTON_FLUID_OUTPUT) + .tooltip(t -> t.setAutoUpdate(true)) + .tooltipBuilder(t -> t.addLine(workingStateValue.getBoolValue() ? + IKey.lang("gregtech.gui.fluid_passthrough.enabled") : + IKey.lang("gregtech.gui.fluid_passthrough.disabled")))); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); tag.setTag("FluidInventory", fluidTankList.serializeNBT()); + tag.setBoolean("WorkingEnabled", workingEnabled); return tag; } @@ -135,6 +184,10 @@ public NBTTagCompound writeToNBT(NBTTagCompound tag) { public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); this.fluidTankList.deserializeNBT(tag.getCompoundTag("FluidInventory")); + // Passthrough hatches before this change won't have WorkingEnabled at all, so we need to check if it exists + if (tag.hasKey("WorkingEnabled")) { + this.workingEnabled = tag.getBoolean("WorkingEnabled"); + } } @Override @@ -174,7 +227,23 @@ public T getCapability(Capability capability, EnumFacing side) { } else if (side == getFrontFacing().getOpposite()) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(exportHandler); } else return null; + } else if (capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE) { + return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this); } return super.getCapability(capability, side); } + + @Override + public void writeInitialSyncData(PacketBuffer buf) { + super.writeInitialSyncData(buf); + + buf.writeBoolean(workingEnabled); + } + + @Override + public void receiveInitialSyncData(PacketBuffer buf) { + super.receiveInitialSyncData(buf); + + this.workingEnabled = buf.readBoolean(); + } } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityPassthroughHatchItem.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityPassthroughHatchItem.java index febd79c80d6..7f9e5dc3b1c 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityPassthroughHatchItem.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityPassthroughHatchItem.java @@ -1,22 +1,24 @@ package gregtech.common.metatileentities.multi.multiblockpart; +import gregtech.api.capability.GregtechDataCodes; +import gregtech.api.capability.GregtechTileCapabilities; +import gregtech.api.capability.IControllable; import gregtech.api.capability.impl.ItemHandlerProxy; import gregtech.api.capability.impl.NotifiableItemStackHandler; -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.ModularUI; -import gregtech.api.gui.widgets.SlotWidget; import gregtech.api.items.itemhandlers.GTItemStackHandler; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; import gregtech.api.metatileentity.multiblock.IPassthroughHatch; import gregtech.api.metatileentity.multiblock.MultiblockAbility; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; import gregtech.client.renderer.texture.Textures; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.PacketBuffer; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; @@ -29,21 +31,37 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Matrix4; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.api.widget.IWidget; +import com.cleanroommc.modularui.factory.PosGuiData; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.BooleanSyncValue; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.value.sync.SyncHandlers; +import com.cleanroommc.modularui.widgets.ItemSlot; +import com.cleanroommc.modularui.widgets.SlotGroupWidget; +import com.cleanroommc.modularui.widgets.ToggleButton; +import com.cleanroommc.modularui.widgets.layout.Grid; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.List; public class MetaTileEntityPassthroughHatchItem extends MetaTileEntityMultiblockPart implements IPassthroughHatch, - IMultiblockAbilityPart { + IMultiblockAbilityPart, + IControllable { private ItemStackHandler itemStackHandler; private IItemHandler importHandler; private IItemHandler exportHandler; + private boolean workingEnabled; + public MetaTileEntityPassthroughHatchItem(ResourceLocation metaTileEntityId, int tier) { super(metaTileEntityId, tier); + this.workingEnabled = true; initializeInventory(); } @@ -69,8 +87,24 @@ private int getInventorySize() { public void update() { super.update(); if (!getWorld().isRemote && getOffsetTimer() % 5 == 0) { - pushItemsIntoNearbyHandlers(getFrontFacing().getOpposite()); // outputs to back - pullItemsFromNearbyHandlers(getFrontFacing()); // inputs from front + if (workingEnabled) { + pushItemsIntoNearbyHandlers(getFrontFacing().getOpposite()); // outputs to back + pullItemsFromNearbyHandlers(getFrontFacing()); // inputs from front + } + } + } + + @Override + public boolean isWorkingEnabled() { + return this.workingEnabled; + } + + @Override + public void setWorkingEnabled(boolean workingEnabled) { + this.workingEnabled = workingEnabled; + World world = getWorld(); + if (world != null && !world.isRemote) { + writeCustomData(GregtechDataCodes.WORKING_ENABLED, buf -> buf.writeBoolean(workingEnabled)); } } @@ -100,31 +134,56 @@ protected IItemHandlerModifiable createImportItemHandler() { } @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - int rowSize = (int) Math.sqrt(getInventorySize()); - return createUITemplate(entityPlayer, rowSize) - .build(getHolder(), entityPlayer); + public boolean usesMui2() { + return true; } - private ModularUI.Builder createUITemplate(EntityPlayer player, int rowSize) { - ModularUI.Builder builder = ModularUI.builder(GuiTextures.BACKGROUND, 176, 18 + 18 * rowSize + 94) - .label(6, 6, getMetaFullName()); + @Override + public ModularPanel buildUI(PosGuiData guiData, PanelSyncManager guiSyncManager) { + int rowSize = (int) Math.sqrt(getInventorySize()); + + guiSyncManager.registerSlotGroup("item_inv", rowSize); + + int backgroundWidth = 9 * 18 + 14; + int backgroundHeight = 18 + 18 * rowSize + 94; - for (int y = 0; y < rowSize; y++) { - for (int x = 0; x < rowSize; x++) { - int index = y * rowSize + x; - builder.widget(new SlotWidget(itemStackHandler, index, - (88 - rowSize * 9 + x * 18), 18 + y * 18, true, true) - .setBackgroundTexture(GuiTextures.SLOT)); + List> widgets = new ArrayList<>(); + for (int i = 0; i < rowSize; i++) { + widgets.add(new ArrayList<>()); + for (int j = 0; j < rowSize; j++) { + widgets.get(i) + .add(new ItemSlot() + .slot(SyncHandlers.itemSlot(itemStackHandler, i * rowSize + j) + .slotGroup("item_inv") + .accessibility(true, true))); } } - return builder.bindPlayerInventory(player.inventory, GuiTextures.SLOT, 7, 18 + 18 * rowSize + 12); + + BooleanSyncValue workingStateValue = new BooleanSyncValue(() -> workingEnabled, val -> workingEnabled = val); + return GTGuis.createPanel(this, backgroundWidth, backgroundHeight) + .child(IKey.lang(getMetaFullName()).asWidget().pos(5, 5)) + .child(SlotGroupWidget.playerInventory().left(7).bottom(7)) + .child(new Grid() + .top(18).height(rowSize * 18) + .minElementMargin(0, 0) + .minColWidth(18).minRowHeight(18) + .alignX(0.5f) + .matrix(widgets)) + .child(new ToggleButton() + .top(18 * 4).left(18 * 8 + 7) + .value(workingStateValue) + .overlay(GTGuiTextures.BUTTON_ITEM_OUTPUT) + .tooltip(t -> t.setAutoUpdate(true)) + .tooltipBuilder(t -> t.addLine(workingStateValue.getBoolValue() ? + IKey.lang("gregtech.gui.item_passthrough.enabled") : + IKey.lang("gregtech.gui.item_passthrough.disabled")))); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); tag.setTag("Inventory", itemStackHandler.serializeNBT()); + tag.setBoolean("WorkingEnabled", workingEnabled); return tag; } @@ -132,6 +191,10 @@ public NBTTagCompound writeToNBT(NBTTagCompound tag) { public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); this.itemStackHandler.deserializeNBT(tag.getCompoundTag("Inventory")); + // Passthrough hatches before this change won't have WorkingEnabled at all, so we need to check if it exists + if (tag.hasKey("WorkingEnabled")) { + this.workingEnabled = tag.getBoolean("WorkingEnabled"); + } } @Override @@ -176,7 +239,23 @@ public T getCapability(Capability capability, EnumFacing side) { } else if (side == getFrontFacing().getOpposite()) { return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(exportHandler); } else return null; + } else if (capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE) { + return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this); } return super.getCapability(capability, side); } + + @Override + public void writeInitialSyncData(PacketBuffer buf) { + super.writeInitialSyncData(buf); + + buf.writeBoolean(workingEnabled); + } + + @Override + public void receiveInitialSyncData(PacketBuffer buf) { + super.receiveInitialSyncData(buf); + + this.workingEnabled = buf.readBoolean(); + } } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityAEHostablePart.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityAEHostablePart.java index c71b4acf74e..6212144fec7 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityAEHostablePart.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityAEHostablePart.java @@ -4,11 +4,14 @@ import gregtech.common.ConfigHolder; import gregtech.common.metatileentities.multi.multiblockpart.MetaTileEntityMultiblockNotifiablePart; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; +import net.minecraft.util.text.TextComponentTranslation; import appeng.api.AEApi; import appeng.api.networking.GridFlags; @@ -24,6 +27,7 @@ import appeng.me.helpers.BaseActionSource; import appeng.me.helpers.IGridProxyable; import appeng.me.helpers.MachineSource; +import codechicken.lib.raytracer.CuboidRayTraceResult; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -40,12 +44,15 @@ public abstract class MetaTileEntityAEHostablePart> extend private AENetworkProxy aeProxy; private int meUpdateTick; protected boolean isOnline; + private boolean allowExtraConnections; + protected boolean meStatusChanged = false; public MetaTileEntityAEHostablePart(ResourceLocation metaTileEntityId, int tier, boolean isExportHatch, Class> storageChannel) { super(metaTileEntityId, tier, isExportHatch); this.meUpdateTick = 0; this.storageChannel = storageChannel; + this.allowExtraConnections = false; } @Override @@ -76,6 +83,7 @@ public void writeInitialSyncData(PacketBuffer buf) { } buf.writeInt(this.meUpdateTick); buf.writeBoolean(this.isOnline); + buf.writeBoolean(this.allowExtraConnections); } @Override @@ -95,6 +103,7 @@ public void receiveInitialSyncData(PacketBuffer buf) { } this.meUpdateTick = buf.readInt(); this.isOnline = buf.readBoolean(); + this.allowExtraConnections = buf.readBoolean(); } @Override @@ -112,7 +121,7 @@ public void receiveCustomData(int dataId, PacketBuffer buf) { @NotNull @Override public AECableType getCableConnectionType(@NotNull AEPartLocation part) { - if (part.getFacing() != this.frontFacing) { + if (part.getFacing() != this.frontFacing && !this.allowExtraConnections) { return AECableType.NONE; } return AECableType.SMART; @@ -133,9 +142,7 @@ public AENetworkProxy getProxy() { @Override public void setFrontFacing(EnumFacing frontFacing) { super.setFrontFacing(frontFacing); - if (this.aeProxy != null) { - this.aeProxy.setValidSides(EnumSet.of(this.getFrontFacing())); - } + updateConnectableSides(); } @Override @@ -152,6 +159,9 @@ public boolean updateMEStatus() { if (this.isOnline != isOnline) { writeCustomData(UPDATE_ONLINE_STATUS, buf -> buf.writeBoolean(isOnline)); this.isOnline = isOnline; + this.meStatusChanged = true; + } else { + this.meStatusChanged = false; } } return this.isOnline; @@ -174,7 +184,7 @@ private AENetworkProxy createProxy() { AENetworkProxy proxy = new AENetworkProxy(holder, "mte_proxy", this.getStackForm(), true); proxy.setFlags(GridFlags.REQUIRE_CHANNEL); proxy.setIdlePowerUsage(ConfigHolder.compat.ae2.meHatchEnergyUsage); - proxy.setValidSides(EnumSet.of(this.getFrontFacing())); + proxy.setValidSides(getConnectableSides()); return proxy; } return null; @@ -198,4 +208,42 @@ protected IMEMonitor getMonitor() { return null; } } + + public EnumSet getConnectableSides() { + return this.allowExtraConnections ? EnumSet.allOf(EnumFacing.class) : EnumSet.of(getFrontFacing()); + } + + public void updateConnectableSides() { + if (this.aeProxy != null) { + this.aeProxy.setValidSides(getConnectableSides()); + } + } + + @Override + public boolean onWireCutterClick(EntityPlayer playerIn, EnumHand hand, EnumFacing facing, + CuboidRayTraceResult hitResult) { + this.allowExtraConnections = !this.allowExtraConnections; + updateConnectableSides(); + + if (!getWorld().isRemote) { + playerIn.sendStatusMessage(new TextComponentTranslation(this.allowExtraConnections ? + "gregtech.machine.me.extra_connections.enabled" : "gregtech.machine.me.extra_connections.disabled"), + true); + } + + return true; + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + data.setBoolean("AllowExtraConnections", this.allowExtraConnections); + return data; + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + this.allowExtraConnections = data.getBoolean("AllowExtraConnections"); + } } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEInputBus.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEInputBus.java index 4c65d935e7f..9c089332d5c 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEInputBus.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEInputBus.java @@ -320,6 +320,7 @@ public void addInformation(ItemStack stack, @Nullable World player, @NotNull Lis tooltip.add(I18n.format("gregtech.machine.me.item_import.tooltip")); tooltip.add(I18n.format("gregtech.machine.me_import_item_hatch.configs.tooltip")); tooltip.add(I18n.format("gregtech.machine.copy_paste.tooltip")); + tooltip.add(I18n.format("gregtech.machine.me.extra_connections.tooltip")); tooltip.add(I18n.format("gregtech.universal.enabled")); } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEInputHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEInputHatch.java index ebbeb73c5ae..c84fb2f58bd 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEInputHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEInputHatch.java @@ -260,6 +260,7 @@ public void addInformation(ItemStack stack, @Nullable World player, @NotNull Lis tooltip.add(I18n.format("gregtech.machine.me.fluid_import.tooltip")); tooltip.add(I18n.format("gregtech.machine.me_import_fluid_hatch.configs.tooltip")); tooltip.add(I18n.format("gregtech.machine.copy_paste.tooltip")); + tooltip.add(I18n.format("gregtech.machine.me.extra_connections.tooltip")); tooltip.add(I18n.format("gregtech.universal.enabled")); } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEOutputBus.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEOutputBus.java index 853321014f9..9e008b857e3 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEOutputBus.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEOutputBus.java @@ -186,6 +186,7 @@ public void addInformation(ItemStack stack, @Nullable World player, @NotNull Lis tooltip.add(I18n.format("gregtech.machine.item_bus.export.tooltip")); tooltip.add(I18n.format("gregtech.machine.me.item_export.tooltip")); tooltip.add(I18n.format("gregtech.machine.me.item_export.tooltip.2")); + tooltip.add(I18n.format("gregtech.machine.me.extra_connections.tooltip")); tooltip.add(I18n.format("gregtech.universal.enabled")); } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEOutputHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEOutputHatch.java index f22c489909b..26a8fcc7947 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEOutputHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEOutputHatch.java @@ -188,6 +188,7 @@ public void addInformation(ItemStack stack, @Nullable World player, @NotNull Lis tooltip.add(I18n.format("gregtech.machine.fluid_hatch.export.tooltip")); tooltip.add(I18n.format("gregtech.machine.me.fluid_export.tooltip")); tooltip.add(I18n.format("gregtech.machine.me.fluid_export.tooltip.2")); + tooltip.add(I18n.format("gregtech.machine.me.extra_connections.tooltip")); tooltip.add(I18n.format("gregtech.universal.enabled")); } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEStockingBus.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEStockingBus.java index fdc0d15eb25..5bc9848c8ad 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEStockingBus.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEStockingBus.java @@ -64,9 +64,22 @@ protected ExportOnlyAEStockingItemList getAEItemHandler() { @Override public void update() { super.update(); - if (!getWorld().isRemote && isWorkingEnabled() && autoPull && getOffsetTimer() % 100 == 0) { - refreshList(); - syncME(); + if (!getWorld().isRemote) { + if (isWorkingEnabled() && autoPull && getOffsetTimer() % 100 == 0) { + refreshList(); + syncME(); + } + + // Immediately clear cached items if the status changed, to prevent running recipes while offline + if (this.meStatusChanged && !this.isOnline) { + if (autoPull) { + clearInventory(0); + } else { + for (int i = 0; i < CONFIG_SIZE; i++) { + getAEItemHandler().getInventory()[i].setStack(null); + } + } + } } } @@ -360,6 +373,7 @@ public void addInformation(ItemStack stack, @Nullable World player, @NotNull Lis tooltip.add(I18n.format("gregtech.machine.me_import_item_hatch.configs.tooltip")); tooltip.add(I18n.format("gregtech.machine.copy_paste.tooltip")); tooltip.add(I18n.format("gregtech.machine.me.stocking_item.tooltip.2")); + tooltip.add(I18n.format("gregtech.machine.me.extra_connections.tooltip")); tooltip.add(I18n.format("gregtech.universal.enabled")); } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEStockingHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEStockingHatch.java index bdafdd1690f..5f92ca70bce 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEStockingHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/appeng/MetaTileEntityMEStockingHatch.java @@ -64,9 +64,22 @@ protected ExportOnlyAEStockingFluidList getAEFluidHandler() { @Override public void update() { super.update(); - if (!getWorld().isRemote && isWorkingEnabled() && autoPull && getOffsetTimer() % 100 == 0) { - refreshList(); - syncME(); + if (!getWorld().isRemote) { + if (isWorkingEnabled() && autoPull && getOffsetTimer() % 100 == 0) { + refreshList(); + syncME(); + } + + // Immediately clear cached fluids if the status changed, to prevent running recipes while offline + if (this.meStatusChanged && !this.isOnline) { + if (autoPull) { + this.getAEFluidHandler().clearConfig(); + } else { + for (int i = 0; i < CONFIG_SIZE; i++) { + getAEFluidHandler().getInventory()[i].setStack(null); + } + } + } } } @@ -265,6 +278,7 @@ public void addInformation(ItemStack stack, @Nullable World player, @NotNull Lis tooltip.add(I18n.format("gregtech.machine.me_import_fluid_hatch.configs.tooltip")); tooltip.add(I18n.format("gregtech.machine.copy_paste.tooltip")); tooltip.add(I18n.format("gregtech.machine.me.stocking_fluid.tooltip.2")); + tooltip.add(I18n.format("gregtech.machine.me.extra_connections.tooltip")); tooltip.add(I18n.format("gregtech.universal.enabled")); } diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/hpca/MetaTileEntityHPCAComponent.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/hpca/MetaTileEntityHPCAComponent.java index 35a257ad2cf..dba69e698e8 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/hpca/MetaTileEntityHPCAComponent.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/hpca/MetaTileEntityHPCAComponent.java @@ -5,7 +5,6 @@ import gregtech.api.capability.IHPCAComponentHatch; import gregtech.api.capability.IHPCAComputationProvider; import gregtech.api.capability.IHPCACoolantProvider; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.multiblock.IMultiblockAbilityPart; import gregtech.api.metatileentity.multiblock.MultiblockAbility; import gregtech.api.unification.material.Materials; @@ -62,11 +61,6 @@ protected boolean openGUIOnRightClick() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public MultiblockAbility getAbility() { return MultiblockAbility.HPCA_COMPONENT; diff --git a/src/main/java/gregtech/common/metatileentities/primitive/MetaTileEntityCharcoalPileIgniter.java b/src/main/java/gregtech/common/metatileentities/primitive/MetaTileEntityCharcoalPileIgniter.java index 1439a5c5554..ecbd0241f1d 100644 --- a/src/main/java/gregtech/common/metatileentities/primitive/MetaTileEntityCharcoalPileIgniter.java +++ b/src/main/java/gregtech/common/metatileentities/primitive/MetaTileEntityCharcoalPileIgniter.java @@ -5,7 +5,6 @@ import gregtech.api.capability.GregtechTileCapabilities; import gregtech.api.capability.IMultiblockController; import gregtech.api.capability.IWorkable; -import gregtech.api.gui.ModularUI; import gregtech.api.items.metaitem.MetaItem; import gregtech.api.items.metaitem.stats.IItemBehaviour; import gregtech.api.metatileentity.MetaTileEntity; @@ -23,7 +22,6 @@ import net.minecraft.block.Block; import net.minecraft.client.resources.I18n; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemFireball; @@ -337,11 +335,6 @@ public ICubeRenderer getBaseTexture(IMultiblockPart sourcePart) { return Textures.BRONZE_PLATED_BRICKS; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override protected boolean openGUIOnRightClick() { return false; diff --git a/src/main/java/gregtech/common/metatileentities/steam/SteamMiner.java b/src/main/java/gregtech/common/metatileentities/steam/SteamMiner.java index e3d3c75cb12..3f70bf75aaf 100644 --- a/src/main/java/gregtech/common/metatileentities/steam/SteamMiner.java +++ b/src/main/java/gregtech/common/metatileentities/steam/SteamMiner.java @@ -254,6 +254,7 @@ public void receiveCustomData(int dataId, PacketBuffer buf) { this.minerLogic.receiveCustomData(dataId, buf); } + @Override @SideOnly(Side.CLIENT) public Pair getParticleTexture() { return Pair.of(Textures.STEAM_CASING_BRONZE.getSpriteOnSide(SimpleSidedCubeRenderer.RenderSide.TOP), diff --git a/src/main/java/gregtech/common/metatileentities/steam/boiler/SteamBoiler.java b/src/main/java/gregtech/common/metatileentities/steam/boiler/SteamBoiler.java index b88dd4e658d..3d63eb651ab 100644 --- a/src/main/java/gregtech/common/metatileentities/steam/boiler/SteamBoiler.java +++ b/src/main/java/gregtech/common/metatileentities/steam/boiler/SteamBoiler.java @@ -216,7 +216,7 @@ private void updateCurrentTemperature() { if (fuelBurnTimeLeft % 2 == 0 && currentTemperature < getMaxTemperate()) currentTemperature++; fuelBurnTimeLeft -= isHighPressure ? 2 : 1; - if (fuelBurnTimeLeft == 0) { + if (fuelBurnTimeLeft <= 0) { this.fuelMaxBurnTime = 0; this.timeBeforeCoolingDown = getCooldownInterval(); // boiler has no fuel now, so queue burning state update @@ -306,6 +306,10 @@ public double getTemperaturePercent() { return currentTemperature / (getMaxTemperate() * 1.0); } + public int getCurrentTemperature() { + return currentTemperature; + } + public double getFuelLeftPercent() { return fuelMaxBurnTime == 0 ? 0.0 : fuelBurnTimeLeft / (fuelMaxBurnTime * 1.0); } diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeChest.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeChest.java index e34f104d679..3829ae30586 100644 --- a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeChest.java +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeChest.java @@ -33,6 +33,7 @@ import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Matrix4; import org.apache.commons.lang3.ArrayUtils; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -42,26 +43,13 @@ public class MetaTileEntityCreativeChest extends MetaTileEntityQuantumChest { private int itemsPerCycle = 1; private int ticksPerCycle = 1; - private final GTItemStackHandler handler = new GTItemStackHandler(this, 1) { - - @Override - protected int getStackLimit(int slot, ItemStack stack) { - return 1; - } - - @Override - public void setStackInSlot(int slot, ItemStack stack) { - this.validateSlotIndex(slot); - stack.setCount(1); - this.stacks.set(slot, stack); - this.onContentsChanged(slot); - } - }; + private final GTItemStackHandler handler; private boolean active; public MetaTileEntityCreativeChest(ResourceLocation metaTileEntityId) { super(metaTileEntityId, GTValues.MAX, 0); + this.handler = new CreativeItemStackHandler(1); } @Override @@ -72,7 +60,10 @@ public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, this); Textures.CREATIVE_CONTAINER_OVERLAY.renderSided(EnumFacing.UP, renderState, translation, pipeline); Textures.PIPE_OUT_OVERLAY.renderSided(this.getOutputFacing(), renderState, translation, pipeline); - Textures.ITEM_OUTPUT_OVERLAY.renderSided(this.getOutputFacing(), renderState, translation, pipeline); + if (!isConnected() && active) { + Textures.ITEM_OUTPUT_OVERLAY.renderSided(this.getOutputFacing(), renderState, translation, pipeline); + } + renderIndicatorOverlay(renderState, translation, pipeline); } @Override @@ -110,8 +101,14 @@ protected ModularUI createUI(EntityPlayer entityPlayer) { }).setMaxLength(11).setNumbersOnly(1, Integer.MAX_VALUE)); builder.label(7, 65, "gregtech.creative.chest.tpc"); - builder.widget(new CycleButtonWidget(7, 101, 162, 20, () -> active, value -> active = value, - "gregtech.creative.activity.off", "gregtech.creative.activity.on")); + builder.widget(new CycleButtonWidget(7, 101, 162, 20, () -> active, value -> { + active = value; + scheduleRenderUpdate(); + var c = getQuantumController(); + if (c != null) c.updateHandler(); + }, "gregtech.creative.activity.off", "gregtech.creative.activity.on")); + + builder.widget(createConnectedGui(6)); return builder.build(getHolder(), entityPlayer); } @@ -122,7 +119,7 @@ public void update() { this.virtualItemStack = stack; // For rendering purposes super.update(); if (ticksPerCycle == 0 || getOffsetTimer() % ticksPerCycle != 0) return; - if (getWorld().isRemote || !active || stack.isEmpty()) return; + if (getWorld().isRemote || !active || stack.isEmpty() || isConnected()) return; TileEntity tile = getNeighbor(getOutputFacing()); if (tile != null) { @@ -189,8 +186,44 @@ public void addInformation(ItemStack stack, @Nullable World player, List } @Override - public void receiveInitialSyncData(PacketBuffer buf) { + public void receiveInitialSyncData(@NotNull PacketBuffer buf) { super.receiveInitialSyncData(buf); this.handler.setStackInSlot(0, this.virtualItemStack); } + + @Override + public IItemHandler getTypeValue() { + return this.handler; + } + + protected class CreativeItemStackHandler extends GTItemStackHandler { + + CreativeItemStackHandler(int size) { + super(MetaTileEntityCreativeChest.this, size); + } + + @NotNull + @Override + public ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) { + return stack; + } + + @NotNull + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate) { + if (!active) return ItemStack.EMPTY; + return GTUtility.copy(Math.min(amount, itemsPerCycle), getStackInSlot(0)); + } + + @Override + protected int getStackLimit(int slot, ItemStack stack) { + return 1; + } + + @Override + public void setStackInSlot(int slot, ItemStack stack) { + super.setStackInSlot(slot, stack); + virtualItemStack = GTUtility.copy(1, stack); + } + } } diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeEnergy.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeEnergy.java index 23e3a09ebba..33e9469453d 100644 --- a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeEnergy.java +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeEnergy.java @@ -146,7 +146,7 @@ protected ModularUI createUI(EntityPlayer entityPlayer) { } else { voltage = V[MAX]; amps = Integer.MAX_VALUE; - setTier = 14; + setTier = MAX; } }, "gregtech.creative.energy.sink", "gregtech.creative.energy.source")); @@ -157,6 +157,7 @@ public void setActive(boolean active) { this.active = active; if (!getWorld().isRemote) { writeCustomData(GregtechDataCodes.UPDATE_ACTIVE, buf -> buf.writeBoolean(active)); + markDirty(); } } diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeTank.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeTank.java index 3e93c1bcbd5..a40d0b54bf2 100644 --- a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeTank.java +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityCreativeTank.java @@ -25,7 +25,9 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.fluids.capability.FluidTankPropertiesWrapper; import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.fluids.capability.IFluidTankProperties; import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.ColourMultiplier; @@ -44,7 +46,7 @@ public class MetaTileEntityCreativeTank extends MetaTileEntityQuantumTank { public MetaTileEntityCreativeTank(ResourceLocation metaTileEntityId) { super(metaTileEntityId, GTValues.MAX, -1); - this.fluidTank = new FluidTank(1); + this.fluidTank = new CreativeFluidTank(1); } @Override @@ -56,12 +58,13 @@ public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, Textures.CREATIVE_CONTAINER_OVERLAY.renderSided(EnumFacing.UP, renderState, translation, pipeline); if (this.getOutputFacing() != null) { Textures.PIPE_OUT_OVERLAY.renderSided(this.getOutputFacing(), renderState, translation, pipeline); - if (isAutoOutputFluids()) { + if (!isConnected() && active) { Textures.FLUID_OUTPUT_OVERLAY.renderSided(this.getOutputFacing(), renderState, translation, pipeline); } } QuantumStorageRenderer.renderTankFluid(renderState, translation, pipeline, this.fluidTank, getWorld(), getPos(), getFrontFacing()); + renderIndicatorOverlay(renderState, translation, pipeline); } @Override @@ -100,8 +103,14 @@ protected ModularUI createUI(EntityPlayer entityPlayer) { }).setMaxLength(11).setNumbersOnly(1, Integer.MAX_VALUE)); builder.label(7, 65, "gregtech.creative.tank.tpc"); - builder.widget(new CycleButtonWidget(7, 101, 162, 20, () -> active, value -> active = value, - "gregtech.creative.activity.off", "gregtech.creative.activity.on")); + builder.widget(new CycleButtonWidget(7, 101, 162, 20, () -> active, value -> { + active = value; + scheduleRenderUpdate(); + var c = getQuantumController(); + if (c != null) c.updateHandler(); + }, "gregtech.creative.activity.off", "gregtech.creative.activity.on")); + + builder.widget(createConnectedGui(6)); return builder.build(getHolder(), entityPlayer); } @@ -110,7 +119,7 @@ protected ModularUI createUI(EntityPlayer entityPlayer) { public void update() { super.update(); if (ticksPerCycle == 0 || getOffsetTimer() % ticksPerCycle != 0 || fluidTank.getFluid() == null || - getWorld().isRemote || !active) + getWorld().isRemote || !active || isConnected()) return; TileEntity tile = getNeighbor(getOutputFacing()); @@ -120,12 +129,7 @@ public void update() { if (fluidHandler == null || fluidHandler.getTankProperties().length == 0) return; - FluidStack stack = fluidTank.getFluid().copy(); - stack.amount = mBPerCycle; - int canInsertAmount = fluidHandler.fill(stack, false); - stack.amount = Math.min(mBPerCycle, canInsertAmount); - - fluidHandler.fill(stack, true); + fluidHandler.fill(fluidTank.drain(mBPerCycle, false), true); } } @@ -165,4 +169,63 @@ public void addInformation(ItemStack stack, @Nullable World player, List I18n.format("gregtech.creative_tooltip.2") + I18n.format("gregtech.creative_tooltip.3")); // do not append the normal tooltips } + + private class CreativeFluidTank extends FluidTank { + + public CreativeFluidTank(int capacity) { + super(capacity); + } + + @Override + public IFluidTankProperties[] getTankProperties() { + if (this.tankProperties == null) { + this.tankProperties = new IFluidTankProperties[] { + new FluidTankPropertiesWrapper(fluidTank) { + + @Override + public int getCapacity() { + return mBPerCycle; + } + + @Override + public FluidStack getContents() { + if (!active) return null; + var f = super.getContents(); + if (f != null) f.amount = mBPerCycle; + return f; + } + + @Override + public boolean canDrainFluidType(FluidStack fluidStack) { + if (!active) return false; + return super.canDrainFluidType(fluidStack); + } + } + }; + } + return this.tankProperties; + } + + @Override + public FluidStack drain(FluidStack resource, boolean doDrain) { + return drain(resource == null ? 0 : resource.amount, doDrain); + } + + @Override + public FluidStack drain(int maxDrain, boolean doDrain) { + if (!active) return null; + + var f = super.drain(maxDrain, false); + if (f != null) { + f = f.copy(); + f.amount = Math.min(mBPerCycle, maxDrain); + } + return f; + } + + @Override + public int fill(FluidStack resource, boolean doFill) { + return 0; + } + } } diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityDrum.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityDrum.java index 2292338425f..a478d5ac3b6 100644 --- a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityDrum.java +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityDrum.java @@ -3,7 +3,6 @@ import gregtech.api.capability.IPropertyFluidFilter; import gregtech.api.capability.impl.FilteredFluidHandler; import gregtech.api.capability.impl.GTFluidHandlerItemStack; -import gregtech.api.gui.ModularUI; import gregtech.api.items.toolitem.ToolClasses; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; @@ -297,11 +296,6 @@ public boolean showToolUsages() { return false; } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public NBTTagCompound writeToNBT(NBTTagCompound data) { super.writeToNBT(data); diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityLongDistanceEndpoint.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityLongDistanceEndpoint.java index 600092ddb2b..84ce773b017 100644 --- a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityLongDistanceEndpoint.java +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityLongDistanceEndpoint.java @@ -5,7 +5,6 @@ import gregtech.api.pipenet.longdist.ILDEndpoint; import gregtech.api.pipenet.longdist.LongDistanceNetwork; import gregtech.api.pipenet.longdist.LongDistancePipeType; -import gregtech.common.ConfigHolder; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.EntityPlayer; @@ -213,15 +212,13 @@ protected boolean openGUIOnRightClick() { @Override public void addInformation(ItemStack stack, @Nullable World player, @NotNull List tooltip, boolean advanced) { + super.addInformation(stack, player, tooltip, advanced); tooltip.add(I18n.format("gregtech.machine.endpoint.tooltip.1")); tooltip.add(I18n.format("gregtech.machine.endpoint.tooltip.2")); tooltip.add(I18n.format("gregtech.machine.endpoint.tooltip.3")); if (pipeType.getMinLength() > 0) { tooltip.add(I18n.format("gregtech.machine.endpoint.tooltip.min_length", pipeType.getMinLength())); } - if (ConfigHolder.machines.doTerrainExplosion && getIsWeatherOrTerrainResistant()) { - tooltip.add(I18n.format("gregtech.universal.tooltip.terrain_resist")); - } } @Override diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumChest.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumChest.java index f51405428e6..d6646cb40de 100644 --- a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumChest.java +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumChest.java @@ -61,7 +61,7 @@ import static gregtech.api.capability.GregtechDataCodes.*; -public class MetaTileEntityQuantumChest extends MetaTileEntity +public class MetaTileEntityQuantumChest extends MetaTileEntityQuantumStorage implements ITieredMetaTileEntity, IActiveOutputSide, IFastRenderMetaTileEntity { private final int tier; @@ -111,6 +111,7 @@ public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, Textures.ITEM_OUTPUT_OVERLAY.renderSided(outputFacing, renderState, translation, pipeline); } } + renderIndicatorOverlay(renderState, translation, pipeline); } @Override @@ -159,7 +160,10 @@ public void update() { } if (previousStack == null || !areItemStackIdentical(previousStack, virtualItemStack)) { - writeCustomData(UPDATE_ITEM, buf -> buf.writeItemStack(virtualItemStack)); + writeCustomData(UPDATE_ITEM, buf -> { + virtualItemStack.setCount(1); + buf.writeItemStack(virtualItemStack); + }); previousStack = virtualItemStack; } if (previousStackSize != itemsStoredInside) { @@ -187,7 +191,6 @@ protected void addDisplayInformation(List textList) { @Override public void addInformation(ItemStack stack, @Nullable World player, List tooltip, boolean advanced) { super.addInformation(stack, player, tooltip, advanced); - tooltip.add(I18n.format("gregtech.machine.quantum_chest.tooltip")); tooltip.add(I18n.format("gregtech.universal.tooltip.item_storage_total", maxStoredItems)); NBTTagCompound compound = stack.getTagCompound(); @@ -350,6 +353,8 @@ protected ModularUI createUI(EntityPlayer entityPlayer) { .shouldUseBaseBackground()) .bindPlayerInventory(entityPlayer.inventory); + builder.widget(createConnectedGui(64)); + return builder.build(getHolder(), entityPlayer); } @@ -382,17 +387,18 @@ public boolean onWrenchClick(EntityPlayer playerIn, EnumHand hand, EnumFacing fa } @Override - public void writeInitialSyncData(PacketBuffer buf) { + public void writeInitialSyncData(@NotNull PacketBuffer buf) { super.writeInitialSyncData(buf); buf.writeByte(getOutputFacing().getIndex()); buf.writeBoolean(autoOutputItems); + this.virtualItemStack.setCount(1); buf.writeItemStack(virtualItemStack); buf.writeLong(itemsStoredInside); buf.writeBoolean(voiding); } @Override - public void receiveInitialSyncData(PacketBuffer buf) { + public void receiveInitialSyncData(@NotNull PacketBuffer buf) { super.receiveInitialSyncData(buf); this.outputFacing = EnumFacing.VALUES[buf.readByte()]; this.autoOutputItems = buf.readBoolean(); @@ -414,7 +420,7 @@ public boolean isValidFrontFacing(EnumFacing facing) { } @Override - public void receiveCustomData(int dataId, PacketBuffer buf) { + public void receiveCustomData(int dataId, @NotNull PacketBuffer buf) { super.receiveCustomData(dataId, buf); if (dataId == UPDATE_OUTPUT_FACING) { this.outputFacing = EnumFacing.VALUES[buf.readByte()]; @@ -548,6 +554,16 @@ public void setAllowInputFromOutputSide(boolean allowInputFromOutputSide) { } } + @Override + public Type getType() { + return Type.ITEM; + } + + @Override + public IItemHandler getTypeValue() { + return this.combinedInventory; + } + @Override public AxisAlignedBB getRenderBoundingBox() { return new AxisAlignedBB(getPos()); diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumExtender.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumExtender.java new file mode 100644 index 00000000000..cc37c7385ca --- /dev/null +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumExtender.java @@ -0,0 +1,81 @@ +package gregtech.common.metatileentities.storage; + +import gregtech.api.capability.GregtechDataCodes; +import gregtech.api.capability.IDualHandler; +import gregtech.api.gui.ModularUI; +import gregtech.api.metatileentity.MetaTileEntity; +import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; +import gregtech.api.util.GTUtility; +import gregtech.client.renderer.texture.Textures; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.ResourceLocation; + +import codechicken.lib.render.CCRenderState; +import codechicken.lib.render.pipeline.ColourMultiplier; +import codechicken.lib.render.pipeline.IVertexOperation; +import codechicken.lib.vec.Matrix4; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.NotNull; + +public class MetaTileEntityQuantumExtender extends MetaTileEntityQuantumStorage { + + public MetaTileEntityQuantumExtender(ResourceLocation metaTileEntityId) { + super(metaTileEntityId); + } + + @Override + public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { + return new MetaTileEntityQuantumExtender(metaTileEntityId); + } + + @Override + public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline) { + var newPipeline = ArrayUtils.add(pipeline, + new ColourMultiplier(GTUtility.convertRGBtoOpaqueRGBA_CL(getPaintingColorForRendering()))); + if (isConnected() && getQuantumController().isPowered()) { + Textures.QUANTUM_EXTENDER_ACTIVE.render(renderState, translation, newPipeline); + } else { + Textures.QUANTUM_EXTENDER.render(renderState, translation, newPipeline); + } + } + + @Override + public Pair getParticleTexture() { + return Pair.of(Textures.QUANTUM_EXTENDER.getParticleSprite(), getPaintingColorForRendering()); + } + + @Override + protected ModularUI createUI(EntityPlayer entityPlayer) { + return null; + } + + @Override + protected boolean openGUIOnRightClick() { + return false; + } + + @Override + public boolean hasFrontFacing() { + return false; + } + + @Override + public Type getType() { + return Type.EXTENDER; + } + + @Override + public IDualHandler getTypeValue() { + return null; + } + + @Override + public void receiveCustomData(int dataId, @NotNull PacketBuffer buf) { + super.receiveCustomData(dataId, buf); + if (dataId == GregtechDataCodes.REMOVE_CONTROLLER) scheduleRenderUpdate(); + } +} diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumProxy.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumProxy.java new file mode 100644 index 00000000000..42deb4d91aa --- /dev/null +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumProxy.java @@ -0,0 +1,105 @@ +package gregtech.common.metatileentities.storage; + +import gregtech.api.capability.IDualHandler; +import gregtech.api.capability.IQuantumController; +import gregtech.api.gui.ModularUI; +import gregtech.api.metatileentity.MetaTileEntity; +import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; +import gregtech.api.util.GTUtility; +import gregtech.client.renderer.texture.Textures; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.items.CapabilityItemHandler; + +import codechicken.lib.render.CCRenderState; +import codechicken.lib.render.pipeline.ColourMultiplier; +import codechicken.lib.render.pipeline.IVertexOperation; +import codechicken.lib.vec.Matrix4; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.Nullable; + +public class MetaTileEntityQuantumProxy extends MetaTileEntityQuantumStorage { + + public MetaTileEntityQuantumProxy(ResourceLocation metaTileEntityId) { + super(metaTileEntityId); + } + + @Override + public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { + return new MetaTileEntityQuantumProxy(metaTileEntityId); + } + + @Override + public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline) { + var newPipeline = ArrayUtils.add(pipeline, + new ColourMultiplier(GTUtility.convertRGBtoOpaqueRGBA_CL(getPaintingColorForRendering()))); + if (isConnected() && getQuantumController().isPowered()) { + Textures.QUANTUM_PROXY_ACTIVE.render(renderState, translation, newPipeline); + } else { + Textures.QUANTUM_PROXY_INACTIVE.render(renderState, translation, newPipeline); + } + } + + @Override + public Pair getParticleTexture() { + return Pair.of(Textures.QUANTUM_PROXY_INACTIVE.getParticleSprite(), getPaintingColorForRendering()); + } + + @Override + protected ModularUI createUI(EntityPlayer entityPlayer) { + return null; + } + + @Override + protected boolean openGUIOnRightClick() { + return false; + } + + @Override + public boolean hasFrontFacing() { + return false; + } + + @Override + public T getCapability(Capability capability, EnumFacing side) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || + capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { + var controller = getPoweredController(); + if (controller != null) + return controller.getCapability(capability, side); + } + return super.getCapability(capability, side); + } + + @Override + public void setDisconnected() { + super.setDisconnected(); + notifyBlockUpdate(); + } + + @Override + public Type getType() { + return Type.PROXY; + } + + @Override + public IDualHandler getTypeValue() { + var controller = getPoweredController(); + if (controller == null) return null; + return controller.getHandler(); + } + + @Nullable + private IQuantumController getPoweredController() { + if (!isConnected()) return null; + var controller = getQuantumController(); + if (controller == null || !controller.isPowered()) return null; + return controller; + } +} diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumStorage.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumStorage.java new file mode 100644 index 00000000000..d57f907af8d --- /dev/null +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumStorage.java @@ -0,0 +1,216 @@ +package gregtech.common.metatileentities.storage; + +import gregtech.api.capability.GregtechDataCodes; +import gregtech.api.capability.IQuantumController; +import gregtech.api.capability.IQuantumStorage; +import gregtech.api.gui.GuiTextures; +import gregtech.api.gui.widgets.ClickButtonWidget; +import gregtech.api.metatileentity.MetaTileEntity; +import gregtech.api.util.GTUtility; +import gregtech.client.renderer.handler.BlockPosHighlightRenderer; +import gregtech.client.renderer.texture.Textures; +import gregtech.client.renderer.texture.cube.SimpleOverlayRenderer; +import gregtech.client.utils.RenderUtil; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.I18n; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import codechicken.lib.render.CCRenderState; +import codechicken.lib.render.pipeline.IVertexOperation; +import codechicken.lib.vec.Matrix4; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.ref.WeakReference; +import java.util.List; + +public abstract class MetaTileEntityQuantumStorage extends MetaTileEntity implements IQuantumStorage { + + /** not synced, server only. lazily initialized from pos */ + private WeakReference controller = new WeakReference<>(null); + + /** synced, server and client */ + private BlockPos controllerPos; + + private ClickButtonWidget connectedIcon; + + public MetaTileEntityQuantumStorage(ResourceLocation metaTileEntityId) { + super(metaTileEntityId); + } + + @SuppressWarnings("DataFlowIssue") + @SideOnly(Side.CLIENT) + protected void renderIndicatorOverlay(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline) { + SimpleOverlayRenderer texture; + if (isConnected()) { + texture = getQuantumController().isPowered() ? + Textures.QUANTUM_INDICATOR_POWERED : + Textures.QUANTUM_INDICATOR_CONNECTED; + } else { + texture = Textures.QUANTUM_INDICATOR; + } + texture.renderSided(getFrontFacing(), renderState, RenderUtil.adjustTrans(translation, getFrontFacing(), 1), + pipeline); + } + + @Override + public void setConnected(IQuantumController controller) { + if (getWorld().isRemote) return; + + if (!controller.getPos().equals(controllerPos)) { + this.controller = new WeakReference<>(controller); + this.controllerPos = controller.getPos(); + writeCustomData(GregtechDataCodes.UPDATE_CONTROLLER_POS, buf -> buf.writeBlockPos(controllerPos)); + markDirty(); + } + } + + @Override + public void setDisconnected() { + if (getWorld().isRemote) return; + + controller.clear(); + controllerPos = null; + writeCustomData(GregtechDataCodes.REMOVE_CONTROLLER, buf -> {}); + markDirty(); + } + + // use this to make sure controller is properly initialized + @Override + public final IQuantumController getQuantumController() { + if (isConnected()) { + if (controller.get() != null) return controller.get(); + MetaTileEntity mte = GTUtility.getMetaTileEntity(getWorld(), controllerPos); + if (mte instanceof IQuantumController quantumController) { + controller = new WeakReference<>(quantumController); + return quantumController; + } else { + // controller is no longer there for some reason, need to disconnect + setDisconnected(); + tryFindNetwork(); + } + } + return null; + } + + @Override + public BlockPos getControllerPos() { + return controllerPos; + } + + @Override + public void onRemoval() { + if (!getWorld().isRemote && isConnected()) { + IQuantumController controller = getQuantumController(); + if (controller != null) controller.rebuildNetwork(); + } + } + + @Override + public void onPlacement(@Nullable EntityLivingBase placer) { + super.onPlacement(placer); + if (getWorld() == null || getWorld().isRemote) + return; + + // add to the network if an adjacent block is part of a network + // use whatever we find first, merging networks is not supported + tryFindNetwork(); + } + + @Override + public void writeInitialSyncData(@NotNull PacketBuffer buf) { + super.writeInitialSyncData(buf); + buf.writeBoolean(controllerPos != null); + if (controllerPos != null) { + buf.writeBlockPos(controllerPos); + } + } + + @Override + public void receiveInitialSyncData(@NotNull PacketBuffer buf) { + super.receiveInitialSyncData(buf); + if (buf.readBoolean()) { + controllerPos = buf.readBlockPos(); + scheduleRenderUpdate(); + } + } + + @Override + public void receiveCustomData(int dataId, @NotNull PacketBuffer buf) { + super.receiveCustomData(dataId, buf); + if (dataId == GregtechDataCodes.UPDATE_CONTROLLER_POS) { + this.controllerPos = buf.readBlockPos(); + this.controller.clear(); + + if (this.connectedIcon != null) { + this.connectedIcon.setButtonTexture(GuiTextures.GREGTECH_LOGO); + this.connectedIcon.setTooltipText("gregtech.machine.quantum_storage.connected", + controllerPos.getX(), controllerPos.getZ(), controllerPos.getY()); + } + scheduleRenderUpdate(); + } else if (dataId == GregtechDataCodes.REMOVE_CONTROLLER) { + this.controllerPos = null; + this.controller.clear(); + if (this.connectedIcon != null) { + this.connectedIcon.setButtonTexture(GuiTextures.GREGTECH_LOGO_DARK); + this.connectedIcon.setTooltipText("gregtech.machine.quantum_storage.disconnected"); + } + scheduleRenderUpdate(); + } else if (dataId == GregtechDataCodes.LOCATE_CONTROLLER) { + // tell controller to highlight + BlockPosHighlightRenderer.renderBlockBoxHighLight(getControllerPos(), 6000, 1500); + Minecraft.getMinecraft().player.closeScreen(); + } + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound data) { + NBTTagCompound tagCompound = super.writeToNBT(data); + tagCompound.setBoolean("HasController", controllerPos != null); + if (controllerPos != null) { + tagCompound.setLong("ControllerPos", controllerPos.toLong()); + } + return tagCompound; + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + if (data.getBoolean("HasController")) { + this.controllerPos = BlockPos.fromLong(data.getLong("ControllerPos")); + } + } + + protected ClickButtonWidget createConnectedGui(int y) { + connectedIcon = new ClickButtonWidget(151, y, 18, 18, "", + clickData -> { + if (isConnected()) + writeCustomData(GregtechDataCodes.LOCATE_CONTROLLER, buffer -> {}); + }); + connectedIcon.setButtonTexture(isConnected() ? GuiTextures.GREGTECH_LOGO : GuiTextures.GREGTECH_LOGO_DARK); + + if (isConnected()) { + connectedIcon.setTooltipText("gregtech.machine.quantum_storage.connected", + controllerPos.getX(), controllerPos.getZ(), controllerPos.getY()); + } else { + connectedIcon.setTooltipText("gregtech.machine.quantum_storage.disconnected"); + } + + return connectedIcon; + } + + @Override + public void addInformation(ItemStack stack, @Nullable World world, @NotNull List tooltip, + boolean advanced) { + tooltip.add(I18n.format("gregtech.machine.quantum_chest.tooltip")); + } +} diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumStorageController.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumStorageController.java new file mode 100644 index 00000000000..c4431e902a9 --- /dev/null +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumStorageController.java @@ -0,0 +1,519 @@ +package gregtech.common.metatileentities.storage; + +import gregtech.api.GTValues; +import gregtech.api.capability.GregtechDataCodes; +import gregtech.api.capability.IDualHandler; +import gregtech.api.capability.IEnergyContainer; +import gregtech.api.capability.IQuantumController; +import gregtech.api.capability.IQuantumStorage; +import gregtech.api.capability.impl.EnergyContainerList; +import gregtech.api.capability.impl.FluidTankList; +import gregtech.api.capability.impl.ItemHandlerList; +import gregtech.api.metatileentity.ITieredMetaTileEntity; +import gregtech.api.metatileentity.MetaTileEntity; +import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; +import gregtech.api.util.GTUtility; +import gregtech.client.renderer.texture.Textures; + +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.I18n; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagLong; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.Constants; +import net.minecraftforge.fluids.IFluidTank; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.items.CapabilityItemHandler; +import net.minecraftforge.items.IItemHandler; + +import codechicken.lib.render.CCRenderState; +import codechicken.lib.render.pipeline.ColourMultiplier; +import codechicken.lib.render.pipeline.IVertexOperation; +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.lang.ref.WeakReference; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; + +import static gregtech.api.capability.IQuantumStorage.Type.*; + +public class MetaTileEntityQuantumStorageController extends MetaTileEntity implements IQuantumController { + + private static final int MAX_DISTANCE_RADIUS = 16; + + private EnergyContainerList energyHandler = new EnergyContainerList(Collections.emptyList()); + private final List energyContainers = new ArrayList<>(); + /** Somewhat lazily initialized, make sure to call {@code getStorage()} before trying to access anything in this */ + private Map>> storageInstances = new HashMap<>(); + + /** The "definitive" set of positions of storage instances */ + private Set storagePositions = new HashSet<>(); + private final Map> typePosMap = new EnumMap<>(IQuantumStorage.Type.class); + private final BlockPos[] bounds = new BlockPos[2]; + private long energyConsumption = 0; + private final QuantumControllerHandler handler = new QuantumControllerHandler(); + + private boolean isDead = false; + private boolean isPowered = false; + + public MetaTileEntityQuantumStorageController(ResourceLocation metaTileEntityId) { + super(metaTileEntityId); + for (var type : VALUES) { + typePosMap.put(type, new HashSet<>()); + } + } + + @Override + public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { + return new MetaTileEntityQuantumStorageController(metaTileEntityId); + } + + @Override + public void update() { + super.update(); + if (getWorld().isRemote) return; + + if (getOffsetTimer() % 10 == 0) { + boolean isPowered = energyHandler.getEnergyStored() > energyConsumption && energyConsumption > 0; + if (isPowered) energyHandler.removeEnergy(energyConsumption); + + if (isPowered != this.isPowered) { + this.isPowered = isPowered; + + writeCustomData(GregtechDataCodes.UPDATE_ENERGY, buf -> { + buf.writeBoolean(this.isPowered); + buf.writeBlockPos(this.bounds[0]); + buf.writeBlockPos(this.bounds[1]); + }); + updateHandler(); + } + } + } + + public boolean isPowered() { + return isPowered; + } + + @Override + public void receiveCustomData(int dataId, @NotNull PacketBuffer buf) { + super.receiveCustomData(dataId, buf); + if (dataId == GregtechDataCodes.UPDATE_ENERGY) { + this.isPowered = buf.readBoolean(); + getWorld().markBlockRangeForRenderUpdate(buf.readBlockPos(), buf.readBlockPos()); + scheduleRenderUpdate(); + } else if (dataId == GregtechDataCodes.UPDATE_ENERGY_PER) { + this.energyConsumption = buf.readLong(); + } + } + + @Override + public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline) { + var front = isPowered() ? + Textures.QUANTUM_CONTROLLER_FRONT_ACTIVE : + Textures.QUANTUM_CONTROLLER_FRONT_INACTIVE; + var sides = isPowered() ? + Textures.QUANTUM_CONTROLLER_ACTIVE : + Textures.QUANTUM_CONTROLLER_INACTIVE; + + var newPipeline = ArrayUtils.add(pipeline, + new ColourMultiplier(GTUtility.convertRGBtoOpaqueRGBA_CL(getPaintingColorForRendering()))); + + front.renderSided(getFrontFacing(), renderState, translation, newPipeline); + + for (EnumFacing facing : EnumFacing.VALUES) { + if (facing == getFrontFacing()) continue; + sides.renderSided(facing, renderState, translation, newPipeline); + } + } + + @Override + public Pair getParticleTexture() { + return Pair.of(Textures.QUANTUM_CONTROLLER_ACTIVE.getParticleSprite(), getPaintingColorForRendering()); + } + + @Override + protected boolean openGUIOnRightClick() { + return false; // todo use mui2 for ui? + } + + @Override + public boolean isValidFrontFacing(EnumFacing facing) { + return true; + } + + @Nullable + @SuppressWarnings("SameParameterValue") + private IQuantumStorage getStorage(BlockPos pos, boolean rebuild) { + if (getWorld().isRemote) return null; + if (storageInstances.containsKey(pos)) { + WeakReference> storageRef = storageInstances.get(pos); + IQuantumStorage storage = storageRef.get(); + if (storage != null) { + return storage; + } + } + // need to make sure it still exists + MetaTileEntity mte = GTUtility.getMetaTileEntity(getWorld(), pos); + if (mte instanceof IQuantumStoragestorage) { + storageInstances.put(pos, new WeakReference<>(storage)); + return storage; + } else if (rebuild) { + // need to remove and rebuild + storagePositions.remove(pos); + rebuildNetwork(); + return null; + } + return null; + } + + @Nullable + public final IQuantumStorage getStorage(BlockPos pos) { + return getStorage(pos, false); + } + + @Override + public boolean canConnect(IQuantumStorage storage) { + return !isDead && isInRange(storage.getPos()); + } + + private boolean isInRange(BlockPos pos) { + return Math.abs(getPos().getX() - pos.getX()) <= MAX_DISTANCE_RADIUS && // valid X + Math.abs(getPos().getY() - pos.getY()) <= MAX_DISTANCE_RADIUS && // valid Y + Math.abs(getPos().getZ() - pos.getZ()) <= MAX_DISTANCE_RADIUS; // valid Z + } + + @Override + public void onRemoval() { + if (getWorld().isRemote) return; + isDead = true; + for (BlockPos pos : storagePositions) { + IQuantumStorage storage = getStorage(pos); + if (storage != null) storage.setDisconnected(); + } + handler.invalidate(); + storagePositions.clear(); + storageInstances.clear(); + typePosMap.clear(); + } + + @Override + public void onPlacement(@Nullable EntityLivingBase placer) { + super.onPlacement(placer); + rebuildNetwork(); + } + + @Override + public void onLoad() { + calculateEnergyUsage(); + super.onLoad(); + } + + // Used when this controller is initially placed. Try to find all possible + // storage instances that are connected and within our distance radius + @Override + public void rebuildNetwork() { + if (getWorld().isRemote) return; + var oldInstances = storageInstances; + var oldPositions = storagePositions; + + storageInstances = new HashMap<>(); + storagePositions = new HashSet<>(); + + typePosMap.values().forEach(Set::clear); + + Queue searchQueue = new ArrayDeque<>(); + Set checked = new HashSet<>(); + + // check the posses around the controller + for (EnumFacing facing : EnumFacing.VALUES) { + if (checkStorageNeighbor(this, facing)) { + searchQueue.add(getPos().offset(facing)); + } + } + + int minx = getPos().getX(); + int miny = getPos().getY(); + int minz = getPos().getZ(); + int maxx = minx; + int maxy = miny; + int maxz = minz; + + // while there are blocks to search + while (!searchQueue.isEmpty()) { + BlockPos pos = searchQueue.remove(); + + if (!checked.add(pos)) + continue; + + if (!isInRange(pos) || !getWorld().isBlockLoaded(pos, false)) continue; + + var state = getWorld().getBlockState(pos); + if (state.getBlock().isAir(state, getWorld(), pos)) continue; + + MetaTileEntity mte = GTUtility.getMetaTileEntity(getWorld(), pos); + // the mte at this pos is always an instance of quantum storage + IQuantumStorage storage = (IQuantumStorage) mte; + + // connected to some other network already, ignore + if (storage.isConnected() && !storage.getControllerPos().equals(getPos())) continue; + + // valid chest/tank located, add it + storageInstances.put(pos, new WeakReference<>(storage)); + storagePositions.add(pos); + typePosMap.get(storage.getType()).add(pos); + storage.setConnected(this); + oldInstances.remove(pos); + oldPositions.remove(pos); + + // calculate bounds + minx = Math.min(minx, pos.getX()); + miny = Math.min(miny, pos.getY()); + minz = Math.min(minz, pos.getZ()); + + maxx = Math.max(maxx, pos.getX()); + maxy = Math.max(maxy, pos.getY()); + maxz = Math.max(maxz, pos.getZ()); + + // check against already check posses so we don't recheck a checked pos + for (EnumFacing facing : EnumFacing.VALUES) { + BlockPos offsetPos = pos.offset(facing); + if (checked.contains(offsetPos) || getPos().equals(offsetPos)) continue; + state = getWorld().getBlockState(offsetPos); + if (state.getBlock().isAir(state, getWorld(), offsetPos)) continue; + + // add a new pos to search + if (checkStorageNeighbor(mte, facing)) + searchQueue.add(offsetPos); + } + } + + // update bounds + this.bounds[0] = new BlockPos(minx, miny, minz); + this.bounds[1] = new BlockPos(maxx, maxy, maxz); + + // check old posses to disconnect the storages + for (BlockPos pos : oldPositions) { + + // if we already checked this pos before, don't check it again + if (checked.contains(pos)) continue; + + // if the pos is air, there's nothing to check + var state = getWorld().getBlockState(pos); + if (state.getBlock().isAir(state, getWorld(), pos)) continue; + + IQuantumStorage storage = oldInstances.get(pos).get(); + if (storage == null) { + MetaTileEntity mte = GTUtility.getMetaTileEntity(getWorld(), pos); + if (!(mte instanceof IQuantumStoragequantumStorage)) { + continue; + } + storage = quantumStorage; + } + storage.setDisconnected(); + } + handler.rebuildCache(); + calculateEnergyUsage(); + markDirty(); + } + + private static boolean checkStorageNeighbor(MetaTileEntity mte, EnumFacing facing) { + if (mte.getNeighbor(facing) instanceof IGregTechTileEntity gtte) { + return gtte.getMetaTileEntity() instanceof IQuantumStorage; + } + return false; + } + + @Override + public void updateHandler() { + if (getWorld().isRemote) return; + notifyBlockUpdate(); + for (var pos : typePosMap.get(PROXY)) { + var storage = getStorage(pos); + if (storage == null) continue; + storage.notifyBlockUpdate(); + } + } + + private void calculateEnergyUsage() { + energyContainers.clear(); + energyConsumption = 0; + for (var pos : storagePositions) { + var storage = getStorage(pos); + if (storage != null) { + typePosMap.get(storage.getType()).add(pos); + energyConsumption += getTypeEnergy(storage); + if (storage.getType() == ENERGY) { + energyContainers.add((IEnergyContainer) storage.getTypeValue()); + } + } + } + energyHandler = new EnergyContainerList(energyContainers); + writeCustomData(GregtechDataCodes.UPDATE_ENERGY_PER, buf -> buf.writeLong(energyConsumption)); + } + + public long getTypeEnergy(IQuantumStorage storage) { + return switch (storage.getType()) { + case ITEM, FLUID -> { + int tier = storage instanceof ITieredMetaTileEntity tieredMTE ? tieredMTE.getTier() : 1; + yield tier > 5 ? + GTValues.VH[GTValues.HV] : + GTValues.VH[GTValues.LV]; + } + case PROXY -> 8L; + case EXTENDER -> 2L; + case ENERGY -> 1L; + }; + } + + @Override + public int getCount(IQuantumStorage.Type type) { + return typePosMap.get(type).size(); + } + + public final long getEnergyUsage() { + return energyConsumption; + } + + @Override + public void writeInitialSyncData(@NotNull PacketBuffer buf) { + super.writeInitialSyncData(buf); + buf.writeBoolean(this.isPowered); + buf.writeLong(this.energyConsumption); + } + + @Override + public void receiveInitialSyncData(@NotNull PacketBuffer buf) { + super.receiveInitialSyncData(buf); + this.isPowered = buf.readBoolean(); + this.energyConsumption = buf.readLong(); + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound data) { + NBTTagCompound tagCompound = super.writeToNBT(data); + NBTTagList list = new NBTTagList(); + for (BlockPos pos : storagePositions) { + list.appendTag(new NBTTagLong(pos.toLong())); + } + tagCompound.setTag("StorageInstances", list); + tagCompound.setLong("MinBound", bounds[0].toLong()); + tagCompound.setLong("MaxBound", bounds[1].toLong()); + tagCompound.setBoolean("isPowered", this.isPowered); + return tagCompound; + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + NBTTagList list = data.getTagList("StorageInstances", Constants.NBT.TAG_LONG); + for (int i = 0; i < list.tagCount(); i++) { + storagePositions.add(BlockPos.fromLong(((NBTTagLong) list.get(i)).getLong())); + } + this.bounds[0] = BlockPos.fromLong(data.getLong("MinBound")); + this.bounds[1] = BlockPos.fromLong(data.getLong("MaxBound")); + this.isPowered = data.getBoolean("isPowered"); + } + + @SuppressWarnings("unchecked") + @Override + public T getCapability(@NotNull Capability capability, EnumFacing side) { + if (isPowered()) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY && handler.hasItemHandlers()) { + return (T) handler.getItemHandlers(); + } else if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY && handler.hasFluidTanks()) { + return (T) handler.getFluidTanks(); + } + } + + return super.getCapability(capability, side); + } + + @Override + public void addInformation(ItemStack stack, @Nullable World world, @NotNull List tooltip, + boolean advanced) { + tooltip.add(I18n.format("gregtech.machine.quantum_chest.tooltip")); + } + + @Override + public IDualHandler getHandler() { + return this.handler; + } + + // todo use DualHandler instead once the multis ability pr is merged + private class QuantumControllerHandler implements IDualHandler { + + // IFluidHandler saved values + private FluidTankList fluidTanks; + + // IItemHandler saved values + private ItemHandlerList itemHandlers; + + private void invalidate() { + fluidTanks = new FluidTankList(false); + itemHandlers = new ItemHandlerList(Collections.emptyList()); + } + + private void rebuildCache() { + List itemHandlerList = new ArrayList<>(); + List fluidTankList = new ArrayList<>(); + for (BlockPos pos : storagePositions) { + IQuantumStorage storage = getStorage(pos); + if (storage == null) continue; + switch (storage.getType()) { + case ITEM -> itemHandlerList.add((IItemHandler) storage.getTypeValue()); + case FLUID -> fluidTankList.add((IFluidTank) storage.getTypeValue()); + } + } + + // todo allow this "allowSameFluidFill" to be configured in this controller? + this.fluidTanks = new FluidTankList(false, fluidTankList); + this.itemHandlers = new ItemHandlerList(itemHandlerList); + } + + @Override + public boolean hasFluidTanks() { + return getFluidTanks().getTanks() > 0; + } + + @Override + public boolean hasItemHandlers() { + return !getItemHandlers().getBackingHandlers().isEmpty(); + } + + @Override + public FluidTankList getFluidTanks() { + if (fluidTanks == null) { + rebuildCache(); + } + return fluidTanks; + } + + @Override + public ItemHandlerList getItemHandlers() { + if (itemHandlers == null) { + rebuildCache(); + } + return itemHandlers; + } + } +} diff --git a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumTank.java b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumTank.java index 41db93d301b..0d675b9b1c9 100644 --- a/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumTank.java +++ b/src/main/java/gregtech/common/metatileentities/storage/MetaTileEntityQuantumTank.java @@ -50,6 +50,7 @@ import net.minecraftforge.common.util.Constants; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; +import net.minecraftforge.fluids.IFluidTank; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fml.relauncher.Side; @@ -73,7 +74,7 @@ import static gregtech.api.capability.GregtechDataCodes.*; import static net.minecraftforge.fluids.capability.templates.FluidHandlerItemStack.FLUID_NBT_KEY; -public class MetaTileEntityQuantumTank extends MetaTileEntity +public class MetaTileEntityQuantumTank extends MetaTileEntityQuantumStorage implements ITieredMetaTileEntity, IActiveOutputSide, IFastRenderMetaTileEntity { private final int tier; @@ -287,6 +288,7 @@ public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, } QuantumStorageRenderer.renderTankFluid(renderState, translation, pipeline, fluidTank, getWorld(), getPos(), getFrontFacing()); + renderIndicatorOverlay(renderState, translation, pipeline); } @Override @@ -305,7 +307,6 @@ public Pair getParticleTexture() { @Override public void addInformation(ItemStack stack, @Nullable World player, List tooltip, boolean advanced) { - super.addInformation(stack, player, tooltip, advanced); tooltip.add(I18n.format("gregtech.machine.quantum_tank.tooltip")); tooltip.add(I18n.format("gregtech.universal.tooltip.fluid_storage_capacity", maxFluidCapacity)); NBTTagCompound tag = stack.getTagCompound(); @@ -349,8 +350,8 @@ protected ModularUI createUI(EntityPlayer entityPlayer) { }) .setAlwaysShowFull(true).setDrawHoveringText(false); - return ModularUI.defaultBuilder() - .widget(new ImageWidget(7, 16, 81, 46, GuiTextures.DISPLAY)) + ModularUI.Builder builder = ModularUI.defaultBuilder(); + builder.widget(new ImageWidget(7, 16, 81, 46, GuiTextures.DISPLAY)) .widget(new LabelWidget(11, 20, "gregtech.gui.fluid_amount", 0xFFFFFF)) .widget(tankWidget) .widget(new AdvancedTextWidget(11, 30, getFluidAmountText(tankWidget), 0xFFFFFF)) @@ -371,8 +372,11 @@ protected ModularUI createUI(EntityPlayer entityPlayer) { .widget(new ToggleButtonWidget(43, 64, 18, 18, GuiTextures.BUTTON_FLUID_VOID, this::isVoiding, this::setVoiding) .setTooltipText("gregtech.gui.fluid_voiding.tooltip") - .shouldUseBaseBackground()) - .bindPlayerInventory(entityPlayer.inventory) + .shouldUseBaseBackground()); + + builder.widget(createConnectedGui(64)); + + return builder.bindPlayerInventory(entityPlayer.inventory) .build(getHolder(), entityPlayer); } @@ -451,7 +455,7 @@ public boolean isAllowInputFromOutputSideFluids() { } @Override - public void receiveCustomData(int dataId, PacketBuffer buf) { + public void receiveCustomData(int dataId, @NotNull PacketBuffer buf) { super.receiveCustomData(dataId, buf); if (dataId == UPDATE_OUTPUT_FACING) { this.outputFacing = EnumFacing.VALUES[buf.readByte()]; @@ -488,7 +492,7 @@ public boolean isValidFrontFacing(EnumFacing facing) { } @Override - public void writeInitialSyncData(PacketBuffer buf) { + public void writeInitialSyncData(@NotNull PacketBuffer buf) { super.writeInitialSyncData(buf); buf.writeByte(getOutputFacing().getIndex()); buf.writeBoolean(autoOutputFluids); @@ -499,7 +503,7 @@ public void writeInitialSyncData(PacketBuffer buf) { } @Override - public void receiveInitialSyncData(PacketBuffer buf) { + public void receiveInitialSyncData(@NotNull PacketBuffer buf) { super.receiveInitialSyncData(buf); this.outputFacing = EnumFacing.VALUES[buf.readByte()]; @@ -714,4 +718,14 @@ public int getPriority() { return !locked || lockedFluid == null ? IFilter.noPriority() : IFilter.whitelistPriority(1); } } + + @Override + public Type getType() { + return Type.FLUID; + } + + @Override + public IFluidTank getTypeValue() { + return fluidTank; + } } diff --git a/src/main/java/gregtech/common/mui/widget/GTFluidSlot.java b/src/main/java/gregtech/common/mui/widget/GTFluidSlot.java new file mode 100644 index 00000000000..2530e38a587 --- /dev/null +++ b/src/main/java/gregtech/common/mui/widget/GTFluidSlot.java @@ -0,0 +1,215 @@ +package gregtech.common.mui.widget; + +import gregtech.api.GTValues; +import gregtech.api.mui.sync.GTFluidSyncHandler; +import gregtech.api.util.FluidTooltipUtil; +import gregtech.api.util.GTUtility; +import gregtech.api.util.LocalizationUtils; +import gregtech.client.utils.TooltipHelper; + +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.item.ItemStack; +import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidTank; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; + +import com.cleanroommc.modularui.api.ITheme; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.api.widget.Interactable; +import com.cleanroommc.modularui.drawable.GuiDraw; +import com.cleanroommc.modularui.drawable.text.TextRenderer; +import com.cleanroommc.modularui.integration.jei.JeiGhostIngredientSlot; +import com.cleanroommc.modularui.integration.jei.JeiIngredientProvider; +import com.cleanroommc.modularui.network.NetworkUtils; +import com.cleanroommc.modularui.screen.ModularScreen; +import com.cleanroommc.modularui.screen.RichTooltip; +import com.cleanroommc.modularui.screen.viewport.ModularGuiContext; +import com.cleanroommc.modularui.theme.WidgetSlotTheme; +import com.cleanroommc.modularui.theme.WidgetTheme; +import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.utils.Color; +import com.cleanroommc.modularui.utils.MouseData; +import com.cleanroommc.modularui.utils.NumberFormat; +import com.cleanroommc.modularui.value.sync.SyncHandler; +import com.cleanroommc.modularui.widget.Widget; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public final class GTFluidSlot extends Widget implements Interactable, JeiIngredientProvider, + JeiGhostIngredientSlot { + + private final TextRenderer textRenderer = new TextRenderer(); + private GTFluidSyncHandler syncHandler; + private boolean disableBackground = false; + + public GTFluidSlot() { + tooltip().setAutoUpdate(true); + // .setHasTitleMargin(true); + tooltipBuilder(tooltip -> { + if (!isSynced()) return; + var fluid = this.syncHandler.getFluid(); + + if (fluid == null) + fluid = this.syncHandler.getLockedFluid(); + + if (fluid == null) return; + + tooltip.addLine(IKey.str(fluid.getLocalizedName())); + if (this.syncHandler.showAmount()) + tooltip.addLine(IKey.lang("gregtech.fluid.amount", fluid.amount, this.syncHandler.getCapacity())); + + if (this.syncHandler.isPhantom() && this.syncHandler.showAmount()) + tooltip.addLine(IKey.lang("modularui.fluid.phantom.control")); + + // Add various tooltips from the material + for (String s : FluidTooltipUtil.getFluidTooltip(fluid)) { + if (s.isEmpty()) continue; + tooltip.addLine(IKey.str(s)); + } + + if (this.syncHandler.showAmount()) + addIngotMolFluidTooltip(fluid, tooltip); + }); + } + + public static GTFluidSyncHandler sync(IFluidTank tank) { + return new GTFluidSyncHandler(tank); + } + + @Override + public void onInit() { + this.textRenderer.setShadow(true); + this.textRenderer.setScale(0.5f); + this.textRenderer.setColor(Color.WHITE.main); + getContext().getJeiSettings().addJeiGhostIngredientSlot(this); + } + + public GTFluidSlot syncHandler(IFluidTank fluidTank) { + return syncHandler(sync(fluidTank)); + } + + public GTFluidSlot syncHandler(GTFluidSyncHandler syncHandler) { + setSyncHandler(syncHandler); + this.syncHandler = syncHandler; + return this; + } + + public GTFluidSlot disableBackground() { + this.disableBackground = true; + return this; + } + + @Override + public boolean isValidSyncHandler(SyncHandler syncHandler) { + return syncHandler instanceof GTFluidSyncHandler; + } + + @Override + public void drawBackground(ModularGuiContext context, WidgetTheme widgetTheme) { + if (disableBackground) return; + super.drawBackground(context, widgetTheme); + } + + @Override + public void draw(ModularGuiContext context, WidgetTheme widgetTheme) { + if (widgetTheme instanceof WidgetSlotTheme slotTheme) { + draw(context, slotTheme); + } + } + + public void draw(ModularGuiContext context, WidgetSlotTheme widgetTheme) { + FluidStack content = this.syncHandler.getFluid(); + if (content == null) + content = this.syncHandler.getLockedFluid(); + + GuiDraw.drawFluidTexture(content, 1, 1, getArea().w() - 2, getArea().h() - 2, 0); + + if (content != null && this.syncHandler.showAmount()) { + String amount = NumberFormat.formatWithMaxDigits(content.amount, 3) + "L"; + this.textRenderer.setAlignment(Alignment.CenterRight, getArea().width - 1f); + this.textRenderer.setPos(0, 12); + this.textRenderer.draw(amount); + } + + if (isHovering()) { + GlStateManager.colorMask(true, true, true, false); + GuiDraw.drawRect(1, 1, getArea().w() - 2, getArea().h() - 2, widgetTheme.getSlotHoverColor()); + GlStateManager.colorMask(true, true, true, true); + } + } + + @Override + public @NotNull Result onMousePressed(int mouseButton) { + var data = MouseData.create(mouseButton); + if (this.syncHandler.canFillSlot() || this.syncHandler.canDrainSlot()) { + this.syncHandler.handleClick(data); + + if (this.syncHandler.canLockFluid()) + this.syncHandler.toggleLockFluid(); + + return Result.SUCCESS; + } + return Result.IGNORE; + } + + @Override + public boolean onMouseScroll(ModularScreen.UpOrDown scrollDirection, int amount) { + if (!this.syncHandler.isPhantom()) return false; + if ((scrollDirection.isUp() && !this.syncHandler.canFillSlot()) || + (scrollDirection.isDown() && !this.syncHandler.canDrainSlot())) { + return false; + } + MouseData mouseData = MouseData.create(scrollDirection.modifier); + this.syncHandler.handlePhantomScroll(mouseData); + return true; + } + + @Override + protected WidgetTheme getWidgetThemeInternal(ITheme theme) { + return theme.getFluidSlotTheme(); + } + + public static void addIngotMolFluidTooltip(FluidStack fluidStack, RichTooltip tooltip) { + // Add tooltip showing how many "ingot moles" (increments of 144) this fluid is if shift is held + if (TooltipHelper.isShiftDown() && fluidStack.amount > GTValues.L) { + int numIngots = fluidStack.amount / GTValues.L; + int extra = fluidStack.amount % GTValues.L; + String fluidAmount = String.format(" %,d L = %,d * %d L", fluidStack.amount, numIngots, GTValues.L); + if (extra != 0) { + fluidAmount += String.format(" + %d L", extra); + } + tooltip.add(TextFormatting.GRAY + LocalizationUtils.format("gregtech.gui.amount_raw") + fluidAmount); + } + } + + @Override + public void setGhostIngredient(@NotNull FluidStack ingredient) { + if (this.syncHandler.isPhantom()) { + this.syncHandler.setFluid(ingredient); + this.syncHandler.syncToServer(GTFluidSyncHandler.UPDATE_TANK, + buffer -> NetworkUtils.writeFluidStack(buffer, ingredient)); + } else { + this.syncHandler.lockFluid(ingredient, true); + } + } + + @Override + public @Nullable FluidStack castGhostIngredientIfValid(@NotNull Object ingredient) { + if (ingredient instanceof FluidStack stack) { + return stack; + } else if (ingredient instanceof ItemStack stack && + stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { + if (stack.getCount() > 1) stack = GTUtility.copy(1, stack); + + var handler = stack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); + return handler == null ? null : handler.drain(Integer.MAX_VALUE, true); + } + return null; + } + + @Override + public @Nullable Object getIngredient() { + return this.syncHandler.getFluid(); + } +} diff --git a/src/main/java/gregtech/common/mui/widget/HighlightedTextField.java b/src/main/java/gregtech/common/mui/widget/HighlightedTextField.java index 3bb6a3e652b..c7f339db275 100644 --- a/src/main/java/gregtech/common/mui/widget/HighlightedTextField.java +++ b/src/main/java/gregtech/common/mui/widget/HighlightedTextField.java @@ -1,7 +1,7 @@ package gregtech.common.mui.widget; import com.cleanroommc.modularui.api.value.IStringValue; -import com.cleanroommc.modularui.screen.viewport.GuiContext; +import com.cleanroommc.modularui.screen.viewport.ModularGuiContext; import com.cleanroommc.modularui.value.sync.StringSyncValue; import com.cleanroommc.modularui.widgets.textfield.TextFieldHandler; import com.cleanroommc.modularui.widgets.textfield.TextFieldRenderer; @@ -53,7 +53,7 @@ public HighlightedTextField getThis() { } @Override - public void onRemoveFocus(GuiContext context) { + public void onRemoveFocus(ModularGuiContext context) { super.onRemoveFocus(context); highlighter.runHighlighter(getText()); if (isSynced()) @@ -70,7 +70,7 @@ public static final class TextHighlighter extends TextFieldRenderer { private Function highlightRule = string -> string; - private Map cacheMap = new Object2ObjectOpenHashMap<>(); + private final Map cacheMap = new Object2ObjectOpenHashMap<>(); public TextHighlighter(TextFieldHandler handler) { super(handler); @@ -81,15 +81,15 @@ public void setHighlightRule(Function highlightRule) { } @Override - protected float draw(String text, float x, float y) { - return super.draw(this.cacheMap.getOrDefault(text, text), x, y); + protected void draw(String text, float x, float y) { + super.draw(this.cacheMap.getOrDefault(text, text), x, y); } public void runHighlighter(String text) { if (this.highlightRule == null) { return; } - this.cacheMap.computeIfAbsent(text, string -> this.highlightRule.apply(string)); + this.cacheMap.computeIfAbsent(text, this.highlightRule); } } } diff --git a/src/main/java/gregtech/common/mui/widget/InteractableText.java b/src/main/java/gregtech/common/mui/widget/InteractableText.java new file mode 100644 index 00000000000..bcafa15208d --- /dev/null +++ b/src/main/java/gregtech/common/mui/widget/InteractableText.java @@ -0,0 +1,68 @@ +package gregtech.common.mui.widget; + +import gregtech.api.util.virtualregistry.VirtualEntry; + +import net.minecraft.network.PacketBuffer; + +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.api.widget.Interactable; +import com.cleanroommc.modularui.network.NetworkUtils; +import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.utils.Color; +import com.cleanroommc.modularui.value.sync.SyncHandler; +import com.cleanroommc.modularui.widgets.TextWidget; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Consumer; + +public class InteractableText extends TextWidget implements Interactable { + + private final T entry; + private final EntryColorSH syncHandler; + + public InteractableText(T entry, Consumer setter) { + super(IKey.str(entry.getColorStr()) + .alignment(Alignment.CenterLeft) + .color(Color.WHITE.darker(1))); + this.entry = entry; + this.syncHandler = new EntryColorSH(setter); + setSyncHandler(this.syncHandler); + } + + @NotNull + @Override + public Result onMousePressed(int mouseButton) { + Interactable.playButtonClickSound(); + this.syncHandler.setColor(this.entry.getColorStr()); + this.syncHandler.syncToServer(1, buf -> NetworkUtils.writeStringSafe(buf, this.entry.getColorStr())); + return Result.SUCCESS; + } + + @Override + public boolean isValidSyncHandler(SyncHandler syncHandler) { + return syncHandler instanceof EntryColorSH; + } + + private static class EntryColorSH extends SyncHandler { + + private final Consumer setter; + + private EntryColorSH(Consumer setter) { + this.setter = setter; + } + + public void setColor(String c) { + this.setter.accept(c); + } + + @Override + public void readOnClient(int id, PacketBuffer buf) {} + + @Override + public void readOnServer(int id, PacketBuffer buf) { + if (id == 1) { + setColor(NetworkUtils.readStringSafe(buf)); + } + } + } +} diff --git a/src/main/java/gregtech/common/mui/widget/orefilter/OreFilterTestSlot.java b/src/main/java/gregtech/common/mui/widget/orefilter/OreFilterTestSlot.java index 1948364bbec..e4d0ea8648c 100644 --- a/src/main/java/gregtech/common/mui/widget/orefilter/OreFilterTestSlot.java +++ b/src/main/java/gregtech/common/mui/widget/orefilter/OreFilterTestSlot.java @@ -7,7 +7,7 @@ import gregtech.common.covers.filter.oreglob.impl.ImpossibleOreGlob; import com.cleanroommc.modularui.api.drawable.IKey; -import com.cleanroommc.modularui.screen.viewport.GuiContext; +import com.cleanroommc.modularui.screen.viewport.ModularGuiContext; import com.cleanroommc.modularui.theme.WidgetTheme; import com.cleanroommc.modularui.widgets.ItemSlot; import it.unimi.dsi.fastutil.objects.Object2BooleanAVLTreeMap; @@ -106,7 +106,7 @@ public void updatePreview() { } @Override - public void draw(GuiContext context, WidgetTheme widgetTheme) { + public void draw(ModularGuiContext context, WidgetTheme widgetTheme) { super.draw(context, widgetTheme); if (this.matchSuccess) { GTGuiTextures.OREDICT_MATCH diff --git a/src/main/java/gregtech/common/pipelike/fluidpipe/longdistance/MetaTileEntityLDFluidEndpoint.java b/src/main/java/gregtech/common/pipelike/fluidpipe/longdistance/MetaTileEntityLDFluidEndpoint.java index 00a550356a7..186b4e4970f 100644 --- a/src/main/java/gregtech/common/pipelike/fluidpipe/longdistance/MetaTileEntityLDFluidEndpoint.java +++ b/src/main/java/gregtech/common/pipelike/fluidpipe/longdistance/MetaTileEntityLDFluidEndpoint.java @@ -2,7 +2,6 @@ import gregtech.api.GTValues; import gregtech.api.capability.impl.FluidHandlerDelegate; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.pipenet.longdist.ILDEndpoint; @@ -11,7 +10,6 @@ import gregtech.common.metatileentities.storage.MetaTileEntityLongDistanceEndpoint; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; @@ -57,11 +55,6 @@ public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { return new MetaTileEntityLDFluidEndpoint(this.metaTileEntityId); } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public T getCapability(Capability capability, EnumFacing side) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { diff --git a/src/main/java/gregtech/common/pipelike/fluidpipe/tile/TileEntityFluidPipeTickable.java b/src/main/java/gregtech/common/pipelike/fluidpipe/tile/TileEntityFluidPipeTickable.java index 038fef391f8..0fb23e4c309 100644 --- a/src/main/java/gregtech/common/pipelike/fluidpipe/tile/TileEntityFluidPipeTickable.java +++ b/src/main/java/gregtech/common/pipelike/fluidpipe/tile/TileEntityFluidPipeTickable.java @@ -13,7 +13,6 @@ import gregtech.api.util.EntityDamageUtil; import gregtech.api.util.TextFormattingUtil; import gregtech.common.covers.CoverPump; -import gregtech.common.covers.ManualImportExportMode; import gregtech.common.pipelike.fluidpipe.net.PipeTankList; import net.minecraft.entity.EntityLivingBase; @@ -202,7 +201,7 @@ private boolean checkForPumpCover(@Nullable Cover cover) { if (coverPump.getTransferRate() > pipeThroughput) { coverPump.setTransferRate(pipeThroughput); } - return coverPump.getManualImportExportMode() == ManualImportExportMode.DISABLED; + return true; // disable pushing completely if there's a pump } return false; } diff --git a/src/main/java/gregtech/common/pipelike/itempipe/BlockItemPipe.java b/src/main/java/gregtech/common/pipelike/itempipe/BlockItemPipe.java index 85a18ca231c..7f6c79f9caa 100644 --- a/src/main/java/gregtech/common/pipelike/itempipe/BlockItemPipe.java +++ b/src/main/java/gregtech/common/pipelike/itempipe/BlockItemPipe.java @@ -77,6 +77,7 @@ public WorldItemPipeNet getWorldPipeNet(World world) { } @Override + @SideOnly(Side.CLIENT) protected Pair getParticleTexture(World world, BlockPos blockPos) { return ItemPipeRenderer.INSTANCE.getParticleTexture((TileEntityItemPipe) world.getTileEntity(blockPos)); } diff --git a/src/main/java/gregtech/common/pipelike/itempipe/longdistance/MetaTileEntityLDItemEndpoint.java b/src/main/java/gregtech/common/pipelike/itempipe/longdistance/MetaTileEntityLDItemEndpoint.java index 4179399fd0e..dd04ac94ab0 100644 --- a/src/main/java/gregtech/common/pipelike/itempipe/longdistance/MetaTileEntityLDItemEndpoint.java +++ b/src/main/java/gregtech/common/pipelike/itempipe/longdistance/MetaTileEntityLDItemEndpoint.java @@ -2,7 +2,6 @@ import gregtech.api.GTValues; import gregtech.api.capability.impl.ItemHandlerDelegate; -import gregtech.api.gui.ModularUI; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.pipenet.longdist.ILDEndpoint; @@ -11,7 +10,6 @@ import gregtech.common.metatileentities.storage.MetaTileEntityLongDistanceEndpoint; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; @@ -57,11 +55,6 @@ public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { return new MetaTileEntityLDItemEndpoint(this.metaTileEntityId); } - @Override - protected ModularUI createUI(EntityPlayer entityPlayer) { - return null; - } - @Override public T getCapability(Capability capability, EnumFacing side) { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { diff --git a/src/main/java/gregtech/common/pipelike/laser/BlockLaserPipe.java b/src/main/java/gregtech/common/pipelike/laser/BlockLaserPipe.java index ff6f9c693f8..1c3ac132b60 100644 --- a/src/main/java/gregtech/common/pipelike/laser/BlockLaserPipe.java +++ b/src/main/java/gregtech/common/pipelike/laser/BlockLaserPipe.java @@ -44,6 +44,7 @@ public BlockLaserPipe(@NotNull LaserPipeType pipeType) { } @Override + @SideOnly(Side.CLIENT) protected Pair getParticleTexture(World world, BlockPos blockPos) { return LaserPipeRenderer.INSTANCE.getParticleTexture((TileEntityLaserPipe) world.getTileEntity(blockPos)); } diff --git a/src/main/java/gregtech/common/pipelike/optical/BlockOpticalPipe.java b/src/main/java/gregtech/common/pipelike/optical/BlockOpticalPipe.java index 3e52f60faba..597fc322801 100644 --- a/src/main/java/gregtech/common/pipelike/optical/BlockOpticalPipe.java +++ b/src/main/java/gregtech/common/pipelike/optical/BlockOpticalPipe.java @@ -42,6 +42,7 @@ public BlockOpticalPipe(@NotNull OpticalPipeType pipeType) { } @Override + @SideOnly(Side.CLIENT) protected Pair getParticleTexture(@NotNull World world, BlockPos blockPos) { return OpticalPipeRenderer.INSTANCE.getParticleTexture((TileEntityOpticalPipe) world.getTileEntity(blockPos)); } diff --git a/src/main/java/gregtech/common/terminal/app/VirtualTankApp.java b/src/main/java/gregtech/common/terminal/app/VirtualTankApp.java deleted file mode 100644 index b6a24a190b9..00000000000 --- a/src/main/java/gregtech/common/terminal/app/VirtualTankApp.java +++ /dev/null @@ -1,261 +0,0 @@ -package gregtech.common.terminal.app; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.gui.widgets.TankWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.terminal.os.menu.IMenuComponent; -import gregtech.api.util.GTLog; -import gregtech.api.util.VirtualTankRegistry; -import gregtech.common.terminal.component.SearchComponent; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.PacketBuffer; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTank; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -public class VirtualTankApp extends AbstractApplication implements SearchComponent.IWidgetSearch> { - - private WidgetGroup widgetGroup; - private Map, FluidStack> cacheServer; - @SideOnly(Side.CLIENT) - private Map, IFluidTank> cacheClient; - - public VirtualTankApp() { - super("vtank_viewer"); - } - - @Override - public AbstractApplication initApp() { - this.addWidget(new ImageWidget(5, 5, 333 - 10, 232 - 10, TerminalTheme.COLOR_B_2)); - this.addWidget(new LabelWidget(10, 10, "terminal.vtank_viewer.title", -1)); - this.addWidget(new RectButtonWidget(216, 7, 110, 18) - .setClickListener(cd -> { - if (cd.isClient) { - reloadWidgets(cacheClient); - } - }) - .setIcon(new TextTexture("terminal.vtank_viewer.refresh", -1)) - .setFill(TerminalTheme.COLOR_B_2.getColor())); - widgetGroup = new DraggableScrollableWidgetGroup(10, 30, 313, 195) - .setDraggable(true) - .setYScrollBarWidth(3) - .setYBarStyle(null, TerminalTheme.COLOR_F_1); - if (isClient) { - cacheClient = new HashMap<>(); - } else { - cacheServer = new HashMap<>(); - } - this.addWidget(widgetGroup); - if (!isRemote()) { - refresh(); - } - return this; - } - - private List> findVirtualTanks() { - List> result = new LinkedList<>(); - Map> tankMap = VirtualTankRegistry.getTankMap(); - for (UUID uuid : tankMap.keySet().stream().sorted(Comparator.nullsLast(UUID::compareTo)) - .collect(Collectors.toList())) { - if (uuid == null || uuid.equals(gui.entityPlayer.getUniqueID())) { - for (String key : tankMap.get(uuid).keySet().stream().sorted().collect(Collectors.toList())) { - result.add(new ImmutablePair<>(uuid, key)); - } - } - } - return result; - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - if (gui.entityPlayer.ticksExisted % 20 == 0) { - refresh(); - } - } - - private void refresh() { - Map> tankMap = VirtualTankRegistry.getTankMap(); - Map, FluidStack> access = new HashMap<>(); - for (Pair virtualTankEntry : findVirtualTanks()) { - UUID uuid = virtualTankEntry.getKey(); - String key = virtualTankEntry.getValue(); - FluidStack fluidStack = tankMap.get(uuid).get(key).getFluid(); - access.put(new ImmutablePair<>(uuid, key), fluidStack == null ? null : fluidStack.copy()); - } - if (access.keySet().containsAll(cacheServer.keySet()) && access.size() == cacheServer.size()) { - List> toUpdated = new LinkedList<>(); - for (Map.Entry, FluidStack> entry : access.entrySet()) { - Pair pair = entry.getKey(); - FluidStack fluidStackNew = entry.getValue(); - FluidStack fluidStackOld = cacheServer.get(pair); - if (fluidStackNew == null && fluidStackOld == null) { - continue; - } - if (fluidStackNew != null && fluidStackOld == null) { - toUpdated.add(pair); - } else if (fluidStackNew == null) { - toUpdated.add(pair); - } else if (fluidStackOld.amount != fluidStackNew.amount || !fluidStackNew.isFluidEqual(fluidStackOld)) { - toUpdated.add(pair); - } - } - if (!toUpdated.isEmpty()) { - writeUpdateInfo(-2, buffer -> { // update specific info - buffer.writeVarInt(toUpdated.size()); - for (Pair update : toUpdated) { - buffer.writeBoolean(update.getKey() != null); - if (update.getKey() != null) { - buffer.writeString(update.getKey().toString()); - } - buffer.writeString(update.getValue()); - FluidStack value = access.get(update); - buffer.writeBoolean(value != null); - if (value != null) { - buffer.writeCompoundTag(value.writeToNBT(new NBTTagCompound())); - } - } - }); - } - return; - } - cacheServer = access; - writeUpdateInfo(-1, buffer -> { // update all info - buffer.writeVarInt(cacheServer.size()); - cacheServer.forEach((key, value) -> { - buffer.writeBoolean(key.getKey() != null); - if (key.getKey() != null) { - buffer.writeString(key.getKey().toString()); - } - buffer.writeString(key.getValue()); - buffer.writeBoolean(value != null); - if (value != null) { - buffer.writeCompoundTag(value.writeToNBT(new NBTTagCompound())); - } - }); - }); - } - - @Override - public void readUpdateInfo(int id, PacketBuffer buffer) { - if (id == -1) { // update all info - int size = buffer.readVarInt(); - cacheClient.clear(); - try { - for (int i = 0; i < size; i++) { - UUID uuid = null; - if (buffer.readBoolean()) { - uuid = UUID.fromString(buffer.readString(32767)); - } - String key = buffer.readString(32767); - IFluidTank fluidTank = new FluidTank(64000); - if (buffer.readBoolean()) { - fluidTank.fill(FluidStack.loadFluidStackFromNBT(buffer.readCompoundTag()), true); - } - cacheClient.put(new ImmutablePair<>(uuid, key), fluidTank); - } - } catch (Exception e) { - GTLog.logger.error("error sync fluid", e); - } - reloadWidgets(cacheClient); - } else if (id == -2) { - int size = buffer.readVarInt(); - try { - for (int i = 0; i < size; i++) { - UUID uuid = null; - if (buffer.readBoolean()) { - uuid = UUID.fromString(buffer.readString(32767)); - } - String key = buffer.readString(32767); - FluidStack fluidStack = null; - if (buffer.readBoolean()) { - fluidStack = FluidStack.loadFluidStackFromNBT(buffer.readCompoundTag()); - } - - IFluidTank fluidTank = cacheClient.get(new ImmutablePair<>(uuid, key)); - if (fluidTank != null) { - fluidTank.drain(64000, true); - if (fluidStack != null) { - fluidTank.fill(fluidStack, true); - } - } - } - } catch (Exception e) { - GTLog.logger.error("error sync fluid", e); - } - } else { - super.readUpdateInfo(id, buffer); - } - } - - private void reloadWidgets(Map, IFluidTank> map) { - widgetGroup.clearAllWidgets(); - AtomicInteger cy = new AtomicInteger(); - map.forEach((key, fluidTank) -> { - if (key.getKey() != null) { - widgetGroup.addWidget(new ImageWidget(0, cy.get() + 4, 8, 8, GuiTextures.LOCK_WHITE)); - } - widgetGroup.addWidget(new TankWidget(fluidTank, 8, cy.get(), 18, 18) - .setAlwaysShowFull(true) - .setBackgroundTexture(GuiTextures.FLUID_SLOT).setClient()); - widgetGroup.addWidget(new LabelWidget(36, cy.get() + 5, key.getValue(), -1) - .setWidth(180)); - cy.addAndGet(23); - }); - } - - @Override - public List getMenuComponents() { - return Collections.singletonList(new SearchComponent<>(this)); - } - - @Override - public String resultDisplay(Pair result) { - FluidStack fluidStack = VirtualTankRegistry.getTankMap().get(result.getKey()).get(result.getValue()).getFluid(); - return String.format("Lock: %b, ID: %s, Fluid: %s", result.getKey() != null, result.getValue(), - fluidStack == null ? "-" : fluidStack.getLocalizedName()); - } - - @Override - public void selectResult(Pair result) { - Map, IFluidTank> map = new HashMap<>(); - map.put(result, cacheClient.get(result)); - reloadWidgets(map); - } - - @Override - public void search(String word, Consumer> find) { - if (!isClient) - return; - for (Map.Entry, IFluidTank> access : cacheClient.entrySet()) { - Pair accessingCover = access.getKey(); - if (accessingCover.getValue() != null && - accessingCover.getValue().toLowerCase().contains(word.toLowerCase())) { - find.accept(accessingCover); - } else { - FluidStack fluidStack = access.getValue().getFluid(); - if (fluidStack != null && fluidStack.getLocalizedName().toLowerCase().contains(word.toLowerCase())) { - find.accept(accessingCover); - } - } - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/appstore/AppCardWidget.java b/src/main/java/gregtech/common/terminal/app/appstore/AppCardWidget.java deleted file mode 100644 index f06ec173db3..00000000000 --- a/src/main/java/gregtech/common/terminal/app/appstore/AppCardWidget.java +++ /dev/null @@ -1,201 +0,0 @@ -package gregtech.common.terminal.app.appstore; - -import gregtech.api.GTValues; -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.resources.*; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.AnimaWidgetGroup; -import gregtech.api.terminal.gui.widgets.CircleButtonWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.interpolate.Eases; -import gregtech.api.util.interpolate.Interpolator; -import gregtech.client.shader.Shaders; -import gregtech.client.utils.RenderUtil; -import gregtech.common.items.behaviors.TerminalBehaviour; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.network.PacketBuffer; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import java.awt.*; -import java.util.List; - -public class AppCardWidget extends AnimaWidgetGroup { - - private final AbstractApplication application; - private final AppStoreApp store; - @SideOnly(Side.CLIENT) - private ImageWidget stateWidget; - @SideOnly(Side.CLIENT) - private ImageWidget bgWidget; - @SideOnly(Side.CLIENT) - private IGuiTexture banner; - @SideOnly(Side.CLIENT) - private int offset; - @SideOnly(Side.CLIENT) - private int alpha; - - public AppCardWidget(int x, int y, AbstractApplication application, AppStoreApp store) { - super(x, y, 100, 100); - this.application = application; - this.store = store; - TerminalOSWidget os = store.getOs(); - if (os.isRemote()) { - this.addWidget(new CircleButtonWidget(15, 17) - .setColors(TerminalTheme.COLOR_B_2.getColor(), - application.getThemeColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setHoverText(application.getUnlocalizedName()) - .setIcon(application.getIcon())); - this.addWidget(new ImageWidget(30, 0, 65, 34, - new TextTexture(application.getUnlocalizedName(), -1).setDropShadow(true) - .setWidth(65))); - offset = Math.abs(GTValues.RNG.nextInt()) % 200; - banner = application.getBanner(); - if (os.installedApps.contains(application)) { - if (TerminalBehaviour.isCreative(os.itemStack) || application.getMaxTier() == - Math.min(os.tabletNBT.getCompoundTag(application.getRegistryName()).getInteger("_tier"), - application.getMaxTier())) { - updateState(0); - } else { - updateState(1); - } - } else { - updateState(2); - } - } - } - - @SideOnly(Side.CLIENT) - public void updateState(int state) { - String text = "Latest"; - int bg = 0xff4B4C4C; - if (state == 1) { - text = "Upgrade"; - bg = 0xffF7911F; - } else if (state == 2) { - text = "Install"; - bg = 0xff67F74B; - } - if (stateWidget != null) { - removeWidget(stateWidget); - removeWidget(bgWidget); - } - stateWidget = new ImageWidget(15, 85, 70, 15, - new TextTexture(text, -1).setWidth(70).setDropShadow(true).setType(TextTexture.TextType.HIDE)); - bgWidget = new ImageWidget(15, 85, 70, 13, new ColorRectTexture(bg)); - this.addWidget(bgWidget); - this.addWidget(stateWidget); - } - - private void openDialog() { - new AppPageWidget(application, store, this).open(); - } - - @Override - public void handleClientAction(int id, PacketBuffer buffer) { - if (id == -1) { // open page - if (buffer.readBoolean()) { - openDialog(); - } - } else { - super.handleClientAction(id, buffer); - } - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (isMouseOverElement(mouseX, mouseY)) { - writeClientAction(-1, buffer -> buffer.writeBoolean(true)); - openDialog(); - } - return super.mouseClicked(mouseX, mouseY, button); - } - - @Override - public void hookDrawInForeground(int mouseX, int mouseY) { - // hover - int x = getPosition().x; - int y = getPosition().y; - int width = getSize().width; - int height = getSize().height; - if (isMouseOverElement(mouseX, mouseY) && - store.getOs().desktop.widgets.stream().noneMatch(app -> app instanceof TerminalDialogWidget)) { - int dur = 7; - int maxAlpha = 100; // 0-255!!!!! - float partialTicks = Minecraft.getMinecraft().getRenderPartialTicks(); - if (alpha != maxAlpha && interpolator == null) { - interpolator = new Interpolator(0, maxAlpha, dur, Eases.LINEAR, - value -> alpha = value.intValue(), - value -> interpolator = null); - interpolator.start(); - } - // smooth - int color; - if (alpha == maxAlpha) { - color = TerminalTheme.COLOR_B_2.getColor() & 0x00ffffff | ((alpha) << 24); - } else { - color = TerminalTheme.COLOR_B_2.getColor() & 0x00ffffff | - ((alpha + (int) (maxAlpha * partialTicks / dur)) << 24); - } - int finalColor = color; - RenderUtil.useScissor(store.getPosition().x, store.getPosition().y, store.getSize().width, - store.getSize().height, () -> { - drawSolidRect(0, 0, gui.getScreenWidth(), y, finalColor); - drawSolidRect(0, y + height, gui.getScreenWidth(), gui.getScreenHeight(), finalColor); - drawSolidRect(0, y, x, height, finalColor); - drawSolidRect(x + width, y, gui.getScreenWidth(), height, finalColor); - - drawBorder(x, y, width, height, application.getThemeColor(), -1); - }); - } else { - alpha = 0; - } - super.hookDrawInForeground(mouseX, mouseY); - } - - @Override - public void hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - int x = getPosition().x; - int y = getPosition().y; - int width = getSize().width; - int height = getSize().height; - Color color = new Color(application.getThemeColor()); - drawSolidRect(x, y, width, height, color.getRGB() & 0x00ffffff | 0x4f000000); - if (banner != null) { - banner.draw(x, y, width, 34); - } else { - if (Shaders.allowedShader()) { - float time = offset + (gui.entityPlayer.ticksExisted + partialTicks) / 20f; - ShaderTexture.createShader("banner.frag").draw(x, y, width, 34, uniformCache -> { - uniformCache.glUniform1F("u_time", time); - uniformCache.glUniform3F("b_color", color.getRed() / 255f, color.getGreen() / 255f, - color.getBlue() / 255f); - }); - } else { - drawSolidRect(x, y, width, 34, color.getRGB()); - } - } - super.hookDrawInBackground(mouseX, mouseY, partialTicks, context); - - // description - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - List description = fr.listFormattedStringToWidth(application.getDescription(), 90); - int fColor = store.darkMode ? -1 : 0xff333333; - for (int i = 0; i < Math.min(description.size(), 4); i++) { - fr.drawString(description.get(i), x + 5, y + 40 + i * fr.FONT_HEIGHT, fColor, store.darkMode); - } - if (description.size() > 4) { - fr.drawString("...", x + 5, y + 40 + 4 * fr.FONT_HEIGHT, fColor, store.darkMode); - } - - // shadow - drawGradientRect(x, y + 34, width, 3, 0x6f000000, 0, false); - drawRectShadow(x, y, width, height, 5); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/appstore/AppPageWidget.java b/src/main/java/gregtech/common/terminal/app/appstore/AppPageWidget.java deleted file mode 100644 index dc02aac2078..00000000000 --- a/src/main/java/gregtech/common/terminal/app/appstore/AppPageWidget.java +++ /dev/null @@ -1,305 +0,0 @@ -package gregtech.common.terminal.app.appstore; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.SlotWidget; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.CircleButtonWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.interpolate.Eases; -import gregtech.api.util.interpolate.Interpolator; -import gregtech.common.inventory.handlers.SingleItemStackHandler; -import gregtech.common.items.behaviors.TerminalBehaviour; - -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.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.nbt.NBTTagString; -import net.minecraftforge.common.util.Constants; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -public class AppPageWidget extends TerminalDialogWidget { - - private final AbstractApplication application; - private final AppCardWidget appCardWidget; - private final AppStoreApp store; - private final CircleButtonWidget[] buttons; - private int lineWidth; - private boolean back; - - public AppPageWidget(AbstractApplication application, AppStoreApp store, AppCardWidget appCardWidget) { // 323 222 - super(store.getOs(), 5, 5, 333 - 10, 232 - 10); - this.appCardWidget = appCardWidget; - this.application = application; - this.store = store; - String name = this.application.getRegistryName(); - int stage = application.getMaxTier() + 1; - - int dur = 323 / (stage + 1); - buttons = new CircleButtonWidget[stage]; - for (int i = 0; i < stage; i++) { - int tier = i; - // upgrade button - buttons[i] = new CircleButtonWidget(dur + dur * i, 110, 6, 2, 0) - .setClickListener(cd -> buttonClicked(tier)); - this.addWidget(buttons[i]); - } - this.addWidget(new CircleButtonWidget(310, 10, 6, 1, 8) - .setColors(0, - TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_3.getColor()) - .setIcon(GuiTextures.ICON_REMOVE) - .setHoverText("terminal.store.close") - .setClickListener(cd -> close())); - if (store.getOs().isRemote()) { - // profile - int color = application.getThemeColor(); - int lightColor = color & 0x00ffffff | ((0x6f) << 24); - IGuiTexture profile = application.getProfile(); - this.addWidget(new ImageWidget(10, 15, 80, 80, profile)); - - for (int i = 0; i < stage; i++) { - List demand = TerminalRegistry.getAppHardwareDemand(name, i) - .stream() - .map(hw -> hw.getLocalizedName() + "(" + hw.addInformation() + ")") - .collect(Collectors.toList()); - demand.add(0, application.getTierInformation(i)); - buttons[i].setColors(0, lightColor, color).setHoverText(demand.toArray(new String[0])); - List conditions = TerminalRegistry.getAppHardwareUpgradeConditions(name, i); - // line - if (conditions.size() > 0) { - this.addWidget(new ImageWidget(dur + dur * i, 115, 1, - -18 + (conditions.size() >= 4 ? 4 * 25 : conditions.size() * 25), - new ColorRectTexture(0xafffffff))); - } - // conditions - for (int j = 0; j < conditions.size(); j++) { - this.addWidget(new SlotWidget(new SingleItemStackHandler(conditions.get(j)), 0, - dur + dur * i + 25 * (j / 4) - 9, 120 + 25 * (j % 4), false, false)); - } - } - } - } - - private void buttonClicked(int tier) { - int lastTier; - TerminalOSWidget os = store.getOs(); - if (!os.installedApps.contains(application)) { - lastTier = -1; - } else if (TerminalBehaviour.isCreative(os.itemStack)) { - lastTier = application.getMaxTier(); - } else { - lastTier = Math.min(os.tabletNBT.getCompoundTag(application.getRegistryName()).getInteger("_tier"), - application.getMaxTier()); - } - String name = application.getRegistryName(); - if (tier > lastTier) { - boolean match = true; // inventory match - List requirements = new ArrayList<>(); - ItemStack missStack = null; - if (!gui.entityPlayer.isCreative()) { - for (int i = lastTier + 1; i <= tier; i++) { - for (ItemStack condition : TerminalRegistry.getAppHardwareUpgradeConditions(name, i)) { - boolean miss = true; - for (ItemStack requirement : requirements) { - if (requirement.isItemEqual(condition)) { - requirement.setCount(requirement.getCount() + condition.getCount()); - miss = false; - break; - } - } - if (miss) { - requirements.add(condition.copy()); - } - } - } - for (ItemStack requirement : requirements) { - int left = requirement.getCount(); - for (ItemStack hold : gui.entityPlayer.inventory.mainInventory) { - if (requirement.isItemEqual(hold)) { - if (hold.getCount() < left) { - left -= hold.getCount(); - } else { - left = 0; - } - if (left == 0) { - break; - } - } - } - if (left > 0) { - missStack = requirement.copy(); - missStack.setCount(left); - match = false; - break; - } - } - } - - if (match) { - if (os.isRemote()) { - appCardWidget.updateState(tier == application.getMaxTier() ? 0 : 1); - } - if (!gui.entityPlayer.isCreative()) { // cost - TerminalDialogWidget - .showConfirmDialog(store.getOs(), "terminal.dialog.notice", "terminal.store.match", res -> { - if (res) { - for (ItemStack requirement : requirements) { - int left = requirement.getCount(); - for (ItemStack hold : gui.entityPlayer.inventory.mainInventory) { - if (requirement.isItemEqual(hold)) { - if (hold.getCount() <= left) { - hold.setCount(0); - left -= hold.getCount(); - } else { - hold.setCount(hold.getCount() - left); - left = 0; - } - if (left == 0) { - break; - } - } - } - } - updateTerminalAppTier(tier, lastTier); - } - }).open(); - } else { - updateTerminalAppTier(tier, lastTier); - } - } else { - if (isRemote()) { - TerminalDialogWidget.showInfoDialog(store.getOs(), - "terminal.dialog.notice", - I18n.format("terminal.store.miss", missStack.getDisplayName(), missStack.getCount())) - .setClientSide().open(); - } - } - } - } - - private void updateTerminalAppTier(int tier, int lastTier) { - TerminalOSWidget os = store.getOs(); - os.openedApps.stream() - .filter(app -> app.getRegistryName().equals(this.application.getRegistryName())) - .findFirst() - .ifPresent(app -> os.closeApplication(app, os.isRemote())); - if (lastTier == -1) { // update terminal - NBTTagList installed = os.tabletNBT.getTagList("_installed", Constants.NBT.TAG_STRING); - installed.appendTag(new NBTTagString(application.getRegistryName())); - os.tabletNBT.setTag("_installed", installed); - os.installApplication(application); - } - NBTTagCompound tag = os.tabletNBT.getCompoundTag(application.getRegistryName()); - tag.setInteger("_tier", tier); - os.tabletNBT.setTag(application.getRegistryName(), tag); - lineWidth = 0; - } - - @Override - public void hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - int x = getPosition().x; - int y = getPosition().y; - int width = getSize().width; - int height = getSize().height; - - GlStateManager.disableDepth(); - - drawSolidRect(x, y, width, height, store.darkMode ? 0xcf000000 : 0xdfdddddd); - super.hookDrawInBackground(mouseX, mouseY, partialTicks, context); - int stage; - TerminalOSWidget os = store.getOs(); - if (!os.installedApps.contains(application)) { - stage = 0; - } else if (TerminalBehaviour.isCreative(os.itemStack)) { - stage = application.getMaxTier() + 1; - } else { - stage = Math.min(os.tabletNBT.getCompoundTag(application.getRegistryName()).getInteger("_tier"), - application.getMaxTier()) + 1; - } - int maxStage = application.getMaxTier() + 1; - int color = application.getThemeColor(); - int lightColor = color & 0x00ffffff | ((0x6f) << 24); - int dur = 323 / (maxStage + 1); - - int hover = -1; - for (int i = 0; i < buttons.length; i++) { - if (buttons[i].isMouseOverElement(mouseX, mouseY)) { - hover = i; - } - } - - // draw current tier - drawSolidRect(x, y + 110 - 2, dur * stage, 4, color); - if (stage == maxStage) { - drawSolidRect(x + stage * dur, y + 110 - 2, dur, 4, color); - } else { - drawSolidRect(x + stage * dur, y + 110 - 2, dur, 4, lightColor); - } - - int end = dur * (hover + 1 - stage); - - if (hover + 1 > stage) { - if (lineWidth != end && (interpolator == null || back)) { - back = false; - interpolator = new Interpolator(lineWidth, end, (end - lineWidth) / 15, Eases.LINEAR, - value -> lineWidth = value.intValue(), - value -> interpolator = null); - interpolator.start(); - } - } else { - if (lineWidth != 0 && (interpolator == null || !back)) { - back = true; - interpolator = new Interpolator(lineWidth, 0, lineWidth / 15, Eases.LINEAR, - value -> lineWidth = value.intValue(), - value -> interpolator = null); - interpolator.start(); - } - } - - if (lineWidth != 0) { - int smoothWidth = lineWidth; - if (hover + 1 > stage) { - if (lineWidth != end) { - smoothWidth += partialTicks * end / 10; - } - } else { - smoothWidth -= partialTicks * end / 10; - } - - drawSolidRect(x + stage * dur, y + 110 - 2, smoothWidth, 4, color); - } - - // description - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - List description = fr.listFormattedStringToWidth(application.getDescription(), 210); - int fColor = store.darkMode ? -1 : 0xff333333; - String localizedName = I18n.format(application.getUnlocalizedName()); - drawStringSized(localizedName, x + 100, y + 14, fColor, store.darkMode, 2, false); - if (isMouseOver(x + 100, y + 14, fr.getStringWidth(localizedName) * 2, fr.FONT_HEIGHT * 2, mouseX, mouseY)) { - drawHoveringText(ItemStack.EMPTY, Collections.singletonList("(" + application.getRegistryName() + ")"), 200, - mouseX, mouseY); - } - for (int i = 0; i < description.size(); i++) { - fr.drawString(description.get(i), x + 100, y + 35 + i * fr.FONT_HEIGHT, fColor, store.darkMode); - } - - drawBorder(x + 10, y + 15, 80, 80, store.darkMode ? -1 : 0xff333333, 2); - - GlStateManager.enableDepth(); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/appstore/AppStoreApp.java b/src/main/java/gregtech/common/terminal/app/appstore/AppStoreApp.java deleted file mode 100644 index 6e1ffea4e6e..00000000000 --- a/src/main/java/gregtech/common/terminal/app/appstore/AppStoreApp.java +++ /dev/null @@ -1,114 +0,0 @@ -package gregtech.common.terminal.app.appstore; - -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.ItemStackTexture; -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.terminal.os.menu.IMenuComponent; -import gregtech.api.util.Size; -import gregtech.common.items.MetaItems; -import gregtech.common.terminal.component.ClickComponent; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import java.util.Collections; -import java.util.List; - -public class AppStoreApp extends AbstractApplication { - - @SideOnly(Side.CLIENT) - protected boolean darkMode; - - public AppStoreApp() { - super("store"); - } - - @Override - public IGuiTexture getIcon() { - return new ItemStackTexture(MetaItems.COIN_GOLD_ANCIENT.getStackForm()); - } - - @Override - public AbstractApplication initApp() { - DraggableScrollableWidgetGroup group = new DraggableScrollableWidgetGroup(0, 0, 333, 232); - this.addWidget(group); - int index = 0; - int yOffset = 50; - group.addWidget(new ImageWidget(0, 0, 333, 30, GuiTextures.UI_FRAME_SIDE_UP)); - group.addWidget(new LabelWidget(333 / 2, 10, getUnlocalizedName(), -1).setShadow(true).setYCentered(true) - .setXCentered(true)); - for (AbstractApplication app : TerminalRegistry.getAllApps()) { - group.addWidget(new AppCardWidget(5 + 110 * (index % 3), yOffset + 110 * (index / 3), app, this)); - index++; - } - int y = yOffset + 110 * ((index + 2) / 3); - group.addWidget(new ImageWidget(0, y, 333, 30, new ColorRectTexture(TerminalTheme.COLOR_B_2.getColor()))); - group.addWidget( - new ImageWidget(0, y, 333, 30, new TextTexture("Copyright @2021-xxxx Gregicality Team XD", -1))); - loadLocalConfig(nbt -> this.darkMode = nbt.getBoolean("dark")); - return this; - } - - @Override - public NBTTagCompound closeApp() { - for (Widget widget : getOs().desktop.widgets) { - if (widget instanceof AppPageWidget) { - ((AppPageWidget) widget).close(); - } - } - saveLocalConfig(nbt -> nbt.setBoolean("dark", this.darkMode)); - return super.closeApp(); - } - - @Override - protected void hookDrawInBackground(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, darkMode ? TerminalTheme.COLOR_B_2.getColor() : 0x9fffffff); - super.hookDrawInBackground(mouseX, mouseY, partialTicks, context); - } - - @Override - public List getMenuComponents() { - ClickComponent darkMode = new ClickComponent().setIcon(GuiTextures.ICON_VISIBLE) - .setHoverText("terminal.prospector.vis_mode").setClickConsumer(cd -> { - if (cd.isClient) { - this.darkMode = !this.darkMode; - } - }); - return Collections.singletonList(darkMode); - } - - @Override - public void onOSSizeUpdate(int width, int height) { - this.setSize(new Size(width, height)); - for (Widget dragWidget : this.widgets) { - if (dragWidget instanceof DraggableScrollableWidgetGroup) { - int lastWidth = dragWidget.getSize().width; - for (Widget widget : ((DraggableScrollableWidgetGroup) dragWidget).widgets) { - if (widget instanceof AppCardWidget) { - widget.addSelfPosition((width - lastWidth) / 2, 0); - } else if (widget instanceof ImageWidget) { - widget.setSize(new Size(width, 30)); - } else { - widget.addSelfPosition((width - lastWidth) / 2, 0); - } - } - dragWidget.setSize(new Size(width, height)); - } - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/batterymanager/BatteryManagerApp.java b/src/main/java/gregtech/common/terminal/app/batterymanager/BatteryManagerApp.java deleted file mode 100644 index 25fae6eee53..00000000000 --- a/src/main/java/gregtech/common/terminal/app/batterymanager/BatteryManagerApp.java +++ /dev/null @@ -1,65 +0,0 @@ -package gregtech.common.terminal.app.batterymanager; - -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.resources.ItemStackTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.common.items.MetaItems; -import gregtech.common.terminal.hardware.BatteryHardware; - -import net.minecraft.client.resources.I18n; - -import java.util.concurrent.atomic.AtomicInteger; - -public class BatteryManagerApp extends AbstractApplication { - - public BatteryManagerApp() { - super("battery"); - } - - @Override - public IGuiTexture getIcon() { - return new ItemStackTexture(MetaItems.BATTERY_HV_SODIUM.getStackForm()); - } - - @Override - public boolean isClientSideApp() { - return true; - } - - @Override - public AbstractApplication initApp() { - if (isClient) { - this.addWidget(new ImageWidget(5, 5, 333 - 10, 232 - 10, TerminalTheme.COLOR_B_2)); - this.addWidget(new ImageWidget(170, 15, 1, 232 - 30, TerminalTheme.COLOR_7)); - this.addWidget(new BatteryWidget(10, 10 + (212 - 150) / 2, 150, 150, getOs())); - addBatteryApps(); - } - return this; - } - - private void addBatteryApps() { - AtomicInteger index = new AtomicInteger(); - for (AbstractApplication installed : getOs().installedApps) { - TerminalRegistry - .getAppHardwareDemand(installed.getRegistryName(), - getOs().tabletNBT.getCompoundTag(installed.getRegistryName()).getInteger("_tier")) - .stream() - .filter(i -> i instanceof BatteryHardware).findFirst() - .ifPresent(battery -> { - long charge = ((BatteryHardware) battery).getCharge(); - this.addWidget(new RectButtonWidget(180 + (index.get() % 5) * 30, 15 + (index.get() / 5) * 30, - 20, 20, 2) - .setIcon(installed.getIcon()) - // warn unsafe call the I18n here. - .setHoverText(I18n.format("terminal.battery.hover", - I18n.format(installed.getUnlocalizedName()), charge)) - .setColors(0, TerminalTheme.COLOR_7.getColor(), 0)); - index.getAndIncrement(); - }); - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/batterymanager/BatteryWidget.java b/src/main/java/gregtech/common/terminal/app/batterymanager/BatteryWidget.java deleted file mode 100644 index 50dc490e3dd..00000000000 --- a/src/main/java/gregtech/common/terminal/app/batterymanager/BatteryWidget.java +++ /dev/null @@ -1,62 +0,0 @@ -package gregtech.common.terminal.app.batterymanager; - -import gregtech.api.capability.GregtechCapabilities; -import gregtech.api.capability.IElectricItem; -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.ShaderTexture; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.client.shader.Shaders; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -public class BatteryWidget extends Widget { - - @SideOnly(Side.CLIENT) - private ShaderTexture battery; - private final TerminalOSWidget os; - - public BatteryWidget(int x, int y, int width, int height, TerminalOSWidget os) { - super(x, y, width, height); - this.os = os; - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - super.drawInBackground(mouseX, mouseY, partialTicks, context); - int x = getPosition().x; - int y = getPosition().y; - int width = getSize().width; - int height = getSize().height; - float left = 0; - IElectricItem electricItem = os.hardwareProvider.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, - null); - if (electricItem != null) { - left = electricItem.getCharge() / (float) electricItem.getMaxCharge(); - } - if (Shaders.allowedShader()) { - float progress = left; - float time = (gui.entityPlayer.ticksExisted + partialTicks) / 20f; - int color = TerminalTheme.COLOR_F_1.getColor(); - if (battery == null) { - battery = ShaderTexture.createShader("battery.frag"); - } - battery.draw(x, y, width, height, uniformCache -> { - uniformCache.glUniform1F("u_time", time); - uniformCache.glUniform1F("progress", progress); - uniformCache.glUniform3F("c_ring", .55f, .7f, .7f); - uniformCache.glUniform3F("c_sector", (color >> 16 & 255) / 255.0F, (color >> 8 & 255) / 255.0F, - (color & 255) / 255.0F); - uniformCache.glUniform3F("c_water", (1 - progress), progress, 0f); - }); - } else { - int b_color = (int) (255 * (1 - left)) << 16 | (int) (255 * left) << 8 | 255 << 24; - drawBorder(x, y, width, height, TerminalTheme.COLOR_1.getColor(), 2); - drawSolidRect(x, y + height - (int) (height * left), width, (int) (height * left), b_color); - } - drawStringSized(String.format("%.2f%%", left * 100), x + width / 2f + 3, y + height / 2f - 7, -1, true, 2, - true); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/capeselector/CapeSelectorApp.java b/src/main/java/gregtech/common/terminal/app/capeselector/CapeSelectorApp.java deleted file mode 100644 index 2105e3ed11e..00000000000 --- a/src/main/java/gregtech/common/terminal/app/capeselector/CapeSelectorApp.java +++ /dev/null @@ -1,62 +0,0 @@ -package gregtech.common.terminal.app.capeselector; - -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.resources.TextureArea; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.SimpleTextWidget; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.client.renderer.texture.Textures; -import gregtech.common.terminal.app.capeselector.widget.CapeListWidget; - -public class CapeSelectorApp extends AbstractApplication { - - protected CapeListWidget capeListWidget; - - public CapeSelectorApp() { - super("cape_selector"); - } - - @Override - public IGuiTexture getIcon() { - return new TextureArea(Textures.GREGTECH_CAPE_TEXTURE, 28f / 64, 0, 22f / 64, 22f / 32); - } - - @Override - public AbstractApplication initApp() { - this.addWidget(new ImageWidget(5, 5, 333 - 10, 232 - 10, TerminalTheme.COLOR_B_2)); - - this.setCapeList(new CapeListWidget(27, 43, 4, 3, this.gui.entityPlayer.getPersistentID())); - this.getCapeList().setYScrollBarWidth(3).setYBarStyle(null, TerminalTheme.COLOR_F_1); - - this.addWidget(new SimpleTextWidget(166, 33, "", 0xFFFFFF, () -> { - if (this.getCapeList().getCapes() == null || this.getCapeList().getCapes().isEmpty()) { - return "terminal.cape_selector.empty"; - } - return "terminal.cape_selector.select"; - })); - - this.addWidget(new SimpleTextWidget(166, 45, "", 0xFFFFFF, () -> { - if (this.getCapeList().getCapes() == null || this.getCapeList().getCapes().isEmpty()) { - return "terminal.cape_selector.tip"; - } - return ""; - })); - - return super.initApp(); - } - - protected void setCapeList(CapeListWidget widget) { - this.capeListWidget = widget; - this.addWidget(capeListWidget); - } - - public CapeListWidget getCapeList() { - return this.capeListWidget; - } - - @Override - public boolean isClientSideApp() { - return false; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/capeselector/widget/CapeListWidget.java b/src/main/java/gregtech/common/terminal/app/capeselector/widget/CapeListWidget.java deleted file mode 100644 index 98f7bd57e35..00000000000 --- a/src/main/java/gregtech/common/terminal/app/capeselector/widget/CapeListWidget.java +++ /dev/null @@ -1,126 +0,0 @@ -package gregtech.common.terminal.app.capeselector.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.SizedTextureArea; -import gregtech.api.gui.resources.TextureArea; -import gregtech.api.gui.widgets.ClickButtonWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.CapesRegistry; -import gregtech.client.utils.RenderUtil; - -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.ResourceLocation; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class CapeListWidget extends DraggableScrollableWidgetGroup { - - private final UUID uuid; - private List capes; - private int selectedX, selectedY = -1; - - public CapeListWidget(int xPosition, int yPosition, int width, int height, UUID uuid) { - super(xPosition, yPosition, width * 70, height * 56); // Cape banners are 28x44, expanded to 70x56 - this.uuid = uuid; - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - if (capes == null) { - updateCapeCandidates(CapesRegistry.getUnlockedCapes(uuid)); - writeUpdateInfo(-1, buf -> { - buf.writeVarInt(capes.size()); - capes.stream().map(ResourceLocation::toString).forEach(buf::writeString); - }); - } - } - - @Override - public void readUpdateInfo(int id, PacketBuffer buffer) { - if (id == -1) { - capes = new ArrayList<>(); - int count = buffer.readVarInt(); - for (int i = 0; i < count; i++) { - capes.add(new ResourceLocation(buffer.readString(Short.MAX_VALUE))); - } - updateCapeCandidates(capes); - } else { - super.readUpdateInfo(id, buffer); - } - } - - private void updateCapeCandidates(List capes) { - this.capes = capes; - int width = (getSize().width) / 70; - int rowNumber = 0; - if (capes == null || capes.isEmpty()) return; - int i = 0; - while (true) { - WidgetGroup row = new WidgetGroup(); - for (int rowPosition = 0; rowPosition < width; rowPosition++) { - TextureArea capeImage = new SizedTextureArea(capes.get(i), 0.5, 0, 14f / 64, 22f / 32, 28, 44); - - int finalRowPosition = rowPosition; - int finalRowNumber = rowNumber; - int finalI = i; - ClickButtonWidget capeButton = new ClickButtonWidget(rowPosition * 70 + 21, rowNumber * 56, 28, 44, "", - (data) -> this.setCape(finalRowPosition, finalRowNumber, capes.get(finalI))) - .setButtonTexture(capeImage) - .setShouldClientCallback(true); - row.addWidget(capeButton); - - if (capes.get(i).equals(CapesRegistry.getPlayerCape(uuid))) { // If this is the cape that the player is - // wearing right now, select it. - selectedX = finalRowPosition; - selectedY = finalRowNumber; - } - i++; - if (i == capes.size()) { - this.addWidget(row); - return; - } - } - this.addWidget(row); - rowNumber++; - } - } - - private void setCape(int x, int y, ResourceLocation cape) { - if (selectedX == x && selectedY == y) { - selectedX = -1; // Sets a "not in use" flag. - cape = null; - } else { - selectedX = x; - selectedY = y; - } - if (!isRemote()) { - CapesRegistry.giveCape(uuid, cape); - } - } - - public List getCapes() { - return capes; - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - super.drawInBackground(mouseX, mouseY, partialTicks, context); - - if (selectedX == -1 || selectedY == -1) - return; - - // Get selected cape button - Widget button = ((WidgetGroup) this.widgets.get(this.selectedY)).widgets.get(this.selectedX); - - RenderUtil.useScissor(getPosition().x, getPosition().y, getSize().width - yBarWidth, - getSize().height - xBarHeight, () -> { - drawSelectionOverlay(button.getPosition().x - 6, button.getPosition().y - 6, - button.getSize().width + 12, button.getSize().height + 12); // Add a bit of margin - }); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/console/ConsoleApp.java b/src/main/java/gregtech/common/terminal/app/console/ConsoleApp.java deleted file mode 100644 index 6147c219ad4..00000000000 --- a/src/main/java/gregtech/common/terminal/app/console/ConsoleApp.java +++ /dev/null @@ -1,55 +0,0 @@ -package gregtech.common.terminal.app.console; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.MachineSceneWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.common.metatileentities.storage.MetaTileEntityWorkbench; - -import net.minecraft.tileentity.TileEntity; - -public class ConsoleApp extends AbstractApplication { - - public ConsoleApp() { - super("console"); - } - - private IGregTechTileEntity getMTE() { - if (os.clickPos != null) { - TileEntity te = os.getModularUI().entityPlayer.world.getTileEntity(os.clickPos); - if (te instanceof IGregTechTileEntity && ((IGregTechTileEntity) te).isValid()) { - return (IGregTechTileEntity) te; - } - } - return null; - } - - @Override - public AbstractApplication initApp() { - IGregTechTileEntity mteResult = getMTE(); - - if (mteResult == null || - mteResult.getMetaTileEntity() instanceof MetaTileEntityWorkbench) // Remove Crafting Station compat - { // 333 232 - TerminalDialogWidget.showInfoDialog(os, - "terminal.dialog.notice", - "terminal.console.notice", - () -> os.closeApplication(this, isClient)).open(); - return this; - } - MachineConsoleWidget consoleWidget = new MachineConsoleWidget(200, 16, 133, 200); - this.addWidget(consoleWidget); - if (isClient) { - this.addWidget(0, - new MachineSceneWidget(0, 16, 200, 200, os.clickPos).setOnSelected(consoleWidget::setFocus)); - this.addWidget(new ImageWidget(0, 0, 333, 16, GuiTextures.UI_FRAME_SIDE_UP)); - this.addWidget(new ImageWidget(0, 216, 333, 16, GuiTextures.UI_FRAME_SIDE_DOWN)); - } else { - this.addWidget(0, new WidgetGroup()); // placeholder - } - return this; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/console/MachineConsoleWidget.java b/src/main/java/gregtech/common/terminal/app/console/MachineConsoleWidget.java deleted file mode 100644 index a3272fa06c3..00000000000 --- a/src/main/java/gregtech/common/terminal/app/console/MachineConsoleWidget.java +++ /dev/null @@ -1,466 +0,0 @@ -package gregtech.common.terminal.app.console; - -import gregtech.api.capability.GregtechTileCapabilities; -import gregtech.api.capability.IControllable; -import gregtech.api.capability.impl.AbstractRecipeLogic; -import gregtech.api.capability.impl.RecipeLogicSteam; -import gregtech.api.cover.Cover; -import gregtech.api.cover.CoverWithUI; -import gregtech.api.gui.GuiTextures; -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.ItemStackTexture; -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.*; -import gregtech.api.metatileentity.MetaTileEntity; -import gregtech.api.metatileentity.SimpleMachineMetaTileEntity; -import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.Size; -import gregtech.common.metatileentities.multi.multiblockpart.MetaTileEntityMaintenanceHatch; -import gregtech.common.metatileentities.multi.multiblockpart.MetaTileEntityMultiblockPart; -import gregtech.common.metatileentities.storage.MetaTileEntityQuantumChest; -import gregtech.common.metatileentities.storage.MetaTileEntityQuantumTank; - -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.init.Items; -import net.minecraft.network.PacketBuffer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.NonNullList; -import net.minecraft.util.math.BlockPos; -import net.minecraftforge.items.ItemStackHandler; - -import org.lwjgl.opengl.GL11; - -/** - * Created with IntelliJ IDEA. - * - * @Author: KilaBash - * @Date: 2021/08/25 - * @Description: - */ -public class MachineConsoleWidget extends WidgetGroup { - - private BlockPos pos; - private EnumFacing facing; - private MetaTileEntity mte; - private UIWidgetGroup uiWidgetGroup; - - public MachineConsoleWidget(int x, int y, int width, int height) { - super(x, y, width, height); - } - - public void setFocus(BlockPos pos, EnumFacing facing) { - this.pos = new BlockPos(pos); - this.facing = facing; - this.mte = null; - checkMachine(); - } - - @Override - public void updateScreen() { - super.updateScreen(); - checkMachine(); - } - - private void checkMachine() { - if (mte != null && mte.isValid()) { - return; - } - if (pos != null && facing != null) { - TileEntity te = gui.entityPlayer.world.getTileEntity(pos); - clearAllWidgets(); - if (te instanceof IGregTechTileEntity && ((IGregTechTileEntity) te).isValid()) { - mte = ((IGregTechTileEntity) te).getMetaTileEntity(); - initWidgets(); - if (isRemote()) { - writeClientAction(5, buf -> { - buf.writeBlockPos(pos); - buf.writeByte(facing.getIndex()); - }); - } - } - } - } - - private void initWidgets() { - if (mte != null) { - uiWidgetGroup = new UIWidgetGroup(); - uiWidgetGroup.setActive(false); - uiWidgetGroup.setVisible(false); - Size size = getSize(); - addWidget(new ImageWidget(0, 0, size.width, size.height, GuiTextures.BACKGROUND)); - addWidget(new SimpleTextWidget(size.width / 2, 12, "", -1, () -> facing.toString().toUpperCase()) - .setShadow(true)); - int y = 20; - if (mte.hasFrontFacing()) { - addWidget(new RectButtonWidget(10, y, size.width - 20, 20, 1) - .setClickListener(clickData -> { - if (!isRemote() && mte.isValidFrontFacing(facing)) { - mte.setFrontFacing(facing); - } - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setIcon(new TextTexture("terminal.console.front", -1))); - y += 25; - } - - // IControllable - IControllable controllable = mte.getCapability(GregtechTileCapabilities.CAPABILITY_CONTROLLABLE, facing); - if (controllable != null) { - addWidget(new RectButtonWidget(10, y, 20, 20, 1) - .setToggleButton(GuiTextures.BUTTON_WORKING_ENABLE.getSubArea(0, 0, 1, 0.5), (c, p) -> { - if (!isRemote()) { - controllable.setWorkingEnabled(p); - } - }) - .setValueSupplier(false, controllable::isWorkingEnabled) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), 0) - .setHoverText("terminal.console.controllable") - .setIcon(GuiTextures.BUTTON_WORKING_ENABLE.getSubArea(0, 0.5, 1, 0.5))); - // AbstractRecipeLogic - AbstractRecipeLogic recipeLogic = mte.getCapability(GregtechTileCapabilities.CAPABILITY_RECIPE_LOGIC, - facing); - if (recipeLogic != null) { - addWidget(new CycleButtonWidget(35, y, 20, 20, - recipeLogic.getAvailableOverclockingTiers(), recipeLogic::getOverclockTier, - recipeLogic::setOverclockTier) - .setTooltipHoverString("gregtech.gui.overclock.description") - .setButtonTexture(GuiTextures.BUTTON_OVERCLOCK)); - addWidget(new ProgressWidget(recipeLogic::getProgressPercent, 60, y, 63, 20, - GuiTextures.PROGRESS_BAR_ARC_FURNACE, ProgressWidget.MoveType.HORIZONTAL)); - if (recipeLogic instanceof RecipeLogicSteam) { - y += 25; - addWidget(new RectButtonWidget(10, y, size.width - 20, 20, 1) - .setClickListener(clickData -> { - EnumFacing currentVentingSide = ((RecipeLogicSteam) recipeLogic).getVentingSide(); - if (currentVentingSide == facing || mte.getFrontFacing() == facing) return; - ((RecipeLogicSteam) recipeLogic).setVentingSide(facing); - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setIcon(new TextTexture("terminal.console.venting", -1))); - } - } - y += 25; - } - - // SimpleMachineMetaTileEntity - if (mte instanceof SimpleMachineMetaTileEntity) { - SimpleMachineMetaTileEntity simpleMTE = (SimpleMachineMetaTileEntity) mte; - // items output - if (simpleMTE.getExportItems().getSlots() > 0) { - addWidget(new ImageWidget(10, y, 20, 20, new ItemStackTexture(Items.GLOWSTONE_DUST))); - addWidget(new RectButtonWidget(33, y, 50, 20, 1) - .setClickListener(clickData -> { - if (!isRemote() && mte.getFrontFacing() != facing) { - simpleMTE.setOutputFacingItems(facing); - } - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setHoverText("terminal.console.items")); - addWidget(new SimpleTextWidget(58, y + 10, "", -1, - () -> simpleMTE.getOutputFacingItems().toString())); - addWidget(new RectButtonWidget(83, y, 20, 20, 1) - .setToggleButton(GuiTextures.BUTTON_ITEM_OUTPUT.getSubArea(0, 0.5, 1, 0.5), (c, p) -> { - if (!isRemote()) { - simpleMTE.setAutoOutputItems(p); - } - }) - .setInitValue(simpleMTE.isAutoOutputItems()) - .setValueSupplier(false, simpleMTE::isAutoOutputItems) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), 0) - .setHoverText("terminal.console.auto_output") - .setIcon(GuiTextures.BUTTON_ITEM_OUTPUT.getSubArea(0, 0, 1, 0.5))); - addWidget(new RectButtonWidget(103, y, 20, 20, 1) - .setToggleButton(GuiTextures.BUTTON_ALLOW_IMPORT_EXPORT.getSubArea(0, 0.5, 1, 0.5), - (c, p) -> { - if (!isRemote()) { - simpleMTE.setAllowInputFromOutputSideItems(p); - } - }) - .setInitValue(simpleMTE.isAllowInputFromOutputSideItems()) - .setValueSupplier(false, simpleMTE::isAllowInputFromOutputSideItems) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), 0) - .setHoverText("terminal.console.input") - .setIcon(GuiTextures.BUTTON_ALLOW_IMPORT_EXPORT.getSubArea(0, 0, 1, 0.5))); - y += 20; - } - - // fluids output - if (simpleMTE.getExportFluids().getTanks() > 0) { - addWidget(new ImageWidget(10, y, 20, 20, new ItemStackTexture(Items.WATER_BUCKET))); - addWidget(new RectButtonWidget(33, y, 50, 20, 1) - .setClickListener(clickData -> { - if (!isRemote() && simpleMTE.getFrontFacing() != facing) { - simpleMTE.setOutputFacingFluids(facing); - } - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setHoverText("terminal.console.fluids")); - addWidget(new SimpleTextWidget(58, y + 10, "", -1, - () -> simpleMTE.getOutputFacingFluids().toString())); - addWidget(new RectButtonWidget(83, y, 20, 20, 1) - .setToggleButton(GuiTextures.BUTTON_FLUID_OUTPUT.getSubArea(0, 0.5, 1, 0.5), (c, p) -> { - if (!isRemote()) { - simpleMTE.setAutoOutputFluids(p); - } - }) - .setInitValue(simpleMTE.isAutoOutputFluids()) - .setValueSupplier(false, simpleMTE::isAutoOutputFluids) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), 0) - .setHoverText("terminal.console.auto_output") - .setIcon(GuiTextures.BUTTON_FLUID_OUTPUT.getSubArea(0, 0, 1, 0.5))); - addWidget(new RectButtonWidget(103, y, 20, 20, 1) - .setToggleButton(GuiTextures.BUTTON_ALLOW_IMPORT_EXPORT.getSubArea(0, 0.5, 1, 0.5), - (c, p) -> { - if (!isRemote()) { - simpleMTE.setAllowInputFromOutputSideFluids(p); - } - }) - .setInitValue(simpleMTE.isAllowInputFromOutputSideFluids()) - .setValueSupplier(false, simpleMTE::isAllowInputFromOutputSideFluids) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), 0) - .setHoverText("terminal.console.input") - .setIcon(GuiTextures.BUTTON_ALLOW_IMPORT_EXPORT.getSubArea(0, 0, 1, 0.5))); - y += 20; - } - y += 5; - } - - // MetaTileEntityQuantumTank - if (mte instanceof MetaTileEntityQuantumChest) { - MetaTileEntityQuantumChest chest = (MetaTileEntityQuantumChest) mte; - addWidget(new ImageWidget(10, y, 20, 20, new ItemStackTexture(Items.GLOWSTONE_DUST))); - addWidget(new RectButtonWidget(33, y, 50, 20, 1) - .setClickListener(clickData -> { - if (!isRemote() && mte.getFrontFacing() != facing) { - chest.setOutputFacing(facing); - } - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setHoverText("terminal.console.items")); - addWidget(new SimpleTextWidget(58, y + 10, "", -1, () -> chest.getOutputFacing().toString())); - addWidget(new RectButtonWidget(83, y, 20, 20, 1) - .setToggleButton(GuiTextures.BUTTON_ITEM_OUTPUT.getSubArea(0, 0.5, 1, 0.5), (c, p) -> { - if (!isRemote()) { - chest.setAutoOutputItems(p); - } - }) - .setInitValue(chest.isAutoOutputItems()) - .setValueSupplier(false, chest::isAutoOutputItems) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), 0) - .setHoverText("terminal.console.auto_output") - .setIcon(GuiTextures.BUTTON_ITEM_OUTPUT.getSubArea(0, 0, 1, 0.5))); - addWidget(new RectButtonWidget(103, y, 20, 20, 1) - .setToggleButton(GuiTextures.BUTTON_ALLOW_IMPORT_EXPORT.getSubArea(0, 0.5, 1, 0.5), (c, p) -> { - if (!isRemote()) { - chest.setAllowInputFromOutputSide(p); - } - }) - .setInitValue(chest.isAllowInputFromOutputSideItems()) - .setValueSupplier(false, chest::isAllowInputFromOutputSideItems) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), 0) - .setHoverText("terminal.console.input") - .setIcon(GuiTextures.BUTTON_ALLOW_IMPORT_EXPORT.getSubArea(0, 0, 1, 0.5))); - y += 25; - } else if (mte instanceof MetaTileEntityQuantumTank) { - MetaTileEntityQuantumTank tank = (MetaTileEntityQuantumTank) mte; - addWidget(new ImageWidget(10, y, 20, 20, new ItemStackTexture(Items.WATER_BUCKET))); - addWidget(new RectButtonWidget(33, y, 50, 20, 1) - .setClickListener(clickData -> { - if (!isRemote() && tank.getFrontFacing() != facing) { - tank.setOutputFacing(facing); - } - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setHoverText("terminal.console.fluids")); - addWidget(new SimpleTextWidget(58, y + 10, "", -1, () -> tank.getOutputFacing().toString())); - addWidget(new RectButtonWidget(83, y, 20, 20, 1) - .setToggleButton(GuiTextures.BUTTON_FLUID_OUTPUT.getSubArea(0, 0.5, 1, 0.5), (c, p) -> { - if (!isRemote()) { - tank.setAutoOutputFluids(p); - } - }) - .setInitValue(tank.isAutoOutputFluids()) - .setValueSupplier(false, tank::isAutoOutputFluids) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), 0) - .setHoverText("terminal.console.auto_output") - .setIcon(GuiTextures.BUTTON_FLUID_OUTPUT.getSubArea(0, 0, 1, 0.5))); - addWidget(new RectButtonWidget(103, y, 20, 20, 1) - .setToggleButton(GuiTextures.BUTTON_ALLOW_IMPORT_EXPORT.getSubArea(0, 0.5, 1, 0.5), (c, p) -> { - if (!isRemote()) { - tank.setAllowInputFromOutputSide(p); - } - }) - .setInitValue(tank.isAllowInputFromOutputSideFluids()) - .setValueSupplier(false, tank::isAllowInputFromOutputSideFluids) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), 0) - .setHoverText("terminal.console.input") - .setIcon(GuiTextures.BUTTON_ALLOW_IMPORT_EXPORT.getSubArea(0, 0, 1, 0.5))); - y += 25; - } - - // MultiBlockPart - if (mte instanceof MetaTileEntityMultiblockPart) { - // MetaTileEntityMaintenanceHatch - if (mte instanceof MetaTileEntityMaintenanceHatch) { - addWidget(new RectButtonWidget(10, y, size.width - 20, 20, 1) - .setClickListener(clickData -> { - if (!isRemote()) { - ((MetaTileEntityMaintenanceHatch) mte).fixAllMaintenanceProblems(); - } - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setIcon(new TextTexture("terminal.console.maintenance", -1))); - y += 25; - } - } - - // CoverBehavior - Cover cover = mte.getCoverAtSide(facing); - if (cover != null) { - this.addWidget(new SlotWidget(new ItemStackHandler(NonNullList.withSize(1, cover.getPickItem())), 0, - 10, y, false, false)); - addWidget(new SimpleTextWidget(58, y + 10, "terminal.console.cover_rs", -1, - () -> String.valueOf(cover.getRedstoneSignalOutput())).setShadow(true).setCenter(true)); - if (cover instanceof CoverWithUI) { - addWidget(new RectButtonWidget(83, y, 40, 20, 1) - .setClickListener( - clickData -> uiWidgetGroup.openUI(((CoverWithUI) cover).createUI(gui.entityPlayer))) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setIcon(new TextTexture("terminal.console.cover_gui", -1))); - } - y += 25; - } - addWidget(new RectButtonWidget(10, y, size.width - 20, 20, 1) - .setClickListener(clickData -> uiWidgetGroup.openUI(mte.getModularUI(gui.entityPlayer))) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setIcon(new TextTexture("terminal.console.gui", -1))); - - addWidget(uiWidgetGroup); - } - } - - @Override - public void handleClientAction(int id, PacketBuffer buffer) { - if (id == 5) { - setFocus(buffer.readBlockPos(), EnumFacing.VALUES[buffer.readByte()]); - } else { - super.handleClientAction(id, buffer); - } - } - - @Override - public void drawInForeground(int mouseX, int mouseY) { - if (uiWidgetGroup != null && uiWidgetGroup.isVisible()) { - return; - } - super.drawInForeground(mouseX, mouseY); - } - - private static class UIWidgetGroup extends WidgetGroup { - - private IGuiTexture background; - - public void clearUI() { - background = null; - clearAllWidgets(); - setActive(false); - setVisible(false); - } - - public void openUI(ModularUI ui) { - clearUI(); - if (ui != null) { - background = ui.backgroundPath; - for (Widget widget : ui.guiWidgets.values()) { - if (widget instanceof SlotWidget) { - SlotWidget slotWidget = (SlotWidget) widget; - if (slotWidget.getHandle().getStack() == gui.entityPlayer.getHeldItem(EnumHand.MAIN_HAND)) { - slotWidget.setActive(false); - } - } - addWidget(widget); - } - setSize(new Size(ui.getWidth(), ui.getHeight())); - addSelfPosition(gui.getScreenWidth() / 2 - getPosition().x - ui.getWidth() / 2, - gui.getScreenHeight() / 2 - getPosition().y - ui.getHeight() / 2); - setActive(true); - setVisible(true); - } - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - drawSolidRect(0, 0, gui.getScreenWidth(), gui.getScreenHeight(), 0xbf000000); - if (background != null) { - background.draw(getPosition().x, getPosition().y, getSize().width, getSize().height); - } - GL11.glDisable(GL11.GL_SCISSOR_TEST); - GlStateManager.disableDepth(); - super.drawInBackground(mouseX, mouseY, partialTicks, context); - GlStateManager.enableDepth(); - GL11.glEnable(GL11.GL_SCISSOR_TEST); - } - - @Override - public boolean keyTyped(char charTyped, int keyCode) { - if (keyCode == 1) { - clearUI(); - writeClientAction(5, buffer -> buffer.writeBoolean(true)); - return true; - } - super.keyTyped(charTyped, keyCode); - return true; - } - - @Override - public void handleClientAction(int id, PacketBuffer buffer) { - if (id == 5) { - if (buffer.readBoolean()) { - clearUI(); - } - } else { - super.handleClientAction(id, buffer); - } - } - - @Override - public boolean mouseWheelMove(int mouseX, int mouseY, int wheelDelta) { - super.mouseWheelMove(mouseX, mouseY, wheelDelta); - return true; - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - super.mouseClicked(mouseX, mouseY, button); - return true; - } - - @Override - public boolean mouseDragged(int mouseX, int mouseY, int button, long timeDragged) { - super.mouseDragged(mouseX, mouseY, button, timeDragged); - return true; - } - - @Override - public boolean mouseReleased(int mouseX, int mouseY, int button) { - super.mouseReleased(mouseX, mouseY, button); - return true; - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/maze/MazeApp.java b/src/main/java/gregtech/common/terminal/app/game/maze/MazeApp.java deleted file mode 100644 index bd944c9d9da..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/maze/MazeApp.java +++ /dev/null @@ -1,274 +0,0 @@ -package gregtech.common.terminal.app.game.maze; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.widgets.ClickButtonWidget; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.gui.widgets.SimpleTextWidget; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.common.terminal.app.game.maze.widget.EnemyWidget; -import gregtech.common.terminal.app.game.maze.widget.MazeWidget; -import gregtech.common.terminal.app.game.maze.widget.PlayerWidget; - -import org.lwjgl.input.Keyboard; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -public class MazeApp extends AbstractApplication { - - private int gameState = 0; - private PlayerWidget player; - private EnemyWidget enemy; - private MazeWidget maze; - private int timer = 0; - private int mazesSolved = 0; - private float speed = 25; - private int lastPlayerInput = -2; - public static int MAZE_SIZE = 9; - private List movementStore; - private boolean lastPausePress; - - private List[] FSM; - - public MazeApp() { - super("maze"); - } - - public AbstractApplication initApp() { - if (isClient) { - movementStore = new ArrayList<>(); - FSM = new List[4]; - FSM[0] = new LinkedList<>(); - FSM[1] = new LinkedList<>(); - FSM[2] = new LinkedList<>(); - FSM[3] = new LinkedList<>(); - this.setOs(os); - this.addWidget(new ImageWidget(5, 5, 333 - 10, 232 - 10, TerminalTheme.COLOR_B_2)); - // enemy 0: Title - this.addWidget(new LabelWidget(333 / 2, 222 / 2 - 50, "terminal.maze.title", 0xFFFFFFFF).setXCentered(true), - 0); - this.addWidget(new ClickButtonWidget(323 / 2 - 10, 222 / 2 - 10, 30, 30, "terminal.maze.play", - (clickData -> { - this.setGameState(1); - this.resetGame(); - })).setShouldClientCallback(true), 0); - // GameState 1: Play - this.setMaze(new MazeWidget()); - this.setPlayer(new PlayerWidget(0, 0, this)); - this.setEnemy(new EnemyWidget(-100, -100, this)); - // GameState 2: Pause - this.addWidget(new ImageWidget(5, 5, 333 - 10, 232 - 10, new ColorRectTexture(0xFF000000)), 2, 3); - this.addWidget(new ClickButtonWidget(323 / 2 - 10, 222 / 2 - 10, 50, 20, "terminal.maze.continue", - (clickData) -> this.setGameState(1)).setShouldClientCallback(true), 2); - this.addWidget(new LabelWidget(333 / 2, 222 / 2 - 50, "terminal.maze.pause", 0xFFFFFFFF).setXCentered(true), - 2); - // GameState 3: Death - this.addWidget( - new SimpleTextWidget(333 / 2, 232 / 2 - 40, "", 0xFFFFFFFF, () -> "terminal.maze.death.1", true), - 3); - this.addWidget(new SimpleTextWidget(333 / 2, 232 / 2 - 28, "terminal.maze.death.2", 0xFFFFFFFF, - () -> String.valueOf(this.getMazesSolved()), true), 3); - this.addWidget( - new SimpleTextWidget(333 / 2, 232 / 2 - 16, "", 0xFFFFFFFF, () -> "terminal.maze.death.3", true), - 3); - this.addWidget( - new ClickButtonWidget(323 / 2 - 10, 222 / 2 + 10, 40, 20, "terminal.maze.retry", (clickData -> { - this.setGameState(1); - this.setMazesSolved(0); - MAZE_SIZE = 9; - speed = 25; - this.resetGame(); - })).setShouldClientCallback(true), 3); - } - return this; - } - - public void addWidget(Widget widget, int... visibleStates) { - this.addWidget(widget); - for (int state : visibleStates) { - FSM[state].add(widget); - } - widget.setVisible(Arrays.stream(visibleStates).allMatch(state -> state == gameState)); - } - - public void setPlayer(PlayerWidget player) { - this.player = player; - this.addWidget(player, 1, 2, 3); - } - - public void setMaze(MazeWidget maze) { - this.maze = maze; - this.addWidget(maze, 1, 2, 3); - } - - public void setEnemy(EnemyWidget enemy) { - this.enemy = enemy; - this.addWidget(enemy, 1, 2, 3); - } - - @Override - public boolean canOpenMenuOnEdge() { - return gameState != 1; - } - - @Override - public boolean isClientSideApp() { - return true; - } - - @Override - public void updateScreen() { - super.updateScreen(); - int lastState = gameState; - if (gameState == 1) { - if (Keyboard.isKeyDown(Keyboard.KEY_P)) { - gameState = 2; - lastPausePress = true; - } - if (Keyboard.isKeyDown(Keyboard.KEY_LEFT) ^ Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) { - if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) - attemptMovePlayer(0); // Left - else - attemptMovePlayer(1); // Right - } - if (Keyboard.isKeyDown(Keyboard.KEY_UP) ^ Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { - if (Keyboard.isKeyDown(Keyboard.KEY_UP)) - attemptMovePlayer(2); // Up - else - attemptMovePlayer(3); // Down - } - timer++; - if (enemy.posX < 0 && timer % (speed * MAZE_SIZE - 1) < 1) { - enemy.setGridPosition(0, 0); - } else if (timer % speed < 1) { - moveEnemy(); - } - if (enemy.posX == player.posX && enemy.posY == player.posY) { - gameState = 3; - } - } - if (gameState == 2) { - if (!Keyboard.isKeyDown(Keyboard.KEY_P)) - lastPausePress = false; - if (Keyboard.isKeyDown(Keyboard.KEY_P) && !lastPausePress) - gameState = 1; - } - if (gameState != lastState) { - FSM[lastState].forEach(widget -> widget.setVisible(false)); - FSM[gameState].forEach(widget -> widget.setVisible(true)); - } - } - - public int getGameState() { - return gameState; - } - - public void setGameState(int gameState) { - if (gameState != this.gameState) { - FSM[this.gameState].forEach(widget -> widget.setVisible(false)); - FSM[gameState].forEach(widget -> widget.setVisible(true)); - } - this.gameState = gameState; - } - - public int getRenderX(int posX) { - return this.maze.getSelfPosition().x + posX * 10; - } - - public int getRenderY(int posY) { - return this.maze.getSelfPosition().y + posY * 10; - } - - public int getTimer() { - return timer; - } - - private void attemptMovePlayer(int direction) { - if (timer < lastPlayerInput + 2) { - return; - } - lastPlayerInput = timer; - - // Did the player reach the end? - if (player.posX == MAZE_SIZE - 1 && player.posY == MAZE_SIZE - 1 && direction == 3) { - mazesSolved++; - speed *= 0.95; - if (mazesSolved % 4 == 0) { - MAZE_SIZE += 2; - speed *= 1.07; - } - resetGame(); - return; - } - - if (direction == 0 && !maze.isThereWallAt(player.posX, player.posY, false)) { - player.move(-1, 0); - if (movementStore.size() > 0 && movementStore.get(movementStore.size() - 1) == 1) { - movementStore.remove(movementStore.size() - 1); - } else { - movementStore.add(direction); - } - } else if (direction == 1 && !maze.isThereWallAt(player.posX + 1, player.posY, false)) { - player.move(1, 0); - if (movementStore.size() > 0 && movementStore.get(movementStore.size() - 1) == 0) { - movementStore.remove(movementStore.size() - 1); - } else { - movementStore.add(direction); - } - } else if (direction == 2 && !maze.isThereWallAt(player.posX, player.posY, true)) { - player.move(0, -1); - if (movementStore.size() > 0 && movementStore.get(movementStore.size() - 1) == 3) { - movementStore.remove(movementStore.size() - 1); - } else { - movementStore.add(direction); - } - } else if (direction == 3 && !maze.isThereWallAt(player.posX, player.posY + 1, true)) { - player.move(0, 1); - if (movementStore.size() > 0 && movementStore.get(movementStore.size() - 1) == 2) { - movementStore.remove(movementStore.size() - 1); - } else { - movementStore.add(direction); - } - } - } - - private void moveEnemy() { // Move enemy with the latest movements - if (enemy.posX < 0 || movementStore.isEmpty()) - return; - - int direction = movementStore.get(0); - if (direction == 0) { - enemy.move(-1, 0); - } else if (direction == 1) { - enemy.move(1, 0); - } else if (direction == 2) { - enemy.move(0, -1); - } else if (direction == 3) { - enemy.move(0, 1); - } - movementStore.remove(0); - } - - private void resetGame() { - player.setGridPosition(0, 0); - maze.recalculateSize(); - maze.initMaze(); - movementStore.clear(); - timer = 0; - lastPlayerInput = -5; - enemy.setGridPosition(-100, -100); - } - - public int getMazesSolved() { - return mazesSolved; - } - - public void setMazesSolved(int mazesSolved) { - this.mazesSolved = mazesSolved; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/maze/widget/EnemyWidget.java b/src/main/java/gregtech/common/terminal/app/game/maze/widget/EnemyWidget.java deleted file mode 100644 index e16117666e2..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/maze/widget/EnemyWidget.java +++ /dev/null @@ -1,17 +0,0 @@ -package gregtech.common.terminal.app.game.maze.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.util.Position; -import gregtech.common.terminal.app.game.maze.MazeApp; - -public class EnemyWidget extends PlayerWidget { - - public EnemyWidget(int posX, int posY, MazeApp app) { - super(posX, posY, app); - } - - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - this.setSelfPosition(new Position(app.getRenderX(posX), app.getRenderY(posY))); - drawSolidRect(this.getPosition().x, this.getPosition().y, 10, 10, 0xFFFFAAAA); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/maze/widget/MazeWidget.java b/src/main/java/gregtech/common/terminal/app/game/maze/widget/MazeWidget.java deleted file mode 100644 index d3f71ebf18e..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/maze/widget/MazeWidget.java +++ /dev/null @@ -1,191 +0,0 @@ -package gregtech.common.terminal.app.game.maze.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.util.Position; -import gregtech.api.util.Size; - -import net.minecraft.util.math.Vec2f; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static gregtech.common.terminal.app.game.maze.MazeApp.MAZE_SIZE; - -public class MazeWidget extends Widget { - - boolean[][] topWalls = new boolean[MAZE_SIZE][MAZE_SIZE]; - boolean[][] leftWalls = new boolean[MAZE_SIZE][MAZE_SIZE]; - boolean[][] includedSpots; - private int squaresChecked; - - public MazeWidget() { - super(333 / 2 - (MAZE_SIZE * 5), 232 / 2 - (MAZE_SIZE * 5), MAZE_SIZE * 10, MAZE_SIZE * 10); - initMaze(); - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - // Draw outer lines - createBorder(); - // Draw inner lines - createInternalLines(); - } - - public void recalculateSize() { - this.setSelfPosition(new Position(333 / 2 - (MAZE_SIZE * 5), 232 / 2 - (MAZE_SIZE * 5))); - this.setSize(new Size(MAZE_SIZE * 10, MAZE_SIZE * 10)); - topWalls = new boolean[MAZE_SIZE][MAZE_SIZE]; - leftWalls = new boolean[MAZE_SIZE][MAZE_SIZE]; - } - - public void createBorder() { - List lineBuffer = new ArrayList<>(); - lineBuffer.add(new Vec2f(getPosition().x + 10, getPosition().y)); - lineBuffer.add(new Vec2f(this.getSize().width + getPosition().x, getPosition().y)); - lineBuffer.add(new Vec2f(this.getSize().width + getPosition().x, this.getSize().height + getPosition().y + 2)); // Corrects - // for - // line - // width - // misalignment - drawLines(lineBuffer, 0xFFFFFFFF, 0xFFFFFFFF, 4); - lineBuffer.clear(); - lineBuffer.add(new Vec2f(this.getSize().width + getPosition().x - 10, this.getSize().height + getPosition().y)); - lineBuffer.add(new Vec2f(getPosition().x, this.getSize().height + getPosition().y)); - lineBuffer.add(new Vec2f(getPosition().x, getPosition().y - 2)); - drawLines(lineBuffer, 0xFFFFFFFF, 0xFFFFFFFF, 4); - } - - public boolean isThereWallAt(int x, int y, boolean onTops) { - if (x >= MAZE_SIZE || y >= MAZE_SIZE) - return true; - if (x < 0 || y < 0) - return true; - if ((x == 0 && !onTops) || (y == 0 && onTops)) - return true; - if (onTops) { - return topWalls[x][y]; - } else { - return leftWalls[x][y]; - } - } - - public void createInternalLines() { - for (int i = 0; i < MAZE_SIZE; i++) { - for (int j = 0; j < MAZE_SIZE; j++) { - List list = new ArrayList<>(); - if (j != 0 && isThereWallAt(i, j, true)) { - list.add(new Vec2f(getPosition().x + 10 * i, getPosition().y + 10 * j)); - list.add(new Vec2f(getPosition().x + 10 * (i + 1), getPosition().y + 10 * j)); - drawLines(list, 0xFFFFFFFF, 0xFFFFFFFF, 2); - list.clear(); - } - if (i != 0 && isThereWallAt(i, j, false)) { - list.add(new Vec2f(getPosition().x + 10 * i, getPosition().y + 10 * j)); - list.add(new Vec2f(getPosition().x + 10 * i, getPosition().y + 10 * (j + 1))); - drawLines(list, 0xFFFFFFFF, 0xFFFFFFFF, 2); - } - } - } - } - - public void initMaze() { - includedSpots = new boolean[MAZE_SIZE][MAZE_SIZE]; - for (int i = 0; i < MAZE_SIZE; i++) { // Fill array with walls so that they can be carved out - for (int j = 0; j < MAZE_SIZE; j++) { - leftWalls[i][j] = true; - topWalls[i][j] = true; - } - } - - includedSpots[(int) (Math.random() * MAZE_SIZE)][(int) (Math.random() * MAZE_SIZE)] = true; // Can seed our - // particular maze - // Improves maze randomization. - List positions = new ArrayList<>(); - for (int i = 0; i < MAZE_SIZE * MAZE_SIZE; i++) { - positions.add(i); - } - Collections.shuffle(positions); - - for (int position : positions) { - if (!includedSpots[position / MAZE_SIZE][position % MAZE_SIZE]) { - do { - resetStuckCounter(); - } while (!this.createPath(position / MAZE_SIZE, position % MAZE_SIZE, - new boolean[MAZE_SIZE][MAZE_SIZE])); - } - } - } - - // Wilson random walk maze generation - public boolean createPath(int x, int y, boolean[][] walkedPaths) { - squaresChecked++; - if (squaresChecked > 20000) // Probably stuck. - return false; - if (walkedPaths[x][y]) - return false; - if (this.includedSpots[x][y]) - return true; - this.includedSpots[x][y] = true; - walkedPaths[x][y] = true; - // Find unoccupied directions - // Left 0 - List directions = new ArrayList<>(); - if (x != 0 && !walkedPaths[x - 1][y]) { - directions.add(0); - } - // Right 1 - if (x != MAZE_SIZE - 1 && !walkedPaths[x + 1][y]) { - directions.add(1); - } - // Up 2 - if (y != 0 && !walkedPaths[x][y - 1]) { - directions.add(2); - } - // Down 3 - if (y != MAZE_SIZE - 1 && !walkedPaths[x][y + 1]) { - directions.add(3); - } - Collections.shuffle(directions); - // Select one - while (directions.size() > 0) { - int direction = directions.get(directions.size() - 1); - // Use direction to create new coordinates - int newX = x; - int newY = y; - if (direction == 0) { - newX--; - } else if (direction == 1) { - newX++; - } else if (direction == 2) { - newY--; - } else if (direction == 3) { - newY++; - } - if (createPath(newX, newY, walkedPaths)) { - // Delete walls and return - if (direction == 0) { - leftWalls[x][y] = false; - } else if (direction == 1) { - leftWalls[x + 1][y] = false; - } else if (direction == 2) { - topWalls[x][y] = false; - } else if (direction == 3) { - topWalls[x][y + 1] = false; - } - return true; - } else { - directions.remove(directions.size() - 1); - } - } - // Reset current position - this.includedSpots[x][y] = false; - walkedPaths[x][y] = false; - return false; - } - - public void resetStuckCounter() { - squaresChecked = 0; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/maze/widget/PlayerWidget.java b/src/main/java/gregtech/common/terminal/app/game/maze/widget/PlayerWidget.java deleted file mode 100644 index 2198456833c..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/maze/widget/PlayerWidget.java +++ /dev/null @@ -1,36 +0,0 @@ -package gregtech.common.terminal.app.game.maze.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.util.Position; -import gregtech.common.terminal.app.game.maze.MazeApp; - -public class PlayerWidget extends Widget { - - protected MazeApp app; - public int posX; - public int posY; - - public PlayerWidget(int posX, int posY, MazeApp app) { - super(app.getRenderX(posX), app.getRenderY(posY), 10, 10); - this.app = app; - this.posX = posX; - this.posY = posY; - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - this.setSelfPosition(new Position(app.getRenderX(posX), app.getRenderY(posY))); - drawSolidRect(this.getPosition().x, this.getPosition().y, 10, 10, 0xAAAAAAFF); - } - - public void move(int deltaX, int deltaY) { - this.posX += deltaX; - this.posY += deltaY; - } - - public void setGridPosition(int posX, int posY) { - this.posX = posX; - this.posY = posY; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/minesweeper/MinesweeperApp.java b/src/main/java/gregtech/common/terminal/app/game/minesweeper/MinesweeperApp.java deleted file mode 100644 index 7608e54b85d..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/minesweeper/MinesweeperApp.java +++ /dev/null @@ -1,82 +0,0 @@ -package gregtech.common.terminal.app.game.minesweeper; - -import gregtech.api.gui.widgets.SimpleTextWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.common.terminal.app.game.minesweeper.widget.MineMapWidget; - -public class MinesweeperApp extends AbstractApplication { - - private MineMapWidget mineField; - private WidgetGroup textGroup; - private int timer; - private int resetCountdown = 100; - - public MinesweeperApp() { - super("minesweeper"); - } - - @Override - public AbstractApplication initApp() { - mineField = new MineMapWidget(20, 12, 40); - this.addWidget(mineField); - this.addWidget(new SimpleTextWidget(333 / 6, 10, "", 0xFFCCCCCC, this::getFlagsPercentage, true)); - textGroup = new WidgetGroup(0, 0, 200, 50); - this.addWidget(textGroup); - setTextStatus(); - - return this; - } - - @Override - public boolean canOpenMenuOnEdge() { - return false; - } - - @Override - public void updateScreen() { - super.updateScreen(); - if (mineField.hasWon() || mineField.hasLost()) { - if (mineField.hasWon()) { - mineField.notifyWon(); - } - resetCountdown--; - setTextStatus(); - } else - timer++; - if (resetCountdown == 0) { - mineField.resetData(); - resetCountdown = 100; - timer = 0; - setTextStatus(); - } - } - - public String getFlagsPercentage() { - return mineField.flagsPlaced + "/" + mineField.mineCount; - } - - public void setTextStatus() { // swap widget for localization - if (resetCountdown == 100) { - textGroup.clearAllWidgets(); - textGroup.addWidget(new SimpleTextWidget(333 / 8 * 5, 10, "terminal.minesweeper.time", 0xFFCCCCCC, - () -> String.valueOf(timer / 20), true)); // Normal - } else if (resetCountdown == 99) { - textGroup.clearAllWidgets(); - if (mineField.hasLost()) { - textGroup.addWidget(new SimpleTextWidget(333 / 8 * 5, 10, "terminal.minesweeper.lose", 0xFFCCCCCC, - () -> String.valueOf(resetCountdown / 20), true)); // Losing condition - } else { - textGroup.addWidget(new SimpleTextWidget(333 / 8 * 5, 10, "terminal.minesweeper.win.1", 0xFFCCCCCC, - () -> String.valueOf(timer / 20), true)); // Winning condition - textGroup.addWidget(new SimpleTextWidget(333 / 8 * 5, 20, "terminal.minesweeper.win.2", 0xFFCCCCCC, - () -> String.valueOf(resetCountdown / 20), true)); - } - } - } - - @Override - public boolean isClientSideApp() { - return true; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/minesweeper/widget/MineMapWidget.java b/src/main/java/gregtech/common/terminal/app/game/minesweeper/widget/MineMapWidget.java deleted file mode 100644 index 5037833c929..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/minesweeper/widget/MineMapWidget.java +++ /dev/null @@ -1,220 +0,0 @@ -package gregtech.common.terminal.app.game.minesweeper.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.TextureArea; -import gregtech.api.util.interpolate.RGBInterpolator; - -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.util.ResourceLocation; - -public class MineMapWidget extends Widget { - - private static final TextureArea COVERED = new TextureArea( - new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/covered.png"), 0, 0, 1, 1); - private static final TextureArea FLAG = new TextureArea( - new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/flag.png"), 0, 0, 1, 1); - private static final TextureArea BOMB = new TextureArea( - new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/bomb.png"), 0, 0, 1, 1); - - private static final TextureArea[] NUMBERS = { - new TextureArea(new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/blank.png"), 0, 0, 1, 1), - new TextureArea(new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/1.png"), 0, 0, 1, 1), - new TextureArea(new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/2.png"), 0, 0, 1, 1), - new TextureArea(new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/3.png"), 0, 0, 1, 1), - new TextureArea(new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/4.png"), 0, 0, 1, 1), - new TextureArea(new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/5.png"), 0, 0, 1, 1), - new TextureArea(new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/6.png"), 0, 0, 1, 1), - new TextureArea(new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/7.png"), 0, 0, 1, 1), - new TextureArea(new ResourceLocation("gregtech:textures/gui/terminal/minesweeper/8.png"), 0, 0, 1, 1) - }; - - public int mineCount; - public int flagsPlaced; - - private int width; - private int height; - - private boolean isPrepared; - - private boolean[][] mines; - private boolean[][] flags; - private boolean[][] checkedSpaces; - private int[][] generatedNumbers; - - private boolean isLost; - private boolean isWon; - private int timer = 0; - private static final RGBInterpolator interpolator = new RGBInterpolator(5, - (r, g, b) -> GlStateManager.color(r.floatValue(), g.floatValue(), b.floatValue()), - (r, g, b) -> GlStateManager.color(0, 0, 0)); - - public MineMapWidget(int width, int height, int mineCount) { - super(333 / 2 - width * 8, 232 / 2 - height * 8, width * 16, height * 16); - this.width = width; - this.height = height; - this.resetData(); - this.mineCount = mineCount; - } - - public void resetData() { - mines = new boolean[width][height]; - generatedNumbers = new int[width][height]; - checkedSpaces = new boolean[width][height]; - flags = new boolean[width][height]; - isLost = false; - isWon = false; - isPrepared = false; - flagsPlaced = 0; - } - - public void initMines(int startX, int startY) { - int minesPlaced = 0; - while (minesPlaced < mineCount) { - for (; minesPlaced < mineCount; minesPlaced++) { - placeMine(startX, startY); - } - - // Are there any sections that we can't figure out what's inside? - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { - boolean isTrapped = true; - // The weird ternaries here are making sure to not cause overflows - for (int xMod = i == 0 ? 0 : -1; xMod < (i == width - 1 ? 1 : 2); xMod++) { - for (int yMod = j == 0 ? 0 : -1; yMod < (j == height - 1 ? 1 : 2); yMod++) { - isTrapped &= mines[i + xMod][j + yMod]; - } - } - if (isTrapped) { - // Yes, so just take out the middle - mines[i][j] = false; - minesPlaced--; - } - } - } - } - - // Add to surrounding numbers for the mine - // The weird ternaries here are making sure to not cause overflows - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - if (mines[x][y]) { - for (int xMod = x == 0 ? 0 : -1; xMod < (x == width - 1 ? 1 : 2); xMod++) { - for (int yMod = y == 0 ? 0 : -1; yMod < (y == height - 1 ? 1 : 2); yMod++) { - generatedNumbers[x + xMod][y + yMod]++; - } - } - } - } - } - isPrepared = true; - } - - private void placeMine(int startX, int startY) { - int x = (int) (Math.random() * width); - int y = (int) (Math.random() * height); - - // The weird part to the right is making sure the player doesn't start on a numbered tile - while (mines[x][y] || ((startX < x + 3 && startX > x - 3) && (startY < y + 3 && startY > y - 3))) { - x = (int) (Math.random() * width); - y = (int) (Math.random() * height); - } - mines[x][y] = true; - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - timer++; - if (isWon && !interpolator.isActivated()) { // Fancy colors :) - interpolator.start(); - } - if (!isWon && interpolator.isActivated()) { - interpolator.stop(); - } - interpolator.update(); - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { - if (isLost && mines[i][j]) // If the player lost, show where the mines are. - BOMB.draw(i * 16 + getPosition().getX(), j * 16 + getPosition().getY(), 16, 16); - else if (!checkedSpaces[i][j]) { - if (flags[i][j]) - FLAG.draw(i * 16 + getPosition().getX(), j * 16 + getPosition().getY(), 16, 16); - else - COVERED.draw(i * 16 + getPosition().getX(), j * 16 + getPosition().getY(), 16, 16); - } else if (!mines[i][j]) - NUMBERS[generatedNumbers[i][j]].draw(i * 16 + getPosition().getX(), j * 16 + getPosition().getY(), - 16, 16); - else - BOMB.draw(i * 16 + getPosition().getX(), j * 16 + getPosition().getY(), 16, 16); - } - } - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (isWon || isLost) { - return false; // Don't let them interact now... - } - - int gridX = (mouseX - getPosition().getX()) / 16; - int gridY = (mouseY - getPosition().getY()) / 16; - if (gridX >= width || gridY >= height || gridX < 0 || gridY < 0) { - return false; - } - - if (button == 0 && !flags[gridX][gridY]) { - if (!isPrepared) - initMines(gridX, gridY); - if (generatedNumbers[gridX][gridY] == 0) - uncoverSafeTiles(gridX, gridY); - else - checkedSpaces[gridX][gridY] = true; - if (mines[gridX][gridY]) - isLost = true; - } else if (button == 1 && !checkedSpaces[gridX][gridY]) { - flags[gridX][gridY] = !flags[gridX][gridY]; - if (flags[gridX][gridY]) - flagsPlaced++; - else - flagsPlaced--; - } - - return true; - } - - private void uncoverSafeTiles(int x, int y) { - checkedSpaces[x][y] = true; - if (generatedNumbers[x][y] != 0) - return; - // Weird ternaries again for preventing ArrayIndexOutOfBounds exceptions - for (int xMod = x == 0 ? 0 : -1; xMod < (x == width - 1 ? 1 : 2); xMod++) { - for (int yMod = y == 0 ? 0 : -1; yMod < (y == height - 1 ? 1 : 2); yMod++) { - if (!checkedSpaces[x + xMod][y + yMod]) - uncoverSafeTiles(x + xMod, y + yMod); - } - } - } - - public boolean hasLost() { - return isLost; - } - - public boolean hasWon() { - if (!isPrepared) - return false; - for (int i = 0; i < width; i++) { - for (int j = 0; j < height; j++) { - if (mines[i][j] != flags[i][j] || checkedSpaces[i][j] == mines[i][j]) { // If there is an unchecked safe - // square, or an uncovered - // bomb... - return false; - } - } - } - return true; - } - - public void notifyWon() { - isWon = true; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/pong/PongApp.java b/src/main/java/gregtech/common/terminal/app/game/pong/PongApp.java deleted file mode 100644 index 32d3ad523aa..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/pong/PongApp.java +++ /dev/null @@ -1,175 +0,0 @@ -package gregtech.common.terminal.app.game.pong; - -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.SimpleTextWidget; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.Position; -import gregtech.common.terminal.app.game.pong.widget.BallWidget; -import gregtech.common.terminal.app.game.pong.widget.PaddleWidget; - -import org.lwjgl.input.Keyboard; -import org.lwjgl.util.vector.Vector2f; - -import java.awt.*; -import java.util.ArrayList; -import java.util.List; - -public class PongApp extends AbstractApplication { - - private BallWidget ball; - private int leftScore; - private int rightScore; - private List paddles; - private List solidObjects; - private int userInput = -1; - private int timer = 0; - - public PongApp() { - super("pong"); - } - - @Override - public AbstractApplication initApp() { - if (isClient) { - paddles = new ArrayList<>(); - solidObjects = new ArrayList<>(); - this.addWidget(new ImageWidget(5, 5, 333 - 10, 232 - 10, TerminalTheme.COLOR_B_2)); - this.addWidget(new ImageWidget(333 / 2 - 4, 5, 6, 232 - 10, new ColorRectTexture(0xAAAAAAAA))); - this.setBall(new BallWidget(333 / 2 - 1, 232 / 2 - 1)); - this.addWidget(new SimpleTextWidget(50, 20, "", 0xAAAAAA, () -> String.valueOf(this.getScore(true)), true)); - this.addWidget( - new SimpleTextWidget(283, 20, "", 0xAAAAAA, () -> String.valueOf(this.getScore(false)), true)); - this.initPaddles(); - } - return this; - } - - @Override - public boolean canOpenMenuOnEdge() { - return false; - } - - @Override - public boolean isClientSideApp() { - return true; - } - - public void setBall(BallWidget ball) { - this.ball = ball; - this.addWidget(ball); - } - - public void initPaddles() { - paddles.add(new PaddleWidget(20, 232 / 2 - 1, 4, 20, (PaddleWidget paddle) -> this.getUserInput())); - paddles.add(new PaddleWidget(313, 232 / 2 - 1, 4, 20, this::simplePaddleAI)); - paddles.forEach(this::addWidget); - this.solidObjects.add(new Rectangle(0, 0, 333, 10)); - this.solidObjects.add(new Rectangle(0, 222, 333, 10)); - } - - public void score(boolean side) { - if (side) { - leftScore++; - ball.theta = (float) Math.PI; - } else { - rightScore++; - ball.theta = (float) 0; - } - ball.theta += Math.random() * 0.2; - ball.setSelfPosition(new Position(333 / 2 - 1, 232 / 2 - 1)); - } - - @Override - public void updateScreenOnFrame() { - if (ball.getSelfPosition().getX() < 10) { - this.score(false); // Right side gains a point - } else if (ball.getSelfPosition().getX() > 323) { - this.score(true); // Left side gains a point - } else { - paddles.forEach((paddle) -> solidObjects.add(new Rectangle(paddle.toSelfRectangleBox()))); - int timeLeft = 1; - - TwoDimensionalRayTracer.TwoDimensionalRayTraceResult result = TwoDimensionalRayTracer - .nearestBoxSegmentCollision( - new Vector2f(ball.getSelfPosition().x, ball.getSelfPosition().y), - new Vector2f((float) (Math.cos(ball.theta) * 2), (float) (Math.sin(ball.theta) * 2)), - solidObjects, - new Vector2f(4, 4)); - while (result.time != 1 && timeLeft != 0) { - float angleMod = 0; - if (result.pos.y < result.collidedWith.getCenterY() - 2) { - angleMod -= Math.signum(result.normal.x) * 0.6; - } else if (result.pos.x > result.collidedWith.getCenterY() + 2) { - angleMod += Math.signum(result.normal.x) * 0.6; - } - ball.theta = (float) (Math.acos(result.normal.x) * 2 - ball.theta + Math.PI + angleMod) % (2 * Math.PI); // Reflects - // with - // a - // slight - // angle - // modification. - - if (ball.theta > Math.PI / 2 - 0.5 && ball.theta < Math.PI / 2 + 0.5) { - if (ball.theta <= Math.PI / 2) - ball.theta = Math.PI / 2 - 0.51; - else - ball.theta = Math.PI / 2 + 0.51; - } - if (ball.theta > 3 * Math.PI / 2 - 0.5 && ball.theta < 3 * Math.PI / 2 + 0.5) { - if (ball.theta < 3 * Math.PI / 2) - ball.theta = 3 * Math.PI / 2 - 0.51; - else - ball.theta = 3 * Math.PI / 2 + 0.51; - } - timeLeft -= result.time * timeLeft; - result = TwoDimensionalRayTracer.nearestBoxSegmentCollision( - new Vector2f(ball.getSelfPosition().x, ball.getSelfPosition().y), - new Vector2f((float) (Math.cos(ball.theta) * 3 * timeLeft), - (float) (Math.sin(ball.theta) * 3 * timeLeft)), - solidObjects, - new Vector2f(4, 4)); - // To prevent it getting permanently lodged into something. - ball.addSelfPosition((Math.cos(ball.theta) * 2 * (result.time + 0.1) * (timeLeft + 0.1)), - (Math.sin(ball.theta) * 2 * (result.time + 0.1) * (timeLeft + 0.1))); - } - ball.addSelfPosition((Math.cos(ball.theta) * 2 * timeLeft), (Math.sin(ball.theta) * 2 * timeLeft)); - solidObjects.remove(2); - solidObjects.remove(2); - } - if (ball.getSelfPosition().getY() > 222) { - ball.setSelfPosition(new Position(ball.getSelfPosition().getX(), 211)); - } else if (ball.getSelfPosition().getY() < 10) - ball.setSelfPosition(new Position(ball.getSelfPosition().getX(), 21)); - timer++; - if (Keyboard.isKeyDown(Keyboard.KEY_UP) ^ Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { - if (Keyboard.isKeyDown(Keyboard.KEY_UP)) - userInput = 1; - else - userInput = 0; - } else { - userInput = -1; - } - super.updateScreenOnFrame(); - } - - public int simplePaddleAI(PaddleWidget paddle) { - if (this.timer % 3 == 0) - return -1; - if ((ball.getSelfPosition().getY() + 2 * paddle.getSelfPosition().getY()) / 3 < paddle.getSelfPosition().getY()) - return 1; - else if ((ball.getSelfPosition().getY() + 2 * paddle.getSelfPosition().getY()) / 3 > - paddle.getSelfPosition().getY()) - return 0; - return -1; - } - - public int getScore(boolean side) { - return side ? leftScore : rightScore; - } - - public int getUserInput() { - return userInput; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/pong/TwoDimensionalRayTracer.java b/src/main/java/gregtech/common/terminal/app/game/pong/TwoDimensionalRayTracer.java deleted file mode 100644 index a32469e6fcb..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/pong/TwoDimensionalRayTracer.java +++ /dev/null @@ -1,86 +0,0 @@ -package gregtech.common.terminal.app.game.pong; - -import org.lwjgl.util.vector.Vector2f; - -import java.awt.*; -import java.util.List; - -import static net.minecraft.util.math.MathHelper.clamp; - -// Huge thanks to https://noonat.github.io/intersect! -public class TwoDimensionalRayTracer { - - public static class TwoDimensionalRayTraceResult { - - public Vector2f pos = new Vector2f(); - public Vector2f delta = new Vector2f(); - public Vector2f normal = new Vector2f(); - public float time = -1; - public Rectangle collidedWith = new Rectangle(); - } - - /** - * Detects the intersection between a segment and a box, if there is any. - * - * @param pos The original position of the point. - * @param delta The proposed new position of the point. - * @param boxSize The half-width and half-height of the box - * @return The resulting intersection between a segment and a box, or else null - */ - public static TwoDimensionalRayTraceResult intersectBoxSegment(Vector2f pos, Vector2f delta, Vector2f boxCenter, - Vector2f boxSize) { - float scaleX = (float) (1.0 / delta.x); - float scaleY = (float) (1.0 / delta.y); - float signX = Math.signum(scaleX); - float signY = Math.signum(scaleY); - float nearTimeX = (boxCenter.x - signX * (boxSize.x) - pos.x) * scaleX; - float nearTimeY = (boxCenter.y - signY * (boxSize.y) - pos.y) * scaleY; - float farTimeX = (boxCenter.x + signX * (boxSize.x) - pos.x) * scaleX; - float farTimeY = (boxCenter.y + signY * (boxSize.y) - pos.y) * scaleY; - - if (nearTimeX > farTimeY || nearTimeY > farTimeX) { - return null; - } - - double nearTime = Math.max(nearTimeX, nearTimeY); - double farTime = Math.min(farTimeX, farTimeY); - - if (nearTime >= 1 || farTime <= 0) { - return null; - } - - TwoDimensionalRayTraceResult result = new TwoDimensionalRayTraceResult(); - - result.time = (float) clamp(nearTime, 0, 1); - if (nearTimeX > nearTimeY) { - result.normal.x = -signX; - result.normal.y = 0; - } else { - result.normal.x = 0; - result.normal.y = -signY; - } - result.delta.x = (float) ((1.0 - result.time) * -delta.x); - result.delta.y = (float) ((1.0 - result.time) * -delta.y); - result.pos.x = pos.x + delta.x * result.time; - result.pos.y = pos.y + delta.y * result.time; - return result; - } - - public static TwoDimensionalRayTraceResult nearestBoxSegmentCollision(Vector2f pos, Vector2f delta, - List boxes, Vector2f padding) { - TwoDimensionalRayTraceResult result = new TwoDimensionalRayTraceResult(); - result.time = 1; - result.pos.x = pos.x + delta.x; - result.pos.y = pos.y + delta.y; - for (Rectangle box : boxes) { - TwoDimensionalRayTraceResult sweep = intersectBoxSegment(pos, delta, - new Vector2f((float) box.getCenterX(), (float) box.getCenterY()), - new Vector2f((float) box.getWidth() / 2 + padding.x, (float) box.getHeight() / 2 + padding.y)); - if (sweep != null && sweep.time < result.time) { - result = sweep; - result.collidedWith = box; - } - } - return result; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/pong/widget/BallWidget.java b/src/main/java/gregtech/common/terminal/app/game/pong/widget/BallWidget.java deleted file mode 100644 index 49aa63629af..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/pong/widget/BallWidget.java +++ /dev/null @@ -1,48 +0,0 @@ -package gregtech.common.terminal.app.game.pong.widget; - -import gregtech.api.gui.resources.TextureArea; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.util.Position; - -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.util.vector.Vector2f; - -public class BallWidget extends ImageWidget { - - public double theta; - private double xAccurate; - private double yAccurate; - - public BallWidget(int xPosition, int yPosition) { - super(xPosition, yPosition, 8, 8, - new TextureArea(new ResourceLocation("gregtech:textures/gui/widget/pong_ball.png"), 0, 0, 1, 1)); - theta = (Math.random() > 0.5 ? Math.PI : Math.PI / 2) + Math.random() * 0.2; - xAccurate = xPosition; - yAccurate = yPosition; - } - - @Override - public void setSelfPosition(Position selfPosition) { - super.setSelfPosition(selfPosition); - xAccurate = selfPosition.x; - yAccurate = selfPosition.y; - } - - @Override - public Position addSelfPosition(int addX, int addY) { - xAccurate += addX; - yAccurate += addY; - return super.addSelfPosition(addX, addY); - } - - public void addSelfPosition(double addX, double addY) { - xAccurate += addX; - yAccurate += addY; - super.setSelfPosition(new Position((int) xAccurate, (int) yAccurate)); - } - - public Vector2f getPreciseSelfPosition() { - return new Vector2f((float) xAccurate, (float) yAccurate); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/game/pong/widget/PaddleWidget.java b/src/main/java/gregtech/common/terminal/app/game/pong/widget/PaddleWidget.java deleted file mode 100644 index 758f2c80a20..00000000000 --- a/src/main/java/gregtech/common/terminal/app/game/pong/widget/PaddleWidget.java +++ /dev/null @@ -1,54 +0,0 @@ -package gregtech.common.terminal.app.game.pong.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.util.Position; - -import java.awt.*; -import java.util.function.Function; - -public class PaddleWidget extends Widget { - - Function controlSupplier; - - public PaddleWidget(int x, int y, int width, int height, Function controlSupplier) { - super(x, y, width, height); - this.controlSupplier = controlSupplier; - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - drawSolidRect(this.toRectangleBox().x - this.toRectangleBox().width / 2, - this.toRectangleBox().y - this.toRectangleBox().height / 2, this.toRectangleBox().width, - this.toRectangleBox().height, 0xFFFFFFFF); - } - - @Override - public void updateScreenOnFrame() { - super.updateScreenOnFrame(); - if (this.getSelfPosition().getY() < 30) { - this.setSelfPosition(new Position(this.getSelfPosition().getX(), 30)); - } - if (this.getSelfPosition().getY() > 202) { - this.setSelfPosition(new Position(this.getSelfPosition().getX(), 202)); - } - int speed; - switch (controlSupplier.apply(this)) { - case 0: - speed = 2; - break; - case 1: - speed = -2; - break; - default: - speed = 0; - } - this.addSelfPosition(0, speed); - } - - public Rectangle toSelfRectangleBox() { - return new Rectangle(this.getSelfPosition().x - this.toRectangleBox().width / 2 - 2, - this.getSelfPosition().y - this.toRectangleBox().height / 2, - this.toRectangleBox().width, this.toRectangleBox().height); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/GuideApp.java b/src/main/java/gregtech/common/terminal/app/guide/GuideApp.java deleted file mode 100644 index 2d94001217a..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/GuideApp.java +++ /dev/null @@ -1,337 +0,0 @@ -package gregtech.common.terminal.app.guide; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.TreeListWidget; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.menu.IMenuComponent; -import gregtech.api.terminal.util.TreeNode; -import gregtech.api.util.FileUtility; -import gregtech.api.util.GTLog; -import gregtech.api.util.Position; -import gregtech.api.util.Size; -import gregtech.common.terminal.app.guide.widget.GuidePageWidget; -import gregtech.common.terminal.component.SearchComponent; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.resources.I18n; -import net.minecraftforge.fml.common.FMLCommonHandler; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.*; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public abstract class GuideApp extends AbstractApplication implements - SearchComponent.IWidgetSearch>> { - - private GuidePageWidget pageWidget; - private TreeListWidget tree; - private TreeNode ROOT; - private Map jsonObjectMap; - private final IGuiTexture icon; - private float scale = 1; - - public GuideApp(String name, IGuiTexture icon) { - super(name); - this.icon = icon; - } - - @Override - public IGuiTexture getIcon() { - return icon; - } - - @Override - public AbstractApplication initApp() { - if (isClient) { - ROOT = new TreeNode<>(0, "root"); - jsonObjectMap = new HashMap<>(); - loadJsonFiles(); - buildTree(); - } - return this; - } - - protected void loadPage(TreeNode leaf) { - if (leaf == null) { - return; - } - if (this.pageWidget != null) { - this.removeWidget(this.pageWidget); - } - this.pageWidget = new GuidePageWidget(getOs().getSize().width - 200, 0, 200, getOs().getSize().height, 5); - if (leaf.isLeaf() && leaf.getContent() != null) { - JsonObject page = jsonObjectMap.get(leaf.getContent()); - if (page != null) { - this.pageWidget.loadJsonConfig(page); - } - } - this.addWidget(this.pageWidget); - this.onOSSizeUpdate(getOs().getSize().width, getOs().getSize().height); - } - - @Override - public boolean isClientSideApp() { - return true; - } - - protected IGuiTexture itemIcon(T item) { - return null; - } - - /** - * Should return a localised representation of the item - * - * @param item item - * @return localised name - */ - protected abstract String itemName(T item); - - protected abstract String rawItemName(T item); - - protected final TreeNode getTree() { - return ROOT; - } - - public final void loadJsonFiles() { - List jsons = new ArrayList<>(); - String lang = Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage().getLanguageCode(); - try { - Path guidePath = TerminalRegistry.TERMINAL_PATH.toPath().resolve("guide/" + this.getRegistryName()); - Path en_us = guidePath.resolve("en_us"); - List configPaths; - try (Stream stream = Files.walk(en_us)) { - configPaths = stream.filter(Files::isRegularFile) - .filter(f -> f.toString().endsWith(".json")) - .collect(Collectors.toList()); - } - configPaths.forEach(file -> { - File langFile = guidePath.resolve(lang + "/" + en_us.relativize(file)).toFile(); - JsonObject json = GuideApp.getConfig(langFile); - if (json == null) { - json = GuideApp.getConfig(file.toFile()); - } - if (json != null) { - jsons.add(json); - } - }); - } catch (IOException e) { - GTLog.logger.error("Failed to load file on path {}", "terminal", e); - } - ROOT = new TreeNode<>(0, "root"); - jsonObjectMap = new HashMap<>(); - for (JsonObject json : jsons) { - T t = ofJson(json); - if (t != null) { - registerItem(t, json.get("section").getAsString()); - jsonObjectMap.put(t, json); - } - } - } - - public abstract T ofJson(JsonObject json); - - private static JsonObject getConfig(File file) { - JsonElement je = FileUtility.loadJson(file); - return je == null ? null : je.isJsonObject() ? je.getAsJsonObject() : null; - } - - // ISearch - @Override - public boolean isManualInterrupt() { - return true; - } - - @Override - public void search(String word, Consumer>> find) { - Stack> stack = new Stack<>(); - if (getTree() != null) { - stack.push(getTree()); - dfsSearch(Thread.currentThread(), stack, word.toLowerCase(), find); - } - } - - private boolean dfsSearch(Thread thread, Stack> stack, String regex, - Consumer>> find) { - if (thread.isInterrupted()) { - return true; - } else { - TreeNode node = stack.peek(); - if (!node.isLeaf() && I18n.format(node.getKey()).toLowerCase().contains(regex)) { - find.accept((Stack>) stack.clone()); - } else if (node.isLeaf()) { - String name = itemName(node.getContent()); - if (name == null) { - name = node.getKey(); - } - if (I18n.format(name).toLowerCase().contains(regex)) { - find.accept((Stack>) stack.clone()); - } - } - if (node.getChildren() != null) { - for (TreeNode child : node.getChildren()) { - stack.push(child); - if (dfsSearch(thread, stack, regex, find)) return true; - stack.pop(); - } - } - } - return false; - } - - protected void registerItem(T item, String path) { - if (FMLCommonHandler.instance().getSide().isClient()) { - String[] parts = path.split("/"); - TreeNode child = ROOT; - if (!parts[0].isEmpty()) { - for (String sub : parts) { - child = child.getOrCreateChild(sub); - } - } - child.addContent(rawItemName(item), item); - } - } - - @Override - public void selectResult(Stack> result) { - if (result.size() > 0 && tree != null) { - List path = result.stream().map(TreeNode::getKey).collect(Collectors.toList()); - path.remove(0); - loadPage(tree.jumpTo(path)); - } - } - - @Override - public String resultDisplay(Stack> result) { - Iterator> iterator = result.iterator(); - if (!iterator.hasNext()) return ""; - iterator.next(); // skip root - StringBuilder builder = new StringBuilder(); - while (iterator.hasNext()) { - TreeNode node = iterator.next(); - builder.append(node.getContent() == null ? node.getKey() : itemName(node.getContent())); - if (iterator.hasNext()) - builder.append(" / "); - } - return builder.toString(); - } - - @Override - public List getMenuComponents() { - return Collections.singletonList(new SearchComponent<>(this)); - } - - private void buildTree() { - this.tree = new TreeListWidget<>(0, 0, getOs().getSize().width - 200, getOs().getSize().height, getTree(), - this::loadPage).setContentIconSupplier(this::itemIcon) - .setContentNameSupplier(this::itemName) - .setKeyNameSupplier(key -> key) - .setNodeTexture(GuiTextures.BORDERED_BACKGROUND) - .setLeafTexture(GuiTextures.SLOT_DARKENED); - this.addWidget(this.tree); - } - - @Override - protected void hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - if (this.tree != null) this.tree.drawInBackground(mouseX, mouseY, partialTicks, context); - if (this.pageWidget != null) { - Position position = this.pageWidget.getPosition(); - mouseX = (int) ((mouseX - position.x * (1 - scale)) / scale); - mouseY = (int) (mouseY / scale); - GlStateManager.translate(position.x * (1 - scale), 0, 0); - GlStateManager.scale(scale, scale, 1); - this.pageWidget.drawInBackground(mouseX, mouseY, partialTicks, context); - GlStateManager.scale(1 / scale, 1 / scale, 1); - GlStateManager.translate(position.x * (scale - 1), 0, 0); - } - } - - @Override - protected void hookDrawInForeground(int mouseX, int mouseY) { - if (this.tree != null) this.tree.drawInForeground(mouseX, mouseY); - if (this.pageWidget != null) { - Position position = this.pageWidget.getPosition(); - mouseX = (int) ((mouseX - position.x * (1 - scale)) / scale); - mouseY = (int) (mouseY / scale); - GlStateManager.translate(position.x * (1 - scale), 0, 0); - GlStateManager.scale(scale, scale, 1); - this.pageWidget.drawInForeground(mouseX, mouseY); - GlStateManager.scale(1 / scale, 1 / scale, 1); - GlStateManager.translate(position.x * (scale - 1), 0, 0); - } - } - - @Override - public boolean mouseWheelMove(int mouseX, int mouseY, int wheelDelta) { - if (this.tree != null && this.tree.mouseWheelMove(mouseX, mouseY, wheelDelta)) return true; - if (this.pageWidget != null) { - Position position = this.pageWidget.getPosition(); - mouseX = (int) ((mouseX - position.x * (1 - scale)) / scale); - mouseY = (int) (mouseY / scale); - return this.pageWidget.mouseWheelMove(mouseX, mouseY, wheelDelta); - } - return false; - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (this.tree != null && this.tree.mouseClicked(mouseX, mouseY, button)) return true; - if (this.pageWidget != null) { - Position position = this.pageWidget.getPosition(); - mouseX = (int) ((mouseX - position.x * (1 - scale)) / scale); - mouseY = (int) (mouseY / scale); - return this.pageWidget.mouseClicked(mouseX, mouseY, button); - } - return false; - } - - @Override - public boolean mouseDragged(int mouseX, int mouseY, int button, long timeDragged) { - if (this.tree != null && this.tree.mouseDragged(mouseX, mouseY, button, timeDragged)) return true; - if (this.pageWidget != null) { - Position position = this.pageWidget.getPosition(); - mouseX = (int) ((mouseX - position.x * (1 - scale)) / scale); - mouseY = (int) (mouseY / scale); - return this.pageWidget.mouseDragged(mouseX, mouseY, button, timeDragged); - } - return false; - } - - @Override - public boolean mouseReleased(int mouseX, int mouseY, int button) { - if (this.tree != null && this.tree.mouseReleased(mouseX, mouseY, button)) return true; - if (this.pageWidget != null) { - Position position = this.pageWidget.getPosition(); - mouseX = (int) ((mouseX - position.x * (1 - scale)) / scale); - mouseY = (int) (mouseY / scale); - return this.pageWidget.mouseReleased(mouseX, mouseY, button); - } - return false; - } - - @Override - public void onOSSizeUpdate(int width, int height) { - this.setSize(new Size(width, height)); - int treeWidth = Math.max(TerminalOSWidget.DEFAULT_WIDTH - 200, getOs().getSize().width / 3); - if (this.tree != null) { - this.tree.setSize(new Size(treeWidth, height)); - } - if (this.pageWidget != null) { - this.scale = (width - treeWidth) / 200f; - this.pageWidget.setSize(new Size(200, (int) (height / scale))); - this.pageWidget.setSelfPosition(new Position(treeWidth, 0)); - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/ItemGuideApp.java b/src/main/java/gregtech/common/terminal/app/guide/ItemGuideApp.java deleted file mode 100644 index d86bfe35d0c..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/ItemGuideApp.java +++ /dev/null @@ -1,103 +0,0 @@ -package gregtech.common.terminal.app.guide; - -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.resources.ItemStackTexture; -import gregtech.api.items.metaitem.MetaItem; -import gregtech.common.items.MetaItems; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.util.Objects; - -public class ItemGuideApp extends GuideApp { - - public ItemGuideApp() { - super("items", new ItemStackTexture(MetaItems.PROSPECTOR_LV.getStackForm())); - } - - @Override - protected String itemName(GuideItem item) { - return item.stack.getDisplayName(); - } - - @Override - protected String rawItemName(GuideItem item) { - if (item.stack.getItem() instanceof MetaItem) { - MetaItem.MetaValueItem metaValueItem = ((MetaItem) item.stack.getItem()) - .getItem((short) item.stack.getMetadata()); - if (metaValueItem != null) return metaValueItem.unlocalizedName; - } - return item.stack.getTranslationKey(); - } - - @Override - protected IGuiTexture itemIcon(GuideItem item) { - return new ItemStackTexture(item.stack); - } - - @Override - public GuideItem ofJson(JsonObject json) { - return GuideItem.ofJson(json); - } - - public static class GuideItem { - - public final ItemStack stack; - public final String name; - - public GuideItem(ItemStack stack, String name) { - this.stack = stack; - this.name = name; - } - - public GuideItem(ItemStack stack) { - this(stack, Objects.requireNonNull(stack.getItem().getRegistryName()) + ":" + stack.getMetadata()); - } - - public GuideItem(MetaItem.MetaValueItem item) { - this(item.getStackForm(), item.unlocalizedName); - } - - public static GuideItem ofJson(JsonObject json) { - if (json.has("item")) { - JsonElement element = json.get("item"); - if (element.isJsonPrimitive()) { - String[] s = element.getAsString().split(":"); - if (s.length < 2) return null; - Item item = Item.getByNameOrId(s[0] + ":" + s[1]); - if (item == null) return null; - int meta = 0; - if (s.length > 2) - meta = Integer.parseInt(s[2]); - return new GuideItem(new ItemStack(item, 1, meta)); - } - } - if (json.has("metaitem")) { - String metaItemId = json.get("metaitem").getAsString(); - for (MetaItem metaItem : MetaItem.getMetaItems()) { - MetaItem.MetaValueItem metaValueItem = metaItem.getAllItems().stream() - .filter(m -> m.unlocalizedName.equals(metaItemId)).findFirst().orElse(null); - if (metaValueItem != null) return new GuideItem(metaValueItem); - } - } - return null; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - GuideItem guideItem = (GuideItem) o; - return Objects.equals(stack, guideItem.stack) && Objects.equals(name, guideItem.name); - } - - @Override - public int hashCode() { - return Objects.hash(stack, name); - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/MultiBlockGuideApp.java b/src/main/java/gregtech/common/terminal/app/guide/MultiBlockGuideApp.java deleted file mode 100644 index 4f731b0572e..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/MultiBlockGuideApp.java +++ /dev/null @@ -1,50 +0,0 @@ -package gregtech.common.terminal.app.guide; - -import gregtech.api.GregTechAPI; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.resources.ItemStackTexture; -import gregtech.api.metatileentity.MetaTileEntity; -import gregtech.api.util.GTUtility; -import gregtech.common.metatileentities.MetaTileEntities; - -import net.minecraft.util.ResourceLocation; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -public class MultiBlockGuideApp extends GuideApp { - - public MultiBlockGuideApp() { - super("multiblocks", new ItemStackTexture(MetaTileEntities.ELECTRIC_BLAST_FURNACE.getStackForm())); - } - - @Override - public MetaTileEntity ofJson(JsonObject json) { - String[] valids = { "multiblock", "metatileentity" }; - if (json.isJsonObject()) { - for (String valid : valids) { - JsonElement id = json.getAsJsonObject().get(valid); - if (id != null && id.isJsonPrimitive()) { - ResourceLocation location = GTUtility.gregtechId(id.getAsString()); - return GregTechAPI.mteManager.getRegistry(location.getNamespace()).getObject(location); - } - } - } - return null; - } - - @Override - protected IGuiTexture itemIcon(MetaTileEntity item) { - return new ItemStackTexture(item.getStackForm()); - } - - @Override - protected String itemName(MetaTileEntity item) { - return item.getStackForm().getDisplayName(); - } - - @Override - protected String rawItemName(MetaTileEntity item) { - return item.metaTileEntityId.getPath(); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/SimpleMachineGuideApp.java b/src/main/java/gregtech/common/terminal/app/guide/SimpleMachineGuideApp.java deleted file mode 100644 index cec7ee6d88f..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/SimpleMachineGuideApp.java +++ /dev/null @@ -1,51 +0,0 @@ -package gregtech.common.terminal.app.guide; - -import gregtech.api.GTValues; -import gregtech.api.GregTechAPI; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.resources.ItemStackTexture; -import gregtech.api.metatileentity.MetaTileEntity; -import gregtech.api.util.GTUtility; -import gregtech.common.metatileentities.MetaTileEntities; - -import net.minecraft.util.ResourceLocation; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -public class SimpleMachineGuideApp extends GuideApp { - - public SimpleMachineGuideApp() { - super("machines", new ItemStackTexture(MetaTileEntities.CHEMICAL_REACTOR[GTValues.LV].getStackForm())); - } - - @Override - protected IGuiTexture itemIcon(MetaTileEntity item) { - return new ItemStackTexture(item.getStackForm()); - } - - @Override - protected String itemName(MetaTileEntity item) { - return item.getStackForm().getDisplayName(); - } - - @Override - protected String rawItemName(MetaTileEntity item) { - return item.metaTileEntityId.getPath(); - } - - @Override - public MetaTileEntity ofJson(JsonObject json) { - String[] valids = { "machine", "generator", "metatileentity" }; - if (json.isJsonObject()) { - for (String valid : valids) { - JsonElement id = json.getAsJsonObject().get(valid); - if (id != null && id.isJsonPrimitive()) { - ResourceLocation location = GTUtility.gregtechId(id.getAsString()); - return GregTechAPI.mteManager.getRegistry(location.getNamespace()).getObject(location); - } - } - } - return null; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/TutorialGuideApp.java b/src/main/java/gregtech/common/terminal/app/guide/TutorialGuideApp.java deleted file mode 100644 index eeed5585413..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/TutorialGuideApp.java +++ /dev/null @@ -1,32 +0,0 @@ -package gregtech.common.terminal.app.guide; - -import gregtech.api.gui.resources.ItemStackTexture; - -import net.minecraft.client.resources.I18n; -import net.minecraft.init.Items; - -import com.google.gson.JsonObject; - -public class TutorialGuideApp extends GuideApp { - - public TutorialGuideApp() { - super("tutorials", new ItemStackTexture(Items.PAPER)); - } - - @Override - protected String itemName(String item) { - return I18n.format(item); - } - - @Override - protected String rawItemName(String item) { - return item; - } - - @Override - public String ofJson(JsonObject json) { - if (json.has("tutorial")) - return json.get("tutorial").getAsString(); - return json.get("title").getAsString(); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/widget/CardWidget.java b/src/main/java/gregtech/common/terminal/app/guide/widget/CardWidget.java deleted file mode 100644 index 3d59cc9f862..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/widget/CardWidget.java +++ /dev/null @@ -1,80 +0,0 @@ -package gregtech.common.terminal.app.guide.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Position; -import gregtech.api.util.Size; -import gregtech.common.terminal.app.guideeditor.widget.configurator.BooleanConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.NumberConfigurator; - -import com.google.gson.JsonObject; - -import java.util.function.Consumer; - -public class CardWidget extends GuideWidget { - - public final static String NAME = "card"; - - // config - public int width; - public int height; - public boolean isShadow; - - @Override - public String getRegistryName() { - return NAME; - } - - @Override - public JsonObject getTemplate(boolean isFixed) { - JsonObject template = super.getTemplate(isFixed); - template.addProperty("fill", -3745585); - template.addProperty("width", 120); - template.addProperty("height", 60); - template.addProperty("isShadow", true); - return template; - } - - @Override - public void loadConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, boolean isFixed, - Consumer needUpdate) { - group.addWidget(new BooleanConfigurator(group, config, "isShadow", true).setOnUpdated(needUpdate)); - if (!isFixed) { - group.addWidget(new NumberConfigurator(group, config, "width").setOnUpdated(needUpdate)); - group.addWidget(new NumberConfigurator(group, config, "height").setOnUpdated(needUpdate)); - } - super.loadConfigurator(group, config, isFixed, needUpdate); - } - - @Override - protected Widget initStream() { - int pageWidth = getSize().width; - int x = getSelfPosition().x; - int y = getSelfPosition().y; - if (page != null) { - x = page.getMargin(); - pageWidth = page.getPageWidth() - 2 * x; - } - this.setSelfPosition(new Position(x + (pageWidth - width) / 2, y)); - return initFixed(); - } - - @Override - protected Widget initFixed() { - this.setSize(new Size(width, height)); - return this; - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - if (isShadow) { - int x = getPosition().x; - int y = getPosition().y; - int width = getSize().width; - int height = getSize().height; - drawRectShadow(x, y, width, height, 5); - } - super.drawInBackground(mouseX, mouseY, partialTicks, context); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/widget/GuidePageWidget.java b/src/main/java/gregtech/common/terminal/app/guide/widget/GuidePageWidget.java deleted file mode 100644 index bf388e66b09..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/widget/GuidePageWidget.java +++ /dev/null @@ -1,190 +0,0 @@ -package gregtech.common.terminal.app.guide.widget; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Position; -import gregtech.api.util.Size; -import gregtech.api.util.interpolate.Eases; -import gregtech.api.util.interpolate.Interpolator; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -import java.awt.*; -import java.util.*; -import java.util.List; - -public class GuidePageWidget extends DraggableScrollableWidgetGroup { - - public static final Map REGISTER_WIDGETS = new HashMap<>(); - - static { // register guide widgets - REGISTER_WIDGETS.put(TextBoxWidget.NAME, new TextBoxWidget()); - REGISTER_WIDGETS.put(ImageWidget.NAME, new ImageWidget()); - REGISTER_WIDGETS.put(CardWidget.NAME, new CardWidget()); - REGISTER_WIDGETS.put(SlotListWidget.NAME, new SlotListWidget()); - REGISTER_WIDGETS.put(TankListWidget.NAME, new TankListWidget()); - } - - protected TextBoxWidget title; - protected List stream = new ArrayList<>(); - protected List fixed = new ArrayList<>(); - protected Interpolator interpolator; - private final int margin; - - public GuidePageWidget(int xPosition, int yPosition, int width, int height, int margin) { - super(xPosition, yPosition, width, height); - this.margin = margin; - this.setBackground(new ColorRectTexture(-1)) - .setDraggable(true) - .setYScrollBarWidth(4) - .setYBarStyle(new ColorRectTexture(new Color(142, 142, 142)), - new ColorRectTexture(new Color(148, 226, 193))); - this.setUseScissor(false); - } - - public int getPageWidth() { - return this.getSize().width - yBarWidth; - } - - public int getMargin() { - return margin; - } - - public void setTitle(String config) { - int x = 5; - int y = 2; - int width = this.getSize().width - yBarWidth - 10; - int height = 0; - if (title != null) { - height = title.getSize().height; - x = title.getSelfPosition().x; - y = title.getSelfPosition().y; - removeWidget(title); - } - title = new TextBoxWidget(5, 2, width, - Collections.singletonList(config), - 0, 15, 0xffffffff, 0x6fff0000, 0xff000000, - true, true); - this.addWidget(title); - title.setSelfPosition(new Position(x, y)); - int offset = title.getSize().height - height; - if (offset != 0) { - for (Widget widget : stream) { - widget.addSelfPosition(0, offset); - } - } - } - - public String getTitle() { - return title == null ? "" : String.join("\n", title.content); - } - - public String loadJsonConfig(String config) { - try { - loadJsonConfig(new JsonParser().parse(config).getAsJsonObject()); - } catch (Exception e) { - this.clearAllWidgets(); - return e.getMessage(); - } - return null; - } - - public void loadJsonConfig(JsonObject config) { - this.stream.clear(); - this.fixed.clear(); - this.title = null; - this.clearAllWidgets(); - int pageWidth = getPageWidth(); - int margin = getMargin(); - // add title - setTitle(config.get("title").getAsString()); - - // add stream widgets - if (config.has("stream")) { - stream = new ArrayList<>(); - int y = title.getSize().height + 10; - for (JsonElement element : config.getAsJsonArray("stream")) { - JsonObject widgetConfig = element.getAsJsonObject(); - Widget widget = REGISTER_WIDGETS.get(widgetConfig.get("type").getAsString()) - .updateOrCreateStreamWidget(margin, y, pageWidth - 2 * margin, widgetConfig); - y += widget.getSize().height + 5; - stream.add(widget); - this.addWidget(widget); - } - } - // add fixed widgets - if (config.has("fixed")) { - fixed = new ArrayList<>(); - for (JsonElement element : config.getAsJsonArray("fixed")) { - JsonObject widgetConfig = element.getAsJsonObject(); - Widget widget = REGISTER_WIDGETS.get(widgetConfig.get("type").getAsString()).updateOrCreateFixedWidget( - widgetConfig.get("x").getAsInt(), - widgetConfig.get("y").getAsInt(), - widgetConfig.get("width").getAsInt(), - widgetConfig.get("height").getAsInt(), - widgetConfig); - fixed.add(widget); - this.addWidget(widget); - } - } - } - - public void onSizeUpdate(Widget widget, Size oldSize) { - int offset = widget.getSize().height - oldSize.height; - maxHeight = Math.max(maxHeight, widget.getSize().height + widget.getSelfPosition().y); - int index = stream.indexOf(widget); - if (index < 0) return; - for (int i = stream.size() - 1; i > index; i--) { - Widget nextWidget = stream.get(i); - nextWidget.addSelfPosition(0, offset); - } - } - - public void onPositionUpdate(Widget widget, Position oldPosition) { - if (oldPosition.y + widget.getSize().height == maxHeight) { - maxHeight = 0; - for (Widget widget1 : widgets) { - maxHeight = Math.max(maxHeight, widget1.getSize().height + widget1.getSelfPosition().y + scrollYOffset); - } - } - } - - protected int getStreamBottom() { - if (stream != null && stream.size() > 0) { - Widget widget = stream.get(stream.size() - 1); - return widget.getSize().height + widget.getSelfPosition().y + scrollYOffset; - } else { - return title.getSize().height + 10; - } - } - - @Override - public void updateScreen() { - if (interpolator != null) interpolator.update(); - super.updateScreen(); - } - - public void jumpToRef(String ref) { - if (interpolator != null && !interpolator.isFinish()) return; - for (Widget widget : widgets) { - if (widget instanceof IGuideWidget && ref.equals(((IGuideWidget) widget).getRef())) { - interpolator = new Interpolator(scrollYOffset, widget.getSelfPosition().y + scrollYOffset, 20, - Eases.QUAD_OUT, - value -> setScrollYOffset(value.intValue()), - value -> interpolator = null); - interpolator.start(); - } - } - } - - @Override - public void addWidget(Widget widget) { - super.addWidget(widget); - if (widget instanceof IGuideWidget) { - ((IGuideWidget) widget).setPage(this); - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/widget/GuideWidget.java b/src/main/java/gregtech/common/terminal/app/guide/widget/GuideWidget.java deleted file mode 100644 index 9055e6cf1cb..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/widget/GuideWidget.java +++ /dev/null @@ -1,185 +0,0 @@ -package gregtech.common.terminal.app.guide.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Position; -import gregtech.api.util.Size; -import gregtech.common.terminal.app.guideeditor.widget.configurator.ColorConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.NumberConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.StringConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.TextListConfigurator; - -import net.minecraft.item.ItemStack; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; - -public abstract class GuideWidget extends Widget implements IGuideWidget { - - // config - public String ref; - public int fill; - public int stroke; - public int stroke_width = 1; - public String link; - public List hover_text; - - private transient boolean isFixed; - protected transient GuidePageWidget page; - protected transient JsonObject config; - - public GuideWidget(int x, int y, int width, int height) { - super(x, y, width, height); - } - - public GuideWidget() { - super(Position.ORIGIN, Size.ZERO); - } - - @Override - public JsonObject getConfig() { - return config; - } - - @Override - public boolean isFixed() { - return isFixed; - } - - protected abstract Widget initFixed(); - - protected Widget initStream() { - return initFixed(); - } - - @Override - public void setStroke(int color) { - this.stroke = color; - } - - @Override - public void setSize(Size size) { - Size oldSize = this.getSize(); - super.setSize(size); - if (page != null) { - page.onSizeUpdate(this, oldSize); - } - } - - @Override - protected void recomputePosition() { - Position oldPosition = getPosition(); - super.recomputePosition(); - if (page != null) { - page.onPositionUpdate(this, oldPosition); - } - } - - @Override - public JsonObject getTemplate(boolean isFixed) { - JsonObject template = new JsonObject(); - template.addProperty("type", getRegistryName()); - if (isFixed) { - template.addProperty("x", 0); - template.addProperty("y", 0); - template.addProperty("width", 100); - template.addProperty("height", 100); - } - template.addProperty("ref", (String) null); - template.addProperty("stroke", (String) null); - template.addProperty("stroke_width", (String) null); - template.addProperty("fill", (String) null); - template.addProperty("link", (String) null); - template.add("hover_text", new Gson().toJsonTree(hover_text)); - return template; - } - - @Override - public void loadConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, boolean isFixed, - Consumer needUpdate) { - group.addWidget(new ColorConfigurator(group, config, "fill", 0).setOnUpdated(needUpdate)); - group.addWidget(new ColorConfigurator(group, config, "stroke", 0).setOnUpdated(needUpdate)); - group.addWidget(new NumberConfigurator(group, config, "stroke_width", 1).setOnUpdated(needUpdate)); - group.addWidget(new StringConfigurator(group, config, "ref", "").setOnUpdated(needUpdate)); - group.addWidget(new StringConfigurator(group, config, "link", "").setOnUpdated(needUpdate)); - group.addWidget(new TextListConfigurator(group, 40, config, "hover_text", "").setOnUpdated(needUpdate)); - } - - @Override - public String getRef() { - return ref; - } - - @Override - public Widget updateOrCreateStreamWidget(int x, int y, int pageWidth, JsonObject config) { - if (config == null) { - return initStream(); - } - GuideWidget widget = new Gson().fromJson(config, this.getClass()); - widget.isFixed = false; - widget.setSelfPosition(new Position(x, y)); - widget.setSize(new Size(pageWidth, 0)); - widget.config = config; - return widget.initStream(); - } - - @Override - public Widget updateOrCreateFixedWidget(int x, int y, int width, int height, JsonObject config) { - if (config == null) { - return initFixed(); - } - GuideWidget widget = new Gson().fromJson(config, this.getClass()); - widget.isFixed = true; - widget.setSelfPosition(new Position(x, y)); - widget.setSize(new Size(width, height)); - widget.config = config; - return widget.initFixed(); - } - - @Override - public void setPage(GuidePageWidget page) { - this.page = page; - } - - @Override - public void drawInForeground(int mouseX, int mouseY) { - if (link != null && isMouseOverElement(mouseX, mouseY)) { - Position position = getPosition(); - Size size = getSize(); - drawBorder(position.x, position.y, size.width, size.height, 0xff0000ff, stroke_width); - } - if ((hover_text != null || link != null) && isMouseOverElement(mouseX, mouseY)) { - List tooltip = hover_text == null ? new ArrayList<>() : new ArrayList<>(hover_text); - if (link != null) { - tooltip.add("§9Ctrl+Click§r §e(" + link + ")§r"); - } - drawHoveringText(ItemStack.EMPTY, tooltip, 100, mouseX, mouseY); - } - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - Position position = getPosition(); - Size size = getSize(); - if (stroke != 0) { - drawBorder(position.x, position.y, size.width, size.height, stroke, stroke_width); - } - if (fill != 0) { - drawSolidRect(position.x, position.y, size.width, size.height, fill); - } - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (link != null && isMouseOverElement(mouseX, mouseY) && isCtrlDown()) { - page.jumpToRef(link); - return true; - } - return false; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/widget/GuideWidgetGroup.java b/src/main/java/gregtech/common/terminal/app/guide/widget/GuideWidgetGroup.java deleted file mode 100644 index 51a91cf93dc..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/widget/GuideWidgetGroup.java +++ /dev/null @@ -1,196 +0,0 @@ -package gregtech.common.terminal.app.guide.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Position; -import gregtech.api.util.Size; -import gregtech.common.terminal.app.guideeditor.widget.configurator.ColorConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.NumberConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.StringConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.TextListConfigurator; - -import net.minecraft.item.ItemStack; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; - -public abstract class GuideWidgetGroup extends WidgetGroup implements IGuideWidget { - - // config - public String ref; - public int fill; - public int stroke; - public int stroke_width = 1; - public String link; - public List hover_text; - - private transient boolean isFixed; - protected transient GuidePageWidget page; - protected transient JsonObject config; - - public GuideWidgetGroup(int x, int y, int width, int height) { - super(x, y, width, height); - } - - public GuideWidgetGroup() { - super(Position.ORIGIN, Size.ZERO); - } - - @Override - public JsonObject getConfig() { - return config; - } - - @Override - public boolean isFixed() { - return isFixed; - } - - @Override - public void setStroke(int color) { - this.stroke = color; - } - - @Override - public void setSize(Size size) { - Size oldSize = this.getSize(); - super.setSize(size); - if (page != null) { - page.onSizeUpdate(this, oldSize); - } - } - - @Override - protected void recomputePosition() { - Position oldPosition = getPosition(); - super.recomputePosition(); - if (page != null) { - page.onPositionUpdate(this, oldPosition); - } - } - - @Override - public JsonObject getTemplate(boolean isFixed) { - JsonObject template = new JsonObject(); - template.addProperty("type", getRegistryName()); - if (isFixed) { - template.addProperty("x", 0); - template.addProperty("y", 0); - template.addProperty("width", 100); - template.addProperty("height", 100); - } - template.addProperty("ref", (String) null); - template.addProperty("stroke", (String) null); - template.addProperty("stroke_width", (String) null); - template.addProperty("fill", (String) null); - template.addProperty("link", (String) null); - template.add("hover_text", new Gson().toJsonTree(hover_text)); - return template; - } - - @Override - public void loadConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, boolean isFixed, - Consumer needUpdate) { - group.addWidget(new ColorConfigurator(group, config, "fill", 0).setOnUpdated(needUpdate)); - group.addWidget(new ColorConfigurator(group, config, "stroke", 0).setOnUpdated(needUpdate)); - group.addWidget(new NumberConfigurator(group, config, "stroke_width", 1).setOnUpdated(needUpdate)); - group.addWidget(new StringConfigurator(group, config, "ref", "").setOnUpdated(needUpdate)); - group.addWidget(new StringConfigurator(group, config, "link", "").setOnUpdated(needUpdate)); - group.addWidget(new TextListConfigurator(group, 40, config, "hover_text", "").setOnUpdated(needUpdate)); - } - - @Override - public String getRef() { - return ref; - } - - protected Widget initStream() { - return initFixed(); - } - - protected abstract Widget initFixed(); - - @Override - public Widget updateOrCreateStreamWidget(int x, int y, int pageWidth, JsonObject config) { - if (config == null) { - return initStream(); - } - GuideWidgetGroup widget = new Gson().fromJson(config, this.getClass()); - widget.isFixed = false; - widget.setSelfPosition(new Position(x, y)); - widget.setSize(new Size(pageWidth, 0)); - widget.config = config; - return widget.initStream(); - } - - @Override - public Widget updateOrCreateFixedWidget(int x, int y, int width, int height, JsonObject config) { - if (config == null) { - return initFixed(); - } - GuideWidgetGroup widget = new Gson().fromJson(config, this.getClass()); - widget.isFixed = true; - widget.setSelfPosition(new Position(x, y)); - widget.setSize(new Size(width, height)); - widget.config = config; - return widget.initFixed(); - } - - @Override - public void setPage(GuidePageWidget page) { - this.page = page; - } - - @Override - public void addWidget(Widget widget) { - super.addWidget(widget); - if (widget instanceof IGuideWidget) { - ((IGuideWidget) widget).setPage(page); - } - } - - @Override - public void drawInForeground(int mouseX, int mouseY) { - if (link != null && isMouseOverElement(mouseX, mouseY)) { - Position position = getPosition(); - Size size = getSize(); - drawBorder(position.x, position.y, size.width, size.height, 0xff0000ff, stroke_width); - } - if ((hover_text != null || link != null) && isMouseOverElement(mouseX, mouseY)) { - List tooltip = hover_text == null ? new ArrayList<>() : new ArrayList<>(hover_text); - if (link != null) { - tooltip.add("§9Ctrl+Click§r §e(" + link + ")§r"); - } - drawHoveringText(ItemStack.EMPTY, tooltip, 100, mouseX, mouseY); - } - super.drawInForeground(mouseX, mouseY); - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - Position position = getPosition(); - Size size = getSize(); - if (stroke != 0) { - drawBorder(position.x, position.y, size.width, size.height, stroke, stroke_width); - } - if (fill != 0) { - drawSolidRect(position.x, position.y, size.width, size.height, fill); - } - super.drawInBackground(mouseX, mouseY, partialTicks, context); - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (link != null && isMouseOverElement(mouseX, mouseY) && isCtrlDown()) { - page.jumpToRef(link); - return true; - } - return super.mouseClicked(mouseX, mouseY, button); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/widget/IGuideWidget.java b/src/main/java/gregtech/common/terminal/app/guide/widget/IGuideWidget.java deleted file mode 100644 index 7fb947c8c26..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/widget/IGuideWidget.java +++ /dev/null @@ -1,61 +0,0 @@ -package gregtech.common.terminal.app.guide.widget; - -import gregtech.api.gui.Widget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Position; -import gregtech.api.util.Size; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.lang.reflect.Field; -import java.util.function.Consumer; - -public interface IGuideWidget { - - String getRegistryName(); - - JsonObject getConfig(); - - boolean isFixed(); - - Widget updateOrCreateStreamWidget(int x, int y, int pageWidth, JsonObject config); - - Widget updateOrCreateFixedWidget(int x, int y, int width, int height, JsonObject config); - - void setPage(GuidePageWidget page); - - default void updateValue(String field) { - JsonObject config = getConfig(); - if (config != null && config.has(field)) { - try { - Field f = this.getClass().getField(field); - JsonElement value = config.get(field); - if (value.isJsonNull()) { // default - f.set(this, f.get(GuidePageWidget.REGISTER_WIDGETS.get(getRegistryName()))); - } else { - f.set(this, new Gson().fromJson(value, f.getGenericType())); - } - if (isFixed()) { - updateOrCreateFixedWidget(0, 0, 0, 0, null); - } else { - updateOrCreateStreamWidget(0, 0, 0, null); - } - } catch (Exception ignored) {} - } - } - - String getRef(); - - JsonObject getTemplate(boolean isFixed); - - void loadConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, boolean isFixed, - Consumer needUpdate); - - void setStroke(int color); - - default void onFixedPositionSizeChanged(Position position, Size size) { - updateOrCreateFixedWidget(0, 0, 0, 0, null); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/widget/ImageWidget.java b/src/main/java/gregtech/common/terminal/app/guide/widget/ImageWidget.java deleted file mode 100644 index b5f6fd5d71b..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/widget/ImageWidget.java +++ /dev/null @@ -1,112 +0,0 @@ -package gregtech.common.terminal.app.guide.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.resources.ItemStackTexture; -import gregtech.api.gui.resources.TextureArea; -import gregtech.api.gui.resources.URLTexture; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Position; -import gregtech.api.util.Size; -import gregtech.common.terminal.app.guideeditor.widget.configurator.NumberConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.SelectorConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.StringConfigurator; - -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.item.Item; -import net.minecraft.util.ResourceLocation; - -import com.google.gson.JsonObject; - -import java.util.Arrays; -import java.util.function.Consumer; - -public class ImageWidget extends GuideWidget { - - public final static String NAME = "image"; - // config - public String form; - public String source; - public int width; - public int height; - - public transient IGuiTexture image; - - @Override - public String getRegistryName() { - return NAME; - } - - @Override - public JsonObject getTemplate(boolean isFixed) { - JsonObject template = super.getTemplate(isFixed); - template.addProperty("form", "resource"); - template.addProperty("source", "gregtech:textures/gui/icon/gregtech_logo.png"); - template.addProperty("width", 50); - template.addProperty("height", 50); - return template; - } - - @Override - public void loadConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, boolean isFixed, - Consumer needUpdate) { - if (!isFixed) { - group.addWidget(new NumberConfigurator(group, config, "width").setOnUpdated(needUpdate)); - group.addWidget(new NumberConfigurator(group, config, "height").setOnUpdated(needUpdate)); - } - group.addWidget(new SelectorConfigurator(group, config, "form", Arrays.asList("url", "item", "resource")) - .setOnUpdated(needUpdate)); - group.addWidget(new StringConfigurator(group, config, "source").setOnUpdated(needUpdate)); - super.loadConfigurator(group, config, isFixed, needUpdate); - } - - @Override - public void updateScreen() { - if (image != null) { - image.updateTick(); - } - } - - @Override - protected Widget initStream() { - int pageWidth = getSize().width; - int x = getSelfPosition().x; - int y = getSelfPosition().y; - if (page != null) { - x = page.getMargin(); - pageWidth = page.getPageWidth() - 2 * x; - } - this.setSelfPosition(new Position(x + (pageWidth - Math.max(0, width)) / 2, y)); - return initFixed(); - } - - @Override - protected Widget initFixed() { - width = Math.max(0, width); - height = Math.max(0, height); - this.setSize(new Size(width, height)); - switch (form) { - case "url": - image = new URLTexture(source); - break; - case "item": - image = new ItemStackTexture(Item.getByNameOrId(source)); - break; - case "resource": - image = new TextureArea(new ResourceLocation(source), 0.0, 0.0, 1.0, 1.0); - break; - } - return this; - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - if (image != null) { - super.drawInBackground(mouseX, mouseY, partialTicks, context); - GlStateManager.color(1, 1, 1, 1); - Position position = getPosition(); - image.draw(position.x, position.y, getSize().width, getSize().height); - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/widget/SlotListWidget.java b/src/main/java/gregtech/common/terminal/app/guide/widget/SlotListWidget.java deleted file mode 100644 index 4fcb005954c..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/widget/SlotListWidget.java +++ /dev/null @@ -1,118 +0,0 @@ -package gregtech.common.terminal.app.guide.widget; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.widgets.SlotWidget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Size; -import gregtech.common.terminal.app.guideeditor.widget.configurator.ItemStackConfigurator; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.items.ItemStackHandler; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - -public class SlotListWidget extends GuideWidgetGroup { - - public final static String NAME = "slots"; - - // config - public List item_list; - - @Override - public Widget initFixed() { - this.clearAllWidgets(); - ItemStackHandler itemStackHandler = new ItemStackHandler(item_list.size()); - IGuiTexture background = new ColorRectTexture(0x4f000000); - int size = item_list.size(); - int maxXSize = getSize().width / 18; - int xPos; - if (maxXSize < 1) { - maxXSize = 1; - xPos = 0; - } else { - xPos = (getSize().width - (Math.min(size, maxXSize)) * 18) / 2; - } - int maxYSize = size / maxXSize + ((size % maxXSize) == 0 ? 0 : 1); - for (int y = 0; y <= size / maxXSize; y++) { - for (int x = 0; x < maxXSize; x++) { - int i = x + y * maxXSize; - if (i < size) { - itemStackHandler.setStackInSlot(i, item_list.get(i).getInstance()); - SlotWidget widget = new SlotWidget(itemStackHandler, i, xPos + x * 18, y * 18, false, false); - widget.setBackgroundTexture(background); - this.addWidget(widget); - } - } - } - setSize(new Size(getSize().width / 18 > 0 ? getSize().width : 18, maxYSize * 18)); - return this; - } - - @Override - public String getRegistryName() { - return NAME; - } - - @Override - public JsonObject getTemplate(boolean isFixed) { - JsonObject template = super.getTemplate(isFixed); - template.add("item_list", - new Gson().toJsonTree(Collections.singletonList(new ItemStackInfo("minecraft:ender_pearl", 0, 1)))); - return template; - } - - @Override - public void loadConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, boolean isFixed, - Consumer needUpdate) { - super.loadConfigurator(group, config, isFixed, needUpdate); - group.addWidget(new ItemStackConfigurator(group, config, "item_list").setOnUpdated(needUpdate)); - } - - public static class ItemStackInfo { - - // config - public String id; - public int damage; - public int count = 1; - - private transient ItemStack itemStack; - - public ItemStackInfo() {} - - public void update(ItemStack itemStack) { - ResourceLocation resourceLocation = itemStack.getItem().getRegistryName(); - id = resourceLocation == null ? "minecraft:air" : resourceLocation.toString(); - damage = itemStack.getItemDamage(); - count = itemStack.getCount(); - } - - public ItemStackInfo(String id, int damage, int count) { - this.id = id; - this.damage = damage; - this.count = count; - } - - public ItemStack getInstance() { - if (itemStack == null && id != null) { - Item item = Item.getByNameOrId(id); - if (item == null) { - itemStack = ItemStack.EMPTY; - return itemStack; - } - itemStack = item.getDefaultInstance(); - itemStack.setCount(count); - itemStack.setItemDamage(damage); - } - return itemStack == null ? ItemStack.EMPTY : itemStack; - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/widget/TankListWidget.java b/src/main/java/gregtech/common/terminal/app/guide/widget/TankListWidget.java deleted file mode 100644 index 8de6641bd72..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/widget/TankListWidget.java +++ /dev/null @@ -1,121 +0,0 @@ -package gregtech.common.terminal.app.guide.widget; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.widgets.TankWidget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Size; -import gregtech.common.terminal.app.guideeditor.widget.configurator.FluidStackConfigurator; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTank; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import java.awt.*; -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - -public class TankListWidget extends GuideWidgetGroup { - - public final static String NAME = "tanks"; - - // config - public List fluid_list; - - protected transient Rectangle scissor; - - @Override - public Widget initFixed() { - this.clearAllWidgets(); - IGuiTexture background = new ColorRectTexture(0x4f000000); - int size = fluid_list.size(); - int maxXSize = getSize().width / 18; - int xPos; - if (maxXSize < 1) { - maxXSize = 1; - xPos = 0; - } else { - xPos = (getSize().width - (Math.min(size, maxXSize)) * 18) / 2; - } - int maxYSize = size / maxXSize + ((size % maxXSize) == 0 ? 0 : 1); - for (int y = 0; y <= size / maxXSize; y++) { - for (int x = 0; x < maxXSize; x++) { - int i = x + y * maxXSize; - if (i < size) { - FluidStack fluidStack = fluid_list.get(i).getInstance(); - TankWidget widget = new TankWidget(new FluidTank(fluidStack, fluid_list.get(i).amount), - xPos + x * 18, y * 18, 18, 18); - widget.setBackgroundTexture(background).setAlwaysShowFull(true).setClient(); - this.addWidget(widget); - } - } - } - setSize(new Size(getSize().width / 18 > 0 ? getSize().width : 18, maxYSize * 18)); - return this; - } - - @Override - public String getRegistryName() { - return NAME; - } - - @Override - public JsonObject getTemplate(boolean isFixed) { - JsonObject template = super.getTemplate(isFixed); - template.add("fluid_list", - new Gson().toJsonTree(Collections.singletonList(new FluidStackInfo("distilled_water", 1)))); - return template; - } - - @Override - public void loadConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, boolean isFixed, - Consumer needUpdate) { - super.loadConfigurator(group, config, isFixed, needUpdate); - group.addWidget(new FluidStackConfigurator(group, config, "fluid_list").setOnUpdated(needUpdate)); - } - - public static class FluidStackInfo { - - // config - public String id; - public int amount = 1; - - private transient FluidStack fluidStack; - - public FluidStackInfo() {} - - public void update(FluidStack itemStack) { - if (itemStack != null) { - id = FluidRegistry.getFluidName(itemStack.getFluid()); - amount = itemStack.amount; - } else { - id = null; - fluidStack = null; - amount = 0; - } - } - - public FluidStackInfo(String id, int amount) { - this.id = id; - this.amount = amount; - } - - public FluidStack getInstance() { - if (fluidStack == null && id != null) { - Fluid fluid = FluidRegistry.getFluid(id); - if (fluid != null) { - fluidStack = new FluidStack(fluid, amount); - } else { - id = null; - } - } - return fluidStack; - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guide/widget/TextBoxWidget.java b/src/main/java/gregtech/common/terminal/app/guide/widget/TextBoxWidget.java deleted file mode 100644 index 465a4679b60..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guide/widget/TextBoxWidget.java +++ /dev/null @@ -1,125 +0,0 @@ -package gregtech.common.terminal.app.guide.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Position; -import gregtech.api.util.Size; -import gregtech.common.terminal.app.guideeditor.widget.configurator.BooleanConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.ColorConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.NumberConfigurator; -import gregtech.common.terminal.app.guideeditor.widget.configurator.TextListConfigurator; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.resources.I18n; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.function.Consumer; - -public class TextBoxWidget extends GuideWidget { - - public final static String NAME = "textbox"; - - // config - public List content; - public int space = 1; - public int fontSize = 9; - public int fontColor = 0xff000000; - public boolean isShadow = false; - public boolean isCenter = false; - - private transient List textLines; - - public TextBoxWidget(int x, int y, int width, List content, int space, int fontSize, int fontColor, - int fill, int stroke, boolean isCenter, boolean isShadow) { - super(x, y, width, 0); - this.content = content; - this.space = space; - this.fontSize = fontSize; - this.fontColor = fontColor; - this.fill = fill; - this.stroke = stroke; - this.isCenter = isCenter; - this.isShadow = isShadow; - this.initFixed(); - } - - public TextBoxWidget() {} - - @Override - public String getRegistryName() { - return NAME; - } - - @Override - public JsonObject getTemplate(boolean isFixed) { - JsonObject template = super.getTemplate(isFixed); - template.addProperty("space", (String) null); - template.addProperty("fontSize", (String) null); - template.addProperty("fontColor", (String) null); - template.addProperty("isCenter", (String) null); - template.addProperty("isShadow", (String) null); - template.add("content", new Gson().toJsonTree(Arrays.asList("this is a", "textbox!"))); - return template; - } - - @Override - public void loadConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, boolean isFixed, - Consumer needUpdate) { - group.addWidget(new TextListConfigurator(group, 200, config, "content").setOnUpdated(needUpdate)); - group.addWidget(new BooleanConfigurator(group, config, "isCenter", false).setOnUpdated(needUpdate)); - group.addWidget(new NumberConfigurator(group, config, "fontSize", 9).setOnUpdated(needUpdate)); - group.addWidget(new BooleanConfigurator(group, config, "isShadow", false).setOnUpdated(needUpdate)); - group.addWidget(new ColorConfigurator(group, config, "fontColor", 0xff000000).setOnUpdated(needUpdate)); - group.addWidget(new NumberConfigurator(group, config, "space", 1).setOnUpdated(needUpdate)); - super.loadConfigurator(group, config, isFixed, needUpdate); - } - - @Override - protected Widget initFixed() { - this.textLines = new ArrayList<>(); - FontRenderer font = Minecraft.getMinecraft().fontRenderer; - this.space = Math.max(space, 0); - this.fontSize = Math.max(fontSize, 1); - int wrapWidth = getSize().width * font.FONT_HEIGHT / fontSize; - if (content != null) { - for (String textLine : content) { - this.textLines.addAll(font.listFormattedStringToWidth(I18n.format(textLine), wrapWidth)); - } - } - this.setSize(new Size(this.getSize().width, this.textLines.size() * (fontSize + space))); - return this; - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - super.drawInBackground(mouseX, mouseY, partialTicks, context); - if (!textLines.isEmpty()) { - Position position = getPosition(); - Size size = getSize(); - FontRenderer font = Minecraft.getMinecraft().fontRenderer; - float scale = fontSize * 1.0f / font.FONT_HEIGHT; - GlStateManager.pushMatrix(); - GlStateManager.scale(scale, scale, 1); - GlStateManager.translate(position.x / scale, position.y / scale, 0); - float x = 0; - float y = 0; - float ySpace = font.FONT_HEIGHT + space / scale; - for (String textLine : textLines) { - if (isCenter) { - x = (size.width / scale - font.getStringWidth(textLine)) / 2; - } - font.drawString(textLine, x, y, fontColor, isShadow); - y += ySpace; - } - GlStateManager.popMatrix(); - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/GuideEditorApp.java b/src/main/java/gregtech/common/terminal/app/guideeditor/GuideEditorApp.java deleted file mode 100644 index a8d19adf9e7..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/GuideEditorApp.java +++ /dev/null @@ -1,61 +0,0 @@ -package gregtech.common.terminal.app.guideeditor; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.os.menu.IMenuComponent; -import gregtech.common.terminal.app.guideeditor.widget.GuideConfigEditor; -import gregtech.common.terminal.app.guideeditor.widget.GuidePageEditorWidget; -import gregtech.common.terminal.component.ClickComponent; - -import java.util.Arrays; -import java.util.List; - -public class GuideEditorApp extends AbstractApplication { - - private GuideConfigEditor configEditor; - - public GuideEditorApp() { - super("guide_editor"); - } - - @Override - public AbstractApplication initApp() { - if (isClient) { - this.configEditor = new GuideConfigEditor(0, 0, 133, 232, this); - GuidePageEditorWidget pageEditor = new GuidePageEditorWidget(133, 0, 200, 232, 5); - this.configEditor.setGuidePageEditorWidget(pageEditor); - pageEditor.setGuideConfigEditor(this.configEditor); - this.addWidget(pageEditor); - this.addWidget(this.configEditor); - } - return this; - } - - @Override - public List getMenuComponents() { - ClickComponent newPage = new ClickComponent().setIcon(GuiTextures.ICON_NEW_PAGE) - .setHoverText("terminal.component.new_page").setClickConsumer(cd -> { - if (configEditor != null) { - configEditor.newPage(); - } - }); - ClickComponent importPage = new ClickComponent().setIcon(GuiTextures.ICON_LOAD) - .setHoverText("terminal.component.load_file").setClickConsumer(cd -> { - if (configEditor != null) { - configEditor.loadJson(); - } - }); - ClickComponent exportPage = new ClickComponent().setIcon(GuiTextures.ICON_SAVE) - .setHoverText("terminal.component.save_file").setClickConsumer(cd -> { - if (configEditor != null) { - configEditor.saveJson(); - } - }); - return Arrays.asList(newPage, importPage, exportPage); - } - - @Override - public boolean isClientSideApp() { - return true; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/GuideConfigEditor.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/GuideConfigEditor.java deleted file mode 100644 index 0e23f2b6e46..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/GuideConfigEditor.java +++ /dev/null @@ -1,339 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget; - -import gregtech.api.GregTechAPI; -import gregtech.api.block.machines.MachineItemBlock; -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.AbstractWidgetGroup; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.gui.widgets.PhantomSlotWidget; -import gregtech.api.gui.widgets.TabGroup; -import gregtech.api.gui.widgets.TextFieldWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.gui.widgets.tab.IGuiTextureTabInfo; -import gregtech.api.metatileentity.MetaTileEntity; -import gregtech.api.metatileentity.registry.MTERegistry; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.CustomTabListRenderer; -import gregtech.api.terminal.gui.widgets.CircleButtonWidget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.SelectorWidget; -import gregtech.api.terminal.gui.widgets.TextEditorWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.FileUtility; -import gregtech.api.util.Position; -import gregtech.api.util.Size; -import gregtech.common.inventory.handlers.SingleItemStackHandler; -import gregtech.common.terminal.app.guide.GuideApp; -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.widget.GuidePageWidget; -import gregtech.common.terminal.app.guide.widget.IGuideWidget; -import gregtech.common.terminal.app.guideeditor.GuideEditorApp; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandlerModifiable; - -import com.google.gson.JsonObject; - -import java.awt.*; -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -public class GuideConfigEditor extends TabGroup { - - public String json; - private IGuideWidget selected; - private GuidePageEditorWidget pageEditor; - private TextEditorWidget titleEditor; - private final DraggableScrollableWidgetGroup widgetSelector; - private final DraggableScrollableWidgetGroup widgetConfigurator; - private final CircleButtonWidget[] addButton; - private final GuideEditorApp app; - private final IItemHandlerModifiable handler; - private final List candidates; - private String type; - - public GuideConfigEditor(int x, int y, int width, int height, GuideEditorApp app) { - super(x, y + 10, new CustomTabListRenderer(TerminalTheme.COLOR_F_2, TerminalTheme.COLOR_B_3, 30, 10)); - setSize(new Size(width, height)); - candidates = TerminalRegistry.getAllApps().stream().filter(GuideApp.class::isInstance) - .map(AbstractApplication::getUnlocalizedName).collect(Collectors.toList()); - type = candidates.get(candidates.size() - 1); - handler = new SingleItemStackHandler(1); - addButton = new CircleButtonWidget[2]; - widgetSelector = createWidgetSelector(); - widgetConfigurator = createConfigurator(); - this.addTab(new IGuiTextureTabInfo(new TextTexture("P", -1), "terminal.guide_editor.page_config"), - createPageConfig()); - this.addTab(new IGuiTextureTabInfo(new TextTexture("W", -1), "terminal.guide_editor.widgets_box"), - widgetSelector); - this.addTab(new IGuiTextureTabInfo(new TextTexture("C", -1), "terminal.guide_editor.widget_config"), - widgetConfigurator); - this.setOnTabChanged((oldIndex, newIndex) -> { - if (newIndex == 1) { - addButton[0].setVisible(true); - addButton[1].setVisible(true); - } else { - addButton[0].setVisible(false); - addButton[1].setVisible(false); - } - }); - addButton[0] = new CircleButtonWidget(115, 15, 8, 1, 8) - .setColors(new Color(255, 255, 255, 0).getRGB(), - TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_4.getColor()) - .setIcon(GuiTextures.ICON_ADD) - .setHoverText("terminal.guide_editor.add_stream") - .setClickListener(this::addStream); - addButton[1] = new CircleButtonWidget(115, 35, 8, 1, 8) - .setColors(new Color(255, 255, 255, 0).getRGB(), - TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_5.getColor()) - .setIcon(GuiTextures.ICON_ADD) - .setHoverText("terminal.guide_editor.add_fixed") - .setClickListener(this::addFixed); - addButton[0].setVisible(false); - addButton[1].setVisible(false); - this.app = app; - this.addWidget(addButton[0]); - this.addWidget(addButton[1]); - } - - public void setGuidePageEditorWidget(GuidePageEditorWidget pageEditor) { - this.pageEditor = pageEditor; - } - - public GuidePageEditorWidget getPageEditor() { - return pageEditor; - } - - private DraggableScrollableWidgetGroup createPageConfig() { - DraggableScrollableWidgetGroup group = new DraggableScrollableWidgetGroup(0, 0, getSize().width, - getSize().height - 10) - .setBackground(TerminalTheme.COLOR_B_3) - .setYScrollBarWidth(4) - .setYBarStyle(null, TerminalTheme.COLOR_F_1); - group.addWidget(new LabelWidget(5, 5, "section", -1).setShadow(true)); - group.addWidget(new TextFieldWidget(5, 15, 116, 20, new ColorRectTexture(0x9f000000), null, null) - .setTextResponder(s -> { - if (pageEditor != null) { - pageEditor.setSection(s); - } - }, true) - .setTextSupplier(() -> getPageEditor().getSection(), true) - .setMaxStringLength(Integer.MAX_VALUE) - .setValidator(s -> true)); - group.addWidget(new ImageWidget(5, 40, 116, 1, new ColorRectTexture(-1))); - group.addWidget(new LabelWidget(5, 45, "type", -1).setShadow(true)); - - group.addWidget(new SelectorWidget(30, 55, 91, 20, candidates, -1, - () -> type, true).setIsUp(true) - .setOnChanged(type -> this.type = type) - .setColors(TerminalTheme.COLOR_B_2.getColor(), TerminalTheme.COLOR_F_1.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setBackground(TerminalTheme.COLOR_6)); - group.addWidget(new PhantomSlotWidget(handler, 0, 6, 56).setBackgroundTexture(TerminalTheme.COLOR_B_2)); - - group.addWidget(new ImageWidget(5, 80, 116, 1, new ColorRectTexture(-1))); - - group.addWidget(new LabelWidget(5, 85, "title", -1).setShadow(true)); - titleEditor = new TextEditorWidget(5, 95, 116, 70, s -> { - if (pageEditor != null) { - pageEditor.setTitle(s); - } - }, true).setContent("Template").setBackground(new ColorRectTexture(0xA3FFFFFF)); - group.addWidget(titleEditor); - return group; - } - - public void updateTitle(String title) { - titleEditor.setContent(title); - } - - private DraggableScrollableWidgetGroup createWidgetSelector() { - DraggableScrollableWidgetGroup group = new DraggableScrollableWidgetGroup(0, 0, getSize().width, - getSize().height - 10) - .setBackground(TerminalTheme.COLOR_B_3) - .setYScrollBarWidth(4) - .setYBarStyle(null, TerminalTheme.COLOR_F_1); - int y = 10; // 133 - for (Map.Entry entry : GuidePageWidget.REGISTER_WIDGETS.entrySet()) { - IGuideWidget widgetTemplate = entry.getValue(); - JsonObject template = widgetTemplate.getTemplate(false); - Widget guideWidget = widgetTemplate.updateOrCreateStreamWidget(5, y + 10, getSize().width - 14, template); - group.addWidget(new LabelWidget(getSize().width / 2 - 1, y - 3, entry.getKey(), -1).setXCentered(true) - .setShadow(true)); - y += guideWidget.getSize().height + 25; - group.addWidget(guideWidget); - } - group.addWidget(new WidgetGroup(new Position(5, group.getWidgetBottomHeight() + 5), Size.ZERO)); - return group; - } - - private DraggableScrollableWidgetGroup createConfigurator() { - return new DraggableScrollableWidgetGroup(0, 0, getSize().width, getSize().height - 10) - .setBackground(TerminalTheme.COLOR_B_3) - .setYScrollBarWidth(4) - .setYBarStyle(null, TerminalTheme.COLOR_F_1); - } - - public void loadConfigurator(IGuideWidget widget) { - widgetConfigurator.clearAllWidgets(); - if (widget != null) { - widget.loadConfigurator(widgetConfigurator, widget.getConfig(), widget.isFixed(), type -> { - widget.updateValue(type); - if (pageEditor != null) { - pageEditor.computeMax(); - } - }); - widgetConfigurator.addWidget( - new WidgetGroup(new Position(5, widgetConfigurator.getWidgetBottomHeight() + 5), Size.ZERO)); - } - } - - public void newPage() { - TerminalDialogWidget - .showConfirmDialog(app.getOs(), "terminal.component.new_page", "terminal.component.confirm", res -> { - if (res) { - pageEditor.loadJsonConfig( - "{\"section\":\"default\",\"title\":\"Template\",\"stream\":[],\"fixed\":[]}"); - getPageEditor().setSection("default"); - updateTitle("Template"); - type = candidates.get(candidates.size() - 1); - handler.setStackInSlot(0, ItemStack.EMPTY); - } - }).setClientSide().open(); - } - - public void loadJson() { - if (pageEditor != null) { - File file = new File(TerminalRegistry.TERMINAL_PATH, "guide"); - TerminalDialogWidget.showFileDialog(app.getOs(), "terminal.component.load_file", file, true, result -> { - if (result != null && result.isFile()) { - try { - JsonObject config = Objects.requireNonNull(FileUtility.loadJson(result)).getAsJsonObject(); - pageEditor.loadJsonConfig(config); - getPageEditor().setSection(config.get("section").getAsString()); - updateTitle(config.get("title").getAsString()); - for (AbstractApplication app : TerminalRegistry.getAllApps()) { - if (app instanceof GuideApp) { - Object object = ((GuideApp) app).ofJson(config); - if (object != null) { - type = app.getUnlocalizedName(); - if (object instanceof ItemGuideApp.GuideItem) { - handler.setStackInSlot(0, ((ItemGuideApp.GuideItem) object).stack.copy()); - } else if (object instanceof MetaTileEntity) { - handler.setStackInSlot(0, ((MetaTileEntity) object).getStackForm()); - } else if (object instanceof ItemStack) { - handler.setStackInSlot(0, ((ItemStack) object).copy()); - } else { - handler.setStackInSlot(0, ItemStack.EMPTY); - } - break; - } - } - } - } catch (Exception e) { - TerminalDialogWidget.showInfoDialog(app.getOs(), "terminal.component.error", - "terminal.component.load_file.error").setClientSide().open(); - } - } - }).setClientSide().open(); - } - } - - public void saveJson() { - if (pageEditor != null) { - File file = new File(TerminalRegistry.TERMINAL_PATH, "guide"); - TerminalDialogWidget.showFileDialog(app.getOs(), "terminal.component.save_file", file, false, result -> { - if (result != null) { - if (!FileUtility.saveJson(result, saveType(pageEditor.getJsonConfig()))) { - TerminalDialogWidget.showInfoDialog(app.getOs(), "terminal.component.error", - "terminal.component.save_file.error").setClientSide().open(); - } - } - }).setClientSide().open(); - } - } - - private JsonObject saveType(JsonObject jsonObject) { - ItemStack stack = handler.getStackInSlot(0); - for (AbstractApplication app : TerminalRegistry.getAllApps()) { - if (app instanceof GuideApp) { - if (type.equals(app.getUnlocalizedName())) { - if (app instanceof ItemGuideApp) { - if (stack.isEmpty()) { - TerminalDialogWidget.showInfoDialog(app.getOs(), "terminal.component.warning", - "terminal.guide_editor.error_type").setClientSide().open(); - } else { - jsonObject.addProperty("item", Item.REGISTRY.getNameForObject(stack.getItem()).toString() + - ":" + stack.getMetadata()); - } - } else if ((app instanceof MultiBlockGuideApp || app instanceof SimpleMachineGuideApp) && - stack.getItem() instanceof MachineItemBlock) { - MTERegistry registry = GregTechAPI.mteManager.getRegistry( - Objects.requireNonNull(stack.getItem().getRegistryName()).getNamespace()); - MetaTileEntity mte = registry.getObjectById(stack.getItemDamage()); - if (mte != null) { - jsonObject.addProperty("metatileentity", - registry.getNameForObject(mte).getPath()); - } else { - TerminalDialogWidget.showInfoDialog(app.getOs(), "terminal.component.warning", - "terminal.guide_editor.error_type").setClientSide().open(); - } - } - return jsonObject; - } - } - } - return jsonObject; - } - - private void addFixed(ClickData data) { - if (pageEditor != null && selected != null) { - selected.setStroke(0); - pageEditor.addGuideWidget(selected, true); - selected.setStroke(0xFF7CA1FF); - } - } - - private void addStream(ClickData data) { - if (pageEditor != null && selected != null) { - selected.setStroke(0); - pageEditor.addGuideWidget(selected, false); - selected.setStroke(0xFF7CA1FF); - } - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - boolean flag = super.mouseClicked(mouseX, mouseY, button); - if (selectedTabIndex == 1 && widgetSelector != null) { - for (Widget widget : widgetSelector.widgets) { - if (widget.isMouseOverElement(mouseX, mouseY)) { - if (widget instanceof IGuideWidget) { - if (selected != null) { - selected.setStroke(0); - } - ((IGuideWidget) widget).setStroke(0xFF7CA1FF); - selected = (IGuideWidget) widget; - } - playButtonClickSound(); - return true; - } - } - } - return flag; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/GuidePageEditorWidget.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/GuidePageEditorWidget.java deleted file mode 100644 index 9f15e37b052..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/GuidePageEditorWidget.java +++ /dev/null @@ -1,408 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.gui.widgets.CircleButtonWidget; -import gregtech.api.terminal.gui.widgets.CustomPositionSizeWidget; -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 gregtech.common.terminal.app.guide.widget.GuidePageWidget; -import gregtech.common.terminal.app.guide.widget.IGuideWidget; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; - -public class GuidePageEditorWidget extends GuidePageWidget { - - private Widget selected; - private final WidgetGroup toolButtons; - private final CustomPositionSizeWidget customPositionSizeWidget; - private GuideConfigEditor configEditor; - private String section = "default"; - - public GuidePageEditorWidget(int xPosition, int yPosition, int width, int height, int margin) { - super(xPosition, yPosition, width, height, margin); - this.setDraggable(false); - setTitle("Template"); - customPositionSizeWidget = new CustomPositionSizeWidget(0xff0000ff, 0xffff0000, 2) - .setOnUpdated(this::onPosSizeChanged); - toolButtons = new WidgetGroup(Position.ORIGIN, Size.ZERO); - toolButtons.setVisible(false); - toolButtons.addWidget(new CircleButtonWidget(-20, -4, 8, 1, 12) - .setColors(0, - TerminalTheme.COLOR_B_2.getColor(), - TerminalTheme.COLOR_1.getColor()) - .setIcon(GuiTextures.ICON_UP) - .setHoverText("terminal.guide_editor.up") - .setClickListener(this::moveUp)); - toolButtons.addWidget(new CircleButtonWidget(0, -4, 8, 1, 12) - .setColors(0, - TerminalTheme.COLOR_B_2.getColor(), - TerminalTheme.COLOR_2.getColor()) - .setIcon(GuiTextures.ICON_DOWN) - .setHoverText("terminal.guide_editor.down") - .setClickListener(this::moveDown)); - toolButtons.addWidget(new CircleButtonWidget(20, -4, 8, 1, 12) - .setColors(0, - TerminalTheme.COLOR_B_2.getColor(), - TerminalTheme.COLOR_3.getColor()) - .setIcon(GuiTextures.ICON_REMOVE) - .setHoverText("terminal.guide_editor.remove") - .setClickListener(this::delete)); - addWidget(customPositionSizeWidget); - addWidget(toolButtons); - } - - public void setSection(String section) { - this.section = section; - } - - public String getSection() { - return section; - } - - private void onPosSizeChanged(Position pos, Size size) { - Widget widget = customPositionSizeWidget.getControlled(); - if (widget instanceof IGuideWidget && ((IGuideWidget) widget).isFixed()) { - JsonObject config = ((IGuideWidget) widget).getConfig(); - if (config.has("x")) { - config.addProperty("x", pos.x + scrollXOffset); - ((IGuideWidget) widget).updateValue("x"); - } - if (config.has("y")) { - config.addProperty("y", pos.y + scrollYOffset); - ((IGuideWidget) widget).updateValue("y"); - } - if (config.has("width")) { - config.addProperty("width", size.width); - ((IGuideWidget) widget).updateValue("width"); - } - if (config.has("height")) { - config.addProperty("height", size.height); - ((IGuideWidget) widget).updateValue("height"); - } - ((IGuideWidget) widget).onFixedPositionSizeChanged(pos, size); - } - toolButtons.setSelfPosition(new Position(pos.x + size.width / 2, pos.y)); - } - - public void setGuideConfigEditor(GuideConfigEditor configEditor) { - this.configEditor = configEditor; - } - - private void setToolButton(Widget widget) { - customPositionSizeWidget.setControlled(widget); - customPositionSizeWidget.setVisible(true); - customPositionSizeWidget.setActive(!(widget instanceof IGuideWidget) || ((IGuideWidget) widget).isFixed()); - toolButtons.setVisible(true); - toolButtons.setSelfPosition( - new Position(widget.getSelfPosition().x + widget.getSize().width / 2, widget.getSelfPosition().y)); - } - - private void delete(ClickData clickData) { - removeWidget(selected); - selected = null; - configEditor.loadConfigurator(null); - toolButtons.setSelfPosition(new Position(-scrollYOffset, -scrollYOffset)); - customPositionSizeWidget.setControlled(null); - toolButtons.setVisible(false); - } - - private void moveUp(ClickData clickData) { - moveUp(selected); - } - - private void moveDown(ClickData clickData) { - moveDown(selected); - } - - public JsonObject getJsonConfig() { - JsonObject json = new JsonObject(); - json.addProperty("section", section); - json.addProperty("title", title.content.get(0)); - JsonArray array = new JsonArray(); - json.add("stream", array); - stream.forEach(widget -> { - if (widget instanceof IGuideWidget) { - array.add(((IGuideWidget) widget).getConfig()); - } - }); - - JsonArray array2 = new JsonArray(); - json.add("fixed", array2); - fixed.forEach(widget -> { - if (widget instanceof IGuideWidget) { - array2.add(((IGuideWidget) widget).getConfig()); - } - }); - - return json; - } - - public JsonObject addGuideWidget(IGuideWidget widget, boolean isFixed) { - int pageWidth = getPageWidth(); - int margin = getMargin(); - JsonObject widgetConfig = widget.getTemplate(isFixed); - Widget guideWidget; - if (isFixed) { - int width = widgetConfig.get("width").getAsInt(); - int height = widgetConfig.get("height").getAsInt(); - - guideWidget = widget.updateOrCreateFixedWidget( - (pageWidth - width) / 2 + 5, - this.scrollYOffset + (this.getSize().height - height) / 2, - width, - height, - widgetConfig); - fixed.add(guideWidget); - this.addWidget(guideWidget); - } else { - int index = stream.indexOf(selected); - if (index >= 0) { - guideWidget = widget.updateOrCreateStreamWidget(margin, - selected.getSize().height + selected.getSelfPosition().y + scrollYOffset + 5, - pageWidth - 2 * margin, widgetConfig); - for (int i = index + 1; i < stream.size(); i++) { - stream.get(i).addSelfPosition(0, guideWidget.getSize().height + 5); - } - stream.add(index + 1, guideWidget); - } else { - guideWidget = widget.updateOrCreateStreamWidget(margin, getStreamBottom() + 5, pageWidth - 2 * margin, - widgetConfig); - stream.add(guideWidget); - } - this.addWidget(guideWidget); - computeMax(); - } - return widgetConfig; - } - - public void moveUp(Widget widget) { - int index = stream.indexOf(widget); - if (index > 0) { - Widget target = stream.get(index - 1); - if (interpolator == null) { - int offsetD = 5 + widget.getSize().height; - int offsetU = widget.getPosition().y - target.getPosition().y; - int y1 = widget.getSelfPosition().y; - int y2 = target.getSelfPosition().y; - interpolator = new Interpolator(0, 1, 10, Eases.LINEAR, value -> { - widget.setSelfPosition( - new Position(widget.getSelfPosition().x, (int) (y1 - value.floatValue() * offsetU))); - target.setSelfPosition( - new Position(target.getSelfPosition().x, (int) (y2 + value.floatValue() * offsetD))); - if (widget == selected) { - setToolButton(selected); - } - widget.setVisible(widget.getSelfPosition().y < scrollYOffset + getSize().height && - widget.getSelfPosition().y + widget.getSize().height > 0); - target.setVisible(target.getSelfPosition().y < scrollYOffset + getSize().height && - target.getSelfPosition().y + target.getSize().height > 0); - }, value -> { - interpolator = null; - stream.remove(widget); - stream.add(index - 1, widget); - }).start(); - } - } else { - int index2 = fixed.indexOf(widget); - if (index2 >= 0 && index2 < fixed.size() - 1) { - Widget target = fixed.get(index2 + 1); - fixed.remove(widget); - fixed.add(index2 + 1, widget); - } - } - } - - public void moveDown(Widget widget) { - int index = stream.indexOf(widget); - if (index >= 0 && index < stream.size() - 1) { - Widget target = stream.get(index + 1); - if (interpolator == null) { - int offsetD = 5 + target.getSize().height; - int offsetU = target.getPosition().y - widget.getPosition().y; - int y1 = widget.getSelfPosition().y; - int y2 = target.getSelfPosition().y; - interpolator = new Interpolator(0, 1, 10, Eases.LINEAR, value -> { - widget.setSelfPosition( - new Position(widget.getSelfPosition().x, (int) (y1 + value.floatValue() * offsetD))); - target.setSelfPosition( - new Position(target.getSelfPosition().x, (int) (y2 - value.floatValue() * offsetU))); - if (widget == selected) { - setToolButton(selected); - } - widget.setVisible(widget.getSelfPosition().y < getSize().height - xBarHeight && - widget.getSelfPosition().y + widget.getSize().height > 0); - target.setVisible(target.getSelfPosition().y < getSize().height - xBarHeight && - target.getSelfPosition().y + target.getSize().height > 0); - }, value -> { - interpolator = null; - stream.remove(widget); - stream.add(index + 1, widget); - }).start(); - } - } else { - int index2 = fixed.indexOf(widget); - if (index2 > 0) { - Widget target = fixed.get(index2 - 1); - fixed.remove(widget); - fixed.add(index2 - 1, widget); - } - } - } - - @Override - protected void setScrollYOffset(int scrollYOffset) { - if (scrollYOffset == this.scrollYOffset) return; - int offset = scrollYOffset - this.scrollYOffset; - this.scrollYOffset = scrollYOffset; - for (Widget widget : widgets) { - Position newPos = widget.addSelfPosition(0, -offset); - if (widget != toolButtons) { - widget.setVisible(newPos.y < getSize().height - xBarHeight && newPos.y + widget.getSize().height > 0); - } - } - } - - @Override - public void removeWidget(Widget widget) { - int index = stream.indexOf(widget); - if (index >= 0) { - int offset = widget.getSize().height + 5; - for (int i = stream.size() - 1; i > index; i--) { - Widget bottom = stream.get(i); - Position newPos = bottom.addSelfPosition(0, -offset); - bottom.setVisible(newPos.y < getSize().height - xBarHeight && newPos.y + widget.getSize().height > 0); - } - stream.remove(widget); - } else { - fixed.remove(widget); - } - super.removeWidget(widget); - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (super.mouseClicked(mouseX, mouseY, button)) { - return true; - } - boolean flag = false; - for (int i = fixed.size() - 1; i >= 0; i--) { - Widget widget = fixed.get(i); - if (widget.isMouseOverElement(mouseX, mouseY)) { - if (widget instanceof IGuideWidget && widget != selected) { - configEditor.loadConfigurator((IGuideWidget) widget); - selected = widget; - setToolButton(selected); - } - playButtonClickSound(); - flag = true; - break; - } - } - if (!flag) { - for (Widget widget : stream) { - if (widget.isMouseOverElement(mouseX, mouseY)) { - if (widget instanceof IGuideWidget && widget != selected) { - configEditor.loadConfigurator((IGuideWidget) widget); - selected = widget; - setToolButton(selected); - } - playButtonClickSound(); - flag = true; - break; - } - } - } - return flag; - } - - @Override - protected boolean hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - int x = getPosition().x; - int width = getSize().width; - if (title.isVisible()) { - title.drawInBackground(mouseX, mouseY, partialTicks, context); - } - for (Widget widget : stream) { - if (widget.isVisible()) { - widget.drawInBackground(mouseX, mouseY, partialTicks, context); - } - } - - boolean flag = false; - for (Widget widget : fixed) { - if (widget.isVisible()) { - widget.drawInBackground(mouseX, mouseY, partialTicks, context); - if (widget.isMouseOverElement(mouseX, mouseY)) { - if (widget != selected) { - drawSelectedBorder(x, width, widget); - } - flag = true; - } - } - } - if (!flag) { - for (Widget widget : stream) { - if (widget.isVisible() && widget != selected && widget.isMouseOverElement(mouseX, mouseY)) { - drawSelectedBorder(x, width, widget); - } - } - } - - if (selected != null) { - FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; - int index = fixed.indexOf(selected); - String layer = "L: " + (index >= 0 ? index : stream.indexOf(selected)); - fontRenderer.drawString(layer, - selected.getPosition().x + (selected.getSize().width - fontRenderer.getStringWidth(layer)) / 2F, - selected.getPosition().y - 20, - 0xffff0000, true); - } - if (toolButtons.isVisible()) { - customPositionSizeWidget.drawInBackground(mouseX, mouseY, partialTicks, context); - toolButtons.drawInBackground(mouseX, mouseY, partialTicks, context); - } - return true; - } - - private void drawSelectedBorder(int x, int width, Widget widget) { - Position pos = widget.getPosition(); - Size s = widget.getSize(); - if (stream.contains(widget)) { - drawSolidRect(x, pos.y, width - yBarWidth, s.height, 0x6f000000); - - } else { - drawSolidRect(pos.x, pos.y, s.width, s.height, 0x6f000000); - } - } - - @Override - public boolean mouseDragged(int mouseX, int mouseY, int button, long timeDragged) { - if (super.mouseDragged(mouseX, mouseY, button, timeDragged) && toolButtons.isVisible()) { - setToolButton(selected); - return true; - } - return false; - } - - @Override - public void clearAllWidgets() { - super.clearAllWidgets(); - selected = null; - configEditor.loadConfigurator(null); - toolButtons.setSelfPosition(new Position(-scrollYOffset, -scrollYOffset)); - customPositionSizeWidget.setControlled(null); - toolButtons.setVisible(false); - addWidget(customPositionSizeWidget); - addWidget(toolButtons); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/BooleanConfigurator.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/BooleanConfigurator.java deleted file mode 100644 index 8814b973136..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/BooleanConfigurator.java +++ /dev/null @@ -1,37 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget.configurator; - -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalTheme; - -import com.google.gson.JsonObject; - -import java.awt.*; - -public class BooleanConfigurator extends ConfiguratorWidget { - - public BooleanConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name) { - super(group, config, name); - } - - public BooleanConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name, - boolean defaultValue) { - super(group, config, name, defaultValue); - } - - protected void init() { - this.addWidget(new RectButtonWidget(0, 15, 10, 10, 2) - .setToggleButton(new ColorRectTexture(new Color(198, 198, 198).getRGB()), (c, p) -> updateValue(p)) - .setValueSupplier(true, () -> { - if (config.get(name).isJsonNull()) { - return defaultValue; - } - return config.get(name).getAsBoolean(); - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setIcon(new ColorRectTexture(new Color(0, 0, 0, 74).getRGB()))); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/ColorConfigurator.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/ColorConfigurator.java deleted file mode 100644 index 5ed6aec5fe6..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/ColorConfigurator.java +++ /dev/null @@ -1,26 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget.configurator; - -import gregtech.api.terminal.gui.widgets.ColorWidget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; - -import com.google.gson.JsonObject; - -public class ColorConfigurator extends ConfiguratorWidget { - - public ColorConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name, int defaultValue) { - super(group, config, name, defaultValue); - } - - public ColorConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name) { - super(group, config, name); - } - - protected void init() { - this.addWidget(new ColorWidget(0, 15, 85, 10).setColorSupplier(() -> { - if (config.get(name).isJsonNull()) { - return defaultValue; - } - return config.get(name).getAsInt(); - }, true).setOnColorChanged(this::updateValue)); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/ConfiguratorWidget.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/ConfiguratorWidget.java deleted file mode 100644 index 6d05bbac593..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/ConfiguratorWidget.java +++ /dev/null @@ -1,126 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget.configurator; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.util.Position; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.resources.I18n; -import net.minecraft.item.ItemStack; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import java.util.Collections; -import java.util.function.Consumer; - -public class ConfiguratorWidget extends WidgetGroup { - - protected T defaultValue; - protected String name; - protected boolean canDefault; - protected boolean isDefault; - protected JsonObject config; - protected DraggableScrollableWidgetGroup group; - private int nameWidth; - private Consumer onUpdated; - - public ConfiguratorWidget(DraggableScrollableWidgetGroup group, JsonObject config, String name) { - this(group, config, name, null); - } - - public ConfiguratorWidget(DraggableScrollableWidgetGroup group, JsonObject config, String name, T defaultValue) { - super(new Position(5, group.getWidgetBottomHeight() + 5)); - this.group = group; - this.defaultValue = defaultValue; - this.name = name; - this.canDefault = defaultValue != null; - this.config = config; - if (config.get(name) == null) { - config.addProperty(name, (String) null); - } - if (canDefault && config.get(name).isJsonNull()) { - isDefault = true; - } - this.addWidget(new LabelWidget(0, 4, name, -1).setShadow(true)); - if (isClientSide()) { - nameWidth = Minecraft.getMinecraft().fontRenderer.getStringWidth(name); - } - init(); - } - - protected void init() {} - - protected void updateValue(T value) { - if (canDefault && isDefault) return; - config.add(name, new Gson().toJsonTree(value)); - update(); - } - - public ConfiguratorWidget setOnUpdated(Consumer onUpdated) { - this.onUpdated = onUpdated; - return this; - } - - protected void update() { - if (onUpdated != null) { - onUpdated.accept(name); - } - } - - @Override - public void drawInForeground(int mouseX, int mouseY) { - int x = getPosition().x; - int y = getPosition().y; - if (canDefault && isMouseOver(x + nameWidth + 4, y + 6, 5, 5, mouseX, mouseY)) { - drawHoveringText(ItemStack.EMPTY, Collections.singletonList(I18n.format("terminal.guide_editor.default")), - 100, mouseX, mouseY); - } - if (!isDefault) { - super.drawInForeground(mouseX, mouseY); - } - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - int x = getPosition().x; - int y = getPosition().y; - drawSolidRect(x, y, this.getSize().width, 1, -1); - if (canDefault) { - drawBorder(x + nameWidth + 4, y + 6, 5, 5, -1, 1); - if (isDefault) { - drawSolidRect(x + nameWidth + 5, y + 7, 3, 3, -1); - } - } - if (canDefault && isDefault) { - super.drawInBackground(-100, -100, partialTicks, context); - drawSolidRect(x, y + 15, this.getSize().width, this.getSize().height - 15, 0x99000000); - } else { - super.drawInBackground(mouseX, mouseY, partialTicks, context); - } - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - int x = getPosition().x; - int y = getPosition().y; - if (!isDefault && super.mouseClicked(mouseX, mouseY, button)) { - return true; - } - if (canDefault && isMouseOver(x + nameWidth + 4, y + 6, 5, 5, mouseX, mouseY)) { - isDefault = !isDefault; - if (isDefault) { - config.addProperty(name, (String) null); - update(); - onDefault(); - } - playButtonClickSound(); - return true; - } - return false; - } - - protected void onDefault() {} -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/FluidStackConfigurator.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/FluidStackConfigurator.java deleted file mode 100644 index 21ab8671f03..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/FluidStackConfigurator.java +++ /dev/null @@ -1,106 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget.configurator; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.PhantomFluidWidget; -import gregtech.api.gui.widgets.SimpleTextWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.common.terminal.app.guide.widget.TankListWidget; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.util.ArrayList; -import java.util.List; - -public class FluidStackConfigurator extends ConfiguratorWidget> { - - DraggableScrollableWidgetGroup container; - List tanks; - - public FluidStackConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name) { - super(group, config, name); - } - - protected void init() { - container = new DraggableScrollableWidgetGroup(0, 27, 116, 100); - this.addWidget(container); - this.addWidget(new RectButtonWidget(0, 15, 116, 10, 1) - .setIcon(new TextTexture("terminal.guide_editor.add_slot", -1)) - .setClickListener(cd -> { - addSlot(container, new TankListWidget.FluidStackInfo(null, 0)); - updateValue(); - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor())); - tanks = new ArrayList<>(); - if (!config.get(name).isJsonNull()) { - Gson gson = new Gson(); - for (JsonElement o : config.get(name).getAsJsonArray()) { - addSlot(container, gson.fromJson(o, TankListWidget.FluidStackInfo.class)); - } - } - } - - private void addSlot(DraggableScrollableWidgetGroup container, TankListWidget.FluidStackInfo fluidStackInfo) { - WidgetGroup group = new WidgetGroup(0, tanks.size() * 20, 116, 20); - tanks.add(fluidStackInfo); - group.addWidget(new PhantomFluidWidget(1, 1, 18, 18, null, null) - .setBackgroundTexture(TerminalTheme.COLOR_B_2) - .setFluidStackSupplier(fluidStackInfo::getInstance, true) - .setFluidStackUpdater(fluidStack -> { - fluidStackInfo.update(fluidStack); - updateValue(); - }, true)); - group.addWidget(new RectButtonWidget(20, 0, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> { - fluidStackInfo.amount = Math.max(0, fluidStackInfo.amount - - (data.isShiftClick ? data.isCtrlClick ? 1000 : 10 : data.isCtrlClick ? 100 : 1)); - updateValue(); - }) - .setHoverText("Shift -10|Ctrl -100|Shift+Ctrl -1000") - .setIcon(new TextTexture("-1", -1))); - group.addWidget(new RectButtonWidget(76, 0, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> { - fluidStackInfo.amount = Math.max(0, fluidStackInfo.amount + - (data.isShiftClick ? data.isCtrlClick ? 1000 : 10 : data.isCtrlClick ? 100 : 1)); - updateValue(); - }) - .setHoverText("Shift +10|Ctrl +100|Shift+Ctrl +1000") - .setIcon(new TextTexture("+1", -1))); - group.addWidget(new ImageWidget(40, 0, 36, 20, TerminalTheme.COLOR_B_2)); - group.addWidget( - new SimpleTextWidget(58, 10, "", 0xFFFFFF, () -> Integer.toString(fluidStackInfo.amount), true)); - group.addWidget(new RectButtonWidget(96, 0, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> { - container.waitToRemoved(group); - tanks.remove(fluidStackInfo); - int index = container.widgets.indexOf(group); - for (int i = container.widgets.size() - 1; i > index; i--) { - container.widgets.get(i).addSelfPosition(0, -20); - } - updateValue(); - }) - .setIcon(GuiTextures.ICON_REMOVE)); - container.addWidget(group); - } - - private void updateValue() { - updateValue(tanks); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/ItemStackConfigurator.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/ItemStackConfigurator.java deleted file mode 100644 index 5171fd0cab7..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/ItemStackConfigurator.java +++ /dev/null @@ -1,104 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget.configurator; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.PhantomSlotWidget; -import gregtech.api.gui.widgets.SimpleTextWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.common.inventory.handlers.SingleItemStackHandler; -import gregtech.common.terminal.app.guide.widget.SlotListWidget; - -import net.minecraftforge.items.IItemHandlerModifiable; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.util.ArrayList; -import java.util.List; - -public class ItemStackConfigurator extends ConfiguratorWidget> { - - DraggableScrollableWidgetGroup container; - List slots; - - public ItemStackConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name) { - super(group, config, name); - } - - protected void init() { - container = new DraggableScrollableWidgetGroup(0, 27, 116, 100); - this.addWidget(container); - this.addWidget(new RectButtonWidget(0, 15, 116, 10, 1) - .setIcon(new TextTexture("terminal.guide_editor.add_slot", -1)) - .setClickListener(cd -> { - addSlot(container, new SlotListWidget.ItemStackInfo("minecraft:air", 0, 0)); - updateValue(); - }) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor())); - slots = new ArrayList<>(); - if (!config.get(name).isJsonNull()) { - Gson gson = new Gson(); - for (JsonElement o : config.get(name).getAsJsonArray()) { - addSlot(container, gson.fromJson(o, SlotListWidget.ItemStackInfo.class)); - } - } - } - - private void addSlot(DraggableScrollableWidgetGroup container, SlotListWidget.ItemStackInfo itemStackInfo) { - WidgetGroup group = new WidgetGroup(0, slots.size() * 20, 116, 20); - slots.add(itemStackInfo); - IItemHandlerModifiable handler = new SingleItemStackHandler(1); - handler.setStackInSlot(0, itemStackInfo.getInstance()); - group.addWidget(new PhantomSlotWidget(handler, 0, 1, 1).setBackgroundTexture(TerminalTheme.COLOR_B_2) - .setChangeListener(() -> { - itemStackInfo.update(handler.getStackInSlot(0)); - updateValue(); - })); - group.addWidget(new RectButtonWidget(20, 0, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> { - itemStackInfo.count = Math.max(0, itemStackInfo.count - (data.isShiftClick ? 10 : 1)); - updateValue(); - }) - .setIcon(new TextTexture("-1", -1))); - group.addWidget(new RectButtonWidget(76, 0, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> { - itemStackInfo.count = Math.max(0, itemStackInfo.count + (data.isShiftClick ? 10 : 1)); - updateValue(); - }) - .setIcon(new TextTexture("+1", -1))); - group.addWidget(new ImageWidget(40, 0, 36, 20, TerminalTheme.COLOR_B_2)); - group.addWidget(new SimpleTextWidget(58, 10, "", 0xFFFFFF, () -> Integer.toString(itemStackInfo.count), true)); - group.addWidget(new RectButtonWidget(96, 0, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> { - container.waitToRemoved(group); - slots.remove(itemStackInfo); - int index = container.widgets.indexOf(group); - for (int i = container.widgets.size() - 1; i > index; i--) { - container.widgets.get(i).addSelfPosition(0, -20); - } - updateValue(); - }) - .setIcon(GuiTextures.ICON_REMOVE)); - container.addWidget(group); - } - - private void updateValue() { - updateValue(slots); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/NumberConfigurator.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/NumberConfigurator.java deleted file mode 100644 index 7435a9fdfce..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/NumberConfigurator.java +++ /dev/null @@ -1,69 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget.configurator; - -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.SimpleTextWidget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalTheme; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -public class NumberConfigurator extends ConfiguratorWidget { - - public NumberConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name) { - super(group, config, name); - } - - public NumberConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name, int defaultValue) { - super(group, config, name, defaultValue); - } - - protected void init() { - int y = 15; - this.addWidget(new RectButtonWidget(0, y, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> adjustTransferRate(data.isShiftClick ? -100 : -10)) - .setIcon(new TextTexture("-10", -1))); - this.addWidget(new RectButtonWidget(96, y, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> adjustTransferRate(data.isShiftClick ? +100 : +10)) - .setIcon(new TextTexture("+10", -1))); - this.addWidget(new RectButtonWidget(20, y, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> adjustTransferRate(data.isShiftClick ? -5 : -1)) - .setIcon(new TextTexture("-1", -1))); - this.addWidget(new RectButtonWidget(76, y, 20, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> adjustTransferRate(data.isShiftClick ? +5 : +1)) - .setIcon(new TextTexture("+1", -1))); - this.addWidget(new ImageWidget(40, y, 36, 20, TerminalTheme.COLOR_B_2)); - this.addWidget(new SimpleTextWidget(58, 25, "", 0xFFFFFF, () -> { - JsonElement element = config.get(name); - if (element.isJsonNull()) { - return Integer.toString(defaultValue); - } - return element.getAsString(); - }, true)); - } - - private void adjustTransferRate(int added) { - JsonElement element = config.get(name); - int num = 0; - if (!element.isJsonNull()) { - num = element.getAsInt(); - } else { - num = defaultValue; - } - updateValue(num + added); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/SelectorConfigurator.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/SelectorConfigurator.java deleted file mode 100644 index e529beb7f32..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/SelectorConfigurator.java +++ /dev/null @@ -1,38 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget.configurator; - -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.SelectorWidget; -import gregtech.api.terminal.os.TerminalTheme; - -import com.google.gson.JsonObject; - -import java.util.List; - -public class SelectorConfigurator extends ConfiguratorWidget { - - public SelectorConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name, - List candidates, String defaultValue) { - super(group, config, name, defaultValue); - init(candidates); - } - - public SelectorConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name, - List candidates) { - super(group, config, name); - init(candidates); - } - - protected void init(List candidates) { - this.addWidget(new SelectorWidget(0, 15, 80, 20, candidates, -1, () -> { - if (config.get(name).isJsonNull()) { - return defaultValue; - } - return config.get(name).getAsString(); - }, true) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setIsUp(true) - .setOnChanged(this::updateValue)); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/StringConfigurator.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/StringConfigurator.java deleted file mode 100644 index a838e3952aa..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/StringConfigurator.java +++ /dev/null @@ -1,48 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget.configurator; - -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.TextFieldWidget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalTheme; - -import com.google.gson.JsonObject; - -public class StringConfigurator extends ConfiguratorWidget { - - private TextFieldWidget textFieldWidget; - - public StringConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name) { - super(group, config, name); - } - - public StringConfigurator(DraggableScrollableWidgetGroup group, JsonObject config, String name, - String defaultValue) { - super(group, config, name, defaultValue); - } - - protected void init() { - this.addWidget(new RectButtonWidget(76, 15, 40, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(data -> updateString()) - .setIcon(new TextTexture("terminal.guide_editor.update", -1))); - textFieldWidget = new TextFieldWidget(0, 15, 76, 20, TerminalTheme.COLOR_B_2, null, null) - .setMaxStringLength(Integer.MAX_VALUE) - .setValidator(s -> true); - if (config.has(name) && config.get(name).isJsonPrimitive()) { - textFieldWidget.setCurrentString(config.get(name).getAsString()); - } - this.addWidget(textFieldWidget); - } - - private void updateString() { - updateValue(textFieldWidget.getCurrentString()); - } - - @Override - protected void onDefault() { - textFieldWidget.setCurrentString(defaultValue); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/TextListConfigurator.java b/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/TextListConfigurator.java deleted file mode 100644 index f40ed1f8255..00000000000 --- a/src/main/java/gregtech/common/terminal/app/guideeditor/widget/configurator/TextListConfigurator.java +++ /dev/null @@ -1,48 +0,0 @@ -package gregtech.common.terminal.app.guideeditor.widget.configurator; - -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.TextEditorWidget; - -import com.google.gson.*; - -import java.util.Collections; -import java.util.List; - -public class TextListConfigurator extends ConfiguratorWidget> { - - private TextEditorWidget editor; - - public TextListConfigurator(DraggableScrollableWidgetGroup group, int height, JsonObject config, String name) { - super(group, config, name); - init(height); - } - - public TextListConfigurator(DraggableScrollableWidgetGroup group, int height, JsonObject config, String name, - String defaultValue) { - super(group, config, name, Collections.singletonList(defaultValue)); - init(height); - } - - protected void init(int height) { - JsonElement element = config.get(name); - String initValue = ""; - if (!element.isJsonNull()) { - List init = new Gson().fromJson(element, List.class); - initValue = String.join("\n", init); - - } - editor = new TextEditorWidget(0, 15, 116, height, this::updateTextList, true).setContent(initValue) - .setBackground(new ColorRectTexture(0xA3FFFFFF)); - this.addWidget(editor); - } - - private void updateTextList(String saved) { - updateValue(Collections.singletonList(saved)); - } - - @Override - protected void onDefault() { - editor.setContent(defaultValue.get(0)); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/hardwaremanager/HardwareManagerApp.java b/src/main/java/gregtech/common/terminal/app/hardwaremanager/HardwareManagerApp.java deleted file mode 100644 index 21554ada83b..00000000000 --- a/src/main/java/gregtech/common/terminal/app/hardwaremanager/HardwareManagerApp.java +++ /dev/null @@ -1,110 +0,0 @@ -package gregtech.common.terminal.app.hardwaremanager; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.resources.*; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.hardware.Hardware; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.client.shader.Shaders; -import gregtech.common.items.MetaItems; - -import net.minecraft.client.renderer.GlStateManager; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import java.util.concurrent.atomic.AtomicInteger; - -public class HardwareManagerApp extends AbstractApplication { - - private static final TextureArea CIRCUIT_LINE = TextureArea - .fullImage("textures/gui/terminal/hardware_manager/circuit.png"); - @SideOnly(Side.CLIENT) - private ShaderTexture circuit; - private HardwareSlotWidget selected; - private WidgetGroup apps; - - public HardwareManagerApp() { - super("hardware"); - } - - @Override - public IGuiTexture getIcon() { - return new ItemStackTexture(MetaItems.INTEGRATED_CIRCUIT.getStackForm()); - } - - @Override - public AbstractApplication initApp() { - apps = new WidgetGroup(); - this.addWidget(apps); - int x = 10; - int y = 65; - for (Hardware hardware : os.hardwareProvider.getProviders().values()) { - HardwareSlotWidget hardwareSlotWidget = new HardwareSlotWidget(x, y, os, hardware); - this.addWidget(hardwareSlotWidget); - hardwareSlotWidget.setOnSelected(() -> { - selected = hardwareSlotWidget; - apps.clearAllWidgets(); - AtomicInteger index = new AtomicInteger(0); - for (AbstractApplication installed : getOs().installedApps) { - TerminalRegistry - .getAppHardwareDemand(installed.getRegistryName(), - getOs().tabletNBT.getCompoundTag(installed.getRegistryName()).getInteger("_tier")) - .stream() - .filter(hardware::isHardwareAdequate).findFirst() - .ifPresent(X -> { - apps.addWidget(new RectButtonWidget(162 + (index.get() % 4) * 25, - 122 + (index.get() / 4) * 30, 20, 20, 2) - .setIcon(installed.getIcon()) - .setHoverText(installed.getUnlocalizedName()) - .setColors(0, TerminalTheme.COLOR_7.getColor(), 0)); - index.getAndIncrement(); - }); - } - }); - x += 25; - } - return this; - } - - @Override - protected void hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - int x = getPosition().x; - int y = getPosition().y; - int width = getSize().width; - int height = getSize().height; - float time = (gui.entityPlayer.ticksExisted + partialTicks) / 20f; - if (Shaders.allowedShader()) { - if (circuit == null) { - circuit = ShaderTexture.createShader("circuit.frag"); - } - ResourceHelper.bindTexture("textures/gui/terminal/terminal_background.png"); - circuit.draw(x, y, width, height, uniformCache -> { - uniformCache.glUniform1F("u_time", time); - uniformCache.glUniform2F("u_mouse", - (float) (mouseX - x) * circuit.getResolution(), - (float) (mouseY - y) * circuit.getResolution()); - }); - } else { - drawSolidRect(x, y, width, height, TerminalTheme.COLOR_B_2.getColor()); - } - GlStateManager.color(1, 1, 1, 0.8f); - CIRCUIT_LINE.draw(x, y, width, height); - GlStateManager.color(1, 1, 1, 1); - - super.hookDrawInBackground(mouseX, mouseY, partialTicks, context); - if (selected != null) { - int sX = x + selected.getSelfPosition().x; - int sY = y + selected.getSelfPosition().y; - int sW = selected.getSize().width; - int sH = selected.getSize().height; - drawBorder(sX, sY, sW, sH, 0xff00af00, 1); - drawSolidRect(sX + sW / 2, sY + sH, 1, 10, 0xff00af00); - drawSolidRect(sX + sW / 2, sY + sH + 10, x + 210 - sX - sW / 2, 1, 0xff00af00); - drawSolidRect(x + 210, sY + sH + 10, 1, y + 110 - sY - sH, 0xff00af00); - } - drawBorder(x + 160, y + 120, 25 * 4, 25 * 4, selected == null ? -1 : 0xff00af00, 1); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/hardwaremanager/HardwareSlotWidget.java b/src/main/java/gregtech/common/terminal/app/hardwaremanager/HardwareSlotWidget.java deleted file mode 100644 index 25c0e795dd3..00000000000 --- a/src/main/java/gregtech/common/terminal/app/hardwaremanager/HardwareSlotWidget.java +++ /dev/null @@ -1,132 +0,0 @@ -package gregtech.common.terminal.app.hardwaremanager; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.hardware.Hardware; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalOSWidget; - -import net.minecraft.client.resources.I18n; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.PacketBuffer; - -import java.util.Arrays; -import java.util.Collections; - -public class HardwareSlotWidget extends WidgetGroup { - - private final Hardware hardware; - private final TerminalOSWidget os; - private Runnable onSelected; - - public HardwareSlotWidget(int x, int y, TerminalOSWidget os, Hardware hardware) { - super(x, y, 20, 20); - this.os = os; - this.hardware = hardware; - } - - public void setOnSelected(Runnable onSelected) { - this.onSelected = onSelected; - } - - private void showDialog(int button) { - if (button == 0) { - if (hardware.hasHW()) { - onSelected.run(); - } else { - TerminalDialogWidget.showItemSelector(os, "terminal.hardware.select", true, - itemStack -> hardware.acceptItemStack(itemStack) != null, - itemStack -> { - NBTTagCompound tag = hardware.acceptItemStack(itemStack); - if (tag != null) { - tag.setTag("item", itemStack.serializeNBT()); - os.hardwareProvider.getOrCreateHardwareCompound().setTag(hardware.getRegistryName(), - tag); - os.hardwareProvider.cleanCache(hardware.getRegistryName()); - } - }).open(); - } - } else { - if (hardware.hasHW()) { - boolean emptySlot = false; - for (ItemStack itemStack : gui.entityPlayer.inventory.mainInventory) { - if (itemStack.isEmpty()) { - emptySlot = true; - break; - } - } - if (emptySlot) { - TerminalDialogWidget - .showConfirmDialog(os, "terminal.hardware.remove", "terminal.component.confirm", result -> { - if (result) { - NBTTagCompound tag = os.hardwareProvider.getOrCreateHardwareCompound() - .getCompoundTag(hardware.getRegistryName()); - if (!tag.isEmpty() && tag.hasKey("item")) { - gui.entityPlayer.inventory.addItemStackToInventory( - hardware.onHardwareRemoved(new ItemStack(tag.getCompoundTag("item")))); - } - os.hardwareProvider.getOrCreateHardwareCompound() - .removeTag(hardware.getRegistryName()); - os.hardwareProvider.cleanCache(hardware.getRegistryName()); - } - }).open(); - } else { - TerminalDialogWidget - .showInfoDialog(os, "terminal.component.warning", "terminal.hardware.remove.full").open(); - } - } - } - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (isMouseOverElement(mouseX, mouseY)) { - writeClientAction(1, buffer -> buffer.writeVarInt(button)); - showDialog(button); - return true; - } - return false; - } - - @Override - public void handleClientAction(int id, PacketBuffer buffer) { - if (id == 1) { - showDialog(buffer.readVarInt()); - } - } - - @Override - public void drawInForeground(int mouseX, int mouseY) { - if (hardware != null && isMouseOverElement(mouseX, mouseY)) { - if (!hardware.hasHW()) { - drawHoveringText(ItemStack.EMPTY, Collections.singletonList(hardware.getLocalizedName()), 300, mouseX, - mouseY); - } else { - String info = hardware.addInformation(); - if (info == null) { - drawHoveringText(ItemStack.EMPTY, - Arrays.asList(hardware.getLocalizedName(), I18n.format("terminal.hardware.tip.remove")), - 300, mouseX, mouseY); - } else { - drawHoveringText(ItemStack.EMPTY, - Arrays.asList(String.format("%s (%s)", hardware.getLocalizedName(), info), - I18n.format("terminal.hardware.tip.remove")), - 300, mouseX, mouseY); - } - } - } - } - - @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; - boolean missing = !hardware.hasHW(); - drawBorder(x - 1, y - 1, width + 2, height + 1, missing ? 0x6fffffff : -1, 1); - hardware.getIcon().draw(x, y, width, height); - super.drawInBackground(mouseX, mouseY, partialTicks, context); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/multiblockhelper/MachineBuilderWidget.java b/src/main/java/gregtech/common/terminal/app/multiblockhelper/MachineBuilderWidget.java deleted file mode 100644 index 899e1dc9d37..00000000000 --- a/src/main/java/gregtech/common/terminal/app/multiblockhelper/MachineBuilderWidget.java +++ /dev/null @@ -1,279 +0,0 @@ -package gregtech.common.terminal.app.multiblockhelper; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.SlotWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.metatileentity.multiblock.MultiblockControllerBase; -import gregtech.api.pattern.MultiblockShapeInfo; -import gregtech.api.pattern.PatternError; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.gui.widgets.MachineSceneWidget; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.BlockInfo; -import gregtech.client.utils.RenderBufferHelper; -import gregtech.common.inventory.handlers.CycleItemStackHandler; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockBush; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.BufferBuilder; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.vertex.DefaultVertexFormats; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.BlockRenderLayer; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.NonNullList; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import org.lwjgl.opengl.GL11; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Created with IntelliJ IDEA. - * - * @Author: KilaBash - * @Date: 2021/09/15 - * @Description: - */ -public class MachineBuilderWidget extends WidgetGroup { - - private BlockPos pos; - private EnumFacing facing; - private SlotWidget[] slotWidgets; - TerminalOSWidget os; - @SideOnly(Side.CLIENT) - private MachineSceneWidget sceneWidget; - @SideOnly(Side.CLIENT) - private Set highLightBlocks; - private final MultiblockControllerBase controllerBase; - private int selected = -1; - @SideOnly(Side.CLIENT) - private DraggableScrollableWidgetGroup candidates; - @SideOnly(Side.CLIENT) - private List handlers; - - public MachineBuilderWidget(int x, int y, int width, int height, MultiblockControllerBase controllerBase, - TerminalOSWidget os) { - super(x, y, width, height); - this.os = os; - this.controllerBase = controllerBase; - addWidget(new ImageWidget(0, 0, width, height, GuiTextures.BACKGROUND)); - addWidget(new RectButtonWidget(12, 125, width - 24, 20, 1) - .setClickListener(this::autoBuildButton) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setIcon(new TextTexture("terminal.multiblock_ar.builder.auto", -1))); - addWidget(new RectButtonWidget(12, 125 + 25, width - 24, 20, 1) - .setClickListener(this::placeButton) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setIcon(new TextTexture("terminal.multiblock_ar.builder.place", -1))); - addWidget(new RectButtonWidget(12, 125 + 50, width - 24, 20, 1) - .setClickListener(this::debugButton) - .setColors(TerminalTheme.COLOR_B_1.getColor(), TerminalTheme.COLOR_7.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setIcon(new TextTexture("terminal.multiblock_ar.builder.debug", -1))); - if (os.isRemote()) { - candidates = new DraggableScrollableWidgetGroup(-20, 0, 20, 180); - addWidget(candidates); - } - } - - @Override - public void handleClientAction(int id, PacketBuffer buffer) { - if (id == -2) { // select - this.selected = buffer.readVarInt(); - } else if (id == -3) { // update pos facing - this.pos = buffer.readBlockPos(); - this.facing = EnumFacing.VALUES[buffer.readByte()]; - } else { - super.handleClientAction(id, buffer); - } - } - - /** - * I had to add slotWidget after parent widget be added, because of gtce's {@link gregtech.api.gui.INativeWidget} - * interface. - * Hopefully one day I can remove this worse interface. - */ - public void addPlayerInventory() { - InventoryPlayer inventoryPlayer = gui.entityPlayer.inventory; - slotWidgets = new SlotWidget[36]; - for (int row = 0; row < 6; row++) { - for (int col = 0; col < 6; col++) { - int index = col + row * 6; - boolean isActive = inventoryPlayer.getStackInSlot(index).getItem() instanceof ItemBlock; - slotWidgets[index] = new SlotWidget(inventoryPlayer, index, 12 + col * 18, 12 + row * 18, false, - false) { - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (isMouseOverElement(mouseX, mouseY) && isActive()) { - if (selected != index) { - selected = index; - MachineBuilderWidget.this.writeClientAction(-2, buf -> buf.writeVarInt(index)); - } - } - return super.mouseClicked(mouseX, mouseY, button); - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - super.drawInBackground(mouseX, mouseY, partialTicks, context); - if (selected == index) { - drawSolidRect(getPosition().x, getPosition().y, getSize().width, getSize().height, - 0x4f00ff00); - } - } - }.setBackgroundTexture(GuiTextures.SLOT); - slotWidgets[index].setActive(isActive); - this.addWidget(slotWidgets[index]); - } - } - } - - @SideOnly(Side.CLIENT) - public void setSceneWidget(MachineSceneWidget sceneWidget) { - this.sceneWidget = sceneWidget; - this.highLightBlocks = new HashSet<>(); - MachineSceneWidget.getWorldSceneRenderer().addRenderedBlocks(highLightBlocks, this::highLightRender); - sceneWidget.setOnSelected(this::setFocus); - sceneWidget.getAround().clear(); - Set cores = sceneWidget.getCores(); - int rX = 5; - int rY = 5; - int rZ = 5; - for (MultiblockShapeInfo shapeInfo : controllerBase.getMatchingShapes()) { - BlockInfo[][][] blockInfos = shapeInfo.getBlocks(); - rX = Math.max(blockInfos.length, rX); - rY = Math.max(blockInfos[0].length, rY); - rZ = Math.max(blockInfos[0][0].length, rZ); - } - for (int x = -rX; x <= rX; x++) { - for (int y = -rY; y <= rY; y++) { - for (int z = -rZ; z <= rZ; z++) { - cores.add(controllerBase.getPos().add(x, y, z)); - } - } - } - } - - @SideOnly(Side.CLIENT) - private void setFocus(BlockPos pos, EnumFacing facing) { - this.pos = new BlockPos(pos); - this.facing = facing; - writeClientAction(-3, buf -> { - buf.writeBlockPos(pos); - buf.writeByte(facing.getIndex()); - }); - } - - private void placeButton(ClickData clickData) { - if (pos != null && facing != null && selected != -1) { - World world = controllerBase.getWorld(); - BlockPos offset = pos.offset(facing); - if (world.getBlockState(offset).getBlock() == Blocks.AIR) { - ItemStack itemStack = slotWidgets[selected].getHandle().getStack(); - if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemBlock) { - ItemBlock itemBlock = (ItemBlock) itemStack.getItem(); - float hitX = pos.getX() + 0.5f; - float hitY = pos.getY() + 0.5f; - float hitZ = pos.getZ() + 0.5f; - Block block = itemBlock.getBlock(); - IBlockState state = block.getStateFromMeta(itemBlock.getMetadata(itemStack.getMetadata())); - if (block instanceof BlockBush) { - // Prevent placing lilypads, grass, etc where they should not be - if (!((BlockBush) block).canBlockStay(world, offset, state)) { - if (clickData.isClient) { - TerminalDialogWidget.showInfoDialog(os, "terminal.component.error", - "This Block cannot be placed here").setClientSide().open(); - } - return; - } - } - - itemBlock.placeBlockAt(itemStack, gui.entityPlayer, world, offset, facing, hitX, hitY, hitZ, state); - itemStack.shrink(1); - } - } - } - } - - @SideOnly(Side.CLIENT) - private void highLightRender(boolean isTESR, int pass, BlockRenderLayer layer) { - if (isTESR && pass == 0) return; - - GlStateManager.disableDepth(); - GlStateManager.disableTexture2D(); - GlStateManager.glLineWidth(5); - - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder buffer = tessellator.getBuffer(); - - buffer.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR); - - for (BlockPos pos : highLightBlocks) { - RenderBufferHelper.renderCubeFrame(buffer, - pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1, - 1, 0, 0, 1); - } - - tessellator.draw(); - - GlStateManager.enableTexture2D(); - GlStateManager.enableDepth(); - GlStateManager.color(1, 1, 1, 1); - } - - private void debugButton(ClickData clickData) { - if (clickData.isClient && controllerBase != null) { - highLightBlocks.clear(); - if (controllerBase.structurePattern.checkPatternFastAt( - controllerBase.getWorld(), controllerBase.getPos(), controllerBase.getFrontFacing().getOpposite(), - controllerBase.getUpwardsFacing(), controllerBase.allowsFlip()) == null) { - PatternError error = controllerBase.structurePattern.getError(); - highLightBlocks.add(new BlockPos(error.getPos())); - List> candidatesItemStack = error.getCandidates(); - candidates.clearAllWidgets(); - int y = 1; - handlers = new ArrayList<>(); - for (List candidate : candidatesItemStack) { - CycleItemStackHandler handler = new CycleItemStackHandler( - NonNullList.from(ItemStack.EMPTY, candidate.toArray(new ItemStack[0]))); - handlers.add(handler); - candidates.addWidget(new SlotWidget(handler, 0, 1, y, false, false) - .setBackgroundTexture(TerminalTheme.COLOR_B_2)); - y += 20; - } - TerminalDialogWidget.showInfoDialog(os, "terminal.component.error", error.getErrorInfo()) - .setClientSide().open(); - } - } - } - - private void autoBuildButton(ClickData clickData) { - if (controllerBase != null) { - if (!clickData.isClient && controllerBase.structurePattern != null) { - controllerBase.structurePattern.autoBuild(gui.entityPlayer, controllerBase); - } - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/multiblockhelper/MultiBlockPreviewARApp.java b/src/main/java/gregtech/common/terminal/app/multiblockhelper/MultiBlockPreviewARApp.java deleted file mode 100644 index 6e9d04b4705..00000000000 --- a/src/main/java/gregtech/common/terminal/app/multiblockhelper/MultiBlockPreviewARApp.java +++ /dev/null @@ -1,273 +0,0 @@ -package gregtech.common.terminal.app.multiblockhelper; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.resources.ShaderTexture; -import gregtech.api.gui.resources.TextureArea; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; -import gregtech.api.metatileentity.multiblock.MultiblockControllerBase; -import gregtech.api.pattern.MultiblockShapeInfo; -import gregtech.api.terminal.app.ARApplication; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.MachineSceneWidget; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.client.renderer.handler.MultiblockPreviewRenderer; -import gregtech.client.shader.Shaders; -import gregtech.client.utils.RenderUtil; -import gregtech.common.ConfigHolder; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.GLAllocation; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.client.event.RenderWorldLastEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL13; - -import java.util.*; - -public class MultiBlockPreviewARApp extends ARApplication { - - @SideOnly(Side.CLIENT) - int lastMouseX; - @SideOnly(Side.CLIENT) - int lastMouseY; - @SideOnly(Side.CLIENT) - float partialTicks; - - public MultiBlockPreviewARApp() { - super("multiblock_ar"); - } - - @Override - public AbstractApplication initApp() { // 232 333 - int bW = 120; - int bH = 120; - - addWidget(new ImageWidget(10, 10, 313, 212, new ColorRectTexture(TerminalTheme.COLOR_B_2.getColor()))); - addWidget(new ImageWidget(333 / 2, 20, 1, 222 - 40, new ColorRectTexture(-1))); - - addWidget(new LabelWidget(10 + 313 / 4, 35, "terminal.multiblock_ar.tier.0", -1).setXCentered(true) - .setYCentered(true)); - addWidget(new RectButtonWidget(10 + (313 / 2 - bW) / 2, 50, bW, bH) - .setIcon(TextureArea.fullImage("textures/gui/terminal/multiblock_ar/profile.png")) - .setColors(-1, 0xff00ff00, 0) - .setHoverText("terminal.ar.open") - .setClickListener(clickData -> openAR())); - - addWidget(new LabelWidget(333 / 2 + 313 / 4, 35, "terminal.multiblock_ar.tier.1", - getAppTier() == 0 ? 0xffff0000 : -1).setXCentered(true).setYCentered(true)); - addWidget(new RectButtonWidget(333 / 2 + (313 / 2 - bW) / 2, 50, bW, bH) - .setIcon(this::drawBuilderButton) - .setColors(getAppTier() == 0 ? 0xffff0000 : -1, getAppTier() == 0 ? 0xffff0000 : 0xff00ff00, 0) - .setHoverText( - getAppTier() > 0 ? "terminal.multiblock_ar.builder.hover" : "terminal.multiblock_ar.unlock") - .setClickListener(clickData -> buildMode())); - return this; - } - - private void drawBuilderButton(double x, double y, int width, int height) { - if (Shaders.allowedShader()) { - float time = (gui.entityPlayer.ticksExisted + partialTicks) / 20f; - - MultiblockControllerBase controllerBase = getController(); - int color = controllerBase == null ? -1 : controllerBase.getPaintingColorForRendering(); - - if (controllerBase != null) { - GlStateManager.setActiveTexture(GL13.GL_TEXTURE0); - GlStateManager.enableTexture2D(); - RenderUtil.bindTextureAtlasSprite(controllerBase.getFrontDefaultTexture()); - GlStateManager.setActiveTexture(GL13.GL_TEXTURE1); - GlStateManager.enableTexture2D(); - RenderUtil.bindTextureAtlasSprite(controllerBase.getBaseTexture(null).getParticleSprite()); - } - ShaderTexture.createShader("showcube.frag").draw(x, y, width, height, uniformCache -> { - uniformCache.glUniform1I("faceTexture", 0); - uniformCache.glUniform1I("baseTexture", 1); - uniformCache.glUniform1F("u_time", time); - uniformCache.glUniform3F("f_color", (color >> 16 & 255) / 255.0F, (color >> 8 & 255) / 255.0F, - (color & 255) / 255.0F); - uniformCache.glUniformBoolean("block", controllerBase != null); - if (isMouseOver((int) x, (int) y, width, height, lastMouseX, lastMouseY)) { - uniformCache.glUniform2F("u_mouse", - (float) (((lastMouseX - x) / 2 + width / 3) * ConfigHolder.client.resolution), - (float) (height / 2 * ConfigHolder.client.resolution)); - } - }); - - GlStateManager.setActiveTexture(GL13.GL_TEXTURE1); - GlStateManager.bindTexture(0); - - GlStateManager.setActiveTexture(GL13.GL_TEXTURE0); - GlStateManager.bindTexture(0); - - } else { - GuiTextures.MULTIBLOCK_CATEGORY.draw(x, y, width, height); - } - } - - @Override - public int getMaxTier() { - return 1; - } - - private MultiblockControllerBase getController() { - if (os.clickPos != null) { - TileEntity te = gui.entityPlayer.world.getTileEntity(os.clickPos); - if (te instanceof IGregTechTileEntity && - ((IGregTechTileEntity) te).getMetaTileEntity() instanceof MultiblockControllerBase) { - return (MultiblockControllerBase) ((IGregTechTileEntity) te).getMetaTileEntity(); - } - } - return null; - } - - private void buildMode() { - if (getAppTier() == 0) { - TerminalDialogWidget.showInfoDialog(getOs(), "terminal.dialog.notice", "terminal.multiblock_ar.unlock") - .open(); - } else if (getController() != null) { - widgets.forEach(this::waitToRemoved); - MultiblockControllerBase controllerBase = getController(); - MachineBuilderWidget builderWidget = new MachineBuilderWidget(200, 16, 133, 200, controllerBase, getOs()); - this.addWidget(builderWidget); - builderWidget.addPlayerInventory(); - if (isClient) { - MachineSceneWidget sceneWidget = new MachineSceneWidget(0, 16, 200, 200, controllerBase); - builderWidget.setSceneWidget(sceneWidget); - this.addWidget(0, sceneWidget); - this.addWidget(new ImageWidget(0, 0, 333, 16, GuiTextures.UI_FRAME_SIDE_UP)); - this.addWidget(new ImageWidget(0, 216, 333, 16, GuiTextures.UI_FRAME_SIDE_DOWN)); - } else { - this.addWidget(0, new WidgetGroup()); // placeholder - } - } else { - TerminalDialogWidget.showInfoDialog(getOs(), "terminal.dialog.notice", "terminal.console.notice").open(); - } - } - - @Override - protected void hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - lastMouseX = mouseX; - lastMouseY = mouseY; - this.partialTicks = partialTicks; - super.hookDrawInBackground(mouseX, mouseY, partialTicks, context); - } - - ////////////////////////////////////// AR///////////////////////////////////////// - - @SideOnly(Side.CLIENT) - private static Map controllerList; - @SideOnly(Side.CLIENT) - private static Set found; - @SideOnly(Side.CLIENT) - private static BlockPos lastPos; - private static int opList = -1; - - @Override - public void onAROpened() { - controllerList = new HashMap<>(); - found = new HashSet<>(); - } - - @SideOnly(Side.CLIENT) - private static boolean inRange(BlockPos playerPos, BlockPos controllerPos) { - return Math.abs(playerPos.getX() - controllerPos.getX()) < 30 && - Math.abs(playerPos.getY() - controllerPos.getY()) < 30 && - Math.abs(playerPos.getZ() - controllerPos.getZ()) < 30; - } - - @SideOnly(Side.CLIENT) - @Override - public void tickAR(EntityPlayer player) { - World world = player.world; - int tick = Math.abs(player.ticksExisted % 27); // 0 - 26 - if (tick == 0) { - boolean reRender = false; - Iterator iterator = controllerList.keySet().iterator(); - if (iterator.hasNext()) { - MultiblockControllerBase controller = iterator.next(); - if (!controller.isValid() || controller.isStructureFormed() || - !inRange(player.getPosition(), controller.getPos())) { - iterator.remove(); - reRender = true; - } - } - for (MultiblockControllerBase controllerBase : found) { - if (!controllerList.containsKey(controllerBase)) { - List shapeInfos = controllerBase.getMatchingShapes(); - if (!shapeInfos.isEmpty()) { - controllerList.put(controllerBase, shapeInfos.get(0)); - reRender = true; - } - } - } - found.clear(); - lastPos = player.getPosition(); - if (reRender) { - opList = GLAllocation.generateDisplayLists(1); // allocate op list - GlStateManager.glNewList(opList, GL11.GL_COMPILE); - controllerList.forEach((controller, shapes) -> MultiblockPreviewRenderer - .renderControllerInList(controller, shapes, 0)); - GlStateManager.glEndList(); - } - } - if (lastPos == null) { - lastPos = player.getPosition(); - } - for (int i = tick * 1000; i < (tick + 1) * 1000; i++) { - int x = i % 30 - 15; - int y = (i / 30) % 30 - 15; - int z = (i / 900) - 15; - TileEntity tileEntity = world.getTileEntity(lastPos.add(x, y, z)); - if (tileEntity instanceof IGregTechTileEntity) { - if (((IGregTechTileEntity) tileEntity).getMetaTileEntity() instanceof MultiblockControllerBase) { - found.add((MultiblockControllerBase) ((IGregTechTileEntity) tileEntity).getMetaTileEntity()); - } - } - } - } - - @SideOnly(Side.CLIENT) - @Override - public void drawARScreen(RenderWorldLastEvent event) { - if (opList != -1) { - MultiblockPreviewRenderer.resetMultiblockRender(); - Minecraft mc = Minecraft.getMinecraft(); - Entity entity = mc.getRenderViewEntity(); - if (entity == null) entity = mc.player; - - float partialTicks = event.getPartialTicks(); - - double tx = entity.lastTickPosX + ((entity.posX - entity.lastTickPosX) * partialTicks); - double ty = entity.lastTickPosY + ((entity.posY - entity.lastTickPosY) * partialTicks); - double tz = entity.lastTickPosZ + ((entity.posZ - entity.lastTickPosZ) * partialTicks); - - Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); - GlStateManager.color(1F, 1F, 1F, 1F); - GlStateManager.pushMatrix(); - GlStateManager.translate(-tx, -ty, -tz); - GlStateManager.enableBlend(); - - GlStateManager.callList(opList); - - GlStateManager.enableLighting(); - GlStateManager.popMatrix(); - GlStateManager.color(1F, 1F, 1F, 0F); - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/prospector/ProspectorApp.java b/src/main/java/gregtech/common/terminal/app/prospector/ProspectorApp.java deleted file mode 100644 index fb2144909ce..00000000000 --- a/src/main/java/gregtech/common/terminal/app/prospector/ProspectorApp.java +++ /dev/null @@ -1,221 +0,0 @@ -package gregtech.common.terminal.app.prospector; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.menu.IMenuComponent; -import gregtech.api.util.GTLog; -import gregtech.common.terminal.app.prospector.widget.WidgetOreList; -import gregtech.common.terminal.app.prospector.widget.WidgetProspectingMap; -import gregtech.common.terminal.component.ClickComponent; -import gregtech.common.terminal.component.SearchComponent; -import gregtech.core.network.packets.PacketProspecting; - -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import com.google.common.collect.Maps; -import com.google.common.collect.Table; -import com.google.common.collect.Tables; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -public class ProspectorApp extends AbstractApplication implements SearchComponent.IWidgetSearch { - - private WidgetOreList widgetOreList; - private WidgetProspectingMap widgetProspectingMap; - private ColorRectTexture background; - @SideOnly(Side.CLIENT) - private Table persist; - private final ProspectorMode mode; - - public ProspectorApp(@NotNull ProspectorMode mode) { - super(mode.terminalName); - this.mode = mode; - } - - @Override - public AbstractApplication createAppInstance(TerminalOSWidget os, boolean isClient, NBTTagCompound nbt) { - ProspectorApp app = new ProspectorApp(mode); - app.isClient = isClient; - app.nbt = nbt; - return app; - } - - @Override - public AbstractApplication initApp() { - int chunkRadius = getAppTier() + 3; - int offset = (232 - 32 * 7 + 16) / 2; - background = new ColorRectTexture(0xA0000000); - this.addWidget(new ImageWidget(0, 0, 333, 232, background)); - if (isClient) { - this.addWidget(new ImageWidget(0, 0, 333, offset, GuiTextures.UI_FRAME_SIDE_UP)); - this.addWidget(new ImageWidget(0, 232 - offset, 333, offset, GuiTextures.UI_FRAME_SIDE_DOWN)); - this.widgetOreList = new WidgetOreList(32 * chunkRadius - 16, offset, 333 - 32 * chunkRadius + 16, - 232 - 2 * offset); - this.addWidget(this.widgetOreList); - } - this.widgetProspectingMap = new WidgetProspectingMap(0, offset + (7 - chunkRadius) * 16, chunkRadius, - this.widgetOreList, mode, 1); - if (isClient) { - persist = Tables.newCustomTable(Maps.newHashMap(), Maps::newHashMap); - widgetProspectingMap.setOnPacketReceived(packet -> persist.put(packet.chunkX, packet.chunkZ, packet)); - } - - this.addWidget(1, this.widgetProspectingMap); - loadLocalConfig(nbt -> { - this.widgetProspectingMap.setDarkMode(nbt.getBoolean("dark")); - background.setColor(this.widgetProspectingMap.getDarkMode() ? 0xA0000000 : 0xA0ffffff); - }); - if (isClient) { - loadPacketLocalConfig(); - // Cardinal directions - this.addWidget(new LabelWidget(-2 + (16 * (chunkRadius * 2 - 1)) / 2, offset, "N", this::labelColor) - .setShadow(true)); - this.addWidget(new LabelWidget(-2 + (16 * (chunkRadius * 2 - 1)) / 2, - offset - 6 + 16 * (chunkRadius * 2 - 1), "S", this::labelColor).setShadow(true)); - this.addWidget(new LabelWidget(0, offset - 3 + (16 * (chunkRadius * 2 - 1)) / 2, "W", this::labelColor) - .setShadow(true)); - this.addWidget(new LabelWidget(-6 + 16 * (chunkRadius * 2 - 1), - offset - 3 + (16 * (chunkRadius * 2 - 1)) / 2, "E", this::labelColor).setShadow(true)); - } - return this; - } - - int labelColor() { - return this.widgetProspectingMap.getDarkMode() ? 0xF0F0F0 : 0x404040; - } - - @SideOnly(Side.CLIENT) - protected void loadPacketLocalConfig() { - new Thread(() -> { // thread for better QoL - int posX = gui.entityPlayer.getPosition().getX(); - int posZ = gui.entityPlayer.getPosition().getZ(); - - if (posX % 16 > 7 || posX % 16 == 0) { - posX -= 1; - } else { - posX += 1; - } - // draw red horizontal line - if (posZ % 16 > 7 || posZ % 16 == 0) { - posZ -= 1; - } else { - posZ += 1; - } - - int playerChunkX = gui.entityPlayer.chunkCoordX; - int playerChunkZ = gui.entityPlayer.chunkCoordZ; - int chunkRadius = getAppTier() + 3 - 1; - for (int i = playerChunkX - chunkRadius; i <= playerChunkX + chunkRadius; i++) { - for (int j = playerChunkZ - chunkRadius; j <= playerChunkZ + chunkRadius; j++) { - NBTTagCompound nbt = null; - try { - nbt = CompressedStreamTools.read(new File(TerminalRegistry.TERMINAL_PATH, - String.format("%s/%d/%d_%d.nbt", getRegistryName(), mode.ordinal(), i, j))); - } catch (IOException e) { - GTLog.logger.error("error while loading local nbt for {}", getRegistryName(), e); - } - if (nbt != null) { - PacketProspecting packet = PacketProspecting.readPacketData(nbt); - if (packet != null) { - packet.posX = posX; - packet.posZ = posZ; - persist.put(i, j, packet); - widgetProspectingMap.addPacketToQueue(packet); - } - } - } - } - }).start(); - } - - @SideOnly(Side.CLIENT) - protected void savePacketLocalConfig() { - new Thread(() -> { // thread for better QoL - File folder = new File(TerminalRegistry.TERMINAL_PATH, - String.format("%s/%d", getRegistryName(), mode.ordinal())); - if (!folder.exists()) { - if (!folder.mkdirs()) return; - } - for (Table.Cell cell : persist.cellSet()) { - if (cell.getValue() != null) { - NBTTagCompound nbt = cell.getValue().writePacketData(); - try { - if (!nbt.isEmpty()) { - CompressedStreamTools.safeWrite(nbt, new File(folder, - String.format("%d_%d.nbt", cell.getRowKey(), cell.getColumnKey()))); - } - } catch (IOException e) { - GTLog.logger.error("error while saving local nbt for {}", getRegistryName(), e); - } - } - } - }).start(); - } - - @Override - public NBTTagCompound closeApp() { - saveLocalConfig(nbt -> { - nbt.setBoolean("dark", this.widgetProspectingMap.getDarkMode()); - }); - if (isClient) savePacketLocalConfig(); - return super.closeApp(); - } - - @Override - public int getMaxTier() { - return 4; - } - - @Override - public List getMenuComponents() { - ClickComponent darkMode = new ClickComponent().setIcon(GuiTextures.ICON_VISIBLE) - .setHoverText("terminal.prospector.vis_mode").setClickConsumer(cd -> { - if (cd.isClient) { - widgetProspectingMap.setDarkMode(!widgetProspectingMap.getDarkMode()); - background.setColor(this.widgetProspectingMap.getDarkMode() ? 0xA0000000 : 0xA0ffffff); - } - }); - return Arrays.asList(darkMode, new SearchComponent<>(this)); - } - - @Override - public String resultDisplay(String result) { - if (widgetOreList != null) { - return widgetOreList.ores.get(result); - } - return ""; - } - - @Override - public void selectResult(String result) { - if (widgetOreList != null) { - widgetOreList.setSelected(result); - } - } - - @Override - public void search(String word, Consumer find) { - if (widgetOreList != null) { - word = word.toLowerCase(); - for (Map.Entry entry : widgetOreList.ores.entrySet()) { - if (entry.getKey().toLowerCase().contains(word) || entry.getValue().toLowerCase().contains(word)) { - find.accept(entry.getKey()); - } - } - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/recipechart/FluidStackHelper.java b/src/main/java/gregtech/common/terminal/app/recipechart/FluidStackHelper.java deleted file mode 100644 index e55f040f585..00000000000 --- a/src/main/java/gregtech/common/terminal/app/recipechart/FluidStackHelper.java +++ /dev/null @@ -1,61 +0,0 @@ -package gregtech.common.terminal.app.recipechart; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.widgets.TankWidget; -import gregtech.api.terminal.os.TerminalTheme; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTank; - -public class FluidStackHelper implements IngredientHelper { - - public static final FluidStackHelper INSTANCE = new FluidStackHelper(); - - @Override - public byte getTypeId() { - return 2; - } - - @Override - public int getAmount(FluidStack fluidStack) { - return fluidStack.amount; - } - - @Override - public void setAmount(FluidStack fluidStack, int amount) { - fluidStack.amount = amount; - } - - @Override - public boolean areEqual(FluidStack t1, FluidStack t2) { - return t1 != null && t1.isFluidEqual(t2); - } - - @Override - public boolean isEmpty(FluidStack fluidStack) { - return fluidStack.getFluid() == null || fluidStack.amount <= 0; - } - - @Override - public String getDisplayName(FluidStack fluidStack) { - return fluidStack.getLocalizedName(); - } - - @Override - public Widget createWidget(FluidStack fluidStack) { - FluidTank tank = new FluidTank(fluidStack, Integer.MAX_VALUE); - return new TankWidget(tank, 0, 0, 18, 18).setAlwaysShowFull(true).setBackgroundTexture(TerminalTheme.COLOR_B_2) - .setClient(); - } - - @Override - public FluidStack deserialize(NBTTagCompound nbt) { - return FluidStack.loadFluidStackFromNBT(nbt); - } - - @Override - public NBTTagCompound serialize(FluidStack fluidStack) { - return fluidStack.writeToNBT(new NBTTagCompound()); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/recipechart/IngredientHelper.java b/src/main/java/gregtech/common/terminal/app/recipechart/IngredientHelper.java deleted file mode 100644 index 74d5fcbf5a1..00000000000 --- a/src/main/java/gregtech/common/terminal/app/recipechart/IngredientHelper.java +++ /dev/null @@ -1,49 +0,0 @@ -package gregtech.common.terminal.app.recipechart; - -import gregtech.api.gui.Widget; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.FluidStack; - -import java.util.Objects; - -public interface IngredientHelper { - - static IngredientHelper getFor(Object o) { - Objects.requireNonNull(o); - if (o.getClass() == ItemStack.class) { - return (IngredientHelper) ItemStackHelper.INSTANCE; - } - if (o.getClass() == FluidStack.class) { - return (IngredientHelper) FluidStackHelper.INSTANCE; - } - throw new IllegalArgumentException(); - } - - static IngredientHelper getForTypeId(int type) { - return switch (type) { - case 1 -> ItemStackHelper.INSTANCE; - case 2 -> FluidStackHelper.INSTANCE; - default -> throw new IllegalArgumentException(); - }; - } - - byte getTypeId(); - - int getAmount(T t); - - void setAmount(T t, int amount); - - boolean areEqual(T t1, T t2); - - boolean isEmpty(T t); - - String getDisplayName(T t); - - Widget createWidget(T t); - - T deserialize(NBTTagCompound nbt); - - NBTTagCompound serialize(T t); -} diff --git a/src/main/java/gregtech/common/terminal/app/recipechart/ItemStackHelper.java b/src/main/java/gregtech/common/terminal/app/recipechart/ItemStackHelper.java deleted file mode 100644 index 268f6799226..00000000000 --- a/src/main/java/gregtech/common/terminal/app/recipechart/ItemStackHelper.java +++ /dev/null @@ -1,62 +0,0 @@ -package gregtech.common.terminal.app.recipechart; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.widgets.SlotWidget; -import gregtech.api.terminal.os.TerminalTheme; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.items.ItemStackHandler; - -public class ItemStackHelper implements IngredientHelper { - - public static final ItemStackHelper INSTANCE = new ItemStackHelper(); - - @Override - public byte getTypeId() { - return 1; - } - - @Override - public int getAmount(ItemStack t) { - return t.getCount(); - } - - @Override - public void setAmount(ItemStack t, int amount) { - t.setCount(amount); - } - - @Override - public boolean areEqual(ItemStack t1, ItemStack t2) { - return ItemHandlerHelper.canItemStacksStack(t1, t2); - } - - @Override - public boolean isEmpty(ItemStack stack) { - return stack.isEmpty(); - } - - @Override - public String getDisplayName(ItemStack stack) { - return stack.getDisplayName(); - } - - @Override - public Widget createWidget(ItemStack stack) { - ItemStackHandler handler = new ItemStackHandler(1); - handler.setStackInSlot(0, stack); - return new SlotWidget(handler, 0, 0, 0, false, false).setBackgroundTexture(TerminalTheme.COLOR_B_2); - } - - @Override - public ItemStack deserialize(NBTTagCompound nbt) { - return new ItemStack(nbt); - } - - @Override - public NBTTagCompound serialize(ItemStack stack) { - return stack.serializeNBT(); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/recipechart/RecipeChartApp.java b/src/main/java/gregtech/common/terminal/app/recipechart/RecipeChartApp.java deleted file mode 100644 index e4abbcd2497..00000000000 --- a/src/main/java/gregtech/common/terminal/app/recipechart/RecipeChartApp.java +++ /dev/null @@ -1,238 +0,0 @@ -package gregtech.common.terminal.app.recipechart; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.Widget; -import gregtech.api.gui.impl.ModularUIContainer; -import gregtech.api.gui.ingredient.IRecipeTransferHandlerWidget; -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.TabGroup; -import gregtech.api.gui.widgets.tab.IGuiTextureTabInfo; -import gregtech.api.gui.widgets.tab.ITabInfo; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.CustomTabListRenderer; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.terminal.os.menu.IMenuComponent; -import gregtech.api.util.Size; -import gregtech.common.terminal.app.recipechart.widget.RGContainer; -import gregtech.common.terminal.app.recipechart.widget.RGNode; -import gregtech.common.terminal.component.ClickComponent; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraftforge.common.util.Constants; - -import mezz.jei.api.gui.IRecipeLayout; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -public class RecipeChartApp extends AbstractApplication implements IRecipeTransferHandlerWidget { - - private TabGroup tabGroup; - - public RecipeChartApp() { - super("recipe_chart"); - } - - @Override - public int getThemeColor() { - return 0xff008001; - } - - @Override - public AbstractApplication initApp() { - if (isClient) { - this.tabGroup = new TabGroup<>(0, 10, new CustomTabListRenderer(TerminalTheme.COLOR_F_2, - TerminalTheme.COLOR_B_3, 333 / getMaxPages(), 10)); - this.tabGroup.setOnTabChanged(this::onPagesChanged); - this.addWidget(this.tabGroup); - loadLocalConfig(nbt -> { - if (nbt == null || nbt.isEmpty()) { - this.addTab("default"); - } else { - for (NBTBase l : nbt.getTagList("list", Constants.NBT.TAG_COMPOUND)) { - NBTTagCompound container = (NBTTagCompound) l; - this.addTab(container.getString("name")).loadFromNBT((NBTTagCompound) container.getTag("data")); - } - tabGroup.setSelectedTab(nbt.getInteger("focus")); - } - }); - } - return this; - } - - private void onPagesChanged(int oldPage, int newPage) { - ITabInfo tabInfo = tabGroup.getTabInfo(newPage); - if (tabInfo instanceof IGuiTextureTabInfo && ((IGuiTextureTabInfo) tabInfo).texture instanceof TextTexture) { - ((TextTexture) ((IGuiTextureTabInfo) tabInfo).texture).setType(TextTexture.TextType.ROLL); - } - tabInfo = tabGroup.getTabInfo(oldPage); - if (tabInfo instanceof IGuiTextureTabInfo && ((IGuiTextureTabInfo) tabInfo).texture instanceof TextTexture) { - ((TextTexture) ((IGuiTextureTabInfo) tabInfo).texture).setType(TextTexture.TextType.HIDE); - } - } - - private RGContainer addTab(String name) { - name = name.isEmpty() ? "default" : name; - RGContainer container = new RGContainer(0, 0, 333, 222, getOs()); - container.setBackground(TerminalTheme.COLOR_B_3); - tabGroup.addTab(new IGuiTextureTabInfo(new TextTexture(name, -1).setWidth(333 / getMaxPages() - 5) - .setType(tabGroup.getAllTag().isEmpty() ? TextTexture.TextType.ROLL : TextTexture.TextType.HIDE), name), - container); - return container; - } - - public int getMaxPages() { - return getAppTier() + 5; - } - - @Override - public List getMenuComponents() { - ClickComponent newPage = new ClickComponent().setIcon(GuiTextures.ICON_NEW_PAGE) - .setHoverText("terminal.component.new_page").setClickConsumer(cd -> { - if (tabGroup == null) return; - if (tabGroup.getAllTag().size() < getMaxPages()) { - TerminalDialogWidget - .showTextFieldDialog(getOs(), "terminal.component.page_name", s -> true, s -> { - if (s != null) { - addTab(s); - } - }).setClientSide().open(); - } else { - TerminalDialogWidget - .showInfoDialog(getOs(), "terminal.component.warning", "terminal.recipe_chart.limit") - .setClientSide().open(); - } - }); - ClickComponent deletePage = new ClickComponent().setIcon(GuiTextures.ICON_REMOVE) - .setHoverText("terminal.recipe_chart.delete").setClickConsumer(cd -> { - if (tabGroup == null) return; - if (tabGroup.getAllTag().size() > 1) { - TerminalDialogWidget.showConfirmDialog(getOs(), "terminal.recipe_chart.delete", - "terminal.component.confirm", r -> { - if (r) { - tabGroup.removeTab(tabGroup.getAllTag().indexOf(tabGroup.getCurrentTag())); - } - }).setClientSide().open(); - } else { - TerminalDialogWidget - .showInfoDialog(getOs(), "terminal.component.warning", "terminal.recipe_chart.limit") - .setClientSide().open(); - } - }); - ClickComponent addSlot = new ClickComponent().setIcon(GuiTextures.ICON_ADD) - .setHoverText("terminal.recipe_chart.add_slot").setClickConsumer(cd -> { - if (tabGroup == null) return; - if (tabGroup.getCurrentTag() != null) { - tabGroup.getCurrentTag().addNode(50, 100); - } - }); - ClickComponent importPage = new ClickComponent().setIcon(GuiTextures.ICON_LOAD) - .setHoverText("terminal.component.load_file").setClickConsumer(cd -> { - if (tabGroup == null) return; - if (tabGroup.getAllTag().size() < getMaxPages()) { - File file = new File(TerminalRegistry.TERMINAL_PATH, "recipe_chart"); - TerminalDialogWidget - .showFileDialog(getOs(), "terminal.component.load_file", file, true, result -> { - if (result != null && result.isFile()) { - try { - NBTTagCompound nbt = CompressedStreamTools.read(result); - addTab(result.getName()).loadFromNBT(nbt); - } catch (IOException e) { - TerminalDialogWidget - .showInfoDialog(getOs(), "terminal.component.error", - "terminal.component.load_file.error") - .setClientSide().open(); - } - } - }).setClientSide().open(); - } else { - TerminalDialogWidget - .showInfoDialog(getOs(), "terminal.component.warning", "terminal.recipe_chart.limit") - .setClientSide().open(); - } - }); - ClickComponent exportPage = new ClickComponent().setIcon(GuiTextures.ICON_SAVE) - .setHoverText("terminal.component.save_file").setClickConsumer(cd -> { - if (tabGroup == null) return; - if (tabGroup.getCurrentTag() != null) { - File file = new File(TerminalRegistry.TERMINAL_PATH, "recipe_chart"); - TerminalDialogWidget - .showFileDialog(getOs(), "terminal.component.save_file", file, false, result -> { - if (result != null) { - try { - CompressedStreamTools.safeWrite(tabGroup.getCurrentTag().saveAsNBT(), - result); - } catch (IOException e) { - TerminalDialogWidget - .showInfoDialog(getOs(), "terminal.component.error", - "terminal.component.save_file.error") - .setClientSide().open(); - } - } - }).setClientSide().open(); - } - }); - return Arrays.asList(newPage, deletePage, addSlot, importPage, exportPage); - } - - @Override - public NBTTagCompound closeApp() { // synced data to server side. - saveLocalConfig(nbt -> { - NBTTagList list = new NBTTagList(); - for (int i = 0; i < tabGroup.getAllTag().size(); i++) { - IGuiTextureTabInfo tabInfo = (IGuiTextureTabInfo) tabGroup.getTabInfo(i); - NBTTagCompound container = new NBTTagCompound(); - container.setString("name", tabInfo.nameLocale); - container.setTag("data", tabGroup.getTabWidget(i).saveAsNBT()); - list.appendTag(container); - } - nbt.setTag("list", list); - nbt.setInteger("focus", tabGroup.getAllTag().indexOf(tabGroup.getCurrentTag())); - }); - return super.closeApp(); - } - - @Override - public boolean isClientSideApp() { - return true; - } - - @Override - public String transferRecipe(ModularUIContainer container, IRecipeLayout recipeLayout, EntityPlayer player, - boolean maxTransfer, boolean doTransfer) { - for (Widget widget : getContainedWidgets(false)) { - if (widget instanceof RGNode && - ((RGNode) widget).transferRecipe(container, recipeLayout, player, maxTransfer, doTransfer)) { - return null; - } - } - return "please select a node."; - } - - @Override - public int getMaxTier() { - return 3; - } - - @Override - public void onOSSizeUpdate(int width, int height) { - this.setSize(new Size(width, height)); - if (tabGroup != null) { - Size size = new Size(width, height - 10); - for (Widget widget : tabGroup.widgets) { - if (widget instanceof RGContainer) { - widget.setSize(size); - } - } - tabGroup.setSize(size); - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/recipechart/widget/PhantomWidget.java b/src/main/java/gregtech/common/terminal/app/recipechart/widget/PhantomWidget.java deleted file mode 100644 index 280722e7dbc..00000000000 --- a/src/main/java/gregtech/common/terminal/app/recipechart/widget/PhantomWidget.java +++ /dev/null @@ -1,148 +0,0 @@ -package gregtech.common.terminal.app.recipechart.widget; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.ingredient.IGhostIngredientTarget; -import gregtech.api.gui.widgets.PhantomFluidWidget; -import gregtech.api.gui.widgets.PhantomSlotWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.common.inventory.handlers.SingleItemStackHandler; - -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.items.IItemHandlerModifiable; - -import mezz.jei.api.gui.IGhostIngredientHandler; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - -public class PhantomWidget extends WidgetGroup implements IGhostIngredientTarget { - - private final IItemHandlerModifiable itemHandler; - private FluidStack fluidStack; - private PhantomFluidWidget fluidWidget; - private PhantomSlotWidget slotWidget; - private Consumer onChanged; - - public PhantomWidget(int x, int y, Object defaultObj) { - super(x, y, 18, 18); - itemHandler = new SingleItemStackHandler(1); - fluidStack = null; - fluidWidget = new PhantomFluidWidget(0, 0, 18, 18, null, null) - .setFluidStackUpdater(fluid -> { - fluidStack = fluid.copy(); - if (fluidStack != null && fluidStack.amount > 0) { - itemHandler.setStackInSlot(0, ItemStack.EMPTY); - slotWidget.setVisible(false); - fluidWidget.setVisible(true); - if (onChanged != null) { - onChanged.accept(fluidStack); - } - } - }, true).setBackgroundTexture(TerminalTheme.COLOR_B_2).showTip(true) - .setFluidStackSupplier(() -> fluidStack, true); - slotWidget = new PhantomSlotWidget(itemHandler, 0, 0, 0) { - - @Override - public boolean isEnabled() { - return isActive(); - } - }; - slotWidget.setChangeListener(() -> { - if (!itemHandler.getStackInSlot(0).isEmpty()) { - fluidStack = null; - fluidWidget.setVisible(false); - slotWidget.setVisible(true); - if (onChanged != null) { - onChanged.accept(itemHandler.getStackInSlot(0)); - } - } - }).setBackgroundTexture(TerminalTheme.COLOR_B_2); - this.addWidget(fluidWidget); - this.addWidget(slotWidget); - - if (defaultObj instanceof ItemStack) { - itemHandler.setStackInSlot(0, (ItemStack) defaultObj); - fluidWidget.setVisible(false); - slotWidget.setVisible(true); - } else if (defaultObj instanceof FluidStack) { - fluidStack = (FluidStack) defaultObj; - slotWidget.setVisible(false); - fluidWidget.setVisible(true); - } - } - - public PhantomWidget setChangeListener(Consumer onChanged) { - this.onChanged = onChanged; - return this; - } - - public void setObject(FluidStack fluid) { - if (fluid != null) { - fluidStack = fluid.copy(); - if (fluidStack != null && fluidStack.amount > 0) { - itemHandler.setStackInSlot(0, ItemStack.EMPTY); - slotWidget.setVisible(false); - fluidWidget.setVisible(true); - if (onChanged != null) { - onChanged.accept(fluidStack); - } - } - } - } - - public void setObject(ItemStack item) { - if (item != null && !item.isEmpty()) { - ItemStack copy = item.copy(); - copy.setCount(1); - itemHandler.setStackInSlot(0, copy); - fluidStack = null; - fluidWidget.setVisible(false); - slotWidget.setVisible(true); - if (onChanged != null) { - onChanged.accept(copy); - } - } - } - - @Override - public List> getPhantomTargets(Object ingredient) { - if (!isVisible()) { - return Collections.emptyList(); - } - ArrayList> targets = new ArrayList<>(); - for (Widget widget : widgets) { - if (widget instanceof IGhostIngredientTarget) { - targets.addAll(((IGhostIngredientTarget) widget).getPhantomTargets(ingredient)); - } - } - return targets; - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (isMouseOverElement(mouseX, mouseY)) { - ItemStack itemStack = gui.entityPlayer.inventory.getItemStack(); - if (!itemStack.isEmpty()) { - IFluidHandler handlerItem = itemStack - .getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); - if (handlerItem != null && handlerItem.getTankProperties().length > 0) { - FluidStack fluidStack = handlerItem.getTankProperties()[0].getContents(); - if (fluidStack != null) { - this.setObject(fluidStack); - return true; - } - } - this.setObject(itemStack); - return true; - } - return true; - } - return super.mouseClicked(mouseX, mouseY, button); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/recipechart/widget/RGContainer.java b/src/main/java/gregtech/common/terminal/app/recipechart/widget/RGContainer.java deleted file mode 100644 index b6988b8e0a6..00000000000 --- a/src/main/java/gregtech/common/terminal/app/recipechart/widget/RGContainer.java +++ /dev/null @@ -1,207 +0,0 @@ -package gregtech.common.terminal.app.recipechart.widget; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.terminal.gui.widgets.DraggableScrollableWidgetGroup; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.TerminalTheme; - -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraftforge.common.util.Constants; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; - -public class RGContainer extends DraggableScrollableWidgetGroup { - - protected TerminalOSWidget os; - private RGNode selectedNode; - private RGLine selectedLine; - protected final List nodes; - protected final List lines; - - public RGContainer(int x, int y, int width, int height, TerminalOSWidget os) { - super(x, y, width, height); - this.os = os; - this.setDraggable(true); - this.setXScrollBarHeight(4); - this.setYScrollBarWidth(4); - this.setXBarStyle(null, TerminalTheme.COLOR_F_1); - this.setYBarStyle(null, TerminalTheme.COLOR_F_1); - nodes = new ArrayList<>(); - lines = new ArrayList<>(); - } - - public RGNode getSelectedNode() { - return selectedNode; - } - - public void setSelectedNode(RGNode selectedNode) { - if (this.selectedNode != null) { - this.selectedNode.updateSelected(false); - } - this.selectedNode = selectedNode; - if (this.selectedNode != null) { - this.selectedNode.updateSelected(true); - } - } - - public RGLine getSelectedLine() { - return selectedLine; - } - - public void setSelectedLine(RGLine selectedLine) { - if (this.selectedLine != null) { - this.selectedLine.updateSelected(false); - } - this.selectedLine = selectedLine; - if (this.selectedLine != null) { - this.selectedLine.updateSelected(true); - } - } - - public RGNode addNode(int x, int y) { - RGNode node = new RGNode(x + getScrollXOffset(), y + getScrollYOffset(), this, null, true); - nodes.add(node); - this.addWidget(node); - return node; - } - - public RGNode addNode(int x, int y, Object object) { - RGNode node = new RGNode(x + getScrollXOffset(), y + getScrollYOffset(), this, object, false); - nodes.add(node); - this.addWidget(node); - return node; - } - - public void removeNode(RGNode node) { - nodes.remove(node); - this.waitToRemoved(node); - } - - public void addOrUpdateLine(RGNode parent, RGNode child) { - Optional optional = lines.stream() - .filter(line -> line.getParent() == parent && line.getChild() == child).findFirst(); - if (!optional.isPresent()) { - RGLine line = new RGLine(parent, child, this); - lines.add(line); - this.addWidget(0, line); - } else { - optional.get().updateLine(); - } - } - - public RGLine getLine(RGNode parent, RGNode child) { - Optional optional = lines.stream() - .filter(line -> line.getParent() == parent && line.getChild() == child).findFirst(); - return optional.orElse(null); - } - - public void removeLine(RGNode parent, RGNode child) { - lines.removeIf(line -> { - if (line.getParent() == parent && line.getChild() == child) { - RGContainer.this.waitToRemoved(line); - return true; - } - return false; - }); - } - - public void loadFromNBT(NBTTagCompound nbt) { - try { - this.clearAllWidgets(); - this.nodes.clear(); - this.lines.clear(); - NBTTagList nodesList = nbt.getTagList("nodes", Constants.NBT.TAG_COMPOUND); - for (NBTBase node : nodesList) { // build nodes - nodes.add(RGNode.deserializeNodeNBT((NBTTagCompound) node, this)); - } - Iterator iterator = nodesList.iterator(); // build relations - for (RGNode node : nodes) { - NBTTagCompound nodeTag = (NBTTagCompound) iterator.next(); - node.deserializeRelationNBT(nodeTag.getTagList("parents", Constants.NBT.TAG_INT_ARRAY), - nodeTag.getTagList("children", Constants.NBT.TAG_INT_ARRAY)); - this.addWidget(node); - } - for (RGLine line : lines) { - removeWidget(line); - } - lines.clear(); - NBTTagList linesList = nbt.getTagList("lines", Constants.NBT.TAG_COMPOUND); - for (NBTBase node : linesList) { // build nodes - RGLine line = RGLine.deserializeLineNBT((NBTTagCompound) node, this); - lines.add(line); - this.addWidget(0, line); - } - } catch (Exception e) { - TerminalDialogWidget.showInfoDialog(os, "ERROR", e.getMessage()).setClientSide().open(); - } - } - - public NBTTagCompound saveAsNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - NBTTagList nodesTag = new NBTTagList(); - for (RGNode node : nodes) { - nodesTag.appendTag(node.serializeNodeNBT()); - } - nbt.setTag("nodes", nodesTag); - NBTTagList linesTag = new NBTTagList(); - for (RGLine line : lines) { - linesTag.appendTag(line.serializeLineNBT()); - } - nbt.setTag("lines", linesTag); - return nbt; - } - - @Override - protected int getMaxHeight() { - return super.getMaxHeight() + 20; - } - - @Override - protected int getMaxWidth() { - return super.getMaxWidth() + 20; - } - - @Override - protected boolean hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - if (draggedWidget != null && draggedWidget == selectedNode) { - for (RGNode node : nodes) { - if (node != selectedNode && node.canMerge(selectedNode)) { - drawBorder(node.getPosition().x, node.getPosition().y, 18, 18, 0XFF0000FF, 2); - break; - } - } - } - return super.hookDrawInBackground(mouseX, mouseY, partialTicks, context); - } - - @Override - public boolean mouseReleased(int mouseX, int mouseY, int button) { - if (draggedWidget != null && draggedWidget == selectedNode) { - for (RGNode node : nodes) { - if (node != selectedNode && node.canMerge(selectedNode)) { - node.mergeNode(selectedNode); - break; - } - } - } - return super.mouseReleased(mouseX, mouseY, button); - } - - @Override - public boolean mouseWheelMove(int mouseX, int mouseY, int wheelDelta) { - for (int i = widgets.size() - 1; i >= 0; i--) { - Widget widget = widgets.get(i); - if (widget.isVisible() && widget.isActive() && widget.mouseWheelMove(mouseX, mouseY, wheelDelta)) { - return true; - } - } - return false; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/recipechart/widget/RGLine.java b/src/main/java/gregtech/common/terminal/app/recipechart/widget/RGLine.java deleted file mode 100644 index 4fca6a6ea70..00000000000 --- a/src/main/java/gregtech/common/terminal/app/recipechart/widget/RGLine.java +++ /dev/null @@ -1,225 +0,0 @@ -package gregtech.common.terminal.app.recipechart.widget; - -import gregtech.api.GTValues; -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.gui.widgets.SimpleTextWidget; -import gregtech.api.gui.widgets.SlotWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.metatileentity.MetaTileEntity; -import gregtech.api.metatileentity.SimpleMachineMetaTileEntity; -import gregtech.api.terminal.gui.widgets.CircleButtonWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.GTUtility; -import gregtech.api.util.Position; -import gregtech.api.util.Size; - -import net.minecraft.client.resources.I18n; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.Vec2f; -import net.minecraftforge.items.ItemStackHandler; - -import java.util.ArrayList; -import java.util.List; - -public class RGLine extends WidgetGroup { - - protected final RGNode parent; - protected final RGNode child; - protected final ItemStack catalyst; - protected int ratio; - private boolean isSelected; - private final List points; - private final RGContainer container; - private final WidgetGroup infoGroup; - private final WidgetGroup toolGroup; - - public RGLine(RGNode parent, RGNode child, RGContainer container) { - super(0, 0, 0, 0); - this.parent = parent; - this.child = child; - this.container = container; - this.points = new ArrayList<>(); - this.catalyst = parent.catalyst; - - infoGroup = new WidgetGroup(0, 0, 0, 0); - if (catalyst != null) { - ItemStackHandler handler = new ItemStackHandler(); - handler.setStackInSlot(0, catalyst); - infoGroup.addWidget( - new SlotWidget(handler, 0, 0, 0, false, false).setBackgroundTexture(new ColorRectTexture(0))); - MetaTileEntity mte = GTUtility.getMetaTileEntity(catalyst); - if (mte instanceof SimpleMachineMetaTileEntity) { - infoGroup.addWidget(new LabelWidget(9, -10, - I18n.format("terminal.recipe_chart.tier") + - GTValues.VN[((SimpleMachineMetaTileEntity) mte).getTier()], - -1).setXCentered(true).setShadow(true)); - } - } - - infoGroup.setVisible(false); - infoGroup.setActive(false); - this.addWidget(infoGroup); - - toolGroup = new WidgetGroup(0, 0, 0, 0); - toolGroup.addWidget(new CircleButtonWidget(-8, 0, 8, 1, 12) - .setColors(0, TerminalTheme.COLOR_7.getColor(), 0) - .setIcon(GuiTextures.ICON_VISIBLE) - .setHoverText("terminal.recipe_chart.visible") - .setClickListener(cd -> { - infoGroup.setActive(!infoGroup.isActive()); - infoGroup.setVisible(!infoGroup.isVisible()); - })); - toolGroup.addWidget(new CircleButtonWidget(8, 0, 8, 1, 12) - .setColors(0, TerminalTheme.COLOR_7.getColor(), 0) - .setIcon(GuiTextures.ICON_CALCULATOR) - .setHoverText("terminal.recipe_chart.ratio") - .setClickListener(cd -> TerminalDialogWidget - .showTextFieldDialog(container.os, "terminal.recipe_chart.ratio", s -> { - try { - return Integer.parseInt(s) > 0; - } catch (Exception ignored) { - return false; - } - }, s -> { - if (s != null) { - ratio = Integer.parseInt(s); - parent.updateDemand(parent.getHeadDemand()); - } - }).setClientSide().open())); - toolGroup.addWidget(new SimpleTextWidget(0, -18, "", -1, () -> Integer.toString(ratio), true).setShadow(true)); - toolGroup.setVisible(false); - this.addWidget(toolGroup); - this.ratio = 1; - updateLine(); - } - - public static RGLine deserializeLineNBT(NBTTagCompound nbt, RGContainer container) { - RGLine line = new RGLine(container.nodes.get(nbt.getInteger("parent")), - container.nodes.get(nbt.getInteger("child")), container); - line.ratio = nbt.getInteger("ratio"); - boolean visible = nbt.getBoolean("visible"); - line.infoGroup.setVisible(visible); - line.infoGroup.setActive(visible); - return line; - } - - public NBTTagCompound serializeLineNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("parent", container.nodes.indexOf(parent)); - nbt.setInteger("child", container.nodes.indexOf(child)); - nbt.setInteger("ratio", ratio); - nbt.setBoolean("visible", infoGroup.isVisible()); - return nbt; - } - - public RGNode getParent() { - return parent; - } - - public RGNode getChild() { - return child; - } - - public List getPoints() { - return points; - } - - public ItemStack getCatalyst() { - return catalyst; - } - - public void updateSelected(boolean isSelected) { - this.isSelected = isSelected; - toolGroup.setVisible(this.isSelected); - } - - public void updateLine() { - this.points.clear(); - Position pos1 = parent.getNodePosition(child); - Position pos2 = child.getNodePosition(null); - int x1, x2, y1, y2; - if (Math.abs(pos1.x - pos2.x) > Math.abs(pos1.y - pos2.y)) { - if (pos1.x > pos2.x) { - x1 = pos1.x; - y1 = pos1.y + 9; - x2 = pos2.x + 18; - } else { - x1 = pos1.x + 18; - y1 = pos1.y + 9; - x2 = pos2.x; - } - y2 = pos2.y + 9; - points.addAll(genBezierPoints(new Vec2f(x1, y1), new Vec2f(x2, y2), true, 0.01f)); - } else { - if (pos1.y > pos2.y) { - x1 = pos1.x + 9; - y1 = pos1.y; - y2 = pos2.y + 18; - } else { - x1 = pos1.x + 9; - y1 = pos1.y + 18; - y2 = pos2.y; - } - x2 = pos2.x + 9; - points.addAll(genBezierPoints(new Vec2f(x1, y1), new Vec2f(x2, y2), false, 0.01f)); - } - Position position = pos2.subtract(child.getSelfPosition()); - this.setSelfPosition(new Position(Math.min(x1, x2), Math.min(y1, y2)).subtract(position)); - int width = Math.abs(x1 - x2); - int height = Math.abs(y1 - y2); - this.setSize(new Size(width, height)); - this.setVisible(true); - this.setActive(true); - toolGroup.setSelfPosition(new Position((width) / 2, 0)); - infoGroup.setSelfPosition(new Position((width - 18) / 2, (height - 18) / 2)); - } - - public boolean isMouseOver(int mouseX, int mouseY) { - if (points == null || points.size() == 0) return false; - float x = points.get(0).x; - float y = points.get(0).y; - float x2 = points.get(points.size() - 1).x; - float y2 = points.get(points.size() - 1).y; - if (mouseX >= Math.min(x, x2) && mouseY >= Math.min(y, y2) && Math.max(x, x2) > mouseX && - Math.max(y, y2) > mouseY) { - for (Vec2f point : points) { - if ((mouseX - point.x) * (mouseX - point.x) + (mouseY - point.y) * (mouseY - point.y) < 4) { - return true; - } - } - } - return false; - } - - @Override - public void drawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - if (isSelected) { - drawSolidRect(getPosition().x, getPosition().y, getSize().width, getSize().height, 0x2fffffff); - drawLines(points, 0x2fff0000, 0xffff0000, 2); - } else { - drawLines(points, 0x2fffff00, 0xff00ff00, 2); - } - Vec2f point = points.get(points.size() - 1); - drawSolidRect((int) (point.x - 1.5), (int) (point.y - 1.5), 3, 3, 0XFF00FF00); - super.drawInBackground(mouseX, mouseY, partialTicks, context); - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (super.mouseClicked(mouseX, mouseY, button)) { - return true; - } else if (isMouseOver(mouseX, mouseY)) { - if (!isSelected) { - container.setSelectedLine(this); - } - } else if (isSelected) { - container.setSelectedLine(null); - } - return false; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/recipechart/widget/RGNode.java b/src/main/java/gregtech/common/terminal/app/recipechart/widget/RGNode.java deleted file mode 100644 index b8b466fb311..00000000000 --- a/src/main/java/gregtech/common/terminal/app/recipechart/widget/RGNode.java +++ /dev/null @@ -1,626 +0,0 @@ -package gregtech.common.terminal.app.recipechart.widget; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.Widget; -import gregtech.api.gui.impl.ModularUIContainer; -import gregtech.api.gui.widgets.SimpleTextWidget; -import gregtech.api.gui.widgets.SlotWidget; -import gregtech.api.gui.widgets.TankWidget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.metatileentity.MetaTileEntity; -import gregtech.api.metatileentity.SimpleMachineMetaTileEntity; -import gregtech.api.recipes.Recipe; -import gregtech.api.terminal.gui.IDraggable; -import gregtech.api.terminal.gui.widgets.CircleButtonWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.GTUtility; -import gregtech.api.util.Position; -import gregtech.common.terminal.app.recipechart.IngredientHelper; -import gregtech.integration.jei.JustEnoughItemsModule; -import gregtech.integration.jei.recipe.GTRecipeWrapper; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagIntArray; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.util.math.MathHelper; -import net.minecraftforge.common.util.Constants; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTank; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fml.common.ObfuscationReflectionHelper; -import net.minecraftforge.items.ItemStackHandler; - -import mezz.jei.api.gui.IRecipeLayout; -import mezz.jei.api.recipe.IFocus; -import mezz.jei.api.recipe.IRecipeCategory; -import mezz.jei.api.recipe.IRecipeWrapper; -import mezz.jei.gui.Focus; -import mezz.jei.gui.recipes.RecipeLayout; - -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; - -public class RGNode extends WidgetGroup implements IDraggable { - - private IngredientHelper headHelper; - protected Object head; - protected int recipePer = 1; - protected ItemStack catalyst; - private boolean isSelected; - private WidgetGroup toolGroup; - private WidgetGroup inputsGroup; - private RGContainer container; - private SimpleTextWidget textWidget; - protected Map parentNodes; - protected Map> children; - - public RGNode(int x, int y, RGContainer container, Object head, boolean isPhantom) { - super(x, y, 18, 18); - init(container); - this.head = head; - if (head != null) { - this.headHelper = IngredientHelper.getFor(head); - } - if (isPhantom) { - PhantomWidget phantom = new PhantomWidget(0, 0, head).setChangeListener(object -> { - RGNode.this.head = object; - RGNode.this.headHelper = object != null ? IngredientHelper.getFor(object) : null; - // Reset any children nodes, now that the parent has changed - for (Set childs : children.values()) { - for (RGNode child : childs) { - child.removeParent(this); - } - } - children.clear(); - - // Clear the Inputs for the replaced parent - this.inputsGroup.widgets.clear(); - - }); - this.addWidget(phantom); - toolGroup.addWidget(new CircleButtonWidget(-11, 49, 8, 1, 12) - .setColors(0, TerminalTheme.COLOR_7.getColor(), 0) - .setIcon(GuiTextures.ICON_CALCULATOR) - .setHoverText("terminal.recipe_chart.calculator") - .setClickListener(cd -> TerminalDialogWidget - .showTextFieldDialog(container.os, "terminal.recipe_chart.demand", s -> { - try { - return Integer.parseInt(s) > 0; - } catch (Exception ignored) { - return false; - } - }, s -> { - if (s != null && !s.isEmpty()) { - updateDemand(Integer.parseInt(s)); - } - }).setClientSide().open())); - toolGroup.addWidget(new CircleButtonWidget(9, 49, 8, 1, 12) - .setColors(0, TerminalTheme.COLOR_7.getColor(), 0) - .setIcon(GuiTextures.ICON_ADD) - .setHoverText("terminal.recipe_chart.add") - .setClickListener(cd -> TerminalDialogWidget - .showItemSelector(container.os, "terminal.recipe_chart.demand", false, itemStack -> true, - itemStack -> { - if (itemStack != null && !itemStack.isEmpty()) { - IFluidHandler handlerItem = itemStack.getCapability( - CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); - if (handlerItem != null && handlerItem.getTankProperties().length > 0) { - FluidStack fluidStack = handlerItem.getTankProperties()[0] - .getContents(); - if (fluidStack != null) { - phantom.setObject(fluidStack); - return; - } - } - phantom.setObject(itemStack); - - // Reset any children nodes, now that the parent has changed - for (Set childs : children.values()) { - for (RGNode child : childs) { - child.removeParent(this); - } - } - children.clear(); - - // Clear the Inputs for the replaced parent - this.inputsGroup.widgets.clear(); - } - }) - .setClientSide().open())); - } else { - addWidget(this.headHelper.createWidget(head)); - } - } - - private void init(RGContainer container) { - this.container = container; - textWidget = new SimpleTextWidget(9, -5, "", -1, - () -> this.head != null ? this.headHelper.getDisplayName(this.head) : "terminal.recipe_chart.drag", - true).setShadow(true); - textWidget.setVisible(false); - textWidget.setActive(false); - this.addWidget(textWidget); - inputsGroup = new WidgetGroup(0, 0, 0, 0); - this.addWidget(inputsGroup); - toolGroup = new WidgetGroup(0, 0, 0, 0); - this.addWidget(toolGroup); - toolGroup.addWidget(new CircleButtonWidget(-11, 9, 8, 1, 12) - .setColors(0, TerminalTheme.COLOR_7.getColor(), TerminalTheme.COLOR_3.getColor()) - .setIcon(GuiTextures.ICON_REMOVE) - .setHoverText("terminal.guide_editor.remove") - .setClickListener(cd -> remove())); - toolGroup.addWidget(new CircleButtonWidget(-11, 29, 8, 1, 12) - .setColors(0, TerminalTheme.COLOR_7.getColor(), 0) - .setIcon(GuiTextures.ICON_VISIBLE) - .setHoverText("terminal.recipe_chart.visible") - .setClickListener(cd -> { - textWidget.setActive(!textWidget.isActive()); - textWidget.setVisible(!textWidget.isVisible()); - })); - toolGroup.addWidget(new CircleButtonWidget(9, 29, 8, 1, 12) - .setColors(0, TerminalTheme.COLOR_7.getColor(), 0) - .setIcon(GuiTextures.ICON_LOCATION) - .setHoverText("terminal.recipe_chart.jei") - .setClickListener(cd -> { - if (JustEnoughItemsModule.jeiRuntime != null && head != null && !this.headHelper.isEmpty(head)) { - JustEnoughItemsModule.jeiRuntime.getRecipesGui().show(new Focus<>(IFocus.Mode.OUTPUT, head)); - } - })); - inputsGroup.setVisible(false); - inputsGroup.setActive(false); - toolGroup.setVisible(false); - toolGroup.setActive(false); - parentNodes = new HashMap<>(); - children = new LinkedHashMap<>(); // important - } - - public int getHeadDemand() { - return this.headHelper.getAmount(this.head); - } - - public int getChildDemand(RGNode child) { - for (Map.Entry> entry : children.entrySet()) { - if (entry.getValue().contains(child)) { - int perC = 0; - if (entry.getKey() instanceof SlotWidget) { - perC = ((SlotWidget) entry.getKey()).getHandle().getStack().getCount(); - } else if (entry.getKey() instanceof TankWidget) { - perC = ((TankWidget) entry.getKey()).fluidTank.getFluidAmount(); - } - int ratioSum = entry.getValue().stream().mapToInt(it -> container.getLine(RGNode.this, it).ratio).sum(); - return MathHelper.ceil(perC * MathHelper.ceil(getHeadDemand() / (float) recipePer) * - container.getLine(RGNode.this, child).ratio / (float) ratioSum); - } - } - return 0; - } - - public boolean canMerge(RGNode node) { - if (this.headHelper == node.headHelper && this.headHelper.areEqual(this.head, node.head)) { - return checkMergeAvailable(node); - } - return false; - } - - private boolean checkMergeAvailable(RGNode node) { - Position pos1 = this.getPosition(); - Position pos2 = node.getPosition(); - return Math.abs(pos1.x - pos2.x) < 18 && Math.abs(pos1.y - pos2.y) < 18 && - !this.findAllChildren().contains(node) && - !node.findAllChildren().contains(this); - } - - public Set findAllChildren() { - Set result = new HashSet<>(); - for (Set nodes : children.values()) { - for (RGNode node : nodes) { - result.add(node); - result.addAll(node.findAllChildren()); - } - } - return result; - } - - public void mergeNode(RGNode node) { - for (RGNode parentNode : node.parentNodes.keySet()) { - for (Set value : parentNode.children.values()) { - if (value.remove(node)) { - value.add(this); - addParent(parentNode); - parentNode.updateDemand(parentNode.getHeadDemand()); - break; - } - } - } - node.remove(); - } - - public void remove() { - if (isSelected) { - container.setSelectedNode(null); - } - container.removeNode(this); - for (RGNode parentNode : parentNodes.keySet()) { - container.removeLine(parentNode, this); - parentNode.onChildRemoved(this); - } - parentNodes.clear(); - for (Set childs : children.values()) { - for (RGNode child : childs) { - child.removeParent(this); - } - } - children.clear(); - } - - public Position getNodePosition(RGNode child) { - if (child != null && isSelected) { - for (Map.Entry> nodeEntry : children.entrySet()) { - if (nodeEntry.getValue().contains(child)) { - return nodeEntry.getKey().getPosition(); - } - } - } - return this.getPosition(); - } - - public void addParent(RGNode parent) { - container.addOrUpdateLine(parent, this); - this.parentNodes.put(parent, parent.getChildDemand(this)); - updateDemand(parentNodes.values().stream().mapToInt(it -> it).sum()); - } - - public void updateDemand(int demand) { - dfsUpdateDemand(demand, new Stack<>()); - } - - private void dfsUpdateDemand(int demand, Stack updated) { - if (updated.contains(this)) return; - updated.push(this); - this.headHelper.setAmount(this.head, demand); - for (Set children : children.values()) { - for (RGNode child : children) { - child.parentNodes.put(this, this.getChildDemand(child)); - child.dfsUpdateDemand(child.parentNodes.values().stream().mapToInt(it -> it).sum(), updated); - } - } - updated.pop(); - } - - public void removeParent(RGNode parent) { - this.parentNodes.remove(parent); - if (parentNodes.size() == 0) { - for (Set childs : children.values()) { - for (RGNode child : childs) { - child.removeParent(RGNode.this); - } - } - children.clear(); - container.removeNode(this); - } else { - updateDemand(parentNodes.values().stream().mapToInt(it -> it).sum()); - } - container.removeLine(parent, this); - } - - public void onChildRemoved(RGNode child) { - for (Set childs : children.values()) { - if (childs.remove(child)) { - updateDemand(getHeadDemand()); - break; - } - } - } - - @Override - protected void onPositionUpdate() { - super.onPositionUpdate(); - for (RGNode parentNode : parentNodes.keySet()) { - container.addOrUpdateLine(parentNode, this); - } - for (Set childs : children.values()) { - for (RGNode child : childs) { - container.addOrUpdateLine(this, child); - } - } - } - - public boolean transferRecipe(ModularUIContainer x, IRecipeLayout recipeLayout, EntityPlayer player, - boolean maxTransfer, boolean doTransfer) { - if (isSelected) { - Object obj = recipeLayout.getFocus() == null ? null : recipeLayout.getFocus().getValue(); - IngredientHelper otherHelper = IngredientHelper.getFor(obj); - if (this.headHelper != otherHelper || !this.headHelper.areEqual(this.head, obj)) { - return false; - } - if (!doTransfer) return true; - RGNode.this.recipePer = 0; - - // items - List itemInputs = new ArrayList<>(); - recipeLayout.getItemStacks().getGuiIngredients().values().forEach(it -> { - if (it.isInput() && it.getDisplayedIngredient() != null) { - ItemStack input = it.getDisplayedIngredient(); - for (ItemStack itemInput : itemInputs) { - if (itemInput.isItemEqual(input)) { - itemInput.setCount(itemInput.getCount() + input.getCount()); - return; - } - } - itemInputs.add(input.copy()); - } else if (head instanceof ItemStack && !it.isInput()) { - for (ItemStack ingredient : it.getAllIngredients()) { - if (((ItemStack) head).isItemEqual(ingredient)) { - RGNode.this.recipePer += ingredient.getCount(); - break; - } - } - } - }); - - // fluids - List fluidInputs = new ArrayList<>(); - recipeLayout.getFluidStacks().getGuiIngredients().values().forEach(it -> { - if (it.isInput() && it.getDisplayedIngredient() != null) { - FluidStack input = it.getDisplayedIngredient(); - for (FluidStack fluidInput : fluidInputs) { - if (fluidInput.isFluidEqual(input)) { - fluidInput.amount += input.amount; - return; - } - } - fluidInputs.add(input.copy()); - } else if (head instanceof FluidStack && !it.isInput()) { - for (FluidStack ingredient : it.getAllIngredients()) { - if (((FluidStack) head).isFluidEqual(ingredient)) { - RGNode.this.recipePer += ingredient.amount; - break; - } - } - } - }); - // CHECK GTCE RECIPES - Recipe recipe = null; - if (recipeLayout instanceof RecipeLayout) { - IRecipeWrapper recipeWrapper = ObfuscationReflectionHelper.getPrivateValue(RecipeLayout.class, - (RecipeLayout) recipeLayout, "recipeWrapper"); - if (recipeWrapper instanceof GTRecipeWrapper) { - recipe = ((GTRecipeWrapper) recipeWrapper).getRecipe(); - } - } - IRecipeCategory category = recipeLayout.getRecipeCategory(); - List catalysts = JustEnoughItemsModule.jeiRuntime.getRecipeRegistry().getRecipeCatalysts(category); - ItemStack catalyst = null; - - if (recipe != null) { // GT - int tierRequire = GTUtility.getTierByVoltage(recipe.getEUt()); - for (Object o : catalysts) { - if (o instanceof ItemStack) { - MetaTileEntity mte = GTUtility.getMetaTileEntity((ItemStack) o); - if (mte instanceof SimpleMachineMetaTileEntity) { - if (tierRequire < ((SimpleMachineMetaTileEntity) mte).getTier()) { - catalyst = (ItemStack) o; - break; - } - } - } - } - } - - if (catalyst == null) { - for (Object o : catalysts) { - if (o instanceof ItemStack) { - catalyst = (ItemStack) o; - break; - } - } - } - setRecipe(itemInputs, fluidInputs, catalyst, Math.max(1, this.recipePer)); - return true; - } - return false; - } - - public void deserializeRelationNBT(NBTTagList parentsTag, NBTTagList childrenTag) { - for (NBTBase nbtBase : parentsTag) { - int[] nbt = ((NBTTagIntArray) nbtBase).getIntArray(); - parentNodes.put(container.nodes.get(nbt[0]), nbt[1]); - } - Iterator iterator = children.keySet().iterator(); - for (NBTBase nbtBase : childrenTag) { - int[] nbt = ((NBTTagIntArray) nbtBase).getIntArray(); - children.get(iterator.next()) - .addAll(Arrays.stream(nbt).mapToObj(it -> container.nodes.get(it)).collect(Collectors.toList())); - } - } - - public static RGNode deserializeNodeNBT(NBTTagCompound nodeTag, RGContainer container) { - byte type = nodeTag.getByte("type"); // 0-null 1-itemstack 2-fluidstack - Object head = null; - if (type != 0) { - IngredientHelper headHelper = (IngredientHelper) IngredientHelper.getForTypeId(type); - head = headHelper.deserialize(nodeTag.getCompoundTag("nbt")); - headHelper.setAmount(head, nodeTag.getInteger("count")); - } - RGNode node = new RGNode(nodeTag.getInteger("x"), nodeTag.getInteger("y"), container, head, - nodeTag.getBoolean("phantom")); - NBTTagList itemsList = nodeTag.getTagList("items", Constants.NBT.TAG_COMPOUND); - NBTTagList fluidsList = nodeTag.getTagList("fluids", Constants.NBT.TAG_COMPOUND); - List itemInputs = new LinkedList<>(); - itemsList.forEach(base -> { - if (base instanceof NBTTagCompound) { - itemInputs.add(new ItemStack((NBTTagCompound) base)); - } - }); - List fluidsInputs = new LinkedList<>(); - fluidsList.forEach(base -> { - if (base instanceof NBTTagCompound) { - fluidsInputs.add(FluidStack.loadFluidStackFromNBT((NBTTagCompound) base)); - } - }); - node.setRecipe(itemInputs, fluidsInputs, - nodeTag.hasKey("catalyst") ? new ItemStack(nodeTag.getCompoundTag("catalyst")) : null, - nodeTag.getInteger("per")); - boolean visible = nodeTag.getBoolean("visible"); - node.textWidget.setVisible(visible); - node.textWidget.setActive(visible); - return node; - } - - public NBTTagCompound serializeNodeNBT() { - // head - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("x", getSelfPosition().x + container.getScrollXOffset()); - nbt.setInteger("y", getSelfPosition().y + container.getScrollYOffset()); - nbt.setByte("type", this.head == null ? 0 : this.headHelper.getTypeId()); - if (this.head != null) { - nbt.setTag("nbt", this.headHelper.serialize(this.head)); - nbt.setInteger("count", this.headHelper.getAmount(this.head)); - } - nbt.setBoolean("phantom", widgets.stream().anyMatch(it -> it instanceof PhantomWidget)); - // recipe + children - NBTTagList itemsList = new NBTTagList(); - NBTTagList fluidsList = new NBTTagList(); - NBTTagList childrenList = new NBTTagList(); - for (Map.Entry> entry : children.entrySet()) { - Widget widget = entry.getKey(); - if (widget instanceof SlotWidget) { - itemsList.appendTag(((SlotWidget) widget).getHandle().getStack().serializeNBT()); - } else if (widget instanceof TankWidget) { - fluidsList.appendTag(((TankWidget) widget).fluidTank.getFluid().writeToNBT(new NBTTagCompound())); - } else { - continue; - } - NBTTagIntArray childList = new NBTTagIntArray( - entry.getValue().stream().mapToInt(it -> container.nodes.indexOf(it)).toArray()); - childrenList.appendTag(childList); - } - nbt.setTag("items", itemsList); - nbt.setTag("fluids", fluidsList); - nbt.setTag("children", childrenList); - if (catalyst != null) { - nbt.setTag("catalyst", catalyst.serializeNBT()); - } - nbt.setInteger("per", recipePer); - // parent - NBTTagList parentsList = new NBTTagList(); - for (Map.Entry entry : parentNodes.entrySet()) { - parentsList.appendTag( - new NBTTagIntArray(new int[] { container.nodes.indexOf(entry.getKey()), entry.getValue() })); - } - nbt.setTag("parents", parentsList); - nbt.setBoolean("visible", textWidget.isVisible()); - return nbt; - } - - private void setRecipe(List itemInputs, List fluidInputs, ItemStack catalyst, - int recipePer) { - this.recipePer = recipePer; - this.catalyst = catalyst; - inputsGroup.clearAllWidgets(); - for (Set childs : children.values()) { - for (RGNode child : childs) { - child.removeParent(this); - } - } - children.clear(); - AtomicInteger y = new AtomicInteger(-20); - for (ItemStack itemInput : itemInputs) { - ItemStackHandler handler = new ItemStackHandler(1); - handler.setStackInSlot(0, itemInput); - Widget widget = new SlotWidget(handler, 0, 0, y.addAndGet(20), false, false) { - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - return RGNode.this.handleTipsSlotClick(mouseX, mouseY, this, handler.getStackInSlot(0).copy()); - } - }.setBackgroundTexture(TerminalTheme.COLOR_B_2); - inputsGroup.addWidget(widget); - children.put(widget, new HashSet<>()); - } - for (FluidStack fluidInput : fluidInputs) { - FluidTank tank = new FluidTank(fluidInput, Integer.MAX_VALUE); - Widget widget = new TankWidget(tank, 0, y.addAndGet(20), 18, 18) { - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - return RGNode.this.handleTipsSlotClick(mouseX, mouseY, this, tank.getFluid().copy()); - } - }.setAlwaysShowFull(true).setBackgroundTexture(TerminalTheme.COLOR_B_2).setClient(); - inputsGroup.addWidget(widget); - children.put(widget, new HashSet<>()); - } - inputsGroup.setSelfPosition(new Position(25, -(inputsGroup.widgets.size() * 20) / 2 + 8)); - } - - private boolean handleTipsSlotClick(int mouseX, int mouseY, Widget slot, Object object) { - if (slot.isMouseOverElement(mouseX, mouseY)) { - Position position = inputsGroup.getSelfPosition(); - RGNode child = container.addNode(RGNode.this.getSelfPosition().x + 50, - RGNode.this.getSelfPosition().y + position.y + slot.getSelfPosition().y, object); - Set childs = RGNode.this.children.get(slot); - childs.add(child); - - child.addParent(RGNode.this); - RGNode.this.updateDemand(RGNode.this.getHeadDemand()); - return true; - } - return false; - } - - public void updateSelected(boolean selected) { - isSelected = selected; - if (selected) { - toolGroup.setActive(true); - toolGroup.setVisible(true); - inputsGroup.setActive(true); - inputsGroup.setVisible(true); - } else { - toolGroup.setActive(false); - toolGroup.setVisible(false); - inputsGroup.setActive(false); - inputsGroup.setVisible(false); - } - children.forEach((widget, rgNode) -> rgNode.forEach(child -> container.addOrUpdateLine(RGNode.this, child))); - } - - @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 (isSelected) { - drawBorder(x, y, width, height, 0xff00ff00, 2); - } - super.drawInBackground(mouseX, mouseY, partialTicks, context); - } - - @Override - public boolean allowDrag(int mouseX, int mouseY, int button) { - return isMouseOverElement(mouseX, mouseY); - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (isMouseOverElement(mouseX, mouseY)) { - if (!isSelected) { - container.setSelectedNode(this); - } - super.mouseClicked(mouseX, mouseY, button); - return false; - } else if (super.mouseClicked(mouseX, mouseY, button)) { - return true; - } else if (isSelected) { - container.setSelectedNode(null); - } - return false; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/settings/SettingsApp.java b/src/main/java/gregtech/common/terminal/app/settings/SettingsApp.java deleted file mode 100644 index a04035afc07..00000000000 --- a/src/main/java/gregtech/common/terminal/app/settings/SettingsApp.java +++ /dev/null @@ -1,64 +0,0 @@ -package gregtech.common.terminal.app.settings; - -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.resources.TextTexture; -import gregtech.api.gui.widgets.AbstractWidgetGroup; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.TabGroup; -import gregtech.api.gui.widgets.tab.IGuiTextureTabInfo; -import gregtech.api.gui.widgets.tab.ITabInfo; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.CustomTabListRenderer; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.common.terminal.app.settings.widgets.HomeButtonSettings; -import gregtech.common.terminal.app.settings.widgets.OsSettings; -import gregtech.common.terminal.app.settings.widgets.ThemeSettings; - -public class SettingsApp extends AbstractApplication { - - private TabGroup tabGroup; - - public SettingsApp() { - super("settings"); - } - - @Override - public AbstractApplication initApp() { - if (isClient) { - this.addWidget(new ImageWidget(5, 15, 323, 212, new ColorRectTexture(TerminalTheme.COLOR_B_2.getColor()))); - this.tabGroup = new TabGroup<>(5, 15, - new CustomTabListRenderer(TerminalTheme.COLOR_B_2, TerminalTheme.COLOR_F_2, 323 / 3, 10)); - this.addWidget(this.tabGroup); - this.tabGroup.setOnTabChanged(this::onPagesChanged); - addTab("terminal.settings.theme", new ThemeSettings(getOs())); - addTab("terminal.settings.home", new HomeButtonSettings(getOs())); - addTab("terminal.settings.os", new OsSettings(getOs())); - } - return this; - } - - private void onPagesChanged(int oldPage, int newPage) { - ITabInfo tabInfo = tabGroup.getTabInfo(newPage); - if (tabInfo instanceof IGuiTextureTabInfo && ((IGuiTextureTabInfo) tabInfo).texture instanceof TextTexture) { - ((TextTexture) ((IGuiTextureTabInfo) tabInfo).texture).setType(TextTexture.TextType.ROLL); - } - tabInfo = tabGroup.getTabInfo(oldPage); - if (tabInfo instanceof IGuiTextureTabInfo && ((IGuiTextureTabInfo) tabInfo).texture instanceof TextTexture) { - ((TextTexture) ((IGuiTextureTabInfo) tabInfo).texture).setType(TextTexture.TextType.HIDE); - } - } - - private void addTab(String name, AbstractWidgetGroup widget) { - tabGroup.addTab( - new IGuiTextureTabInfo( - new TextTexture(name, -1).setWidth(323 / 3 - 5).setType( - tabGroup.getAllTag().isEmpty() ? TextTexture.TextType.ROLL : TextTexture.TextType.HIDE), - name), - widget); - } - - @Override - public boolean isClientSideApp() { - return true; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/settings/widgets/HomeButtonSettings.java b/src/main/java/gregtech/common/terminal/app/settings/widgets/HomeButtonSettings.java deleted file mode 100644 index 48ab589601f..00000000000 --- a/src/main/java/gregtech/common/terminal/app/settings/widgets/HomeButtonSettings.java +++ /dev/null @@ -1,133 +0,0 @@ -package gregtech.common.terminal.app.settings.widgets; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.Widget; -import gregtech.api.gui.widgets.AbstractWidgetGroup; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.gui.widgets.TextFieldWidget; -import gregtech.api.terminal.gui.widgets.SelectorWidget; -import gregtech.api.terminal.os.SystemCall; -import gregtech.api.terminal.os.TerminalHomeButtonWidget; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.Position; -import gregtech.api.util.Size; - -import net.minecraft.client.resources.I18n; - -import org.apache.commons.lang3.tuple.MutablePair; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -public class HomeButtonSettings extends AbstractWidgetGroup { - - final TerminalOSWidget os; - - public HomeButtonSettings(TerminalOSWidget os) { - super(Position.ORIGIN, new Size(323, 212)); - this.os = os; - List candidates = Arrays.stream(SystemCall.values()).map(SystemCall::getTranslateKey) - .collect(Collectors.toList()); - candidates.add(0, "terminal.system_call.null"); - TerminalHomeButtonWidget home = this.os.home; - this.addWidget(new LabelWidget(10, 15, "terminal.settings.home.double", -1).setYCentered(true)); - this.addWidget(new LabelWidget(50, 15, "+Ctrl", -1).setYCentered(true)); - this.addWidget(new LabelWidget(85, 15, "+Shift", -1).setYCentered(true)); - this.addWidget( - new LabelWidget(170, 15, "terminal.settings.home.action", -1).setXCentered(true).setYCentered(true)); - this.addWidget( - new LabelWidget(270, 15, "terminal.settings.home.args", -1).setXCentered(true).setYCentered(true)); - - for (int shift = 0; shift < 2; shift++) { - for (int ctrl = 0; ctrl < 2; ctrl++) { - for (int doubleClick = 0; doubleClick < 2; doubleClick++) { - int i = TerminalHomeButtonWidget.actionMap(doubleClick == 1, ctrl == 1, shift == 1); - Pair pair = home.getActions()[i]; - int y = i * 22 + 30; - if (doubleClick == 1) { - this.addWidget(new ImageWidget(15, y + 5, 10, 10, GuiTextures.ICON_VISIBLE)); - } - if (ctrl == 1) { - this.addWidget(new ImageWidget(55, y + 5, 10, 10, GuiTextures.ICON_VISIBLE)); - } - if (shift == 1) { - this.addWidget(new ImageWidget(90, y + 5, 10, 10, GuiTextures.ICON_VISIBLE)); - } - TextFieldWidget textFieldWidget = new TextFieldWidget(230, y, 80, 20, TerminalTheme.COLOR_B_3, null, - null) - .setMaxStringLength(Integer.MAX_VALUE) - .setTextResponder(arg -> { - if (arg != null && home.getActions()[i] != null) { - home.getActions()[i].setValue(arg); - } - home.saveConfig(); - }, true) - .setValidator(s -> true); - if (pair != null && pair.getValue() != null) { - textFieldWidget.setCurrentString(pair.getValue()); - } else { - textFieldWidget.setCurrentString(""); - } - - this.addWidget(new SelectorWidget(120, y, 100, 20, candidates, -1, - () -> { - Pair _pair = home.getActions()[i]; - if (_pair != null) { - return _pair.getKey().getTranslateKey(); - } - return "terminal.system_call.null"; - }, true) - .setIsUp(i > 3) - .setHoverText(I18n - .format(doubleClick == 1 ? "terminal.settings.home.double_click" : - "terminal.settings.home.click") + - (ctrl == 1 ? "+Ctrl" : "") + (shift == 1 ? "+Shift" : "")) - .setOnChanged(selected -> { - SystemCall action = SystemCall.getFromName(selected); - if (action != null) { - if (home.getActions()[i] == null) { - home.getActions()[i] = new MutablePair<>(action, null); - } else { - home.getActions()[i] = new MutablePair<>(action, - home.getActions()[i].getValue()); - } - } else { - home.getActions()[i] = null; - } - home.saveConfig(); - }) - .setOnShowChange(isShow -> { - if (isShow) { - for (Widget widget : widgets) { - if (widget instanceof SelectorWidget) { - ((SelectorWidget) widget).hide(); - } - } - } - }) - .setColors(TerminalTheme.COLOR_B_2.getColor(), TerminalTheme.COLOR_F_1.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setBackground(TerminalTheme.COLOR_6)); - - this.addWidget(textFieldWidget); - } - } - } - } - - @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() && widget.isActive() && widget.mouseClicked(mouseX, mouseY, button)) { - mouseX = -10000; - mouseY = -10000; - } - } - return mouseX == -10000; - } -} diff --git a/src/main/java/gregtech/common/terminal/app/settings/widgets/OsSettings.java b/src/main/java/gregtech/common/terminal/app/settings/widgets/OsSettings.java deleted file mode 100644 index 1ed390a5352..00000000000 --- a/src/main/java/gregtech/common/terminal/app/settings/widgets/OsSettings.java +++ /dev/null @@ -1,72 +0,0 @@ -package gregtech.common.terminal.app.settings.widgets; - -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.widgets.AbstractWidgetGroup; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.GTLog; -import gregtech.api.util.Position; -import gregtech.api.util.Size; - -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fml.common.FMLCommonHandler; - -import java.io.File; -import java.io.IOException; - -public class OsSettings extends AbstractWidgetGroup { - - public static boolean DOUBLE_CHECK; - static { - if (FMLCommonHandler.instance().getSide().isClient()) { - NBTTagCompound nbt = null; - try { - nbt = CompressedStreamTools.read(new File(TerminalRegistry.TERMINAL_PATH, "config/os_settings.nbt")); - } catch (IOException e) { - GTLog.logger.error("error while loading local nbt for the os settings", e); - } - if (nbt == null) { - DOUBLE_CHECK = true; - } else { - DOUBLE_CHECK = nbt.getBoolean("double_check"); - } - } - } - final TerminalOSWidget os; - - public static void saveConfig() { - if (FMLCommonHandler.instance().getSide().isClient()) { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setBoolean("double_check", DOUBLE_CHECK); - try { - if (!nbt.isEmpty()) { - CompressedStreamTools.safeWrite(nbt, - new File(TerminalRegistry.TERMINAL_PATH, "config/os_settings.nbt")); - } - } catch (IOException e) { - GTLog.logger.error("error while saving local nbt for the os settings", e); - } - } - } - - public OsSettings(TerminalOSWidget os) { - super(Position.ORIGIN, new Size(323, 212)); - this.os = os; - this.addWidget(new LabelWidget(25, 15, "terminal.settings.os.double_check", -1).setYCentered(true)); - this.addWidget(new RectButtonWidget(10, 10, 10, 10, 2) - .setToggleButton(new ColorRectTexture(TerminalTheme.COLOR_B_2.getColor()), (c, p) -> { - DOUBLE_CHECK = !p; - saveConfig(); - }) - .setValueSupplier(true, () -> !DOUBLE_CHECK) - .setColors(TerminalTheme.COLOR_B_3.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_3.getColor()) - .setIcon(new ColorRectTexture(TerminalTheme.COLOR_7.getColor())) - .setHoverText("terminal.settings.os.double_check.desc")); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/settings/widgets/ThemeSettings.java b/src/main/java/gregtech/common/terminal/app/settings/widgets/ThemeSettings.java deleted file mode 100644 index d0894a487c1..00000000000 --- a/src/main/java/gregtech/common/terminal/app/settings/widgets/ThemeSettings.java +++ /dev/null @@ -1,167 +0,0 @@ -package gregtech.common.terminal.app.settings.widgets; - -import gregtech.api.gui.resources.*; -import gregtech.api.gui.widgets.*; -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.gui.widgets.CircleButtonWidget; -import gregtech.api.terminal.gui.widgets.ColorWidget; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.gui.widgets.SelectorWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalOSWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.Position; -import gregtech.api.util.Size; - -import net.minecraft.util.ResourceLocation; - -import java.util.Arrays; -import java.util.function.Consumer; - -public class ThemeSettings extends AbstractWidgetGroup { - - private final WidgetGroup textureGroup; - final TerminalOSWidget os; - - public ThemeSettings(TerminalOSWidget os) { - super(Position.ORIGIN, new Size(323, 212)); - this.os = os; - float x = 323 * 1.0f / 13; - int y = 40; - this.addWidget(new LabelWidget(323 / 2, 10, "terminal.settings.theme.color", -1).setXCentered(true)); - this.addColorButton(TerminalTheme.COLOR_1, "COLOR_1", (int) x, y); - this.addColorButton(TerminalTheme.COLOR_2, "COLOR_2", (int) (x * 2), y); - this.addColorButton(TerminalTheme.COLOR_3, "COLOR_3", (int) (x * 3), y); - this.addColorButton(TerminalTheme.COLOR_4, "COLOR_4", (int) (x * 4), y); - this.addColorButton(TerminalTheme.COLOR_5, "COLOR_5", (int) (x * 5), y); - this.addColorButton(TerminalTheme.COLOR_6, "COLOR_6", (int) (x * 6), y); - this.addColorButton(TerminalTheme.COLOR_7, "COLOR_7", (int) (x * 7), y); - this.addColorButton(TerminalTheme.COLOR_F_1, "COLOR_F_1", (int) (x * 8), y); - this.addColorButton(TerminalTheme.COLOR_F_2, "COLOR_F_2", (int) (x * 9), y); - this.addColorButton(TerminalTheme.COLOR_B_1, "COLOR_B_1", (int) (x * 10), y); - this.addColorButton(TerminalTheme.COLOR_B_2, "COLOR_B_2", (int) (x * 11), y); - this.addColorButton(TerminalTheme.COLOR_B_3, "COLOR_B_3", (int) (x * 12), y); - this.addWidget(new LabelWidget(323 / 2, 75, "terminal.settings.theme.wallpaper", -1).setXCentered(true)); - this.addWidget(new ImageWidget((int) x, 95, 150, 105, TerminalTheme.WALL_PAPER).setBorder(2, -1)); - this.addWidget(new SelectorWidget((int) (x + 170), 95, 116, 20, - Arrays.asList( - "terminal.settings.theme.wallpaper.resource", - "terminal.settings.theme.wallpaper.url", - "terminal.settings.theme.wallpaper.color", - "terminal.settings.theme.wallpaper.file"), - -1, this::getLocalizedWallpaperTypeName, true) - .setIsUp(true) - .setOnChanged(this::onModifyTextureChanged) - .setColors(TerminalTheme.COLOR_B_2.getColor(), TerminalTheme.COLOR_F_1.getColor(), - TerminalTheme.COLOR_B_2.getColor()) - .setBackground(TerminalTheme.COLOR_6)); - textureGroup = new WidgetGroup((int) (x + 170), 122, (int) (x * 11 - 170), 65); - this.addWidget(textureGroup); - } - - private String getLocalizedWallpaperTypeName() { - switch (TerminalTheme.WALL_PAPER.getTypeName()) { - case "resource": - return "terminal.settings.theme.wallpaper.resource"; - case "url": - return "terminal.settings.theme.wallpaper.url"; - case "color": - return "terminal.settings.theme.wallpaper.color"; - case "file": - return "terminal.settings.theme.wallpaper.file"; - } - return null; - } - - private void addColorButton(ColorRectTexture texture, String name, int x, int y) { - CircleButtonWidget buttonWidget = new CircleButtonWidget(x, y, 8, 1, 0).setFill(texture.getColor()) - .setStrokeAnima(-1).setHoverText(name); - buttonWidget.setClickListener(cd -> TerminalDialogWidget.showColorDialog(os, name, color -> { - if (color != null) { - buttonWidget.setFill(color); - texture.setColor(color); - if (!TerminalTheme.saveConfig()) { - TerminalDialogWidget - .showInfoDialog(os, "terminal.component.error", "terminal.component.save_file.error") - .setClientSide().open(); - } - } - }, texture.color).setClientSide().open()); - addWidget(buttonWidget); - } - - private void onModifyTextureChanged(String type) { - textureGroup.clearAllWidgets(); - switch (type) { - case "terminal.settings.theme.wallpaper.resource": - if (!(TerminalTheme.WALL_PAPER.getTexture() instanceof TextureArea)) { - TerminalTheme.WALL_PAPER.setTexture(new TextureArea( - new ResourceLocation("gregtech:textures/gui/terminal/terminal_background.png"), 0.0, 0.0, - 1.0, 1.0)); - TerminalTheme.saveConfig(); - } - addStringSetting(((TextureArea) TerminalTheme.WALL_PAPER.getTexture()).imageLocation.toString(), - s -> { - TerminalTheme.WALL_PAPER - .setTexture(new TextureArea(new ResourceLocation(s), 0.0, 0.0, 1.0, 1.0)); - TerminalTheme.saveConfig(); - }); - break; - case "terminal.settings.theme.wallpaper.url": - if (!(TerminalTheme.WALL_PAPER.getTexture() instanceof URLTexture)) { - TerminalTheme.WALL_PAPER.setTexture(new URLTexture(null)); - TerminalTheme.saveConfig(); - } - addStringSetting(((URLTexture) TerminalTheme.WALL_PAPER.getTexture()).url, s -> { - TerminalTheme.WALL_PAPER.setTexture(new URLTexture(s)); - TerminalTheme.saveConfig(); - }); - break; - case "terminal.settings.theme.wallpaper.color": - ColorRectTexture texture; - if (!(TerminalTheme.WALL_PAPER.getTexture() instanceof ColorRectTexture)) { - texture = new ColorRectTexture(-1); - TerminalTheme.WALL_PAPER.setTexture(texture); - TerminalTheme.saveConfig(); - } else { - texture = (ColorRectTexture) TerminalTheme.WALL_PAPER.getTexture(); - } - textureGroup.addWidget(new ColorWidget(0, 0, 80, 10) - .setColorSupplier(texture::getColor, true) - .setOnColorChanged(texture::setColor)); - break; - case "terminal.settings.theme.wallpaper.file": - if (!(TerminalTheme.WALL_PAPER.getTexture() instanceof FileTexture)) { - TerminalTheme.WALL_PAPER.setTexture(new FileTexture(null)); - TerminalTheme.saveConfig(); - } - textureGroup.addWidget(new RectButtonWidget(0, 0, 116, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(cd -> TerminalDialogWidget.showFileDialog(os, "terminal.settings.theme.image", - TerminalRegistry.TERMINAL_PATH, true, file -> { - if (file != null && file.isFile()) { - TerminalTheme.WALL_PAPER.setTexture(new FileTexture(file)); - TerminalTheme.saveConfig(); - } - }).setClientSide().open()) - .setIcon(new TextTexture("terminal.settings.theme.select", -1))); - break; - } - } - - private void addStringSetting(String init, Consumer callback) { - TextFieldWidget textFieldWidget = new TextFieldWidget(0, 0, 76, 20, TerminalTheme.COLOR_B_2, null, null) - .setMaxStringLength(Integer.MAX_VALUE) - .setValidator(s -> true) - .setCurrentString(init == null ? "" : init); - textureGroup.addWidget(textFieldWidget); - textureGroup.addWidget(new RectButtonWidget(76, 0, 40, 20) - .setColors(TerminalTheme.COLOR_B_1.getColor(), - TerminalTheme.COLOR_1.getColor(), - TerminalTheme.COLOR_B_1.getColor()) - .setClickListener(cd -> callback.accept(textFieldWidget.getCurrentString())) - .setIcon(new TextTexture("terminal.guide_editor.update", -1))); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/teleport/TeleportApp.java b/src/main/java/gregtech/common/terminal/app/teleport/TeleportApp.java deleted file mode 100644 index 288f5f39bd2..00000000000 --- a/src/main/java/gregtech/common/terminal/app/teleport/TeleportApp.java +++ /dev/null @@ -1,118 +0,0 @@ -package gregtech.common.terminal.app.teleport; - -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.widgets.*; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.os.SystemCall; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.util.TeleportHandler; -import gregtech.common.entities.PortalEntity; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.chunk.Chunk; - -public class TeleportApp extends AbstractApplication { - - private int coordinateX = 0; - private int coordinateY = 1; - private int coordinateZ = 0; - - private int dimension = 0; - - public TeleportApp() { - super("teleport"); - } - - @Override - public AbstractApplication initApp() { - if (nbt != null && nbt.hasKey("LastTeleport")) { - BlockPos pos = BlockPos.fromLong(nbt.getLong("LastTeleport")); - this.coordinateX = pos.getX(); - this.coordinateY = pos.getY(); - this.coordinateZ = pos.getZ(); - this.dimension = nbt.getShort("LastDim"); - } - - // background - this.addWidget(new ImageWidget(5, 5, 323, 212, new ColorRectTexture(TerminalTheme.COLOR_B_2.getColor()))); - int textFieldColor = TerminalTheme.COLOR_B_2.getColor(); - textFieldColor &= 0xFFFFFF; // remove alpha - textFieldColor |= (200 << 24); // alpha 175 - // text field backgrounds - this.addWidget(new ImageWidget(9, 104, 77, 10, new ColorRectTexture(textFieldColor))); - this.addWidget(new ImageWidget(9, 64, 77, 10, new ColorRectTexture(textFieldColor))); - this.addWidget(new ImageWidget(9, 44, 77, 10, new ColorRectTexture(textFieldColor))); - this.addWidget(new ImageWidget(9, 24, 77, 10, new ColorRectTexture(textFieldColor))); - // text field labels - this.addWidget(new LabelWidget(10, 15, "X: ", 0xFFFFFF)); - this.addWidget(new LabelWidget(10, 35, "Y: ", 0xFFFFFF)); - this.addWidget(new LabelWidget(10, 55, "Z: ", 0xFFFFFF)); - this.addWidget( - new SimpleTextWidget(10, 95, "terminal.teleporter.dimension", 0xFFFFFF, () -> "").setCenter(false)); - - this.addWidget(new TextFieldWidget2(10, 105, 75, 16, () -> String.valueOf(dimension), value -> { - if (!value.isEmpty()) { - dimension = Integer.parseInt(value); - } - }).setMaxLength(9).setNumbersOnly(Short.MIN_VALUE, Short.MAX_VALUE)); - this.addWidget(new TextFieldWidget2(10, 65, 75, 16, () -> String.valueOf(coordinateZ), value -> { - if (!value.isEmpty()) { - coordinateZ = Integer.parseInt(value); - } - }).setMaxLength(9).setNumbersOnly(-30000000, 30000000)); - this.addWidget(new TextFieldWidget2(10, 45, 75, 16, () -> String.valueOf(coordinateY), value -> { - if (!value.isEmpty()) { - coordinateY = Integer.parseInt(value); - } - }).setMaxLength(9).setNumbersOnly(1, 255)); - this.addWidget(new TextFieldWidget2(10, 25, 75, 16, () -> String.valueOf(coordinateX), value -> { - if (!value.isEmpty()) { - coordinateX = Integer.parseInt(value); - } - }).setMaxLength(9).setNumbersOnly(-30000000, 30000000)); - - this.addWidget(new ClickButtonWidget(15, 140, 65, 20, "terminal.teleporter.spawn_portal", - data -> this.spawnPortals())); - - return this; - } - - @Override - public NBTTagCompound closeApp() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setLong("LastTeleport", new BlockPos(coordinateX, coordinateY, coordinateZ).toLong()); - nbt.setShort("LastDim", (short) dimension); - return nbt; - } - - /** - * Creates two portals, one 5 blocks in front of the player targeting the other portal, the other at the destination - * targeting the first portal - */ - public void spawnPortals() { - Vec3d position = new Vec3d( - gui.entityPlayer.getPosition().getX() + gui.entityPlayer.getLookVec().x * 5, - gui.entityPlayer.getPosition().getY(), - gui.entityPlayer.getPosition().getZ() + gui.entityPlayer.getLookVec().z * 5); - - PortalEntity portal1 = new PortalEntity(gui.entityPlayer.getEntityWorld(), position.x, position.y, position.z); - portal1.setRotation(gui.entityPlayer.rotationYaw, 0.F); - - PortalEntity portal2 = new PortalEntity(gui.entityPlayer.getEntityWorld(), coordinateX, coordinateY, - coordinateZ); - portal2.setRotation(gui.entityPlayer.rotationYaw, 0.F); - - portal1.setTargetCoordinates(dimension, coordinateX, coordinateY, coordinateZ); - portal2.setTargetCoordinates(gui.entityPlayer.dimension, position.x, position.y, position.z); - - gui.entityPlayer.getEntityWorld().spawnEntity(portal1); - Chunk destination = TeleportHandler.getWorldByDimensionID(dimension).getChunkProvider() - .provideChunk(coordinateX >> 4, coordinateZ >> 4); - TeleportHandler.getWorldByDimensionID(dimension).spawnEntity(portal2); - TeleportHandler.getWorldByDimensionID(dimension).getChunkProvider().queueUnload(destination); - - SystemCall.SHUT_DOWN.call(getOs(), isClient); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/worldprospector/WorldProspectorARApp.java b/src/main/java/gregtech/common/terminal/app/worldprospector/WorldProspectorARApp.java deleted file mode 100644 index 8ead4466af8..00000000000 --- a/src/main/java/gregtech/common/terminal/app/worldprospector/WorldProspectorARApp.java +++ /dev/null @@ -1,521 +0,0 @@ -package gregtech.common.terminal.app.worldprospector; - -import gregtech.api.gui.IRenderContext; -import gregtech.api.gui.resources.ColorRectTexture; -import gregtech.api.gui.resources.ItemStackTexture; -import gregtech.api.gui.resources.ShaderTexture; -import gregtech.api.gui.widgets.ImageWidget; -import gregtech.api.gui.widgets.LabelWidget; -import gregtech.api.gui.widgets.PhantomSlotUtil; -import gregtech.api.gui.widgets.PhantomSlotWidget; -import gregtech.api.terminal.app.ARApplication; -import gregtech.api.terminal.app.AbstractApplication; -import gregtech.api.terminal.gui.widgets.CircleButtonWidget; -import gregtech.api.terminal.gui.widgets.RectButtonWidget; -import gregtech.api.terminal.os.TerminalDialogWidget; -import gregtech.api.terminal.os.TerminalTheme; -import gregtech.api.unification.OreDictUnifier; -import gregtech.api.unification.stack.MaterialStack; -import gregtech.api.util.GTLog; -import gregtech.api.util.Mods; -import gregtech.client.shader.Shaders; -import gregtech.client.utils.DepthTextureUtil; -import gregtech.client.utils.RenderBufferHelper; -import gregtech.client.utils.TooltipHelper; -import gregtech.common.inventory.handlers.SingleItemStackHandler; -import gregtech.common.items.MetaItems; -import gregtech.common.terminal.app.worldprospector.matcher.BlockStateMatcher; -import gregtech.common.terminal.app.worldprospector.matcher.IMatcher; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockFalling; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.BufferBuilder; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.vertex.DefaultVertexFormats; -import net.minecraft.client.shader.Framebuffer; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.inventory.ClickType; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.Tuple; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraftforge.client.event.RenderWorldLastEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import mezz.jei.api.gui.IGhostIngredientHandler; -import org.jetbrains.annotations.NotNull; -import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.GL11; - -import java.awt.*; -import java.io.IOException; -import java.util.*; -import java.util.List; - -public class WorldProspectorARApp extends ARApplication { - - private SingleItemStackHandler[] handlers; - private int[] colors; - - public WorldProspectorARApp() { - super("world_prospector"); - } - - @Override - public AbstractApplication initApp() { - addWidget(new ImageWidget(10, 10, 313, 212, new ColorRectTexture(TerminalTheme.COLOR_B_2.getColor()))); - addWidget(new LabelWidget(15 + 150 / 2, 232 / 2, "terminal.world_prospector.radius", -1, - new Object[] { getMaxRadius() }) - .setShadow(true) - .setYCentered(true) - .setXCentered(true)); - int slotSize = (int) Math.pow(2, getAppTier()); - int x = 250 - slotSize * 12; - int y = 232 / 2 - 18; - handlers = new SingleItemStackHandler[slotSize]; - colors = new int[slotSize]; - for (int i = 0; i < slotSize; i++) { - int index = i; - Tuple stack = getSlotStack(i); - if (stack == null) { - handlers[i] = new SingleItemStackHandler(ItemStack.EMPTY); - colors[i] = 0; - } else { - handlers[i] = new SingleItemStackHandler(stack.getFirst()); - colors[i] = stack.getSecond(); - } - RectButtonWidget buttonWidget = new RectButtonWidget(x + i * 24, y + 18, 18, 18, 1); - addWidget(new PhantomSlotWidget(handlers[i], 0, x + i * 24, y) { - - @Override - public List> getPhantomTargets(Object ingredient) { - if (!(ingredient instanceof ItemStack)) { - return Collections.emptyList(); - } - Rectangle rectangle = toRectangleBox(); - return Collections.singletonList(new IGhostIngredientHandler.Target() { - - @NotNull - @Override - public Rectangle getArea() { - return rectangle; - } - - @Override - public void accept(@NotNull Object ingredient) { - if (ingredient instanceof ItemStack) { - int mouseButton = Mouse.getEventButton(); - boolean shiftDown = TooltipHelper.isShiftDown(); - ClickType clickType = shiftDown ? ClickType.QUICK_MOVE : ClickType.PICKUP; - PhantomSlotUtil.slotClickPhantom(slotReference, mouseButton, clickType, - (ItemStack) ingredient); - updateBlockSelectionAndColor((ItemStack) ingredient, index, buttonWidget); - writeClientAction(1, buffer -> { - buffer.writeItemStack((ItemStack) ingredient); - buffer.writeVarInt(mouseButton); - buffer.writeBoolean(shiftDown); - }); - } - } - }); - } - - @Override - public boolean mouseClicked(int mouseX, int mouseY, int button) { - if (handlers[index].getStackInSlot(0).isEmpty() && isMouseOverElement(mouseX, mouseY)) { - writeClientAction(-1, buffer -> {}); - selectReference(index, buttonWidget); - return true; - } else if (isMouseOverElement(mouseX, mouseY)) { - writeClientAction(0, buffer -> {}); - updateBlockSelectionAndColor(ItemStack.EMPTY, index, buttonWidget); - } - return super.mouseClicked(mouseX, mouseY, button); - } - - @Override - public void handleClientAction(int id, PacketBuffer buffer) { - if (id == -1) { - selectReference(index, buttonWidget); - } else if (id == 0) { - updateBlockSelectionAndColor(ItemStack.EMPTY, index, buttonWidget); - } else if (id == 1) { - try { - buffer.markReaderIndex(); // just want to reset reader index, not both with .clear - ItemStack stack = buffer.readItemStack(); - updateBlockSelectionAndColor(stack, index, buttonWidget); - buffer.resetReaderIndex(); - } catch (IOException e) { - GTLog.logger.error("Could not update block selection from world prospector buffer", e); - } - super.handleClientAction(id, buffer); - } else { - super.handleClientAction(id, buffer); - } - } - }.setBackgroundTexture(new ColorRectTexture(0x4fffffff))); - addWidget(buttonWidget - .setHoverText("terminal.world_prospector.color") - .setColors(0x4fffffff, -1, colors[i]) - .setClickListener(cd -> TerminalDialogWidget - .showColorDialog(getOs(), "terminal.world_prospector.color", res -> { - if (res != null) { - buttonWidget.setFill(res | 0xff000000); - colors[index] = res | 0xff000000; - } - }, colors[index]).open())); - } - addWidget(new CircleButtonWidget(333 / 2, 200) - .setClickListener(cd -> openAR()) - .setHoverText("terminal.ar.open") - .setColors(0, -1, TerminalTheme.COLOR_B_3.getColor()) - .setIcon(new ItemStackTexture(MetaItems.CAMERA.getStackForm()))); - return this; - } - - private void updateBlockSelectionAndColor(ItemStack stack, int index, RectButtonWidget buttonWidget) { - if (stack.getItem() instanceof ItemBlock) { - ItemStack copy = stack.copy(); - copy.setCount(1); - handlers[index].setStackInSlot(0, copy); - - MaterialStack ms = OreDictUnifier.getMaterial(copy); - Block block = ((ItemBlock) copy.getItem()).getBlock(); - if (block instanceof BlockFalling) { - colors[index] = ((BlockFalling) block).getDustColor(block.getStateFromMeta(copy.getMetadata())); - } else if (ms != null) { - colors[index] = ms.material.getMaterialRGB(); - } else { - colors[index] = block.getStateFromMeta(copy.getMetadata()).getMaterial() - .getMaterialMapColor().colorValue; - } - if (colors[index] == 0) { - colors[index] = block.hashCode(); - } - colors[index] = colors[index] | 0xff000000; - buttonWidget.setFill(colors[index]); - } else if (stack.isEmpty()) { - handlers[index].setStackInSlot(0, stack); - colors[index] = 0x00000000; - buttonWidget.setFill(colors[index]); - } - } - - @Override - public NBTTagCompound closeApp() { - NBTTagCompound slots = new NBTTagCompound(); - nbt.removeTag("slots"); - for (int i = 0; i < handlers.length; i++) { - if (!handlers[i].getStackInSlot(0).isEmpty()) { - NBTTagCompound itemTag = new NBTTagCompound(); - itemTag.setTag("item", handlers[i].getStackInSlot(0).serializeNBT()); - itemTag.setInteger("color", colors[i]); - slots.setTag("s" + i, itemTag); - } - } - nbt.setTag("slots", slots); - return nbt; - } - - @Override - public int getMaxTier() { - return 2; - } - - @Override - protected void hookDrawInBackground(int mouseX, int mouseY, float partialTicks, IRenderContext context) { - super.hookDrawInBackground(mouseX, mouseY, partialTicks, context); - float time = (gui.entityPlayer.ticksExisted + partialTicks) / 20f; - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); - if (Shaders.allowedShader()) { - ShaderTexture.createShader("lightring.frag").draw(getPosition().x + 15, getPosition().y + (232 - 150) / 2f, - 150, 150, uniformCache -> uniformCache.glUniform1F("u_time", time)); - } - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - } - - private void selectReference(int index, RectButtonWidget buttonWidget) { - TerminalDialogWidget.showItemSelector(getOs(), "terminal.world_prospector.reference", false, - stack -> stack.getItem() instanceof ItemBlock, - stack -> updateBlockSelectionAndColor(stack, index, buttonWidget)).open(); - } - - private int getMaxRadius() { - return (int) (15 * Math.pow(2, getAppTier())); - } - - private Tuple getSlotStack(int i) { - if (nbt != null) { - NBTTagCompound slots = nbt.getCompoundTag("slots"); - if (slots.hasKey("s" + i)) { - NBTTagCompound itemTag = slots.getCompoundTag("s" + i); - return new Tuple<>(new ItemStack(itemTag.getCompoundTag("item")), itemTag.getInteger("color")); - } - } - return null; - } - - private List> getAllSlotStack() { - List> stacks = new ArrayList<>(); - if (nbt != null) { - NBTTagCompound slots = nbt.getCompoundTag("slots"); - for (String key : slots.getKeySet()) { - NBTTagCompound itemTag = slots.getCompoundTag(key); - stacks.add(new Tuple<>(new ItemStack(itemTag.getCompoundTag("item")), itemTag.getInteger("color"))); - } - } - return stacks; - } - - ////////////////////////////////////// AR///////////////////////////////////////// - - @SideOnly(Side.CLIENT) - private static Set matchers; - @SideOnly(Side.CLIENT) - private static Map>> founds; - @SideOnly(Side.CLIENT) - private static BlockPos lastPos; - @SideOnly(Side.CLIENT) - private static int radius; - @SideOnly(Side.CLIENT) - private static int maxRadius; - - @SideOnly(Side.CLIENT) - @Override - public void onAROpened() { - founds = new HashMap<>(); - radius = 0; - maxRadius = getMaxRadius(); - lastPos = null; - matchers = new HashSet<>(); - for (Tuple stack : getAllSlotStack()) { - if (stack.getFirst().getItem() instanceof ItemBlock) { - Block block = ((ItemBlock) stack.getFirst().getItem()).getBlock(); - - if (block != Blocks.AIR) { - matchers.add(new BlockStateMatcher(block.getStateFromMeta(stack.getFirst().getMetadata()), - stack.getSecond())); - } - } - } - matchers.forEach(matcher -> founds.put(matcher, new HashMap<>())); - } - - @SideOnly(Side.CLIENT) - private static List bresenhamCircle(int xc, int zc, int r) { - List blockPos = new ArrayList<>(); - int x, z, d; - x = 0; - z = r; - d = 3 - 2 * r; - circlePlot(blockPos, xc, zc, x, z); - while (x < z) { - if (d < 0) { - d = d + 4 * x + 6; - } else { - d = d + 4 * (x - z) + 10; - z--; - } - x++; - circlePlot(blockPos, xc, zc, x, z); - } - return blockPos; - } - - @SideOnly(Side.CLIENT) - private static void circlePlot(List blockPos, int xc, int zc, int x, int z) { - blockPos.add(new BlockPos(xc + x, 0, zc + z)); - blockPos.add(new BlockPos(xc - x, 0, zc + z)); - blockPos.add(new BlockPos(xc + x, 0, zc - z)); - blockPos.add(new BlockPos(xc - x, 0, zc - z)); - blockPos.add(new BlockPos(xc + z, 0, zc + x)); - blockPos.add(new BlockPos(xc - z, 0, zc + x)); - blockPos.add(new BlockPos(xc + z, 0, zc - x)); - blockPos.add(new BlockPos(xc - z, 0, zc - x)); - } - - @SideOnly(Side.CLIENT) - private static void addCluster(BlockPos pos, Map> found) { - final BlockPos min = pos.add(-1, -1, -1); - final BlockPos max = pos.add(1, 1, 1); - - AxisAlignedBB root = null; - for (int y = min.getY(); y <= max.getY(); y++) { - for (int x = min.getX(); x <= max.getX(); x++) { - for (int z = min.getZ(); z <= max.getZ(); z++) { - Vec3d clusterPos = new Vec3d(x + 0.5, y + 0.5, z + 0.5); - AxisAlignedBB find = null; - for (AxisAlignedBB bb : found.keySet()) { - if (bb != root && bb.contains(clusterPos)) { - find = bb; - break; - } - } - if (find != null) { - AxisAlignedBB union; - Set blocks; - if (root == null) { - union = new AxisAlignedBB(pos).union(find); - blocks = found.get(find); - found.remove(find); - } else { - union = root.union(find); - blocks = new HashSet<>(); - blocks.addAll(found.get(find)); - blocks.addAll(found.get(root)); - found.remove(find); - found.remove(root); - } - found.put(union, blocks); - root = union; - found.get(root).add(pos); - } - } - } - } - if (root == null) { - Set blocks = new HashSet<>(); - blocks.add(pos); - found.put(new AxisAlignedBB(pos), blocks); - } - } - - @SideOnly(Side.CLIENT) - @Override - public void tickAR(EntityPlayer player) { - World world = player.world; - if (Minecraft.getMinecraft().isGamePaused()) return; - - if (radius == 0 || lastPos == null) { - lastPos = player.getPosition(); - } - - int maxY = Math.min(256, maxRadius + player.getPosition().getY()); - int minY = Math.max(0, -maxRadius + player.getPosition().getY()); - for (BlockPos pos : bresenhamCircle(lastPos.getX(), lastPos.getZ(), radius)) { - for (int y = minY; y <= maxY; y++) { - for (IMatcher matcher : matchers) { - BlockPos blockPos = new BlockPos(pos.getX(), y, pos.getZ()); - if (matcher.match(world.getBlockState(blockPos))) { - addCluster(blockPos, founds.get(matcher)); - } - } - - } - } - - if (radius == maxRadius) { - radius = 0; - for (IMatcher matcher : matchers) { - Iterator>> it = founds.get(matcher).entrySet().iterator(); - while (it.hasNext()) { - Map.Entry> entry = it.next(); - entry.getValue().removeIf(pos -> !matcher.match(world.getBlockState(pos))); - if (entry.getValue().isEmpty()) { - it.remove(); - } - } - } - } else { - radius++; - } - } - - @SideOnly(Side.CLIENT) - @Override - public void drawARScreen(RenderWorldLastEvent event) { - renderScan(event.getPartialTicks()); - renderAxisAlignedBB(event.getPartialTicks()); - } - - @SideOnly(Side.CLIENT) - private static void renderAxisAlignedBB(float partialTicks) { - Minecraft mc = Minecraft.getMinecraft(); - Entity entity = mc.getRenderViewEntity(); - if (entity == null) return; - final double posX = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * partialTicks; - final double posY = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks; - final double posZ = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * partialTicks; - - GlStateManager.disableLighting(); - GlStateManager.disableDepth(); - GlStateManager.enableBlend(); - GlStateManager.disableTexture2D(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); - - GlStateManager.pushMatrix(); - GlStateManager.translate(-posX, -posY, -posZ); - - final Tessellator tessellator = Tessellator.getInstance(); - final BufferBuilder buffer = tessellator.getBuffer(); - - buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); - - for (IMatcher matcher : matchers) { - int color = matcher.getColor(); - final float r = ((color >> 16) & 0xFF) / 255f; - final float g = ((color >> 8) & 0xFF) / 255f; - final float b = (color & 0xFF) / 255f; - final float a = 1; - for (AxisAlignedBB bound : founds.get(matcher).keySet()) { - RenderBufferHelper.renderCubeFace(buffer, bound.minX, bound.minY, bound.minZ, bound.maxX, bound.maxY, - bound.maxZ, r, g, b, a); - } - } - - tessellator.draw(); - - GlStateManager.popMatrix(); - - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - GlStateManager.enableDepth(); - GlStateManager.enableLighting(); - } - - @SideOnly(Side.CLIENT) - private static void renderScan(float getPartialTicks) { - Minecraft mc = Minecraft.getMinecraft(); - World world = mc.world; - Entity viewer = mc.getRenderViewEntity(); - if (world != null && viewer != null && !Mods.Optifine.isModLoaded()) { - - Framebuffer fbo = mc.getFramebuffer(); - - GlStateManager.depthMask(false); - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); - - DepthTextureUtil.bindDepthTexture(); - - float time = (viewer.ticksExisted + getPartialTicks) / 20; - - Shaders.renderFullImageInFBO(fbo, Shaders.SCANNING, uniformCache -> { - uniformCache.glUniform1F("u_time", time); - uniformCache.glUniform1F("radius", radius + getPartialTicks); - uniformCache.glUniform1F("u_zFar", mc.gameSettings.renderDistanceChunks * 16 * MathHelper.SQRT_2); - uniformCache.glUniform1F("u_FOV", mc.gameSettings.fovSetting); - }); - - DepthTextureUtil.unBindDepthTexture(); - - GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GlStateManager.disableBlend(); - GlStateManager.depthMask(true); - - } - } -} diff --git a/src/main/java/gregtech/common/terminal/app/worldprospector/matcher/BlockStateMatcher.java b/src/main/java/gregtech/common/terminal/app/worldprospector/matcher/BlockStateMatcher.java deleted file mode 100644 index 1848972b122..00000000000 --- a/src/main/java/gregtech/common/terminal/app/worldprospector/matcher/BlockStateMatcher.java +++ /dev/null @@ -1,71 +0,0 @@ -package gregtech.common.terminal.app.worldprospector.matcher; - -import net.minecraft.block.properties.IProperty; -import net.minecraft.block.state.IBlockState; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public class BlockStateMatcher implements IMatcher { - - private final IBlockState reference; - private final List> properties = new ArrayList<>(); - private final int meta; - private final int color; - - public BlockStateMatcher(IBlockState state, int color) { - this.reference = state; - for (final IProperty property : state.getPropertyKeys()) { - if (Objects.equals(property.getName(), "variant") || // Vanilla Minecraft. - Objects.equals(property.getName(), "type") || // E.g. ThermalFoundation, TiCon, IC2, Immersive - // Engineering. - Objects.equals(property.getName(), "ore") || // E.g. BigReactors. - Objects.equals(property.getName(), "oretype") || // E.g. DeepResonance. - Objects.equals(property.getName(), "stone_type") || // E.g. gtce. - Objects.equals(property.getName(), "basictype")) { // Galacticraft. - properties.add(property); - } - } - this.meta = reference.getBlock().getMetaFromState(reference); - this.color = color; - } - - public boolean match(final IBlockState state) { - if (reference.getBlock() != state.getBlock()) { - return false; - } - - if (state.getBlock().getMetaFromState(state) != meta) { - return false; - } - - if (properties.isEmpty()) { - return true; - } - - for (final IProperty property : properties) { - if (!state.getPropertyKeys().contains(property)) { - continue; - } - if (!Objects.equals(state.getValue(property), reference.getValue(property))) { - return false; - } - } - - return true; - } - - @Override - public int getColor() { - return color; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof BlockStateMatcher) { - return match(((BlockStateMatcher) obj).reference); - } - return super.equals(obj); - } -} diff --git a/src/main/java/gregtech/common/terminal/app/worldprospector/matcher/IMatcher.java b/src/main/java/gregtech/common/terminal/app/worldprospector/matcher/IMatcher.java deleted file mode 100644 index c96a6c22c36..00000000000 --- a/src/main/java/gregtech/common/terminal/app/worldprospector/matcher/IMatcher.java +++ /dev/null @@ -1,17 +0,0 @@ -package gregtech.common.terminal.app.worldprospector.matcher; - -import net.minecraft.block.state.IBlockState; - -/** - * Created with IntelliJ IDEA. - * - * @Author: KilaBash - * @Date: 2021/09/16 - * @Description: - */ -public interface IMatcher { - - boolean match(final IBlockState state); - - int getColor(); -} diff --git a/src/main/java/gregtech/common/terminal/component/ClickComponent.java b/src/main/java/gregtech/common/terminal/component/ClickComponent.java deleted file mode 100644 index 24031ee4c73..00000000000 --- a/src/main/java/gregtech/common/terminal/component/ClickComponent.java +++ /dev/null @@ -1,46 +0,0 @@ -package gregtech.common.terminal.component; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.terminal.os.menu.IMenuComponent; - -import java.util.function.Consumer; - -public class ClickComponent implements IMenuComponent { - - private IGuiTexture icon; - private String hoverText; - private Consumer consumer; - - public ClickComponent setIcon(IGuiTexture icon) { - this.icon = icon; - return this; - } - - public ClickComponent setHoverText(String hoverText) { - this.hoverText = hoverText; - return this; - } - - public ClickComponent setClickConsumer(Consumer consumer) { - this.consumer = consumer; - return this; - } - - @Override - public IGuiTexture buttonIcon() { - return icon; - } - - @Override - public String hoverText() { - return hoverText; - } - - @Override - public void click(Widget.ClickData clickData) { - if (consumer != null) { - consumer.accept(clickData); - } - } -} diff --git a/src/main/java/gregtech/common/terminal/component/setting/GuiTextureSetter.java b/src/main/java/gregtech/common/terminal/component/setting/GuiTextureSetter.java deleted file mode 100644 index add78dfa301..00000000000 --- a/src/main/java/gregtech/common/terminal/component/setting/GuiTextureSetter.java +++ /dev/null @@ -1,33 +0,0 @@ -package gregtech.common.terminal.component.setting; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.widgets.WidgetGroup; - -import java.util.function.Consumer; - -public class GuiTextureSetter extends WidgetGroup implements ISetting { - - private final String name; - private Consumer updated; - - public GuiTextureSetter(String name, Consumer updated) { - this.name = name; - this.updated = updated; - } - - @Override - public String getName() { - return name; - } - - @Override - public IGuiTexture getIcon() { - return null; - } - - @Override - public Widget getWidget() { - return null; - } -} diff --git a/src/main/java/gregtech/common/terminal/component/setting/ISetting.java b/src/main/java/gregtech/common/terminal/component/setting/ISetting.java deleted file mode 100644 index 2b3f2fa05d2..00000000000 --- a/src/main/java/gregtech/common/terminal/component/setting/ISetting.java +++ /dev/null @@ -1,13 +0,0 @@ -package gregtech.common.terminal.component.setting; - -import gregtech.api.gui.Widget; -import gregtech.api.gui.resources.IGuiTexture; - -public interface ISetting { - - String getName(); - - IGuiTexture getIcon(); - - Widget getWidget(); -} diff --git a/src/main/java/gregtech/common/terminal/component/setting/IWidgetSettings.java b/src/main/java/gregtech/common/terminal/component/setting/IWidgetSettings.java deleted file mode 100644 index e3affc80eb1..00000000000 --- a/src/main/java/gregtech/common/terminal/component/setting/IWidgetSettings.java +++ /dev/null @@ -1,8 +0,0 @@ -package gregtech.common.terminal.component.setting; - -import gregtech.api.terminal.util.TreeNode; - -public interface IWidgetSettings { - - TreeNode getSettings(); -} diff --git a/src/main/java/gregtech/common/terminal/component/setting/SettingComponent.java b/src/main/java/gregtech/common/terminal/component/setting/SettingComponent.java deleted file mode 100644 index 1f011df5a03..00000000000 --- a/src/main/java/gregtech/common/terminal/component/setting/SettingComponent.java +++ /dev/null @@ -1,29 +0,0 @@ -package gregtech.common.terminal.component.setting; - -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.Widget; -import gregtech.api.gui.widgets.WidgetGroup; -import gregtech.api.terminal.gui.widgets.TreeListWidget; -import gregtech.api.terminal.os.menu.IMenuComponent; - -public class SettingComponent extends WidgetGroup implements IMenuComponent { - - private Widget settingWidget; - - public SettingComponent(IWidgetSettings settings) { - this.addWidget(new TreeListWidget<>(0, 0, 130, 232, settings.getSettings(), (selected) -> { - if (selected.getContent() != null) { - if (settingWidget != null) { - removeWidget(settingWidget); - } - settingWidget = selected.getContent().getWidget(); - if (settingWidget != null) { - addWidget(settingWidget); - } - } - }).setContentIconSupplier(ISetting::getIcon) - .setContentNameSupplier(ISetting::getName) - .setNodeTexture(GuiTextures.BORDERED_BACKGROUND) - .setLeafTexture(GuiTextures.SLOT_DARKENED)); - } -} diff --git a/src/main/java/gregtech/common/terminal/hardware/BatteryHardware.java b/src/main/java/gregtech/common/terminal/hardware/BatteryHardware.java deleted file mode 100644 index b9343e2df94..00000000000 --- a/src/main/java/gregtech/common/terminal/hardware/BatteryHardware.java +++ /dev/null @@ -1,202 +0,0 @@ -package gregtech.common.terminal.hardware; - -import gregtech.api.GTValues; -import gregtech.api.capability.GregtechCapabilities; -import gregtech.api.capability.IElectricItem; -import gregtech.api.capability.impl.ElectricItem; -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.resources.ItemStackTexture; -import gregtech.api.terminal.hardware.Hardware; -import gregtech.api.terminal.hardware.IHardwareCapability; -import gregtech.common.items.MetaItems; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.common.capabilities.Capability; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.BiConsumer; - -/** - * Created with IntelliJ IDEA. - * - * @Author: KilaBash - * @Date: 2021/08/28 - * @Description: - */ -public class BatteryHardware extends Hardware implements IElectricItem, IHardwareCapability { - - protected final List> listeners = new ArrayList<>(); - - public BatteryHardware() {} - - @Override - public boolean isHardwareAdequate(Hardware demand) { - return demand instanceof BatteryHardware && ((BatteryHardware) demand).getTier() <= this.getTier() && - this.getCharge() > 0; - } - - @Override - public String addInformation() { - return GTValues.VN[getTier()]; - } - - @Override - public Hardware createHardware(ItemStack itemStack) { - return new BatteryHardware(); - } - - @Override - public NBTTagCompound acceptItemStack(ItemStack itemStack) { - IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null); - if (electricItem == null || !electricItem.canProvideChargeExternally() || !electricItem.chargeable()) { - return null; - } - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setLong("maxCharge", electricItem.getMaxCharge()); - nbt.setLong("charge", electricItem.getCharge()); - nbt.setInteger("tier", electricItem.getTier()); - return nbt; - } - - @Override - public String getRegistryName() { - return "battery"; - } - - @Override - public IGuiTexture getIcon() { - if (!hasHW()) { - return super.getIcon(); - } - return new ItemStackTexture(isCreative() ? MetaItems.ULTIMATE_BATTERY.getInfiniteChargedStack() : getItem()); - } - - @Override - public void addChargeListener(BiConsumer chargeListener) { - listeners.add(chargeListener); - } - - public void setCharge(long change) { - getNBT().setLong("charge", change); - listeners.forEach(l -> l.accept(provider.getItemStack(), change)); - } - - @Override - public long getTransferLimit() { - return GTValues.V[getTier()]; - } - - @Override - public long getMaxCharge() { - return isCreative() ? Long.MAX_VALUE : getNBT().getLong("maxCharge"); - } - - public long getCharge() { - return isCreative() ? Long.MAX_VALUE : getNBT().getLong("charge"); - } - - @Override - public boolean canProvideChargeExternally() { - return false; - } - - @Override - public boolean chargeable() { - return true; - } - - @Override - public long charge(long amount, int chargerTier, boolean ignoreTransferLimit, boolean simulate) { - if (provider.getItemStack().getCount() != 1) { - return 0L; - } - if ((chargerTier >= getTier()) && amount > 0L) { - long canReceive = getMaxCharge() - getCharge(); - if (!ignoreTransferLimit) { - amount = Math.min(amount, getTransferLimit()); - } - long charged = Math.min(amount, canReceive); - if (!simulate) { - setCharge(getCharge() + charged); - } - return charged; - } - return 0; - } - - @Override - public long discharge(long amount, int chargerTier, boolean ignoreTransferLimit, boolean externally, - boolean simulate) { - if (provider.getItemStack().getCount() != 1) { - return 0L; - } - if ((!externally || amount == Long.MAX_VALUE) && (chargerTier >= getTier()) && amount > 0L) { - if (!ignoreTransferLimit) { - amount = Math.min(amount, getTransferLimit()); - } - long charge = getCharge(); - long discharged = Math.min(amount, charge); - if (!simulate) { - setCharge(charge - discharged); - } - return discharged; - } - return 0; - } - - @Override - public int getTier() { - return isCreative() ? GTValues.V.length - 1 : getNBT().getInteger("tier"); - } - - @Override - public boolean hasCapability(@NotNull Capability capability) { - return capability == GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM; - } - - @Nullable - @Override - public T getCapability(@NotNull Capability capability) { - return capability == GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM ? - GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM.cast(this) : null; - } - - @Override - public ItemStack onHardwareRemoved(ItemStack itemStack) { - IElectricItem item = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null); - if (item instanceof ElectricItem) { - ((ElectricItem) item).setCharge(getCharge()); - } - return itemStack; - } - - public static class BatteryDemand extends BatteryHardware { - - public final int tier; - public final long cost; - - public BatteryDemand(int tier, long cost) { - this.tier = tier; - this.cost = cost; - } - - @Override - public int getTier() { - return tier; - } - - @Override - public long getCharge() { - return this.getCost(); - } - - public long getCost() { - return cost; - } - } -} diff --git a/src/main/java/gregtech/common/terminal/hardware/DeviceHardware.java b/src/main/java/gregtech/common/terminal/hardware/DeviceHardware.java deleted file mode 100644 index ccfa77d077d..00000000000 --- a/src/main/java/gregtech/common/terminal/hardware/DeviceHardware.java +++ /dev/null @@ -1,142 +0,0 @@ -package gregtech.common.terminal.hardware; - -import gregtech.api.gui.resources.IGuiTexture; -import gregtech.api.gui.resources.ItemStackTexture; -import gregtech.api.items.metaitem.MetaItem; -import gregtech.api.terminal.hardware.Hardware; -import gregtech.common.items.MetaItems; - -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; - -public class DeviceHardware extends Hardware { - - private final int slot; - - public DeviceHardware(int slot) { - this.slot = slot; - } - - @Override - public String getRegistryName() { - return "device" + slot; - } - - @SideOnly(Side.CLIENT) - @Override - public String getLocalizedName() { - return I18n.format("terminal.hw.device") + " " + slot; - } - - @Override - protected Hardware createHardware(ItemStack itemStack) { - return new DeviceHardware(slot); - } - - @Override - public NBTTagCompound acceptItemStack(ItemStack itemStack) { - for (DEVICE device : DEVICE.values()) { - if (device.itemStack.isItemEqual(itemStack)) { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("d", device.ordinal()); - return nbt; - } - } - return null; - } - - @Override - public IGuiTexture getIcon() { - if (!hasHW()) { - return super.getIcon(); - } - if (isCreative()) { - return new ItemStackTexture(DEVICE.values()[slot % DEVICE.values().length].itemStack); - } - return new ItemStackTexture(getDevice().itemStack); - } - - @Override - public boolean isHardwareAdequate(Hardware demand) { - if (demand instanceof DeviceHardware && isCreative()) { - return DEVICE.values()[slot % DEVICE.values().length] == ((DeviceHardware) demand).getDevice(); - } - return demand instanceof DeviceHardware && ((DeviceHardware) demand).getDevice() == this.getDevice(); - } - - @Override - public String addInformation() { - if (isCreative()) { - return DEVICE.values()[slot % DEVICE.values().length].itemStack.getDisplayName(); - } - return getDevice().itemStack.getDisplayName(); - } - - public DEVICE getDevice() { - return DEVICE.values()[getNBT().getInteger("d") % DEVICE.values().length]; - } - - public enum DEVICE { - - PROSPECTOR_LV(MetaItems.PROSPECTOR_LV, "prospector"), - PROSPECTOR_HV(MetaItems.PROSPECTOR_HV, "advanced_prospector"), - WIRELESS(MetaItems.WIRELESS, "wireless"), - CAMERA(MetaItems.CAMERA, "camera"), - - // FIELD GEN - FIELD_GENERATOR_UV(MetaItems.FIELD_GENERATOR_UV, "field_generator"), - - // SOLAR - SOLAR_LV(MetaItems.COVER_SOLAR_PANEL_LV, "solar_lv"); - - ItemStack itemStack; - String name; - - DEVICE(ItemStack itemStack, String name) { - this.itemStack = itemStack; - this.name = name; - } - - DEVICE(MetaItem.MetaValueItem metaItem, String name) { - this.itemStack = metaItem.getStackForm(); - this.name = name; - } - - public static DEVICE fromString(String name) { - for (DEVICE device : values()) { - if (device.name.equals(name.toLowerCase())) { - return device; - } - } - return null; - } - } - - public static class DeviceDemand extends DeviceHardware { - - private final DEVICE device; - - public DeviceDemand(DEVICE device) { - super(0); - this.device = device; - } - - public DeviceDemand(String device) { - super(0); - this.device = DEVICE.fromString(device); - } - - @Override - public String getLocalizedName() { - return I18n.format("terminal.hw.device"); - } - - @Override - public DEVICE getDevice() { - return device; - } - } -} diff --git a/src/main/java/gregtech/core/CoreModule.java b/src/main/java/gregtech/core/CoreModule.java index 5e80c4b3b31..c964db8563f 100644 --- a/src/main/java/gregtech/core/CoreModule.java +++ b/src/main/java/gregtech/core/CoreModule.java @@ -20,7 +20,7 @@ import gregtech.api.mui.GTGuis; import gregtech.api.recipes.ModHandler; import gregtech.api.recipes.RecipeMap; -import gregtech.api.recipes.recipeproperties.TemperatureProperty; +import gregtech.api.recipes.properties.impl.TemperatureProperty; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; import gregtech.api.unification.material.event.MaterialEvent; @@ -29,9 +29,9 @@ import gregtech.api.unification.material.registry.MarkerMaterialRegistry; import gregtech.api.util.CapesRegistry; import gregtech.api.util.Mods; -import gregtech.api.util.VirtualTankRegistry; import gregtech.api.util.input.KeyBind; import gregtech.api.util.oreglob.OreGlob; +import gregtech.api.util.virtualregistry.VirtualEnderRegistry; import gregtech.api.worldgen.bedrockFluids.BedrockFluidVeinHandler; import gregtech.api.worldgen.bedrockFluids.BedrockFluidVeinSaveData; import gregtech.api.worldgen.config.WorldGenRegistry; @@ -66,6 +66,7 @@ import gregtech.core.network.packets.PacketPluginSynced; import gregtech.core.network.packets.PacketRecoverMTE; import gregtech.core.network.packets.PacketReloadShaders; +import gregtech.core.network.packets.PacketToolbeltSelectionChange; import gregtech.core.network.packets.PacketUIClientAction; import gregtech.core.network.packets.PacketUIOpen; import gregtech.core.network.packets.PacketUIWidgetUpdate; @@ -245,6 +246,8 @@ public void registerPackets() { GregTechAPI.networkHandler.registerPacket(PacketNotifyCapeChange.class); GregTechAPI.networkHandler.registerPacket(PacketReloadShaders.class); GregTechAPI.networkHandler.registerPacket(PacketClipboardNBTUpdate.class); + GregTechAPI.networkHandler.registerPacket(PacketToolbeltSelectionChange.Server.class); + GregTechAPI.networkHandler.registerPacket(PacketToolbeltSelectionChange.Client.class); } @Override @@ -347,7 +350,7 @@ public void serverStarted(FMLServerStartedEvent event) { @Override public void serverStopped(FMLServerStoppedEvent event) { - VirtualTankRegistry.clearMaps(); + VirtualEnderRegistry.clearMaps(); CapesRegistry.clearMaps(); } } diff --git a/src/main/java/gregtech/core/network/packets/PacketProspecting.java b/src/main/java/gregtech/core/network/packets/PacketProspecting.java index 47a1780f930..babd70b0db6 100644 --- a/src/main/java/gregtech/core/network/packets/PacketProspecting.java +++ b/src/main/java/gregtech/core/network/packets/PacketProspecting.java @@ -1,6 +1,6 @@ package gregtech.core.network.packets; -import gregtech.common.terminal.app.prospector.ProspectorMode; +import gregtech.common.gui.widget.prospector.ProspectorMode; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; diff --git a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java new file mode 100644 index 00000000000..d9c41f61bc5 --- /dev/null +++ b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java @@ -0,0 +1,102 @@ +package gregtech.core.network.packets; + +import gregtech.api.GregTechAPI; +import gregtech.api.items.toolitem.ItemGTToolbelt; +import gregtech.api.network.IClientExecutor; +import gregtech.api.network.IPacket; +import gregtech.api.network.IServerExecutor; +import gregtech.core.sound.GTSoundEvents; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.SoundCategory; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +public abstract class PacketToolbeltSelectionChange implements IPacket { + + protected int slot; + + public PacketToolbeltSelectionChange() {} + + public PacketToolbeltSelectionChange(int slot) { + this.slot = slot; + } + + @Override + public void encode(PacketBuffer buf) { + buf.writeByte(slot); + } + + @Override + public void decode(PacketBuffer buf) { + this.slot = buf.readByte(); + } + + public static void toClient(int slot, int matrixSlot, EntityPlayerMP player) { + if (player == null) return; + GregTechAPI.networkHandler.sendTo(new Client(slot, matrixSlot), player); + } + + public static void toServer(int slot) { + GregTechAPI.networkHandler.sendToServer(new Server(slot)); + } + + public static class Server extends PacketToolbeltSelectionChange implements IServerExecutor { + + public Server() {} + + public Server(int slot) { + super(slot); + } + + @Override + public void executeServer(NetHandlerPlayServer handler) { + EntityPlayerMP player = handler.player; + ItemStack stack = player.getHeldItemMainhand(); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + player.getServerWorld().playSound(null, player.posX, player.posY, player.posZ, GTSoundEvents.CLICK, + SoundCategory.PLAYERS, 2F, 1F); + toolbelt.setSelectedTool(slot, stack); + } + } + } + + public static class Client extends PacketToolbeltSelectionChange implements IClientExecutor { + + int index; + + public Client() {} + + public Client(int slot, int index) { + super(slot); + this.index = index; + } + + @Override + public void encode(PacketBuffer buf) { + super.encode(buf); + buf.writeVarInt(index); + } + + @Override + public void decode(PacketBuffer buf) { + super.decode(buf); + this.index = buf.readVarInt(); + } + + @Override + @SideOnly(Side.CLIENT) + public void executeClient(NetHandlerPlayClient handler) { + EntityPlayerSP player = Minecraft.getMinecraft().player; + ItemStack stack = player.openContainer.getSlot(index).getStack(); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) + toolbelt.setSelectedTool(slot, stack); + } + } +} diff --git a/src/main/java/gregtech/core/sound/GTSoundEvents.java b/src/main/java/gregtech/core/sound/GTSoundEvents.java index 53fd8067972..80f5caccd3b 100644 --- a/src/main/java/gregtech/core/sound/GTSoundEvents.java +++ b/src/main/java/gregtech/core/sound/GTSoundEvents.java @@ -57,6 +57,7 @@ public class GTSoundEvents { // Misc public static SoundEvent DEFAULT_ALARM; + public static SoundEvent CLICK; public static void register() { FORGE_HAMMER = soundManager.registerSound("tick.forge_hammer"); @@ -102,5 +103,6 @@ public static void register() { BREAKDOWN_MECHANICAL = soundManager.registerSound("maintenance.mechanical"); DEFAULT_ALARM = soundManager.registerSound("alarm"); + CLICK = soundManager.registerSound("click"); } } diff --git a/src/main/java/gregtech/integration/crafttweaker/CraftTweakerModule.java b/src/main/java/gregtech/integration/crafttweaker/CraftTweakerModule.java index 37fb6535fe5..f66293465e9 100644 --- a/src/main/java/gregtech/integration/crafttweaker/CraftTweakerModule.java +++ b/src/main/java/gregtech/integration/crafttweaker/CraftTweakerModule.java @@ -8,13 +8,11 @@ import gregtech.integration.IntegrationModule; import gregtech.integration.IntegrationSubmodule; import gregtech.integration.crafttweaker.recipe.MetaItemBracketHandler; -import gregtech.integration.crafttweaker.terminal.CTTerminalRegistry; import gregtech.modules.GregTechModules; import net.minecraft.item.crafting.IRecipe; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent; -import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; @@ -47,11 +45,6 @@ public void preInit(FMLPreInitializationEvent event) { CT_OREDICT_ITEM.setRegistryName("meta_oredict_item_ct"); } - @Override - public void postInit(FMLPostInitializationEvent event) { - CTTerminalRegistry.register(); - } - @Override public void loadComplete(FMLLoadCompleteEvent event) { MetaItemBracketHandler.clearComponentRegistry(); diff --git a/src/main/java/gregtech/integration/crafttweaker/recipe/CTRecipe.java b/src/main/java/gregtech/integration/crafttweaker/recipe/CTRecipe.java index 728c190a0d3..ac71e2f0fbb 100644 --- a/src/main/java/gregtech/integration/crafttweaker/recipe/CTRecipe.java +++ b/src/main/java/gregtech/integration/crafttweaker/recipe/CTRecipe.java @@ -15,7 +15,6 @@ import stanhebben.zenscript.annotations.ZenGetter; import stanhebben.zenscript.annotations.ZenMethod; -import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -90,16 +89,6 @@ public boolean isHidden() { return this.backingRecipe.isHidden(); } - @ZenGetter("propertyKeys") - public List getPropertyKeys() { - return new ArrayList<>(this.backingRecipe.getPropertyKeys()); - } - - @ZenMethod - public Object getProperty(String key) { - return this.backingRecipe.getPropertyRaw(key); - } - @ZenMethod public boolean remove() { return this.recipeMap.removeRecipe(this.backingRecipe); diff --git a/src/main/java/gregtech/integration/crafttweaker/recipe/CTRecipeBuilder.java b/src/main/java/gregtech/integration/crafttweaker/recipe/CTRecipeBuilder.java index be74a57456c..b419cc4960b 100644 --- a/src/main/java/gregtech/integration/crafttweaker/recipe/CTRecipeBuilder.java +++ b/src/main/java/gregtech/integration/crafttweaker/recipe/CTRecipeBuilder.java @@ -220,7 +220,7 @@ public CTRecipeBuilder fluidOutputs(ILiquidStack... ingredients) { @ZenMethod public CTRecipeBuilder property(String key, int value) { - boolean applied = this.backingBuilder.applyProperty(key, value); + boolean applied = this.backingBuilder.applyPropertyCT(key, value); if (!applied) { throw new IllegalArgumentException("Property " + key + " cannot be applied to recipe type " + @@ -231,7 +231,7 @@ public CTRecipeBuilder property(String key, int value) { @ZenMethod public CTRecipeBuilder property(String key, String value) { - boolean applied = this.backingBuilder.applyProperty(key, value); + boolean applied = this.backingBuilder.applyPropertyCT(key, value); if (!applied) { throw new IllegalArgumentException("Property " + key + " cannot be applied to recipe type " + @@ -242,7 +242,7 @@ public CTRecipeBuilder property(String key, String value) { @ZenMethod public CTRecipeBuilder property(String key, boolean value) { - boolean applied = this.backingBuilder.applyProperty(key, value); + boolean applied = this.backingBuilder.applyPropertyCT(key, value); if (!applied) { throw new IllegalArgumentException("Property " + key + " cannot be applied to recipe type " + @@ -253,7 +253,7 @@ public CTRecipeBuilder property(String key, boolean value) { @ZenMethod public CTRecipeBuilder property(String key, long value) { - boolean applied = this.backingBuilder.applyProperty(key, value); + boolean applied = this.backingBuilder.applyPropertyCT(key, value); if (!applied) { throw new IllegalArgumentException("Property " + key + " cannot be applied to recipe type " + @@ -264,7 +264,7 @@ public CTRecipeBuilder property(String key, long value) { @ZenMethod public CTRecipeBuilder property(String key, float value) { - boolean applied = this.backingBuilder.applyProperty(key, value); + boolean applied = this.backingBuilder.applyPropertyCT(key, value); if (!applied) { throw new IllegalArgumentException("Property " + key + " cannot be applied to recipe type " + @@ -275,7 +275,7 @@ public CTRecipeBuilder property(String key, float value) { @ZenMethod public CTRecipeBuilder property(String key, IItemStack item) { - boolean applied = this.backingBuilder.applyProperty(key, CraftTweakerMC.getItemStack(item)); + boolean applied = this.backingBuilder.applyPropertyCT(key, CraftTweakerMC.getItemStack(item)); if (!applied) { throw new IllegalArgumentException("Property " + key + " cannot be applied to recipe type " + diff --git a/src/main/java/gregtech/integration/crafttweaker/terminal/CTTerminalRegistry.java b/src/main/java/gregtech/integration/crafttweaker/terminal/CTTerminalRegistry.java deleted file mode 100644 index 6b3989d8447..00000000000 --- a/src/main/java/gregtech/integration/crafttweaker/terminal/CTTerminalRegistry.java +++ /dev/null @@ -1,184 +0,0 @@ -package gregtech.integration.crafttweaker.terminal; - -import gregtech.api.terminal.TerminalRegistry; -import gregtech.api.terminal.hardware.Hardware; -import gregtech.api.util.GTLog; -import gregtech.common.terminal.hardware.BatteryHardware; -import gregtech.common.terminal.hardware.DeviceHardware; - -import net.minecraft.item.ItemStack; -import net.minecraftforge.common.util.EnumHelper; - -import crafttweaker.annotations.ZenRegister; -import crafttweaker.api.item.IItemStack; -import crafttweaker.api.minecraft.CraftTweakerMC; -import stanhebben.zenscript.annotations.ZenClass; -import stanhebben.zenscript.annotations.ZenMethod; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -@ZenClass("mods.gregtech.TerminalRegistry") -@ZenRegister -@SuppressWarnings("unused") -public class CTTerminalRegistry { - - private static List ctAppRegistryBuilders = new LinkedList<>(); - - @ZenMethod - public static CTAppRegistryBuilder createAppRegistryBuilder(String appName) { - return new CTAppRegistryBuilder(appName); - } - - @ZenMethod - public static void registerDevice(IItemStack device, String name) { - ItemStack itemStack = CraftTweakerMC.getItemStack(device).copy(); - if (!itemStack.isEmpty()) { - itemStack.setCount(1); - EnumHelper.addEnum(DeviceHardware.DEVICE.class, name.toUpperCase(), - new Class[] { ItemStack.class, String.class }, itemStack, name.toLowerCase()); - } - } - - public static void registerAPP(CTAppRegistryBuilder builder) { - if (TerminalRegistry.APP_REGISTER.containsKey(builder.appName)) { - if (builder.isDefaultApp != null) { - TerminalRegistry.DEFAULT_APPS.remove(builder.appName); - if (builder.isDefaultApp) { - TerminalRegistry.DEFAULT_APPS.add(builder.appName); - } - } - if (!builder.hardware.isEmpty()) { - int maxTier = TerminalRegistry.APP_HW_DEMAND.get(builder.appName).length; - List[] hardware = new List[maxTier]; - for (int i = 0; i < maxTier; i++) { - List list = new LinkedList<>(); - if (builder.battery.containsKey(i)) { - list.add(builder.battery.get(i)); - } else if (builder.battery.containsKey(-1)) { - list.add(builder.battery.get(-1)); - } - if (builder.hardware.containsKey(i)) { - list.addAll(builder.hardware.get(i)); - } else if (builder.hardware.containsKey(-1)) { - list.addAll(builder.hardware.get(-1)); - } - if (list.size() > 0) { - hardware[i] = list; - } - } - TerminalRegistry.APP_HW_DEMAND.put(builder.appName, hardware); - } - if (!builder.upgrade.isEmpty()) { - int maxTier = TerminalRegistry.APP_UPGRADE_CONDITIONS.get(builder.appName).length; - List[] upgrade = new List[maxTier]; - if (builder.upgrade.containsKey(-1)) { // register for all tier - Arrays.fill(upgrade, builder.upgrade.get(-1)); - } - builder.upgrade.forEach((tier, listBuilder) -> { // register for specific tier - if (tier != -1 && tier < maxTier) { - upgrade[tier] = listBuilder; - } - }); - TerminalRegistry.APP_UPGRADE_CONDITIONS.put(builder.appName, upgrade); - } - } else { - GTLog.logger.error("Not found the app {}, while load the CT script", builder.appName); - } - } - - public static void register() { - ctAppRegistryBuilders.forEach(CTTerminalRegistry::registerAPP); - ctAppRegistryBuilders = null; - } - - @ZenClass("mods.gregtech.AppRegistryBuilder") - @ZenRegister - public static class CTAppRegistryBuilder { - - final String appName; - Boolean isDefaultApp; - Map battery; - Map> hardware; - Map> upgrade; - - public CTAppRegistryBuilder(String appName) { - this.appName = appName; - this.battery = new HashMap<>(); - this.hardware = new HashMap<>(); - this.upgrade = new HashMap<>(); - } - - @ZenMethod - public CTAppRegistryBuilder isDefaultApp(boolean isDefaultApp) { - this.isDefaultApp = isDefaultApp; - return this; - } - - @ZenMethod - public CTAppRegistryBuilder battery(int batteryTier, long cost) { - battery.put(-1, new BatteryHardware.BatteryDemand(batteryTier, cost)); - return this; - } - - @ZenMethod - public CTAppRegistryBuilder battery(int tier, int batteryTier, long cost) { - battery.put(tier, new BatteryHardware.BatteryDemand(batteryTier, cost)); - return this; - } - - @ZenMethod - public CTAppRegistryBuilder device(String... device) { - Hardware[] hw = Arrays.stream(device).map(DeviceHardware.DeviceDemand::new) - .filter(deviceDemand -> deviceDemand.getDevice() != null).toArray(Hardware[]::new); - hardware(hw); - return this; - } - - @ZenMethod - public CTAppRegistryBuilder device(int tier, String... device) { - this.hardware(tier, Arrays.stream(device).map(DeviceHardware.DeviceDemand::new) - .filter(deviceDemand -> deviceDemand.getDevice() != null).toArray(Hardware[]::new)); - return this; - } - - private void hardware(Hardware... hardware) { - hardware(-1, hardware); - } - - private void hardware(int tier, Hardware... hardware) { - this.hardware.put(tier, new LinkedList<>()); - for (Hardware hw : hardware) { - this.hardware.get(tier).add(hw); - } - } - - @ZenMethod - public CTAppRegistryBuilder upgrade(IItemStack... upgrades) { - upgrade(-1, upgrades); - return this; - } - - @ZenMethod - public CTAppRegistryBuilder upgrade(int tier, IItemStack... upgrades) { - this.upgrade.put(tier, new LinkedList<>()); - for (ItemStack up : Arrays.stream(upgrades).map(CraftTweakerMC::getItemStack) - .filter(itemStack -> !itemStack.isEmpty()).toArray(ItemStack[]::new)) { - this.upgrade.get(tier).add(up); - } - return this; - } - - @ZenMethod - public void build() { - if (ctAppRegistryBuilders == null) { - registerAPP(this); - } else { - ctAppRegistryBuilders.add(this); - } - } - } -} diff --git a/src/main/java/gregtech/integration/groovy/GrSRecipeHelper.java b/src/main/java/gregtech/integration/groovy/GrSRecipeHelper.java index 9c686f88946..f2f8c4cb67e 100644 --- a/src/main/java/gregtech/integration/groovy/GrSRecipeHelper.java +++ b/src/main/java/gregtech/integration/groovy/GrSRecipeHelper.java @@ -7,7 +7,7 @@ import net.minecraft.item.ItemStack; -import com.cleanroommc.groovyscript.helper.ingredient.IngredientHelper; +import com.cleanroommc.groovyscript.helper.ingredient.GroovyScriptCodeConverter; import com.cleanroommc.groovyscript.helper.ingredient.NbtHelper; public class GrSRecipeHelper { @@ -20,7 +20,7 @@ public static String getRecipeRemoveLine(RecipeMap recipeMap, Recipe recipe) .append(recipe.getEUt()) .append(", "); - if (recipe.getInputs().size() > 0) { + if (!recipe.getInputs().isEmpty()) { builder.append("["); for (GTRecipeInput ci : recipe.getInputs()) { String ingredient = getGroovyItemString(ci); @@ -32,10 +32,10 @@ public static String getRecipeRemoveLine(RecipeMap recipeMap, Recipe recipe) builder.append("null, "); } - if (recipe.getFluidInputs().size() > 0) { + if (!recipe.getFluidInputs().isEmpty()) { builder.append("["); for (GTRecipeInput fluidIngredient : recipe.getFluidInputs()) { - builder.append(IngredientHelper.asGroovyCode(fluidIngredient.getInputFluidStack(), false)); + builder.append(GroovyScriptCodeConverter.asGroovyCode(fluidIngredient.getInputFluidStack(), false)); if (fluidIngredient.getAmount() > 1) { builder.append(" * ") @@ -72,7 +72,7 @@ public static String getGroovyItemString(GTRecipeInput recipeInput) { } if (itemStack != null) { if (itemId == null) { - builder.append(IngredientHelper.asGroovyCode(itemStack, false)); + builder.append(GroovyScriptCodeConverter.asGroovyCode(itemStack, false)); } if (itemStack.getTagCompound() != null) { diff --git a/src/main/java/gregtech/integration/groovy/GroovyExpansions.java b/src/main/java/gregtech/integration/groovy/GroovyExpansions.java index ff00a9d1b5b..bd7e01ca643 100644 --- a/src/main/java/gregtech/integration/groovy/GroovyExpansions.java +++ b/src/main/java/gregtech/integration/groovy/GroovyExpansions.java @@ -18,7 +18,7 @@ public class GroovyExpansions { public static > RecipeBuilder property(RecipeBuilder builder, String key, Object value) { - if (!builder.applyProperty(key, value)) { + if (!builder.applyPropertyCT(key, value)) { GroovyLog.get().error("Failed to add property '{}' with '{}' to recipe", key, value); } return builder; @@ -29,7 +29,7 @@ public static Material.Builder materialBuilder(MaterialEvent event, int id, Reso } public static Material.Builder materialBuilder(MaterialEvent event, int id, String domain, String path) { - return materialBuilder(event, id, domain, path); + return materialBuilder(event, id, new ResourceLocation(domain, path)); } public static Material.Builder materialBuilder(MaterialEvent event, int id, String s) { diff --git a/src/main/java/gregtech/integration/groovy/PropertyContainer.java b/src/main/java/gregtech/integration/groovy/PropertyContainer.java index 30930c68f9c..bbafd3c7d92 100644 --- a/src/main/java/gregtech/integration/groovy/PropertyContainer.java +++ b/src/main/java/gregtech/integration/groovy/PropertyContainer.java @@ -42,6 +42,6 @@ public void lateMaterialEvent(EventPriority priority, Closure eventListener) } public void lateMaterialEvent(Closure eventListener) { - materialEvent(EventPriority.NORMAL, eventListener); + lateMaterialEvent(EventPriority.NORMAL, eventListener); } } diff --git a/src/main/java/gregtech/integration/hwyla/HWYLAModule.java b/src/main/java/gregtech/integration/hwyla/HWYLAModule.java index d26defcbde3..a604d6331e1 100644 --- a/src/main/java/gregtech/integration/hwyla/HWYLAModule.java +++ b/src/main/java/gregtech/integration/hwyla/HWYLAModule.java @@ -40,6 +40,8 @@ public void register(IWailaRegistrar registrar) { // one day, if cover provider is ported to waila, register it right here BlockOreDataProvider.INSTANCE.register(registrar); LampDataProvider.INSTANCE.register(registrar); + ActiveTransformerDataProvider.INSTANCE.register(registrar); + BatteryBufferDataProvider.INSTANCE.register(registrar); } /** Render an ItemStack. */ diff --git a/src/main/java/gregtech/integration/hwyla/provider/ActiveTransformerDataProvider.java b/src/main/java/gregtech/integration/hwyla/provider/ActiveTransformerDataProvider.java new file mode 100644 index 00000000000..d1b20e6ddfd --- /dev/null +++ b/src/main/java/gregtech/integration/hwyla/provider/ActiveTransformerDataProvider.java @@ -0,0 +1,70 @@ +package gregtech.integration.hwyla.provider; + +import gregtech.api.GTValues; +import gregtech.api.capability.GregtechCapabilities; +import gregtech.api.capability.IMultiblockController; +import gregtech.api.util.TextFormattingUtil; +import gregtech.common.metatileentities.multi.electric.MetaTileEntityActiveTransformer; + +import net.minecraft.client.resources.I18n; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.capabilities.Capability; + +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaRegistrar; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class ActiveTransformerDataProvider extends CapabilityDataProvider { + + public static final ActiveTransformerDataProvider INSTANCE = new ActiveTransformerDataProvider(); + + @Override + public void register(@NotNull IWailaRegistrar registrar) { + registrar.registerBodyProvider(this, TileEntity.class); + registrar.registerNBTProvider(this, TileEntity.class); + registrar.addConfig(GTValues.MOD_NAME, "gregtech.multiblock.activetransformer"); + } + + @Override + protected @NotNull Capability getCapability() { + return GregtechCapabilities.CAPABILITY_MULTIBLOCK_CONTROLLER; + } + + @Override + protected NBTTagCompound getNBTData(IMultiblockController capability, NBTTagCompound tag) { + if (capability instanceof MetaTileEntityActiveTransformer activeTransformer) { + if (activeTransformer.isStructureFormed() && activeTransformer.isActive()) { + NBTTagCompound subTag = new NBTTagCompound(); + + subTag.setLong("AverageIO", activeTransformer.getAverageIOLastSec()); + + tag.setTag("gregtech.IMultiblockController.ActiveTransformer", subTag); + } + } + return tag; + } + + @Override + @NotNull + public List getWailaBody(ItemStack itemStack, List tooltip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + if (!config.getConfig("gregtech.multiblock") || accessor.getTileEntity() == null) { + return tooltip; + } + + if (accessor.getNBTData().hasKey("gregtech.IMultiblockController.ActiveTransformer")) { + NBTTagCompound tag = accessor.getNBTData() + .getCompoundTag("gregtech.IMultiblockController.ActiveTransformer"); + + tooltip.add(I18n.format("gregtech.waila.active_transformer.average_io", + TextFormattingUtil.formatNumbers(tag.getLong("AverageIO")))); + } + + return tooltip; + } +} diff --git a/src/main/java/gregtech/integration/hwyla/provider/BatteryBufferDataProvider.java b/src/main/java/gregtech/integration/hwyla/provider/BatteryBufferDataProvider.java new file mode 100644 index 00000000000..67f08fd7737 --- /dev/null +++ b/src/main/java/gregtech/integration/hwyla/provider/BatteryBufferDataProvider.java @@ -0,0 +1,79 @@ +package gregtech.integration.hwyla.provider; + +import gregtech.api.GTValues; +import gregtech.api.capability.GregtechCapabilities; +import gregtech.api.capability.IEnergyContainer; +import gregtech.api.metatileentity.MetaTileEntity; +import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; +import gregtech.api.util.TextFormattingUtil; +import gregtech.common.metatileentities.electric.MetaTileEntityBatteryBuffer; + +import net.minecraft.client.resources.I18n; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.capabilities.Capability; + +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaRegistrar; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class BatteryBufferDataProvider extends CapabilityDataProvider { + + public static final BatteryBufferDataProvider INSTANCE = new BatteryBufferDataProvider(); + + @Override + public void register(@NotNull IWailaRegistrar registrar) { + registrar.registerBodyProvider(this, TileEntity.class); + registrar.registerNBTProvider(this, TileEntity.class); + registrar.addConfig(GTValues.MOD_NAME, "gregtech.battery-buffer"); + } + + @Override + protected @NotNull Capability getCapability() { + return GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER; + } + + @Override + protected NBTTagCompound getNBTData(IEnergyContainer capability, NBTTagCompound tag) { + NBTTagCompound subTag = new NBTTagCompound(); + subTag.setLong("InputPerSec", capability.getInputPerSec()); + subTag.setLong("OutputPerSec", capability.getOutputPerSec()); + tag.setTag("gregtech.BatteryBuffer", subTag); + return tag; + } + + @Override + @NotNull + public List getWailaBody(ItemStack itemStack, List tooltip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + if (!config.getConfig("gregtech.battery-buffer") || accessor.getTileEntity() == null) { + return tooltip; + } + + if (accessor.getNBTData().hasKey("gregtech.BatteryBuffer")) { + NBTTagCompound batteryTag = accessor.getNBTData().getCompoundTag("gregtech.BatteryBuffer"); + + if (accessor.getTileEntity() instanceof IGregTechTileEntity iGregTechTileEntity) { + MetaTileEntity metaTileEntity = iGregTechTileEntity.getMetaTileEntity(); + + if (metaTileEntity instanceof MetaTileEntityBatteryBuffer) { + long averageIn = batteryTag.getLong("InputPerSec") / 20; + String averageInFormatted = I18n.format("gregtech.waila.energy_input", + TextFormattingUtil.formatNumbers(averageIn)); + tooltip.add(averageInFormatted); + + long averageOut = batteryTag.getLong("OutputPerSec") / 20; + String averageOutFormatted = I18n.format("gregtech.waila.energy_output", + TextFormattingUtil.formatNumbers(averageOut)); + tooltip.add(averageOutFormatted); + } + } + } + + return tooltip; + } +} diff --git a/src/main/java/gregtech/integration/hwyla/provider/ElectricContainerDataProvider.java b/src/main/java/gregtech/integration/hwyla/provider/ElectricContainerDataProvider.java index 71c14e185f8..719fd15363e 100644 --- a/src/main/java/gregtech/integration/hwyla/provider/ElectricContainerDataProvider.java +++ b/src/main/java/gregtech/integration/hwyla/provider/ElectricContainerDataProvider.java @@ -3,6 +3,7 @@ import gregtech.api.GTValues; import gregtech.api.capability.GregtechCapabilities; import gregtech.api.capability.IEnergyContainer; +import gregtech.api.util.TextFormattingUtil; import net.minecraft.client.resources.I18n; import net.minecraft.item.ItemStack; @@ -59,7 +60,9 @@ public List getWailaBody(ItemStack itemStack, List tooltip, IWai NBTTagCompound energyTag = accessor.getNBTData().getCompoundTag("gregtech.IEnergyContainer"); long stored = energyTag.getLong("Stored"); long capacity = energyTag.getLong("Capacity"); - tooltip.add(I18n.format("gregtech.waila.energy_stored", stored, capacity)); + tooltip.add(I18n.format("gregtech.waila.energy_stored", + TextFormattingUtil.formatNumbers(stored), + TextFormattingUtil.formatNumbers(capacity))); } return tooltip; } diff --git a/src/main/java/gregtech/integration/hwyla/provider/RecipeLogicDataProvider.java b/src/main/java/gregtech/integration/hwyla/provider/RecipeLogicDataProvider.java index afeb607e153..08391814820 100644 --- a/src/main/java/gregtech/integration/hwyla/provider/RecipeLogicDataProvider.java +++ b/src/main/java/gregtech/integration/hwyla/provider/RecipeLogicDataProvider.java @@ -83,7 +83,7 @@ public List getWailaBody(ItemStack itemStack, List tooltip, IWai } if (endText == null) { endText = ": " + TextFormattingUtil.formatNumbers(eut) + TextFormatting.RESET + " EU/t (" + - GTValues.VNF[GTUtility.getTierByVoltage(eut)] + TextFormatting.RESET + ")"; + GTValues.VOCNF[GTUtility.getOCTierByVoltage(eut)] + TextFormatting.RESET + ")"; } if (eut == 0) return tooltip; diff --git a/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java b/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java index 5ce3cff1cb9..5a182dbadde 100644 --- a/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java +++ b/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java @@ -29,6 +29,7 @@ import gregtech.common.blocks.MetaBlocks; import gregtech.common.gui.widget.craftingstation.CraftingSlotWidget; import gregtech.common.items.MetaItems; +import gregtech.common.items.ToolItems; import gregtech.common.metatileentities.MetaTileEntities; import gregtech.integration.IntegrationSubmodule; import gregtech.integration.jei.basic.GTFluidVeinCategory; @@ -84,6 +85,9 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import static gregtech.api.unification.material.info.MaterialFlags.GENERATE_BOLT_SCREW; +import static gregtech.api.unification.material.info.MaterialFlags.GENERATE_RING; + @JEIPlugin @GregTechModule( moduleID = GregTechModules.MODULE_JEI, @@ -237,11 +241,22 @@ public void register(IModRegistry registry) { } List oreByproductList = new ArrayList<>(); + List materialTreeList = new ArrayList<>(); for (Material material : GregTechAPI.materialManager.getRegisteredMaterials()) { if (material.hasProperty(PropertyKey.ORE)) { oreByproductList.add(new OreByProduct(material)); } + if (material.hasProperty(PropertyKey.DUST)) { + materialTreeList.add(new MaterialTree(material)); + } + if (material.hasFlag(GENERATE_BOLT_SCREW) && material.hasFlag(GENERATE_RING) && + material.hasProperty(PropertyKey.TOOL)) { + registry.addIngredientInfo(ToolItems.TOOLBELT.get(material), VanillaTypes.ITEM, + "item.gt.tool.toolbelt.tooltip", "item.gt.tool.toolbelt.paint", "item.gt.tool.toolbelt.dye", + "item.gt.tool.toolbelt.maintenance"); + } } + String oreByProductId = GTValues.MODID + ":" + "ore_by_product"; registry.addRecipes(oreByproductList, oreByProductId); MetaTileEntity[][] machineLists = { @@ -259,12 +274,6 @@ public void register(IModRegistry registry) { } // Material Tree - List materialTreeList = new ArrayList<>(); - for (Material material : GregTechAPI.materialManager.getRegisteredMaterials()) { - if (material.hasProperty(PropertyKey.DUST)) { - materialTreeList.add(new MaterialTree(material)); - } - } registry.addRecipes(materialTreeList, GTValues.MODID + ":" + "material_tree"); // Ore Veins diff --git a/src/main/java/gregtech/integration/jei/basic/MaterialTreeCategory.java b/src/main/java/gregtech/integration/jei/basic/MaterialTreeCategory.java index 16a26032f73..b3c8b6e10b2 100644 --- a/src/main/java/gregtech/integration/jei/basic/MaterialTreeCategory.java +++ b/src/main/java/gregtech/integration/jei/basic/MaterialTreeCategory.java @@ -2,7 +2,7 @@ import gregtech.api.GTValues; import gregtech.api.gui.GuiTextures; -import gregtech.api.recipes.recipeproperties.TemperatureProperty; +import gregtech.api.recipes.properties.impl.TemperatureProperty; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; import gregtech.api.unification.ore.OrePrefix; diff --git a/src/main/java/gregtech/integration/jei/recipe/GTRecipeWrapper.java b/src/main/java/gregtech/integration/jei/recipe/GTRecipeWrapper.java index f0fb97c1f1c..4d88c1f1e5b 100644 --- a/src/main/java/gregtech/integration/jei/recipe/GTRecipeWrapper.java +++ b/src/main/java/gregtech/integration/jei/recipe/GTRecipeWrapper.java @@ -16,13 +16,14 @@ import gregtech.api.recipes.ingredients.GTRecipeInput; import gregtech.api.recipes.machines.IResearchRecipeMap; import gregtech.api.recipes.machines.IScannerRecipeMap; -import gregtech.api.recipes.recipeproperties.ComputationProperty; -import gregtech.api.recipes.recipeproperties.RecipeProperty; -import gregtech.api.recipes.recipeproperties.ScanProperty; -import gregtech.api.recipes.recipeproperties.TotalComputationProperty; +import gregtech.api.recipes.properties.RecipeProperty; +import gregtech.api.recipes.properties.impl.ComputationProperty; +import gregtech.api.recipes.properties.impl.ScanProperty; +import gregtech.api.recipes.properties.impl.TotalComputationProperty; import gregtech.api.util.AssemblyLineManager; import gregtech.api.util.ClipboardUtil; import gregtech.api.util.GTUtility; +import gregtech.api.util.LocalizationUtils; import gregtech.api.util.TextFormattingUtil; import gregtech.client.utils.TooltipHelper; import gregtech.integration.RecipeCompatUtil; @@ -44,7 +45,6 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Map; import java.util.function.BooleanSupplier; import java.util.stream.Collectors; @@ -239,7 +239,8 @@ public void addIngredientTooltips(@NotNull Collection tooltip, boolean n @Override public void drawInfo(@NotNull Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) { super.drawInfo(minecraft, recipeWidth, recipeHeight, mouseX, mouseY); - var properties = recipe.getPropertyTypes(); + var storage = recipe.propertyStorage(); + var properties = storage.values(); boolean drawTotalEU = properties.isEmpty() || properties.stream().noneMatch(RecipeProperty::hideTotalEU); boolean drawEUt = properties.isEmpty() || properties.stream().noneMatch(RecipeProperty::hideEUt); boolean drawDuration = properties.isEmpty() || properties.stream().noneMatch(RecipeProperty::hideDuration); @@ -249,15 +250,18 @@ public void drawInfo(@NotNull Minecraft minecraft, int recipeWidth, int recipeHe if (drawEUt) defaultLines++; if (drawDuration) defaultLines++; - int yPosition = recipeHeight - ((recipe.getUnhiddenPropertyCount() + defaultLines) * 10 - 3); + int unhiddenCount = (int) storage.entrySet().stream() + .filter((property) -> !property.getKey().isHidden()) + .count(); + int yPosition = recipeHeight - ((unhiddenCount + defaultLines) * 10 - 3); // Default entries if (drawTotalEU) { long eu = recipe.getEUt() * recipe.getDuration(); // sadly we still need a custom override here, since computation uses duration and EU/t very differently - if (recipe.hasProperty(TotalComputationProperty.getInstance()) && - recipe.hasProperty(ComputationProperty.getInstance())) { - int minimumCWUt = recipe.getProperty(ComputationProperty.getInstance(), 1); + if (storage.contains(TotalComputationProperty.getInstance()) && + storage.contains(ComputationProperty.getInstance())) { + int minimumCWUt = storage.get(ComputationProperty.getInstance(), 1); minecraft.fontRenderer.drawString(I18n.format("gregtech.recipe.max_eu", eu / minimumCWUt), 0, yPosition, 0x111111); } else { @@ -280,10 +284,10 @@ public void drawInfo(@NotNull Minecraft minecraft, int recipeWidth, int recipeHe } // Property custom entries - for (Map.Entry, Object> propertyEntry : recipe.getPropertyValues()) { + for (var propertyEntry : storage.entrySet()) { if (!propertyEntry.getKey().isHidden()) { RecipeProperty property = propertyEntry.getKey(); - Object value = propertyEntry.getValue(); + var value = propertyEntry.getValue(); property.drawInfo(minecraft, 0, yPosition += property.getInfoHeight(value), 0x111111, value, mouseX, mouseY); } @@ -294,7 +298,7 @@ public void drawInfo(@NotNull Minecraft minecraft, int recipeWidth, int recipeHe @Override public List getTooltipStrings(int mouseX, int mouseY) { List tooltips = new ArrayList<>(); - for (var entry : recipe.getPropertyValues()) { + for (var entry : recipe.propertyStorage().entrySet()) { if (!entry.getKey().isHidden()) { RecipeProperty property = entry.getKey(); Object value = entry.getValue(); @@ -306,15 +310,22 @@ public List getTooltipStrings(int mouseX, int mouseY) { @Override public void initExtras() { - // do not add the X button if no tweaker mod is present + // do not add the info or X button if no tweaker mod is present if (!RecipeCompatUtil.isTweakerLoaded()) return; - BooleanSupplier creativePlayerCtPredicate = () -> Minecraft.getMinecraft().player != null && + BooleanSupplier creativePlayerPredicate = () -> Minecraft.getMinecraft().player != null && Minecraft.getMinecraft().player.isCreative(); + BooleanSupplier creativeTweaker = () -> creativePlayerPredicate.getAsBoolean() && + (recipe.getIsCTRecipe() || recipe.isGroovyRecipe()); + BooleanSupplier creativeDefault = () -> creativePlayerPredicate.getAsBoolean() && !recipe.getIsCTRecipe() && + !recipe.isGroovyRecipe(); + + // X Button buttons.add(new JeiButton(166, 2, 10, 10) .setTextures(GuiTextures.BUTTON_CLEAR_GRID) - .setTooltipBuilder(lines -> lines.add("Copies a " + RecipeCompatUtil.getTweakerName() + - " script, to remove this recipe, to the clipboard")) + .setTooltipBuilder(lines -> lines.add( + LocalizationUtils.format("gregtech.jei.remove_recipe.tooltip", + RecipeCompatUtil.getTweakerName()))) .setClickAction((minecraft, mouseX, mouseY, mouseButton) -> { String recipeLine = RecipeCompatUtil.getRecipeRemoveLine(recipeMap, recipe); String output = RecipeCompatUtil.getFirstOutputString(recipe); @@ -327,7 +338,16 @@ public void initExtras() { new TextComponentString("Copied [\u00A76" + recipeLine + "\u00A7r] to the clipboard")); return true; }) - .setActiveSupplier(creativePlayerCtPredicate)); + .setActiveSupplier(creativeDefault)); + + // CT/GS Info + buttons.add(new JeiButton(166, 2, 10, 10) + .setTextures(GuiTextures.INFO_ICON) + .setTooltipBuilder(lines -> lines.add(recipe.isGroovyRecipe() ? + LocalizationUtils.format("gregtech.jei.gs_recipe.tooltip") : + LocalizationUtils.format("gregtech.jei.ct_recipe.tooltip"))) + .setClickAction((mc, x, y, button) -> false) + .setActiveSupplier(creativeTweaker)); } public ChancedItemOutput getOutputChance(int slot) { diff --git a/src/main/java/gregtech/integration/jei/recipe/RecipeMapCategory.java b/src/main/java/gregtech/integration/jei/recipe/RecipeMapCategory.java index 52039a21b07..31dde8f7874 100644 --- a/src/main/java/gregtech/integration/jei/recipe/RecipeMapCategory.java +++ b/src/main/java/gregtech/integration/jei/recipe/RecipeMapCategory.java @@ -12,8 +12,8 @@ import gregtech.api.recipes.RecipeMap; import gregtech.api.recipes.RecipeMaps; import gregtech.api.recipes.category.GTRecipeCategory; -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.GTUtility; import gregtech.api.util.LocalizationUtils; @@ -213,9 +213,9 @@ public void setRecipe(IRecipeLayout recipeLayout, @NotNull GTRecipeWrapper recip if (data != null) { List dataItems = new ArrayList<>(); for (ResearchPropertyData.ResearchEntry entry : data) { - ItemStack dataStick = entry.getDataItem().copy(); + ItemStack dataStick = entry.dataItem().copy(); AssemblyLineManager.writeResearchToNBT(GTUtility.getOrCreateNbtCompound(dataStick), - entry.getResearchId()); + entry.researchId()); dataItems.add(dataStick); } itemStackGroup.set(16, dataItems); diff --git a/src/main/java/gregtech/integration/opencomputers/drivers/DriverCoverHolder.java b/src/main/java/gregtech/integration/opencomputers/drivers/DriverCoverHolder.java index be85082485c..b05a8e3f7af 100644 --- a/src/main/java/gregtech/integration/opencomputers/drivers/DriverCoverHolder.java +++ b/src/main/java/gregtech/integration/opencomputers/drivers/DriverCoverHolder.java @@ -5,6 +5,7 @@ import gregtech.api.cover.CoverHolder; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.common.covers.*; +import gregtech.common.covers.ender.CoverEnderFluidLink; import gregtech.integration.opencomputers.InputValidator; import gregtech.integration.opencomputers.values.*; diff --git a/src/main/java/gregtech/integration/opencomputers/values/ValueCoverEnderFluidLink.java b/src/main/java/gregtech/integration/opencomputers/values/ValueCoverEnderFluidLink.java index 8f919385959..31c8b2ae10d 100644 --- a/src/main/java/gregtech/integration/opencomputers/values/ValueCoverEnderFluidLink.java +++ b/src/main/java/gregtech/integration/opencomputers/values/ValueCoverEnderFluidLink.java @@ -1,8 +1,8 @@ package gregtech.integration.opencomputers.values; import gregtech.api.cover.Cover; -import gregtech.common.covers.CoverEnderFluidLink; import gregtech.common.covers.CoverPump.PumpMode; +import gregtech.common.covers.ender.CoverEnderFluidLink; import gregtech.integration.opencomputers.InputValidator; import net.minecraft.util.EnumFacing; diff --git a/src/main/java/gregtech/integration/theoneprobe/TheOneProbeModule.java b/src/main/java/gregtech/integration/theoneprobe/TheOneProbeModule.java index 8b64c066cc9..4ce285fc92e 100644 --- a/src/main/java/gregtech/integration/theoneprobe/TheOneProbeModule.java +++ b/src/main/java/gregtech/integration/theoneprobe/TheOneProbeModule.java @@ -43,6 +43,9 @@ public void init(FMLInitializationEvent event) { oneProbe.registerProvider(new LampInfoProvider()); oneProbe.registerProvider(new LDPipeProvider()); oneProbe.registerProvider(new LaserContainerInfoProvider()); + oneProbe.registerProvider(new QuantumStorageProvider()); + oneProbe.registerProvider(new ActiveTransformerInfoProvider()); + oneProbe.registerProvider(new BatteryBufferInfoProvider()); // Dev environment debug providers oneProbe.registerProvider(new DebugPipeNetInfoProvider()); diff --git a/src/main/java/gregtech/integration/theoneprobe/provider/ActiveTransformerInfoProvider.java b/src/main/java/gregtech/integration/theoneprobe/provider/ActiveTransformerInfoProvider.java new file mode 100644 index 00000000000..a96607dc2e1 --- /dev/null +++ b/src/main/java/gregtech/integration/theoneprobe/provider/ActiveTransformerInfoProvider.java @@ -0,0 +1,53 @@ +package gregtech.integration.theoneprobe.provider; + +import gregtech.api.GTValues; +import gregtech.api.capability.GregtechCapabilities; +import gregtech.api.capability.IMultiblockController; +import gregtech.api.util.TextComponentUtil; +import gregtech.api.util.TextFormattingUtil; +import gregtech.common.metatileentities.multi.electric.MetaTileEntityActiveTransformer; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.common.capabilities.Capability; + +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.NumberFormat; +import mcjty.theoneprobe.apiimpl.elements.ElementProgress; +import org.jetbrains.annotations.NotNull; + +public class ActiveTransformerInfoProvider extends CapabilityInfoProvider { + + @Override + public String getID() { + return GTValues.MODID + ":active_transformer_info_provider"; + } + + @Override + protected boolean allowDisplaying(@NotNull IMultiblockController capability) { + return capability instanceof MetaTileEntityActiveTransformer activeTransformer && activeTransformer.isActive(); + } + + @Override + protected @NotNull Capability getCapability() { + return GregtechCapabilities.CAPABILITY_MULTIBLOCK_CONTROLLER; + } + + @Override + protected void addProbeInfo(IMultiblockController capability, IProbeInfo probeInfo, EntityPlayer player, + TileEntity tileEntity, IProbeHitData data) { + long averageIO = ((MetaTileEntityActiveTransformer) capability).getAverageIOLastSec(); + ITextComponent text = TextComponentUtil.translationWithColor( + TextFormatting.AQUA, + "gregtech.multiblock.active_transformer.average_io", + TextComponentUtil.stringWithColor(TextFormatting.WHITE, + player.isSneaking() || averageIO < 10_000 ? + TextFormattingUtil.formatNumbers(averageIO) + " EU/t" : + ElementProgress.format(averageIO, NumberFormat.COMPACT, "EU/t"))); + + probeInfo.text(text.getFormattedText()); + } +} diff --git a/src/main/java/gregtech/integration/theoneprobe/provider/BatteryBufferInfoProvider.java b/src/main/java/gregtech/integration/theoneprobe/provider/BatteryBufferInfoProvider.java new file mode 100644 index 00000000000..0c990604954 --- /dev/null +++ b/src/main/java/gregtech/integration/theoneprobe/provider/BatteryBufferInfoProvider.java @@ -0,0 +1,67 @@ +package gregtech.integration.theoneprobe.provider; + +import gregtech.api.GTValues; +import gregtech.api.capability.GregtechCapabilities; +import gregtech.api.capability.IEnergyContainer; +import gregtech.api.metatileentity.MetaTileEntity; +import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; +import gregtech.api.util.TextComponentUtil; +import gregtech.api.util.TextFormattingUtil; +import gregtech.common.metatileentities.electric.MetaTileEntityBatteryBuffer; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.common.capabilities.Capability; + +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.NumberFormat; +import mcjty.theoneprobe.apiimpl.elements.ElementProgress; +import org.jetbrains.annotations.NotNull; + +public class BatteryBufferInfoProvider extends CapabilityInfoProvider { + + @Override + public String getID() { + return GTValues.MODID + ":battery_buffer_provider"; + } + + @Override + protected @NotNull Capability getCapability() { + return GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER; + } + + @Override + protected void addProbeInfo(IEnergyContainer capability, IProbeInfo probeInfo, EntityPlayer player, + TileEntity tileEntity, IProbeHitData data) { + if (tileEntity instanceof IGregTechTileEntity iGregTechTileEntity) { + MetaTileEntity metaTileEntity = iGregTechTileEntity.getMetaTileEntity(); + + if (metaTileEntity instanceof MetaTileEntityBatteryBuffer) { + long averageIn = capability.getInputPerSec() / 20; + ITextComponent averageInFormatted = TextComponentUtil.translationWithColor( + TextFormatting.GREEN, + "gregtech.battery_buffer.average_input.top", + TextComponentUtil.stringWithColor( + TextFormatting.WHITE, + player.isSneaking() || averageIn < 10_000 ? + TextFormattingUtil.formatNumbers(averageIn) + " EU/t" : + ElementProgress.format(averageIn, NumberFormat.COMPACT, "EU/t"))); + probeInfo.text(averageInFormatted.getFormattedText()); + + long averageOut = capability.getOutputPerSec() / 20; + ITextComponent averageOutFormatted = TextComponentUtil.translationWithColor( + TextFormatting.RED, + "gregtech.battery_buffer.average_output.top", + TextComponentUtil.stringWithColor( + TextFormatting.WHITE, + player.isSneaking() || averageOut < 10_000 ? + TextFormattingUtil.formatNumbers(averageOut) + " EU/t" : + ElementProgress.format(averageOut, NumberFormat.COMPACT, "EU/t"))); + probeInfo.text(averageOutFormatted.getFormattedText()); + } + } + } +} diff --git a/src/main/java/gregtech/integration/theoneprobe/provider/CoverInfoProvider.java b/src/main/java/gregtech/integration/theoneprobe/provider/CoverInfoProvider.java index 0aebf88036a..377ff7a51d7 100644 --- a/src/main/java/gregtech/integration/theoneprobe/provider/CoverInfoProvider.java +++ b/src/main/java/gregtech/integration/theoneprobe/provider/CoverInfoProvider.java @@ -6,6 +6,7 @@ import gregtech.api.cover.CoverHolder; import gregtech.api.util.TextFormattingUtil; import gregtech.common.covers.*; +import gregtech.common.covers.ender.CoverEnderFluidLink; import gregtech.common.covers.filter.*; import net.minecraft.entity.player.EntityPlayer; @@ -181,8 +182,8 @@ private static void fluidFilterInfo(@NotNull IProbeInfo probeInfo, @NotNull Cove * @param enderFluidLink the ender fluid link cover to get data from */ private static void enderFluidLinkInfo(@NotNull IProbeInfo probeInfo, @NotNull CoverEnderFluidLink enderFluidLink) { - transferRateText(probeInfo, enderFluidLink.getPumpMode(), " " + lang("cover.bucket.mode.milli_bucket_rate"), - enderFluidLink.isIOEnabled() ? CoverEnderFluidLink.TRANSFER_RATE : 0); + transferRateText(probeInfo, enderFluidLink.getPumpMode(), " " + lang("cover.ender_fluid_link.transfer_unit"), + enderFluidLink.isIoEnabled() ? CoverEnderFluidLink.TRANSFER_RATE : 0); fluidFilterText(probeInfo, enderFluidLink.getFluidFilterContainer().getFilter()); if (!enderFluidLink.getColorStr().isEmpty()) { diff --git a/src/main/java/gregtech/integration/theoneprobe/provider/ElectricContainerInfoProvider.java b/src/main/java/gregtech/integration/theoneprobe/provider/ElectricContainerInfoProvider.java index a15622a1160..b80350912d8 100644 --- a/src/main/java/gregtech/integration/theoneprobe/provider/ElectricContainerInfoProvider.java +++ b/src/main/java/gregtech/integration/theoneprobe/provider/ElectricContainerInfoProvider.java @@ -40,8 +40,11 @@ protected void addProbeInfo(@NotNull IEnergyContainer capability, @NotNull IProb long stored = capability.getEnergyStored(); if (maxStorage == 0) return; // do not add empty max storage progress bar probeInfo.progress(capability.getEnergyStored(), maxStorage, probeInfo.defaultProgressStyle() - .numberFormat(player.isSneaking() || stored < 10000 ? NumberFormat.FULL : NumberFormat.COMPACT) - .suffix(" / " + (player.isSneaking() || maxStorage < 10000 ? maxStorage + " EU" : + .numberFormat(player.isSneaking() || stored < 10000 ? + NumberFormat.COMMAS : + NumberFormat.COMPACT) + .suffix(" / " + (player.isSneaking() || maxStorage < 10000 ? + ElementProgress.format(maxStorage, NumberFormat.COMMAS, " EU") : ElementProgress.format(maxStorage, NumberFormat.COMPACT, "EU"))) .filledColor(0xFFEEE600) .alternateFilledColor(0xFFEEE600) diff --git a/src/main/java/gregtech/integration/theoneprobe/provider/QuantumStorageProvider.java b/src/main/java/gregtech/integration/theoneprobe/provider/QuantumStorageProvider.java new file mode 100644 index 00000000000..792be0ac4e5 --- /dev/null +++ b/src/main/java/gregtech/integration/theoneprobe/provider/QuantumStorageProvider.java @@ -0,0 +1,68 @@ +package gregtech.integration.theoneprobe.provider; + +import gregtech.api.GTValues; +import gregtech.api.capability.IQuantumController; +import gregtech.api.capability.IQuantumStorage; +import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; +import gregtech.api.util.GTUtility; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.world.World; + +import mcjty.theoneprobe.api.IProbeHitData; +import mcjty.theoneprobe.api.IProbeInfo; +import mcjty.theoneprobe.api.IProbeInfoProvider; +import mcjty.theoneprobe.api.ProbeMode; +import mcjty.theoneprobe.api.TextStyleClass; +import org.jetbrains.annotations.NotNull; + +public class QuantumStorageProvider implements IProbeInfoProvider { + + @Override + public String getID() { + return ":quantum_storage_provider"; + } + + @Override + public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, + IBlockState blockState, IProbeHitData data) { + if (blockState.getBlock().hasTileEntity(blockState) && + world.getTileEntity(data.getPos()) instanceof IGregTechTileEntity gtte) { + if (gtte.getMetaTileEntity() instanceof IQuantumController controller) { + if (controller.getCount(IQuantumStorage.Type.ENERGY) == 0) { + probeInfo.text("{*gregtech.top.quantum_controller.no_hatches*}"); + } else if (!controller.isPowered()) { + probeInfo.text("{*gregtech.top.quantum_controller.no_power*}"); + } else { + long usage = controller.getEnergyUsage(); + configureEnergyUsage(usage / 10, probeInfo); + } + } else if (gtte.getMetaTileEntity() instanceof IQuantumStoragestorage && + (storage.getType() == IQuantumStorage.Type.ITEM || + storage.getType() == IQuantumStorage.Type.FLUID)) { + probeInfo.text(getConnectionStatus(storage)); + } + } + } + + private static @NotNull String getConnectionStatus(IQuantumStorage storage) { + var qcontroller = storage.getQuantumController(); + String status = "gregtech.top.quantum_status.disconnected"; + if (qcontroller != null) { + status = qcontroller.isPowered() ? + "gregtech.top.quantum_status.powered" : + "gregtech.top.quantum_status.connected"; + } + return TextStyleClass.INFO + "{*gregtech.top.quantum_status.label*} " + + "{*" + status + "*}"; + } + + public void configureEnergyUsage(long EUs, IProbeInfo probeInfo) { + if (EUs == 0) return; + String text = TextFormatting.RED.toString() + EUs + TextStyleClass.INFO + " EU/t" + TextFormatting.GREEN + + " (" + GTValues.VNF[GTUtility.getTierByVoltage(EUs)] + TextFormatting.GREEN + ")"; + probeInfo.text(TextStyleClass.INFO + "{*gregtech.top.energy_consumption*} " + text); + } +} diff --git a/src/main/java/gregtech/integration/theoneprobe/provider/RecipeLogicInfoProvider.java b/src/main/java/gregtech/integration/theoneprobe/provider/RecipeLogicInfoProvider.java index 930f073408b..3c69af74b50 100644 --- a/src/main/java/gregtech/integration/theoneprobe/provider/RecipeLogicInfoProvider.java +++ b/src/main/java/gregtech/integration/theoneprobe/provider/RecipeLogicInfoProvider.java @@ -63,7 +63,7 @@ protected void addProbeInfo(@NotNull AbstractRecipeLogic capability, @NotNull IP // IGregTechTileEntity...) text = TextFormatting.RED + TextFormattingUtil.formatNumbers(eut) + TextStyleClass.INFO + " EU/t" + TextFormatting.GREEN + - " (" + GTValues.VNF[GTUtility.getTierByVoltage(eut)] + TextFormatting.GREEN + ")"; + " (" + GTValues.VOCNF[GTUtility.getOCTierByVoltage(eut)] + TextFormatting.GREEN + ")"; } if (eut == 0) return; // do not display 0 eut diff --git a/src/main/java/gregtech/integration/theoneprobe/provider/SteamBoilerInfoProvider.java b/src/main/java/gregtech/integration/theoneprobe/provider/SteamBoilerInfoProvider.java index 248d0fc1d02..25decb1cba7 100644 --- a/src/main/java/gregtech/integration/theoneprobe/provider/SteamBoilerInfoProvider.java +++ b/src/main/java/gregtech/integration/theoneprobe/provider/SteamBoilerInfoProvider.java @@ -30,10 +30,9 @@ public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer play if (te instanceof IGregTechTileEntity igtte) { MetaTileEntity mte = igtte.getMetaTileEntity(); if (mte instanceof SteamBoiler boiler) { - if (boiler.isBurning()) { - // Boiler is active - int steamOutput = boiler.getTotalSteamOutput(); - + int steamOutput = boiler.getTotalSteamOutput(); + // If we are producing steam, or we have fuel + if (steamOutput > 0 || boiler.isBurning()) { // Creating steam if (steamOutput > 0 && boiler.hasWater()) { probeInfo.text(TextStyleClass.INFO + "{*gregtech.top.energy_production*} " + @@ -42,10 +41,18 @@ public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer play Materials.Steam.getUnlocalizedName() + "*}"); } + // Cooling Down + if (!boiler.isBurning()) { + probeInfo.text(TextStyleClass.INFO.toString() + TextFormatting.RED + + "{*gregtech.top.steam_cooling_down*}"); + } + // Initial heat-up - if (steamOutput <= 0) { + if (steamOutput <= 0 && boiler.getCurrentTemperature() > 0) { + // Current Temperature = the % until the boiler reaches 100 probeInfo.text(TextStyleClass.INFO.toString() + TextFormatting.RED + - "{*gregtech.top.steam_heating_up*}"); + "{*gregtech.top.steam_heating_up*} " + + TextFormattingUtil.formatNumbers(boiler.getCurrentTemperature()) + "%"); } // No water diff --git a/src/main/java/gregtech/loaders/recipe/BatteryRecipes.java b/src/main/java/gregtech/loaders/recipe/BatteryRecipes.java index c23ec372712..41f43499d7f 100644 --- a/src/main/java/gregtech/loaders/recipe/BatteryRecipes.java +++ b/src/main/java/gregtech/loaders/recipe/BatteryRecipes.java @@ -86,7 +86,7 @@ private static void standardBatteries() { // EV ASSEMBLER_RECIPES.recipeBuilder().duration(100).EUt(VA[HV]) .input(cableGtSingle, Aluminium, 2) - .input(plate, BlueSteel, 2) + .input(plate, RedSteel, 2) .fluidInputs(Polytetrafluoroethylene.getFluid(144)) .output(BATTERY_HULL_SMALL_VANADIUM) .buildAndRegister(); @@ -102,7 +102,7 @@ private static void standardBatteries() { // LuV ASSEMBLER_RECIPES.recipeBuilder().duration(300).EUt(VA[IV]) .input(cableGtSingle, NiobiumTitanium, 2) - .input(plate, RedSteel, 18) + .input(plate, BlueSteel, 18) .fluidInputs(Polybenzimidazole.getFluid(144)) .output(BATTERY_HULL_LARGE_VANADIUM) .buildAndRegister(); @@ -281,7 +281,7 @@ private static void gemBatteries() { AUTOCLAVE_RECIPES.recipeBuilder() .input(ENERGIUM_DUST, 9) - .fluidInputs(BlueSteel.getFluid(L / 2)) + .fluidInputs(RedSteel.getFluid(L / 2)) .output(ENERGIUM_CRYSTAL) .duration(150).EUt(192).buildAndRegister(); @@ -307,13 +307,13 @@ private static void gemBatteries() { AUTOCLAVE_RECIPES.recipeBuilder() .input(dust, Lapotron, 15) - .fluidInputs(BlueSteel.getFluid(L * 2)) + .fluidInputs(RedSteel.getFluid(L * 2)) .output(gem, Lapotron) .duration(300).EUt(256).buildAndRegister(); AUTOCLAVE_RECIPES.recipeBuilder() .input(dust, Lapotron, 15) - .fluidInputs(RedSteel.getFluid(L / 2)) + .fluidInputs(BlueSteel.getFluid(L / 2)) .output(gem, Lapotron) .duration(150).EUt(192).buildAndRegister(); diff --git a/src/main/java/gregtech/loaders/recipe/CraftingComponent.java b/src/main/java/gregtech/loaders/recipe/CraftingComponent.java index 1d1debf9b6f..e207b77fdad 100644 --- a/src/main/java/gregtech/loaders/recipe/CraftingComponent.java +++ b/src/main/java/gregtech/loaders/recipe/CraftingComponent.java @@ -546,7 +546,7 @@ public static void initializeComponents() { { 0, new UnificationEntry(OrePrefix.toolHeadBuzzSaw, Materials.Bronze) }, { 1, new UnificationEntry(OrePrefix.toolHeadBuzzSaw, Materials.CobaltBrass) }, { 2, new UnificationEntry(OrePrefix.toolHeadBuzzSaw, Materials.VanadiumSteel) }, - { 3, new UnificationEntry(OrePrefix.toolHeadBuzzSaw, Materials.BlueSteel) }, + { 3, new UnificationEntry(OrePrefix.toolHeadBuzzSaw, Materials.RedSteel) }, { 4, new UnificationEntry(OrePrefix.toolHeadBuzzSaw, Materials.Ultimet) }, { 5, new UnificationEntry(OrePrefix.toolHeadBuzzSaw, Materials.TungstenCarbide) }, { 6, new UnificationEntry(OrePrefix.toolHeadBuzzSaw, Materials.HSSE) }, diff --git a/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java b/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java index e91a9bd2c7a..2b757b217c1 100644 --- a/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java +++ b/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java @@ -1,11 +1,13 @@ package gregtech.loaders.recipe; import gregtech.api.event.MaterialInfoEvent; +import gregtech.common.crafting.DyeableRecipes; import gregtech.loaders.recipe.handlers.DecompositionRecipeHandler; import gregtech.loaders.recipe.handlers.RecipeHandlerList; import gregtech.loaders.recipe.handlers.ToolRecipeHandler; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.registry.ForgeRegistries; public final class GTRecipeManager { @@ -21,6 +23,7 @@ public static void load() { MetaTileEntityLoader.init(); MetaTileEntityMachineRecipeLoader.init(); RecipeHandlerList.register(); + ForgeRegistries.RECIPES.register(new DyeableRecipes()); } public static void loadLatest() { diff --git a/src/main/java/gregtech/loaders/recipe/MetaTileEntityLoader.java b/src/main/java/gregtech/loaders/recipe/MetaTileEntityLoader.java index 192c35d1d16..840fd0077d8 100644 --- a/src/main/java/gregtech/loaders/recipe/MetaTileEntityLoader.java +++ b/src/main/java/gregtech/loaders/recipe/MetaTileEntityLoader.java @@ -1001,6 +1001,35 @@ public static void init() { "PPP", "PFP", "PPP", 'P', new UnificationEntry(OrePrefix.plate, Materials.Neutronium), 'F', new UnificationEntry(OrePrefix.pipeLargeFluid, Materials.Duranium)); + // Quantum Storage Controller + ModHandler.addShapedRecipe(true, "quantum_storage_controller", + MetaTileEntities.QUANTUM_STORAGE_CONTROLLER.getStackForm(), + "PCP", "EHS", "CFC", + 'C', new UnificationEntry(OrePrefix.circuit, Tier.MV), + 'P', new UnificationEntry(OrePrefix.plate, Materials.Steel), + 'H', MetaTileEntities.HULL[GTValues.MV].getStackForm(), + 'F', MetaItems.FIELD_GENERATOR_MV.getStackForm(), + 'E', MetaItems.EMITTER_MV.getStackForm(), + 'S', MetaItems.SENSOR_MV.getStackForm()); + + // Quantum Storage Proxy + ModHandler.addShapedRecipe(true, "quantum_storage_proxy", + MetaTileEntities.QUANTUM_STORAGE_PROXY.getStackForm(), + "PEP", "ACA", "PHP", + 'P', new UnificationEntry(OrePrefix.plate, Materials.Steel), + 'E', MetaItems.EMITTER_MV.getStackForm(), + 'C', new UnificationEntry(OrePrefix.pipeHugeItem, Materials.SterlingSilver), + 'A', MetaItems.ROBOT_ARM_MV.getStackForm(), + 'H', MetaTileEntities.HULL[GTValues.MV].getStackForm()); + + // Quantum Storage Extender + ModHandler.addShapedRecipe(true, "quantum_storage_extender", + MetaTileEntities.QUANTUM_STORAGE_EXTENDER.getStackForm(4), + "PPP", "CHC", "PPP", + 'P', new UnificationEntry(OrePrefix.plate, Materials.Steel), + 'C', new UnificationEntry(OrePrefix.pipeSmallItem, Materials.SterlingSilver), + 'H', MetaTileEntities.HULL[GTValues.MV].getStackForm()); + // Super / Quantum Chests ModHandler.addShapedRecipe(true, "super_chest_lv", MetaTileEntities.QUANTUM_CHEST[0].getStackForm(), "CPC", "PFP", "CPC", 'C', new UnificationEntry(OrePrefix.circuit, Tier.LV), 'P', diff --git a/src/main/java/gregtech/loaders/recipe/MetaTileEntityMachineRecipeLoader.java b/src/main/java/gregtech/loaders/recipe/MetaTileEntityMachineRecipeLoader.java index 39e12fe8af3..1f99174cb3b 100644 --- a/src/main/java/gregtech/loaders/recipe/MetaTileEntityMachineRecipeLoader.java +++ b/src/main/java/gregtech/loaders/recipe/MetaTileEntityMachineRecipeLoader.java @@ -1169,7 +1169,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_IV) .input(cableGtSingle, Platinum, 4) .circuitMeta(1) - .output(LASER_INPUT_HATCH_256[0]) + .output(LASER_OUTPUT_HATCH_256[0]) .duration(300).EUt(VA[IV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1179,7 +1179,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_LuV) .input(cableGtSingle, NiobiumTitanium, 4) .circuitMeta(1) - .output(LASER_INPUT_HATCH_256[1]) + .output(LASER_OUTPUT_HATCH_256[1]) .duration(300).EUt(VA[LuV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1189,7 +1189,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_ZPM) .input(cableGtSingle, VanadiumGallium, 4) .circuitMeta(1) - .output(LASER_INPUT_HATCH_256[2]) + .output(LASER_OUTPUT_HATCH_256[2]) .duration(300).EUt(VA[ZPM]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1199,7 +1199,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_UV) .input(cableGtSingle, YttriumBariumCuprate, 4) .circuitMeta(1) - .output(LASER_INPUT_HATCH_256[3]) + .output(LASER_OUTPUT_HATCH_256[3]) .duration(300).EUt(VA[UV]).buildAndRegister(); // 256A Laser Target Hatches @@ -1210,7 +1210,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_IV) .input(cableGtSingle, Platinum, 4) .circuitMeta(1) - .output(LASER_OUTPUT_HATCH_256[0]) + .output(LASER_INPUT_HATCH_256[0]) .duration(300).EUt(VA[IV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1220,7 +1220,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_LuV) .input(cableGtSingle, NiobiumTitanium, 4) .circuitMeta(1) - .output(LASER_OUTPUT_HATCH_256[1]) + .output(LASER_INPUT_HATCH_256[1]) .duration(300).EUt(VA[LuV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1230,7 +1230,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_ZPM) .input(cableGtSingle, VanadiumGallium, 4) .circuitMeta(1) - .output(LASER_OUTPUT_HATCH_256[2]) + .output(LASER_INPUT_HATCH_256[2]) .duration(300).EUt(VA[ZPM]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1240,7 +1240,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_UV) .input(cableGtSingle, YttriumBariumCuprate, 4) .circuitMeta(1) - .output(LASER_OUTPUT_HATCH_256[3]) + .output(LASER_INPUT_HATCH_256[3]) .duration(300).EUt(VA[UV]).buildAndRegister(); // 1024A Laser Source Hatches @@ -1251,7 +1251,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_IV, 2) .input(cableGtDouble, Platinum, 4) .circuitMeta(2) - .output(LASER_INPUT_HATCH_1024[0]) + .output(LASER_OUTPUT_HATCH_1024[0]) .duration(600).EUt(VA[IV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1261,7 +1261,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_LuV, 2) .input(cableGtDouble, NiobiumTitanium, 4) .circuitMeta(2) - .output(LASER_INPUT_HATCH_1024[1]) + .output(LASER_OUTPUT_HATCH_1024[1]) .duration(600).EUt(VA[LuV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1271,7 +1271,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_ZPM, 2) .input(cableGtDouble, VanadiumGallium, 4) .circuitMeta(2) - .output(LASER_INPUT_HATCH_1024[2]) + .output(LASER_OUTPUT_HATCH_1024[2]) .duration(600).EUt(VA[ZPM]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1281,7 +1281,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_UV, 2) .input(cableGtDouble, YttriumBariumCuprate, 4) .circuitMeta(2) - .output(LASER_INPUT_HATCH_1024[3]) + .output(LASER_OUTPUT_HATCH_1024[3]) .duration(600).EUt(VA[UV]).buildAndRegister(); // 1024A Laser Target Hatches @@ -1292,7 +1292,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_IV, 2) .input(cableGtDouble, Platinum, 4) .circuitMeta(2) - .output(LASER_OUTPUT_HATCH_1024[0]) + .output(LASER_INPUT_HATCH_1024[0]) .duration(600).EUt(VA[IV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1302,7 +1302,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_LuV, 2) .input(cableGtDouble, NiobiumTitanium, 4) .circuitMeta(2) - .output(LASER_OUTPUT_HATCH_1024[1]) + .output(LASER_INPUT_HATCH_1024[1]) .duration(600).EUt(VA[LuV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1312,7 +1312,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_ZPM, 2) .input(cableGtDouble, VanadiumGallium, 4) .circuitMeta(2) - .output(LASER_OUTPUT_HATCH_1024[2]) + .output(LASER_INPUT_HATCH_1024[2]) .duration(600).EUt(VA[ZPM]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1322,7 +1322,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_UV, 2) .input(cableGtDouble, YttriumBariumCuprate, 4) .circuitMeta(2) - .output(LASER_OUTPUT_HATCH_1024[3]) + .output(LASER_INPUT_HATCH_1024[3]) .duration(600).EUt(VA[UV]).buildAndRegister(); // 4096A Laser Source Hatches @@ -1333,7 +1333,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_IV, 4) .input(cableGtQuadruple, Platinum, 4) .circuitMeta(3) - .output(LASER_INPUT_HATCH_4096[0]) + .output(LASER_OUTPUT_HATCH_4096[0]) .duration(1200).EUt(VA[IV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1343,7 +1343,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_LuV, 4) .input(cableGtQuadruple, NiobiumTitanium, 4) .circuitMeta(3) - .output(LASER_INPUT_HATCH_4096[1]) + .output(LASER_OUTPUT_HATCH_4096[1]) .duration(1200).EUt(VA[LuV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1353,7 +1353,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_ZPM, 4) .input(cableGtQuadruple, VanadiumGallium, 4) .circuitMeta(3) - .output(LASER_INPUT_HATCH_4096[2]) + .output(LASER_OUTPUT_HATCH_4096[2]) .duration(1200).EUt(VA[ZPM]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1363,7 +1363,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_UV, 4) .input(cableGtQuadruple, YttriumBariumCuprate, 4) .circuitMeta(3) - .output(LASER_INPUT_HATCH_4096[3]) + .output(LASER_OUTPUT_HATCH_4096[3]) .duration(1200).EUt(VA[UV]).buildAndRegister(); // 4096A Laser Target Hatches @@ -1374,7 +1374,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_IV, 4) .input(cableGtQuadruple, Platinum, 4) .circuitMeta(3) - .output(LASER_OUTPUT_HATCH_4096[0]) + .output(LASER_INPUT_HATCH_4096[0]) .duration(1200).EUt(VA[IV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1384,7 +1384,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_LuV, 4) .input(cableGtQuadruple, NiobiumTitanium, 4) .circuitMeta(3) - .output(LASER_OUTPUT_HATCH_4096[1]) + .output(LASER_INPUT_HATCH_4096[1]) .duration(1200).EUt(VA[LuV]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1394,7 +1394,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_ZPM, 4) .input(cableGtQuadruple, VanadiumGallium, 4) .circuitMeta(3) - .output(LASER_OUTPUT_HATCH_4096[2]) + .output(LASER_INPUT_HATCH_4096[2]) .duration(1200).EUt(VA[ZPM]).buildAndRegister(); ASSEMBLER_RECIPES.recipeBuilder() @@ -1404,7 +1404,7 @@ private static void registerLaserRecipes() { .input(ELECTRIC_PUMP_UV, 4) .input(cableGtQuadruple, YttriumBariumCuprate, 4) .circuitMeta(3) - .output(LASER_OUTPUT_HATCH_4096[3]) + .output(LASER_INPUT_HATCH_4096[3]) .duration(1200).EUt(VA[UV]).buildAndRegister(); } } diff --git a/src/main/java/gregtech/loaders/recipe/chemistry/ChemicalBathRecipes.java b/src/main/java/gregtech/loaders/recipe/chemistry/ChemicalBathRecipes.java index 56904e7dd4f..bcc82139fd2 100644 --- a/src/main/java/gregtech/loaders/recipe/chemistry/ChemicalBathRecipes.java +++ b/src/main/java/gregtech/loaders/recipe/chemistry/ChemicalBathRecipes.java @@ -102,5 +102,41 @@ public static void init() { .fluidInputs(DistilledWater.getFluid(100)) .output(ingot, Silicon) .duration(125).EUt(VA[MV]).buildAndRegister(); + + CHEMICAL_BATH_RECIPES.recipeBuilder() + .input(ingotHot, BlackSteel) + .fluidInputs(Water.getFluid(100)) + .output(ingot, BlackSteel) + .duration(200).EUt(VA[MV]).buildAndRegister(); + + CHEMICAL_BATH_RECIPES.recipeBuilder() + .input(ingotHot, BlackSteel) + .fluidInputs(DistilledWater.getFluid(100)) + .output(ingot, BlackSteel) + .duration(125).EUt(VA[MV]).buildAndRegister(); + + CHEMICAL_BATH_RECIPES.recipeBuilder() + .input(ingotHot, RedSteel) + .fluidInputs(Water.getFluid(100)) + .output(ingot, RedSteel) + .duration(400).EUt(VA[MV]).buildAndRegister(); + + CHEMICAL_BATH_RECIPES.recipeBuilder() + .input(ingotHot, RedSteel) + .fluidInputs(DistilledWater.getFluid(100)) + .output(ingot, RedSteel) + .duration(250).EUt(VA[MV]).buildAndRegister(); + + CHEMICAL_BATH_RECIPES.recipeBuilder() + .input(ingotHot, BlueSteel) + .fluidInputs(Water.getFluid(100)) + .output(ingot, BlueSteel) + .duration(400).EUt(VA[MV]).buildAndRegister(); + + CHEMICAL_BATH_RECIPES.recipeBuilder() + .input(ingotHot, BlueSteel) + .fluidInputs(DistilledWater.getFluid(100)) + .output(ingot, BlueSteel) + .duration(250).EUt(VA[MV]).buildAndRegister(); } } diff --git a/src/main/java/gregtech/loaders/recipe/chemistry/MixerRecipes.java b/src/main/java/gregtech/loaders/recipe/chemistry/MixerRecipes.java index c0edbab21b7..95bc9ced2df 100644 --- a/src/main/java/gregtech/loaders/recipe/chemistry/MixerRecipes.java +++ b/src/main/java/gregtech/loaders/recipe/chemistry/MixerRecipes.java @@ -288,7 +288,7 @@ public static void init() { .input(dust, BlackSteel, 4) .input(dust, Steel, 2) .circuitMeta(1) - .output(dust, BlueSteel, 8) + .output(dust, RedSteel, 8) .buildAndRegister(); MIXER_RECIPES.recipeBuilder().duration(800).EUt(VA[ULV]) @@ -297,7 +297,7 @@ public static void init() { .input(dust, BlackSteel, 4) .input(dust, Steel, 2) .circuitMeta(1) - .output(dust, RedSteel, 8) + .output(dust, BlueSteel, 8) .buildAndRegister(); MIXER_RECIPES.recipeBuilder().duration(900).EUt(VA[ULV]) diff --git a/src/main/java/gregtech/loaders/recipe/handlers/MaterialRecipeHandler.java b/src/main/java/gregtech/loaders/recipe/handlers/MaterialRecipeHandler.java index cbdf94add16..3b048b093c6 100644 --- a/src/main/java/gregtech/loaders/recipe/handlers/MaterialRecipeHandler.java +++ b/src/main/java/gregtech/loaders/recipe/handlers/MaterialRecipeHandler.java @@ -91,28 +91,28 @@ public static void processDust(OrePrefix dustPrefix, Material mat, DustProperty .inputs(GTUtility.copy(4, dustStack)) .outputs(GTUtility.copy(3, gemStack)) .chancedOutput(dust, Materials.DarkAsh, 2500, 0) - .explosivesType(new ItemStack(MetaBlocks.POWDERBARREL, 8)) + .explosives(new ItemStack(MetaBlocks.POWDERBARREL, 8)) .buildAndRegister(); RecipeMaps.IMPLOSION_RECIPES.recipeBuilder() .inputs(GTUtility.copy(4, dustStack)) .outputs(GTUtility.copy(3, gemStack)) .chancedOutput(dust, Materials.DarkAsh, 2500, 0) - .explosivesAmount(4) + .explosives(4) .buildAndRegister(); RecipeMaps.IMPLOSION_RECIPES.recipeBuilder() .inputs(GTUtility.copy(4, dustStack)) .outputs(GTUtility.copy(3, gemStack)) .chancedOutput(dust, Materials.DarkAsh, 2500, 0) - .explosivesType(MetaItems.DYNAMITE.getStackForm(2)) + .explosives(MetaItems.DYNAMITE.getStackForm(2)) .buildAndRegister(); RecipeMaps.IMPLOSION_RECIPES.recipeBuilder() .inputs(GTUtility.copy(4, dustStack)) .outputs(GTUtility.copy(3, gemStack)) .chancedOutput(dust, Materials.DarkAsh, 2500, 0) - .explosivesType(new ItemStack(MetaBlocks.ITNT)) + .explosives(new ItemStack(MetaBlocks.ITNT)) .buildAndRegister(); } diff --git a/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java b/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java index 1997631a38c..84e5cd91450 100644 --- a/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java +++ b/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java @@ -19,6 +19,7 @@ import gregtech.common.items.MetaItems; import gregtech.common.items.ToolItems; +import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.ResourceLocation; @@ -215,6 +216,14 @@ private static void processTool(OrePrefix prefix, Material material, ToolPropert } } + if (material.hasFlag(GENERATE_BOLT_SCREW) && material.hasFlag(GENERATE_RING)) { + addToolRecipe(material, ToolItems.TOOLBELT, false, + "SSS", "LLL", "RSR", + 'L', Items.LEATHER, + 'S', new UnificationEntry(OrePrefix.screw, material), + 'R', new UnificationEntry(OrePrefix.ring, material)); + } + addToolRecipe(material, ToolItems.SCREWDRIVER, true, " fS", " Sh", "W ", 'S', rod, diff --git a/src/main/java/gregtech/mixins/GregTechLateMixinLoadingPlugin.java b/src/main/java/gregtech/mixins/GregTechLateMixinLoadingPlugin.java index a582e924088..f26eacee77a 100644 --- a/src/main/java/gregtech/mixins/GregTechLateMixinLoadingPlugin.java +++ b/src/main/java/gregtech/mixins/GregTechLateMixinLoadingPlugin.java @@ -19,6 +19,8 @@ public List getMixinConfigs() { configs.add("mixins.gregtech.ccl.json"); configs.add("mixins.gregtech.littletiles.json"); configs.add("mixins.gregtech.vintagium.json"); + configs.add("mixins.gregtech.mui2.json"); + configs.add("mixins.gregtech.nothirium.json"); return configs; } @@ -31,6 +33,7 @@ public boolean shouldMixinConfigQueue(String mixinConfig) { case "mixin.gregtech.ctm.json" -> Mods.CTM.isModLoaded(); case "mixins.gregtech.littletiles.json" -> Mods.LittleTiles.isModLoaded(); case "mixins.gregtech.vintagium.json" -> Mods.Vintagium.isModLoaded(); + case "mixins.gregtech.nothirium.json" -> Mods.Nothirium.isModLoaded(); default -> true; }; } diff --git a/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java b/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java new file mode 100644 index 00000000000..b34c7b1d416 --- /dev/null +++ b/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java @@ -0,0 +1,30 @@ +package gregtech.mixins.forge; + +import gregtech.api.items.toolitem.ItemGTToolbelt; +import gregtech.common.ConfigHolder; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiIngame; +import net.minecraftforge.client.GuiIngameForge; + +import com.llamalad7.mixinextras.injector.ModifyExpressionValue; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(GuiIngameForge.class) +public class GuiIngameForgeMixin extends GuiIngame { + + private GuiIngameForgeMixin(Minecraft mcIn) { + super(mcIn); + } + + @ModifyExpressionValue(method = "renderToolHighlight", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/gui/ScaledResolution;getScaledHeight()I")) + private int shiftToolHighlightText(int y) { + if (ConfigHolder.client.toolbeltConfig.enableToolbeltHotbarDisplay && + highlightingItemStack.getItem() instanceof ItemGTToolbelt) + return y - 31 + 6; + else return y; + } +} diff --git a/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java b/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java new file mode 100644 index 00000000000..b9a3641343c --- /dev/null +++ b/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java @@ -0,0 +1,22 @@ +package gregtech.mixins.forge; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreIngredient; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(OreIngredient.class) +public abstract class OreIngredientMixin { + + @Inject(method = "apply(Lnet/minecraft/item/ItemStack;)Z", at = @At("HEAD"), cancellable = true) + private void checkToolbelt(ItemStack input, CallbackInfoReturnable cir) { + if (ItemGTToolbelt.checkIngredientAgainstToolbelt(input, (OreIngredient) (Object) this)) { + cir.setReturnValue(true); + } + } +} diff --git a/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java b/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java new file mode 100644 index 00000000000..cbd4a6c140d --- /dev/null +++ b/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java @@ -0,0 +1,79 @@ +package gregtech.mixins.jei; + +import gregtech.api.items.toolitem.ToolHelper; + +import net.minecraft.item.ItemStack; + +import com.llamalad7.mixinextras.injector.ModifyExpressionValue; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.sugar.Local; +import com.llamalad7.mixinextras.sugar.Share; +import com.llamalad7.mixinextras.sugar.ref.LocalRef; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import mezz.jei.transfer.BasicRecipeTransferHandlerServer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.Iterator; +import java.util.Map; + +@Mixin(value = BasicRecipeTransferHandlerServer.class, remap = false) +public class BasicRecipeTransferHandlerServerMixin { + + /** + * @reason create the list used to indicate what slots contain tools, and thus should be ignored on the 2nd+ checks + */ + @Inject(method = "removeItemsFromInventory", at = @At("HEAD")) + private static void gregtechCEu$initCompletedList(CallbackInfoReturnable> cir, + @Share("completed") LocalRef completed) { + completed.set(new IntArrayList()); + } + + /** + * @reason add the index of the entry to the list of skipped locations on the 2nd+ checks + */ + @Inject(method = "removeItemsFromInventory", + at = @At(value = "INVOKE", + target = "Ljava/util/Map;put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", + ordinal = 1)) + private static void gregtechCEu$markItemStackAsCompleted(CallbackInfoReturnable> cir, + @Local(ordinal = 0) Map.Entry entry, + @Local(ordinal = 2) ItemStack removedItemStack, + @Share("completed") LocalRef completed) { + // mark tool stacks as 'permanently' satisfied + if (removedItemStack != null && ToolHelper.isTool(removedItemStack)) completed.get().add(entry.getKey()); + } + + /** + * @reason if the given location is marked as completed, skip processing this slot and check the next slot + */ + @ModifyExpressionValue(method = "removeItemsFromInventory", + at = @At(value = "INVOKE", target = "Ljava/util/Iterator;hasNext()Z", ordinal = 0)) + private static boolean gregtechCEu$skipCompletedStacks(boolean original, + @Local(ordinal = 0) Iterator> iterator, + @Share("completed") LocalRef completed, + @Share("iterator_next") LocalRef> next) { + if (!original) return false; + next.set(iterator.next()); + while (completed.get().contains(next.get().getKey())) { + if (!iterator.hasNext()) return false; + next.set(iterator.next()); + } + return true; + } + + /** + * @reason use the next variable that respects the completed status + */ + @WrapOperation(method = "removeItemsFromInventory", + at = @At(value = "INVOKE", target = "Ljava/util/Iterator;next()Ljava/lang/Object;", ordinal = 0)) + private static Object gregtechCEu$useCorrectIteratorNext(Iterator> instance, + Operation> original, + @Share("completed") LocalRef completed, + @Share("iterator_next") LocalRef> next) { + return next.get() == null ? original.call(instance) : next.get(); + } +} diff --git a/src/main/java/gregtech/mixins/jei/IngredientGridMixin.java b/src/main/java/gregtech/mixins/jei/IngredientGridMixin.java new file mode 100644 index 00000000000..2b876ca38b8 --- /dev/null +++ b/src/main/java/gregtech/mixins/jei/IngredientGridMixin.java @@ -0,0 +1,30 @@ +package gregtech.mixins.jei; + +import net.minecraft.client.Minecraft; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import mezz.jei.gui.GuiScreenHelper; +import mezz.jei.gui.overlay.IngredientGrid; +import mezz.jei.gui.overlay.IngredientGridWithNavigation; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(value = IngredientGridWithNavigation.class, remap = false) +public class IngredientGridMixin { + + @Shadow + @Final + private GuiScreenHelper guiScreenHelper; + + @WrapOperation(method = "drawTooltips", + at = @At(value = "INVOKE", + target = "Lmezz/jei/gui/overlay/IngredientGrid;drawTooltips(Lnet/minecraft/client/Minecraft;II)V")) + private void considerExclusions(IngredientGrid instance, Minecraft minecraft, int mouseX, int mouseY, + Operation original) { + if (!guiScreenHelper.isInGuiExclusionArea(mouseX, mouseY)) + original.call(instance, minecraft, mouseX, mouseY); + } +} diff --git a/src/main/java/gregtech/mixins/jei/StackHelperMixin.java b/src/main/java/gregtech/mixins/jei/StackHelperMixin.java new file mode 100644 index 00000000000..16906220c90 --- /dev/null +++ b/src/main/java/gregtech/mixins/jei/StackHelperMixin.java @@ -0,0 +1,22 @@ +package gregtech.mixins.jei; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.item.ItemStack; + +import mezz.jei.startup.StackHelper; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(StackHelper.class) +public class StackHelperMixin { + + @Inject(method = "isEquivalent", at = @At(value = "RETURN", ordinal = 2), cancellable = true, remap = false) + private void toolbeltIsEquivalent(ItemStack lhs, ItemStack rhs, CallbackInfoReturnable cir) { + if (ItemGTToolbelt.checkToolAgainstToolbelt(rhs, lhs)) { + cir.setReturnValue(true); + } + } +} diff --git a/src/main/java/gregtech/mixins/minecraft/BlockRenderLayerMixin.java b/src/main/java/gregtech/mixins/minecraft/BlockRenderLayerMixin.java new file mode 100644 index 00000000000..d3c352a94dd --- /dev/null +++ b/src/main/java/gregtech/mixins/minecraft/BlockRenderLayerMixin.java @@ -0,0 +1,31 @@ +package gregtech.mixins.minecraft; + +import net.minecraft.util.BlockRenderLayer; + +import org.apache.commons.lang3.ArrayUtils; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(BlockRenderLayer.class) +public class BlockRenderLayerMixin { + + @Final + @Shadow + @Mutable + private static BlockRenderLayer[] $VALUES; + + @SuppressWarnings("all") + @Invoker("") + private static BlockRenderLayer create(String name, int ordinal, String directoryName) { + throw new IllegalStateException("Unreachable"); + } + + static { + BlockRenderLayer bloom = create("BLOOM", $VALUES.length, "Bloom"); + + $VALUES = ArrayUtils.add($VALUES, bloom); + } +} diff --git a/src/main/java/gregtech/mixins/minecraft/ContainerMixin.java b/src/main/java/gregtech/mixins/minecraft/ContainerMixin.java new file mode 100644 index 00000000000..9f1e2afa6ec --- /dev/null +++ b/src/main/java/gregtech/mixins/minecraft/ContainerMixin.java @@ -0,0 +1,30 @@ +package gregtech.mixins.minecraft; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.ClickType; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(Container.class) +public abstract class ContainerMixin { + + @Inject(method = "slotClick", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/item/ItemStack;splitStack(I)Lnet/minecraft/item/ItemStack;", + ordinal = 1)) + private void setPlayer(int slotId, int dragType, ClickType clickTypeIn, EntityPlayer player, + CallbackInfoReturnable cir) { + var playerStack = player.inventory.getItemStack(); + if (player instanceof EntityPlayerMP serverPlayer && playerStack.getItem() instanceof ItemGTToolbelt) { + ItemGTToolbelt.setCraftingSlot(slotId, serverPlayer); + } + } +} diff --git a/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java b/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java index 31ada3545f0..0bba8ad4f03 100644 --- a/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java +++ b/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java @@ -1,12 +1,19 @@ package gregtech.mixins.minecraft; +import gregtech.api.items.toolitem.ItemGTToolbelt; +import gregtech.common.ConfigHolder; + import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextComponentTranslation; import org.lwjgl.input.Keyboard; +import org.objectweb.asm.Opcodes; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Minecraft.class) @@ -19,4 +26,20 @@ public void addGregTechDebugMessage(int auxKey, CallbackInfoReturnable .printChatMessage(new TextComponentTranslation("gregtech.debug.f3_h.enabled")); } } + + @Redirect(method = "processKeyBinds", + at = @At(value = "FIELD", + target = "Lnet/minecraft/entity/player/InventoryPlayer;currentItem:I", + opcode = Opcodes.PUTFIELD)) + public void interceptHotbarKeybindsForToolbelt(InventoryPlayer inventoryPlayer, int i) { + if (!ConfigHolder.client.toolbeltConfig.enableToolbeltKeypressCapture) return; + if (inventoryPlayer.player.isSneaking()) { + ItemStack stack = inventoryPlayer.player.getHeldItemMainhand(); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + toolbelt.changeSelectedToolHotkey(i, stack); + return; + } + } + inventoryPlayer.currentItem = i; + } } diff --git a/src/main/java/gregtech/mixins/minecraft/RecipeRepairItemMixin.java b/src/main/java/gregtech/mixins/minecraft/RecipeRepairItemMixin.java index 5cd275b6cf8..dd76f8d959c 100644 --- a/src/main/java/gregtech/mixins/minecraft/RecipeRepairItemMixin.java +++ b/src/main/java/gregtech/mixins/minecraft/RecipeRepairItemMixin.java @@ -1,6 +1,7 @@ package gregtech.mixins.minecraft; import gregtech.api.items.toolitem.IGTTool; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolHelper; import net.minecraft.inventory.InventoryCrafting; @@ -36,7 +37,8 @@ public class RecipeRepairItemMixin { ItemStack itemstack1 = list.get(0); if (itemstack.getItem() instanceof IGTTool first && itemstack1.getItem() instanceof IGTTool second) { - if (first.isElectric() || second.isElectric()) { + if (first.isElectric() || second.isElectric() || + first instanceof ItemGTToolbelt || second instanceof ItemGTToolbelt) { cir.setReturnValue(false); } else { cir.setReturnValue(first.getToolMaterial(itemstack) == second.getToolMaterial(itemstack1)); diff --git a/src/main/java/gregtech/mixins/mui2/ClientEventHandlerMixin.java b/src/main/java/gregtech/mixins/mui2/ClientEventHandlerMixin.java new file mode 100644 index 00000000000..678de031802 --- /dev/null +++ b/src/main/java/gregtech/mixins/mui2/ClientEventHandlerMixin.java @@ -0,0 +1,79 @@ +package gregtech.mixins.mui2; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.client.event.GuiScreenEvent; + +import com.cleanroommc.modularui.ClientEventHandler; +import com.cleanroommc.modularui.api.IMuiScreen; +import com.cleanroommc.modularui.core.mixin.GuiScreenAccessor; +import com.cleanroommc.modularui.screen.ClientScreenHandler; +import com.cleanroommc.modularui.screen.ModularScreen; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.io.IOException; + +@Mixin(value = ClientEventHandler.class, remap = false) +@SuppressWarnings("UnstableApiUsage") +public abstract class ClientEventHandlerMixin { + + @Redirect(method = "onGuiInput(Lnet/minecraftforge/client/event/GuiScreenEvent$MouseInputEvent$Pre;)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiScreen;handleMouseInput()V")) + private static void fixMouseInput(GuiScreen instance) { + int button = Mouse.getEventButton(); + if (instance instanceof IMuiScreen screen && instance instanceof GuiScreenAccessor acc) { + ModularScreen ms = screen.getScreen(); + if (Mouse.getEventButtonState()) { + acc.setEventButton(button); + acc.setLastMouseEvent(Minecraft.getSystemTime()); + ms.onMousePressed(button); + + } else if (button != -1) { + acc.setEventButton(-1); + ms.onMouseRelease(button); + + } else if (acc.getEventButton() != -1 && acc.getLastMouseEvent() > 0L) { + long l = Minecraft.getSystemTime() - acc.getLastMouseEvent(); + ms.onMouseDrag(button, l); + } + } + } + + @Inject(method = "onGuiInput(Lnet/minecraftforge/client/event/GuiScreenEvent$MouseInputEvent$Pre;)V", + at = @At("TAIL")) + private static void fixScrollJei(GuiScreenEvent.MouseInputEvent.Pre event, CallbackInfo ci) throws IOException { + if (!event.isCanceled()) + ClientScreenHandler.onGuiInputLow(event); + } + + @Unique + private static Character gregTech$lastChar = null; + + @Redirect(method = "onGuiInput(Lnet/minecraftforge/client/event/GuiScreenEvent$KeyboardInputEvent$Pre;)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiScreen;handleKeyboardInput()V")) + private static void fixKeyInput(GuiScreen instance) { + if (instance instanceof IMuiScreen screen && instance instanceof GuiScreenAccessor acc) { + char c0 = Keyboard.getEventCharacter(); + int key = Keyboard.getEventKey(); + boolean state = Keyboard.getEventKeyState(); + if (state) { + gregTech$lastChar = c0; + screen.getScreen().onKeyPressed(c0, key); + } else { + // releasing a key + // for some reason when you press E after joining a world the button will not trigger the press event, + // but only the release event, causing this to be null + if (gregTech$lastChar == null) return; + // when the key is released, the event char is empty + screen.getScreen().onKeyRelease(gregTech$lastChar, key); + } + } + } +} diff --git a/src/main/java/gregtech/mixins/mui2/ItemSlotSHMixin.java b/src/main/java/gregtech/mixins/mui2/ItemSlotSHMixin.java new file mode 100644 index 00000000000..5d53a35d3d0 --- /dev/null +++ b/src/main/java/gregtech/mixins/mui2/ItemSlotSHMixin.java @@ -0,0 +1,141 @@ +package gregtech.mixins.mui2; + +import net.minecraft.item.ItemStack; +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.items.ItemHandlerHelper; + +import com.cleanroommc.modularui.network.NetworkUtils; +import com.cleanroommc.modularui.screen.ModularContainer; +import com.cleanroommc.modularui.utils.MouseData; +import com.cleanroommc.modularui.value.sync.ItemSlotSH; +import com.cleanroommc.modularui.value.sync.SyncHandler; +import com.cleanroommc.modularui.widgets.slot.ModularSlot; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.io.IOException; + +@Mixin(value = ItemSlotSH.class, remap = false) +public abstract class ItemSlotSHMixin extends SyncHandler { + + @Unique + private boolean gregTech$registered; + + @Shadow + protected abstract void phantomScroll(MouseData mouseData); + + @Shadow + public abstract void setEnabled(boolean enabled, boolean sync); + + @Shadow + public abstract boolean isPhantom(); + + @Shadow + private ItemStack lastStoredPhantomItem; + + @Shadow + public abstract ModularSlot getSlot(); + + @Shadow + public abstract void incrementStackCount(int amount); + + @WrapOperation(method = "init", + at = @At(value = "INVOKE", + target = "Lcom/cleanroommc/modularui/screen/ModularContainer;registerSlot(Ljava/lang/String;Lcom/cleanroommc/modularui/widgets/slot/ModularSlot;)V")) + protected void wrapRegister(ModularContainer instance, String slotGroup, ModularSlot modularSlot, + Operation original) { + if (!gregTech$registered) { + original.call(instance, slotGroup, modularSlot); + gregTech$registered = true; + } + } + + /** + * @author GTCEu - Ghzdude + * @reason Implement MUI2 PR#90 + */ + @Overwrite + public void readOnServer(int id, PacketBuffer buf) throws IOException { + if (id == 2) { + phantomClick(MouseData.readPacket(buf)); + } else if (id == 3) { + phantomScroll(MouseData.readPacket(buf)); + } else if (id == 4) { + setEnabled(buf.readBoolean(), false); + } else if (id == 5) { + if (!isPhantom()) return; + gregTech$phantomClick(MouseData.create(0), buf.readItemStack()); + } + } + + @Inject(method = "readOnClient", at = @At("HEAD")) + protected void handlePhantomScroll(int id, PacketBuffer buf, CallbackInfo ci) { + if (id == 3) { + this.lastStoredPhantomItem = NetworkUtils.readItemStack(buf); + getSlot().putStack(this.lastStoredPhantomItem.copy()); + } + } + + @Inject(method = "phantomScroll", at = @At("TAIL")) + protected void syncPhantomScroll(MouseData mouseData, CallbackInfo ci) { + syncToClient(3, buffer -> NetworkUtils.writeItemStack(buffer, this.lastStoredPhantomItem)); + } + + /** + * @author GTCEu - Ghzdude + * @reason Implement MUI2 PR#90 + */ + @Overwrite + protected void phantomClick(MouseData mouseData) { + gregTech$phantomClick(mouseData, getSyncManager().getCursorItem()); + } + + @Unique + protected void gregTech$phantomClick(MouseData mouseData, ItemStack cursorStack) { + ItemStack slotStack = getSlot().getStack(); + ItemStack stackToPut; + if (!cursorStack.isEmpty() && !slotStack.isEmpty() && + !ItemHandlerHelper.canItemStacksStack(cursorStack, slotStack)) { + stackToPut = cursorStack.copy(); + if (mouseData.mouseButton == 1) { + stackToPut.setCount(1); + } + stackToPut.setCount(Math.min(stackToPut.getCount(), getSlot().getItemStackLimit(stackToPut))); + getSlot().putStack(stackToPut); + this.lastStoredPhantomItem = stackToPut.copy(); + } else if (slotStack.isEmpty()) { + if (cursorStack.isEmpty()) { + if (mouseData.mouseButton == 1 && !this.lastStoredPhantomItem.isEmpty()) { + stackToPut = this.lastStoredPhantomItem.copy(); + } else { + return; + } + } else { + stackToPut = cursorStack.copy(); + } + if (mouseData.mouseButton == 1) { + stackToPut.setCount(1); + } + stackToPut.setCount(Math.min(stackToPut.getCount(), getSlot().getItemStackLimit(stackToPut))); + getSlot().putStack(stackToPut); + this.lastStoredPhantomItem = stackToPut.copy(); + } else { + if (mouseData.mouseButton == 0) { + if (mouseData.shift) { + getSlot().putStack(ItemStack.EMPTY); + } else { + incrementStackCount(-1); + } + } else if (mouseData.mouseButton == 1) { + incrementStackCount(1); + } + } + } +} diff --git a/src/main/java/gregtech/mixins/mui2/PanelSyncHandlerMixin.java b/src/main/java/gregtech/mixins/mui2/PanelSyncHandlerMixin.java new file mode 100644 index 00000000000..99a850b1c10 --- /dev/null +++ b/src/main/java/gregtech/mixins/mui2/PanelSyncHandlerMixin.java @@ -0,0 +1,47 @@ +package gregtech.mixins.mui2; + +import com.cleanroommc.modularui.api.widget.ISynced; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.ModularSyncManager; +import com.cleanroommc.modularui.value.sync.PanelSyncHandler; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.widget.WidgetTree; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.concurrent.atomic.AtomicInteger; + +@Mixin(value = PanelSyncHandler.class, remap = false) +public abstract class PanelSyncHandlerMixin { + + @Shadow + private PanelSyncManager syncManager; + + @Shadow + public abstract boolean isPanelOpen(); + + @Redirect(method = "openPanel(Z)V", + at = @At(value = "INVOKE", + target = "Lcom/cleanroommc/modularui/widget/WidgetTree;collectSyncValues(Lcom/cleanroommc/modularui/value/sync/PanelSyncManager;Lcom/cleanroommc/modularui/screen/ModularPanel;)V")) + protected void redirectCollectValues(PanelSyncManager syncManager, ModularPanel panel) { + AtomicInteger id = new AtomicInteger(0); + String syncKey = ModularSyncManager.AUTO_SYNC_PREFIX + panel.getName(); + WidgetTree.foreachChildBFS(panel, widget -> { + if (widget instanceof ISyncedsynced) { + if (synced.isSynced() && !this.syncManager.hasSyncHandler(synced.getSyncHandler())) { + this.syncManager.syncValue(syncKey, id.getAndIncrement(), synced.getSyncHandler()); + } + } + return true; + }, false); + } + + @Inject(method = "openPanel(Z)V", at = @At("HEAD"), cancellable = true) + protected void openCheck(boolean syncToServer, CallbackInfo ci) { + if (isPanelOpen()) ci.cancel(); + } +} diff --git a/src/main/java/gregtech/mixins/mui2/PanelSyncManagerMixin.java b/src/main/java/gregtech/mixins/mui2/PanelSyncManagerMixin.java new file mode 100644 index 00000000000..9bea0ab1af2 --- /dev/null +++ b/src/main/java/gregtech/mixins/mui2/PanelSyncManagerMixin.java @@ -0,0 +1,36 @@ +package gregtech.mixins.mui2; + +import gregtech.api.util.GTLog; + +import net.minecraft.network.PacketBuffer; + +import com.cleanroommc.modularui.value.sync.PanelSyncManager; +import com.cleanroommc.modularui.value.sync.SyncHandler; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.Map; + +@Mixin(value = PanelSyncManager.class, remap = false) +public abstract class PanelSyncManagerMixin { + + @Shadow + @Final + private Map syncHandlers; + + @Shadow + private String panelName; + + @Inject(method = "receiveWidgetUpdate", at = @At("HEAD"), cancellable = true) + public void injectCheck(String mapKey, int id, PacketBuffer buf, CallbackInfo ci) { + if (!this.syncHandlers.containsKey(mapKey)) { + GTLog.logger.warn("[ModularUI] SyncHandler \"{}\" does not exist for panel \"{}\"! ID was {}.", mapKey, + panelName, id); + ci.cancel(); + } + } +} diff --git a/src/main/java/gregtech/mixins/mui2/StyledTextMixin.java b/src/main/java/gregtech/mixins/mui2/StyledTextMixin.java new file mode 100644 index 00000000000..41c269111ab --- /dev/null +++ b/src/main/java/gregtech/mixins/mui2/StyledTextMixin.java @@ -0,0 +1,119 @@ +package gregtech.mixins.mui2; + +import gregtech.api.mui.UnboxFix; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.drawable.text.AnimatedText; +import com.cleanroommc.modularui.drawable.text.StyledText; +import com.cleanroommc.modularui.theme.WidgetTheme; +import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.widgets.TextWidget; +import com.llamalad7.mixinextras.sugar.Local; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(value = StyledText.class, remap = false) +public abstract class StyledTextMixin implements UnboxFix { + + @Shadow + @Final + private IKey key; + + @Shadow + private Alignment alignment; + + @Shadow + private Integer color; + + @Shadow + private float scale; + + @Shadow + private Boolean shadow; + + @Unique + private boolean gregTech$defaultTextColor = true; + + @Unique + private boolean gregTech$defaultShadow = true; + + @Override + public void gregTech$useDefaultTextColor(boolean b) { + gregTech$defaultTextColor = b; + } + + @Override + public void gregTech$useDefaultShadow(boolean b) { + gregTech$defaultShadow = b; + } + + @Inject(method = "color", at = @At("HEAD")) + private void setDefault(int color, CallbackInfoReturnable cir) { + gregTech$useDefaultTextColor(false); + } + + @Inject(method = "shadow", at = @At("HEAD")) + private void setDefault(boolean shadow, CallbackInfoReturnable cir) { + gregTech$useDefaultShadow(false); + } + + /** + * @author GTCEu - Ghzdude + * @reason Implement MUI2 PR#86 + */ + @Overwrite + public TextWidget asWidget() { + var text = new TextWidget(this.key) + .alignment(this.alignment) + .scale(this.scale); + + ((UnboxFix) text).gregTech$useDefaultTextColor(this.gregTech$defaultTextColor); + ((UnboxFix) text).gregTech$useDefaultShadow(this.gregTech$defaultShadow); + + return text.color(color == null ? 0 : color) + .shadow(shadow != null && shadow); + } + + /** + * @author GTCEu - Ghzdude + * @reason Implement MUI2 PR#86 + */ + @Overwrite + public AnimatedText withAnimation() { + var text = new AnimatedText(this.key) + .alignment(this.alignment) + .scale(this.scale); + + ((UnboxFix) text).gregTech$useDefaultTextColor(this.gregTech$defaultTextColor); + ((UnboxFix) text).gregTech$useDefaultShadow(this.gregTech$defaultShadow); + + return text.color(color == null ? 0 : color) + .shadow(shadow != null && shadow); + } + + @SideOnly(Side.CLIENT) + @ModifyArg(method = "draw", + at = @At(value = "INVOKE", + target = "Lcom/cleanroommc/modularui/drawable/text/TextRenderer;setColor(I)V")) + public int fixColor(int color, @Local(argsOnly = true) WidgetTheme theme) { + return gregTech$defaultTextColor ? theme.getTextColor() : color; + } + + @SideOnly(Side.CLIENT) + @ModifyArg(method = "draw", + at = @At(value = "INVOKE", + target = "Lcom/cleanroommc/modularui/drawable/text/TextRenderer;setShadow(Z)V")) + public boolean fixShadow(boolean shadow, @Local(argsOnly = true) WidgetTheme theme) { + return gregTech$defaultShadow ? theme.getTextShadow() : shadow; + } +} diff --git a/src/main/java/gregtech/mixins/mui2/TextWidgetMixin.java b/src/main/java/gregtech/mixins/mui2/TextWidgetMixin.java new file mode 100644 index 00000000000..40320a51020 --- /dev/null +++ b/src/main/java/gregtech/mixins/mui2/TextWidgetMixin.java @@ -0,0 +1,57 @@ +package gregtech.mixins.mui2; + +import gregtech.api.mui.UnboxFix; + +import com.cleanroommc.modularui.theme.WidgetTheme; +import com.cleanroommc.modularui.widget.Widget; +import com.cleanroommc.modularui.widgets.TextWidget; +import com.llamalad7.mixinextras.injector.ModifyReturnValue; +import com.llamalad7.mixinextras.sugar.Local; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +@Mixin(value = TextWidget.class, remap = false) +public abstract class TextWidgetMixin extends Widget implements UnboxFix { + + @Unique + private boolean gregTech$defaultTextColor = true; + + @Unique + private boolean gregTech$defaultShadow = true; + + @Override + public void gregTech$useDefaultTextColor(boolean b) { + gregTech$defaultTextColor = b; + } + + @Override + public void gregTech$useDefaultShadow(boolean b) { + gregTech$defaultShadow = b; + } + + @Override + public boolean canHover() { + return hasTooltip(); + } + + @ModifyReturnValue(method = { "getDefaultHeight", "getDefaultWidth" }, at = @At("TAIL")) + public int clamp(int r) { + return Math.max(1, r); + } + + @ModifyArg(method = "draw", + at = @At(value = "INVOKE", + target = "Lcom/cleanroommc/modularui/drawable/text/TextRenderer;setColor(I)V")) + public int fixColor(int color, @Local(argsOnly = true) WidgetTheme theme) { + return gregTech$defaultTextColor ? theme.getTextColor() : color; + } + + @ModifyArg(method = "draw", + at = @At(value = "INVOKE", + target = "Lcom/cleanroommc/modularui/drawable/text/TextRenderer;setShadow(Z)V")) + public boolean fixShadow(boolean shadow, @Local(argsOnly = true) WidgetTheme theme) { + return gregTech$defaultShadow ? theme.getTextShadow() : shadow; + } +} diff --git a/src/main/java/gregtech/mixins/mui2/ToggleButtonMixin.java b/src/main/java/gregtech/mixins/mui2/ToggleButtonMixin.java new file mode 100644 index 00000000000..3838ecf5805 --- /dev/null +++ b/src/main/java/gregtech/mixins/mui2/ToggleButtonMixin.java @@ -0,0 +1,22 @@ +package gregtech.mixins.mui2; + +import gregtech.api.mui.StateOverlay; + +import com.cleanroommc.modularui.api.drawable.IDrawable; +import com.cleanroommc.modularui.widgets.AbstractCycleButtonWidget; +import com.cleanroommc.modularui.widgets.ToggleButton; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(value = ToggleButton.class, remap = false) +public class ToggleButtonMixin extends AbstractCycleButtonWidget implements StateOverlay { + + public StateOverlay overlay(boolean selected, IDrawable... overlay) { + this.overlay = addToArray(this.overlay, overlay, selected ? 1 : 0); + return (StateOverlay) getThis(); + } + + public StateOverlay hoverOverlay(boolean selected, IDrawable... overlay) { + this.hoverOverlay = addToArray(this.hoverOverlay, overlay, selected ? 1 : 0); + return (StateOverlay) getThis(); + } +} diff --git a/src/main/java/gregtech/mixins/mui2/TooltipMixin.java b/src/main/java/gregtech/mixins/mui2/TooltipMixin.java new file mode 100644 index 00000000000..7883e8b12de --- /dev/null +++ b/src/main/java/gregtech/mixins/mui2/TooltipMixin.java @@ -0,0 +1,100 @@ +package gregtech.mixins.mui2; + +import com.cleanroommc.modularui.drawable.text.RichText; +import com.cleanroommc.modularui.screen.RichTooltip; +import com.cleanroommc.modularui.screen.viewport.ModularGuiContext; +import com.cleanroommc.modularui.theme.WidgetTheme; +import com.cleanroommc.modularui.widget.Widget; +import com.cleanroommc.modularui.widgets.RichTextWidget; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.function.Consumer; + +@Mixin(value = RichTooltip.class, remap = false) +public abstract class TooltipMixin { + + @Shadow + private boolean dirty; + + @Shadow + @Final + private RichText text; + + @Shadow + private Consumer tooltipBuilder; + + @Shadow + public abstract RichTooltip getThis(); + + @Shadow + public abstract void markDirty(); + + /** + * @author GTCEu - Ghzdude + * @reason Implement MUI2 PR#83 + */ + @Overwrite + public void buildTooltip() { + this.dirty = false; + if (this.tooltipBuilder != null) { + this.text.clearText(); + this.tooltipBuilder.accept(getThis()); + } + } + + /** + * @author GTCEu - Ghzdude + * @reason Implement MUI2 PR#83 + */ + @Overwrite + public RichTooltip tooltipBuilder(Consumer tooltipBuilder) { + Consumer existingBuilder = this.tooltipBuilder; + if (existingBuilder != null) { + this.tooltipBuilder = tooltip -> { + existingBuilder.accept(getThis()); + tooltipBuilder.accept(getThis()); + }; + } else { + this.tooltipBuilder = tooltipBuilder; + } + markDirty(); + return getThis(); + } + + @Mixin(value = RichTextWidget.class, remap = false) + private static abstract class RichTextWidgetMixin extends Widget { + + @Shadow + private boolean autoUpdate; + + @Shadow + private boolean dirty; + + @Shadow + @Final + private RichText text; + + @Shadow + private Consumer builder; + + /** + * @author GTCEu - Ghzdude + * @reason Implement MUI2 PR#83 + */ + @Overwrite + public void draw(ModularGuiContext context, WidgetTheme widgetTheme) { + super.draw(context, widgetTheme); + if (this.autoUpdate || this.dirty) { + if (this.builder != null) { + this.text.clearText(); + this.builder.accept(this.text); + } + this.dirty = false; + } + this.text.drawAtZero(context, getArea(), widgetTheme); + } + } +} diff --git a/src/main/java/gregtech/mixins/nothirium/ChunkRenderPassMixin.java b/src/main/java/gregtech/mixins/nothirium/ChunkRenderPassMixin.java new file mode 100644 index 00000000000..9785abe9978 --- /dev/null +++ b/src/main/java/gregtech/mixins/nothirium/ChunkRenderPassMixin.java @@ -0,0 +1,35 @@ +package gregtech.mixins.nothirium; + +import meldexun.nothirium.api.renderer.chunk.ChunkRenderPass; +import org.apache.commons.lang3.ArrayUtils; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(ChunkRenderPass.class) +public class ChunkRenderPassMixin { + + @Final + @Mutable + @Shadow(remap = false) + public static ChunkRenderPass[] $VALUES; + + @Final + @Mutable + @Shadow(remap = false) + public static ChunkRenderPass[] ALL; + + @SuppressWarnings("all") + @Invoker(value = "") + private static ChunkRenderPass create(String name, int ordinal) { + throw new IllegalStateException("Unreachable"); + } + + static { + ChunkRenderPass bloom = create("BLOOM", $VALUES.length); + $VALUES = ArrayUtils.add($VALUES, bloom); + ALL = ChunkRenderPass.values(); + } +} diff --git a/src/main/java/gregtech/mixins/vintagium/BlockRenderPassMixin.java b/src/main/java/gregtech/mixins/vintagium/BlockRenderPassMixin.java index 5544bd8069e..731128ddca0 100644 --- a/src/main/java/gregtech/mixins/vintagium/BlockRenderPassMixin.java +++ b/src/main/java/gregtech/mixins/vintagium/BlockRenderPassMixin.java @@ -1,25 +1,26 @@ package gregtech.mixins.vintagium; import gregtech.client.utils.BloomEffectUtil; -import gregtech.client.utils.BloomEffectVintagiumUtil; import net.minecraft.util.BlockRenderLayer; -import net.minecraftforge.common.util.EnumHelper; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import me.jellysquid.mods.sodium.client.util.BufferSizeUtil; -import me.jellysquid.mods.sodium.client.util.EnumUtil; +import org.apache.commons.lang3.ArrayUtils; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(BlockRenderPass.class) public abstract class BlockRenderPassMixin { + @Final + @Mutable + @Shadow(remap = false) + public static BlockRenderPass[] $VALUES; + @Final @Mutable @Shadow(remap = false) @@ -30,17 +31,17 @@ public abstract class BlockRenderPassMixin { @Shadow(remap = false) public static int COUNT; - @SuppressWarnings("UnresolvedMixinReference") - @Inject(method = "", - at = @At(value = "TAIL"), - remap = false) - private static void init(CallbackInfo ci) { - EnumUtil.LAYERS = BlockRenderLayer.values(); + @SuppressWarnings("all") + @Invoker("") + private static BlockRenderPass create(String name, int ordinal, BlockRenderLayer layer, boolean translucent) { + throw new IllegalStateException("Unreachable"); + } + + static { BufferSizeUtil.BUFFER_SIZES.put(BloomEffectUtil.getBloomLayer(), 131072); - var params = new Class[] { BlockRenderLayer.class, boolean.class }; - var values = new Object[] { BloomEffectUtil.getBloomLayer(), true }; - BloomEffectVintagiumUtil.bloom = EnumHelper.addEnum(BlockRenderPass.class, "BLOOM", params, values); + BlockRenderPass bloom = create("BLOOM", $VALUES.length, BloomEffectUtil.getBloomLayer(), true); + $VALUES = ArrayUtils.add($VALUES, bloom); VALUES = BlockRenderPass.values(); COUNT = VALUES.length; } diff --git a/src/main/resources/assets/gregtech/lang/en_us.lang b/src/main/resources/assets/gregtech/lang/en_us.lang index 89f3cedfda1..cbb86f128e6 100644 --- a/src/main/resources/assets/gregtech/lang/en_us.lang +++ b/src/main/resources/assets/gregtech/lang/en_us.lang @@ -39,6 +39,10 @@ death.attack.screwdriver_lv=%s had their screws removed by %s enchantment.disjunction=Disjunction +gregtech.jei.remove_recipe.tooltip=Copies a %s Snippet to Remove this Recipe +gregtech.jei.ct_recipe.tooltip=CraftTweaker Recipe +gregtech.jei.gs_recipe.tooltip=GroovyScript Recipe + gregtech.machine.steam_grinder.name=Steam Grinder gregtech.multiblock.steam_grinder.description=A Multiblock Macerator at the Steam Age. Requires at least 14 Bronze Casings to form. Cannot use normal Input/Output busses, nor Fluid Hatches other than the Steam Hatch. gregtech.multiblock.steam.low_steam=Not enough Steam to run! @@ -53,6 +57,13 @@ gregtech.multiblock.steam_oven.description=A Multi Smelter at the Steam Age. Req gregtech.multiblock.require_steam_parts=Requires Steam Hatches and Buses! gregtech.multiblock.steam_.duration_modifier=Takes §f1.5x §7base duration to process, not affected by number of items. +gregtech.top.quantum_status.label=Status: +gregtech.top.quantum_status.powered=§bOnline +gregtech.top.quantum_status.connected=§cNo Power +gregtech.top.quantum_status.disconnected=Not connected +gregtech.top.quantum_controller.no_hatches=§cNo Energy Hatches Connected +gregtech.top.quantum_controller.no_power=§cNo Power + gregtech.top.working_disabled=Working Disabled gregtech.top.energy_consumption=Using @@ -62,7 +73,8 @@ gregtech.top.transform_up=Step Up gregtech.top.transform_down=Step Down gregtech.top.transform_input=Input: gregtech.top.transform_output=Output: -gregtech.top.steam_heating_up=Heating up +gregtech.top.steam_heating_up=Heating Up: +gregtech.top.steam_cooling_down=Cooling Down gregtech.top.steam_no_water=No Water gregtech.top.convert_eu=Converting §eEU§r -> §cFE§r @@ -119,11 +131,14 @@ option.gregtech.steam_boiler=Steam Boilers option.gregtech.transformer=Transformers option.gregtech.workable=Workable Machines -gregtech.waila.energy_stored=Energy: %d EU / %d EU +gregtech.waila.energy_stored=Energy: %s EU / %s EU +gregtech.waila.energy_input=Input: %s EU/t +gregtech.waila.energy_output=Output: %s EU/t gregtech.waila.progress_idle=Idle gregtech.waila.progress_tick=Progress: %d t / %d t gregtech.waila.progress_sec=Progress: %d s / %d s gregtech.waila.progress_computation=Computation: %s / %s +gregtech.waila.active_transformer.average_io=Average I/O: %s EU/t gregtech.multiblock.title=Multiblock Pattern gregtech.multiblock.primitive_blast_furnace.bronze.description=The Primitive Blast Furnace (PBF) is a multiblock structure used for cooking steel in the early game. Although not very fast, it will provide you with steel for your first setups. @@ -1027,6 +1042,14 @@ item.gt.tool.plunger.tooltip=§8Removes Fluids from Machines item.gt.tool.wire_cutter_lv.name=%s Wire Cutter (LV) item.gt.tool.wire_cutter_hv.name=%s Wire Cutter (HV) item.gt.tool.wire_cutter_iv.name=%s Wire Cutter (IV) +item.gt.tool.toolbelt.name=%s Toolbelt%s +item.gt.tool.toolbelt.size=§a%s Tool Slots +item.gt.tool.toolbelt.tooltip=Holds GT or vanilla-esque tools that can be manually selected for in-world use, automatically selected for crafting, or stored for maintenance repair. +item.gt.tool.toolbelt.paint=Also supports Spray Cans. +item.gt.tool.toolbelt.dye=Can be dyed like leather equipment, and the dye can be removed via water cauldron, also like leather equipment. +item.gt.tool.toolbelt.maintenance=Repairs maintenance problems with only inserted tools upon interacting with a maintenance hatch in-world. +item.gt.tool.toolbelt.tool=§aSlot %s: §f%s +item.gt.tool.toolbelt.selected=- §aSlot %s: §f%s item.gt.tool.tooltip.crafting_uses=§a%s Crafting Uses @@ -1265,6 +1288,8 @@ cover.filter.mode.title=Filter Mode cover.filter.mode.filter_insert=Filter Insert cover.filter.mode.filter_extract=Filter Extract cover.filter.mode.filter_both=Filter Insert/Extract +cover.filter.allow_flow.label=Allow Flow +cover.filter.allow_flow.tooltip=By default, Items/Fluids can only move in the direction\nof the filter with respect to the filter's setting.\n\nIf Enabled, Items/Fluids are allowed to pass unfiltered\nthrough the opposite direction of this filter. cover.item_filter.ignore_damage.enabled=Ignore Damage cover.item_filter.ignore_damage.disabled=Respect Damage cover.item_filter.ignore_nbt.enabled=Ignore NBT @@ -1294,6 +1319,8 @@ cover.smart_item_filter.filtering_mode.centrifuge=Centrifuge cover.smart_item_filter.filtering_mode.sifter=Sifter cover.smart_item_filter.filtering_mode.description=Select Machine this Smart Filter will use for filtering./nIt will automatically pick right portions of items for robotic arm. +cover.generic.disabled=Disabled +cover.generic.enabled=Enabled cover.generic.transfer_mode=Transfer Mode cover.generic.manual_io=Manual IO Mode cover.generic.io=IO Mode @@ -1358,6 +1385,13 @@ cover.ender_fluid_link.iomode.disabled=I/O Disabled cover.ender_fluid_link.private.tooltip.disabled=Switch to private tank mode\nPrivate mode uses the player who originally placed the cover cover.ender_fluid_link.private.tooltip.enabled=Switch to public tank mode cover.ender_fluid_link.incomplete_hex=Inputted color is incomplete!/nIt will be applied once complete (all 8 hex digits)/nClosing the gui will lose edits! +cover.ender_fluid_link.transfer_unit=L/t + +cover.generic.ender.known_channels=Known Channels +cover.generic.ender.open_selector=Open Entry Selector +cover.generic.ender.set_description.tooltip=Set Description +cover.generic.ender.set_description.title=Set Description [%s] +cover.generic.ender.delete_entry=Delete Entry cover.generic.advanced_detector.latched=Latched cover.generic.advanced_detector.continuous=Continuous @@ -2466,6 +2500,13 @@ behavior.tricorder.debug_machine_invalid_null=invalid! MetaTileEntity == null! behavior.tricorder.debug_cpu_load=Average CPU load of ~%sns over %s ticks with worst time of %sns. behavior.tricorder.debug_cpu_load_seconds=This is %s seconds. behavior.tricorder.debug_lag_count=Caused %s Lag Spike Warnings (anything taking longer than %sms) on the Server. +behavior.tricorder.mte_owner=Owner: %s +behavior.tricorder.mte_owner_offline=Owner is Offline or Offworld! +behavior.tricorder.mte_owner_null=This wasn't placed by a player! +behavior.tricorder.quantum_controller.usage=Using %s EU/t (%s) +behavior.tricorder.quantum_controller.connected_items=Connected item storages: %s +behavior.tricorder.quantum_controller.connected_fluids=Connected fluid storages: %s +behavior.tricorder.quantum_storage.usage=Contributing %s EU/t to Quantum Controller metaitem.item_magnet.lv.name=Low Voltage Item Magnet metaitem.item_magnet.hv.name=High Voltage Item Magnet @@ -4150,6 +4191,8 @@ gregtech.machine.battery_buffer.max.16.name=Maximum Voltage 16x Battery Buffer gregtech.battery_buffer.average_input=Average input: %s EU/t gregtech.battery_buffer.average_output=Average output: %s EU/t +gregtech.battery_buffer.average_input.top=Input: %s +gregtech.battery_buffer.average_output.top=Output: %s # Transformers gregtech.machine.transformer.description=Transforms Energy between voltage tiers @@ -4209,9 +4252,9 @@ gregtech.machine.transformer.adjustable.opv.name=Overpowered Voltage Power Trans # Diodes gregtech.machine.diode.message=Max Amperage throughput: %s -gregtech.machine.diode.tooltip_tool_usage=Hit with a Soft Mallet to change Amperage flow. +gregtech.machine.diode.tooltip_tool_usage_screwdriver=§8Use Screwdriver to change Amperage flow or access Covers gregtech.machine.diode.tooltip_general=Allows Energy Flow in one direction and limits Amperage -gregtech.machine.diode.tooltip_starts_at=Starts as §f1A§7, use Soft Mallet to change +gregtech.machine.diode.tooltip_starts_at=Starts as §f1A§7, use Screwdriver to change gregtech.machine.diode.ulv.name=Ultra Low Voltage Diode gregtech.machine.diode.lv.name=Low Voltage Diode @@ -4340,6 +4383,7 @@ gregtech.machine.alarm.tooltip=Plays a Sound when given a Redstone signal #Quantum Chests gregtech.machine.quantum_chest.tooltip=Better than Storage Drawers +gregtech.machine.super_chest.ulv.name=Primitive Chest I gregtech.machine.super_chest.lv.name=Super Chest I gregtech.machine.super_chest.mv.name=Super Chest II gregtech.machine.super_chest.hv.name=Super Chest III @@ -4355,6 +4399,7 @@ gregtech.machine.quantum_chest.items_stored=Item Amount: #Quantum Tanks gregtech.machine.quantum_tank.tooltip=Compact place to store all your fluids gregtech.machine.quantum_tank.tooltip.voiding_enabled=Excess Fluid Voiding §aEnabled +gregtech.machine.super_tank.ulv.name=Primitive Tank I gregtech.machine.super_tank.lv.name=Super Tank I gregtech.machine.super_tank.mv.name=Super Tank II gregtech.machine.super_tank.hv.name=Super Tank III @@ -4366,6 +4411,16 @@ gregtech.machine.quantum_tank.zpm.name=Quantum Tank III gregtech.machine.quantum_tank.uv.name=Quantum Tank IV gregtech.machine.quantum_tank.uhv.name=Quantum Tank V +#Quantum Storage Controller +gregtech.machine.quantum_storage_controller.name=Quantum Storage Controller +gregtech.machine.quantum_storage_controller.tooltip=Heart of the Quantum Storage Network/nConnect Energy Hatches to power the Quantum Storage Network +gregtech.machine.quantum_storage_proxy.name=Quantum Storage Proxy +gregtech.machine.quantum_storage_proxy.tooltip=Proxies the Quantum Storage Network's inventory +gregtech.machine.quantum_storage_extender.name=Quantum Storage Extender +gregtech.machine.quantum_storage_extender.tooltip=Extends the Quantum Storage Network to other chests/tanks +gregtech.machine.quantum_storage.connected=Connected to Quantum Controller at [%d, %d, %d]/n/nClick to highlight the controller +gregtech.machine.quantum_storage.disconnected=Not Connected + #Buffers gregtech.machine.buffer.tooltip=A Small Buffer to store Items and Fluids gregtech.machine.buffer.lv.name=Basic Buffer @@ -4885,6 +4940,9 @@ gregtech.machine.active_transformer.tooltip3=Can transmit power at incredible di gregtech.machine.active_transformer.tooltip3.5= Lasers§7. gregtech.multiblock.active_transformer.description=The Active Transformer is a multiblock structure that can accept any number or tier of Energy Hatches, and transform them into any number or tier of Dynamo Hatches. They can be chained with Laser Source and Target Hatches, allowing long distance power transportation without any losses. Lasers must be in a straight line, otherwise they will not send energy. gregtech.machine.active_transformer.routing=Routing. +gregtech.multiblock.active_transformer.max_in=Max Input: %s +gregtech.multiblock.active_transformer.max_out=Max Output: %s +gregtech.multiblock.active_transformer.average_io=Average I/O: %s gregtech.machine.research_station.name=Research Station gregtech.machine.research_station.tooltip.1=More than just a Multiblock Scanner @@ -5330,6 +5388,10 @@ gregtech.machine.me.fluid_export.tooltip=Stores fluids directly into the ME netw gregtech.machine.me.fluid_export.tooltip.2=Can cache an infinite amount of fluid gregtech.machine.me.stocking_auto_pull_enabled=Auto-Pull Enabled gregtech.machine.me.stocking_auto_pull_disabled=Auto-Pull Disabled +gregtech.machine.me.extra_connections.enabled=Allow connections from all sides +gregtech.machine.me.extra_connections.disabled=Allow connection only on front face +gregtech.machine.me.extra_connections.tooltip=Right-click with wire cutters to allow connecting to AE2 on all sides + # Universal tooltips gregtech.universal.tooltip.voltage_in=§aVoltage IN: §f%,d EU/t (%s§f) @@ -5367,7 +5429,7 @@ gregtech.universal.tooltip.uses_per_op=Uses §f%,d EU/operation gregtech.universal.tooltip.base_production_eut=§eBase Production: §f%,d EU/t gregtech.universal.tooltip.base_production_fluid=§eBase Production: §f%,d L/t gregtech.universal.tooltip.produces_fluid=§eProduces: §f%,d L/t -gregtech.universal.tooltip.terrain_resist=This Machine will not explode when exposed to the Elements +gregtech.universal.tooltip.terrain_resist=§eThis Machine will not explode when exposed to the Elements gregtech.universal.tooltip.requires_redstone=§4Requires Redstone power gregtech.block.tooltip.no_mob_spawning=§bMobs cannot spawn on this block @@ -5480,6 +5542,10 @@ gregtech.gui.config_slot.auto_pull_managed=§4Disabled:§7 Managed by Auto-Pull gregtech.gui.me_bus.extra_slot=Extra Slot/n§7Put extra items for recipes here, like Molds or Lenses gregtech.gui.me_bus.auto_pull_button=Click to toggle automatic item pulling from ME gregtech.gui.alarm.radius=Radius: +gregtech.gui.item_passthrough.enabled=Item Passthough Enabled +gregtech.gui.item_passthrough.disabled=Item Passthough Disabled +gregtech.gui.fluid_passthrough.enabled=Fluid Passthough Enabled +gregtech.gui.fluid_passthrough.disabled=Fluid Passthough Disabled ore.spawnlocation.name=Ore Spawn Information @@ -6109,6 +6175,9 @@ gregtech.subtitle.entity.portal_opening=Portal opens gregtech.subtitle.entity.portal_closing=Portal closes gregtech.subtitle.maintenance.electrical=Electrical breakdown gregtech.subtitle.maintenance.mechanical=Mechanical breakdown +gregtech.subtitle.alarm=Alarm Whines +gregtech.subtitle.click=Something Clicks + # Debug messaging gregtech.debug.f3_h.enabled=GregTech has modified the debug info! For Developers: enable the misc:debug config option in the GregTech config file to see more diff --git a/src/main/resources/assets/gregtech/lang/ja_jp.lang b/src/main/resources/assets/gregtech/lang/ja_jp.lang index e4024638d3f..a1ed0f8ebbc 100644 --- a/src/main/resources/assets/gregtech/lang/ja_jp.lang +++ b/src/main/resources/assets/gregtech/lang/ja_jp.lang @@ -109,7 +109,7 @@ gregtech.top.ld_pipe_output=搬出 gregtech.top.ld_pipe_input_endpoint=搬入口: gregtech.top.ld_pipe_output_endpoint=搬出口: -gregtech.waila.energy_stored=エネルギー: %d EU / %d EU +gregtech.waila.energy_stored=エネルギー: %s EU / %s EU gregtech.waila.progress_idle=停止中 gregtech.waila.progress_tick=進捗: %d t / %d t gregtech.waila.progress_sec=進捗: %d s / %d s diff --git a/src/main/resources/assets/gregtech/lang/ru_ru.lang b/src/main/resources/assets/gregtech/lang/ru_ru.lang index e9614e0fadc..1645d98a9af 100644 --- a/src/main/resources/assets/gregtech/lang/ru_ru.lang +++ b/src/main/resources/assets/gregtech/lang/ru_ru.lang @@ -39,7 +39,7 @@ enchantment.disjunction=Разъединение gregtech.machine.steam_grinder.name=Паровой измельчитель gregtech.multiblock.steam_grinder.description=Многоблочный измельчитель в паровой эпохе. Требует как минимум 14 бронзовых машинных корпусов. Может использовать только паровые люки. gregtech.multiblock.steam.low_steam=Недостаточно пара для работы! -gregtech.multiblock.steam.steam_stored=Пар: %s / %s mB +gregtech.multiblock.steam.steam_stored=Пар: %s gregtech.machine.steam_hatch.name=Паровой люк gregtech.machine.steam.steam_hatch.tooltip=§eПринимает жидкости: §fПар gregtech.machine.steam_import_bus.name=Паровой входной люк @@ -75,7 +75,7 @@ gregtech.top.link_cover.color=Цвет: gregtech.top.mode.export=Экспорт gregtech.top.mode.import=Импорт gregtech.top.unit.items=Предметы -gregtech.top.unit.fluid_milibuckets=mB +gregtech.top.unit.fluid_milibuckets=Л gregtech.top.unit.fluid_buckets=B gregtech.top.block_drops=Добыча gregtech.top.ld_pipe_no_network=Трубопровод не найден @@ -86,14 +86,14 @@ gregtech.top.ld_pipe_input=Ввод gregtech.top.ld_pipe_output=Вывод gregtech.top.ld_pipe_input_endpoint=Входная конечная точка: gregtech.top.ld_pipe_output_endpoint=Выходная конечная точка: -gregtech.waila.energy_stored=Энергия: %d EU / %d EU +gregtech.waila.energy_stored=Энергия: %s EU / %s EU gregtech.waila.progress_idle=Простой gregtech.waila.progress_tick=Прогресс: %d t / %d t gregtech.waila.progress_sec=Прогресс: %d s / %d s gregtech.multiblock.title=Шаблон многоблочной структуры gregtech.multiblock.primitive_blast_furnace.bronze.description=Примитивная доменная печь (ПДП) - это многоблочная структура, используемая для изготовления стали в ранней стадии игры. Не очень быстрая, но обеспечивает вас сталью на первое время. gregtech.multiblock.coke_oven.description=Коксовая печь - это многоблочная структура, используемая для получения кокосового угля и креозота на ранней стадии игры. Не требует топлива и имеет внутренний бак на 32 ведра креозота. Доступ к инвентарю можно получить через Люк коксовой печи. -gregtech.multiblock.vacuum_freezer.description=Вакуумный морозильник - это многоблочная структура, в основном используемая для охлаждения горячих слитков в обычные слитки. Тем не менее, он также может охлаждать другие вещества, к примеру воду. +gregtech.multiblock.vacuum_freezer.description=Вакуумный холодильник - это многоблочная структура, в основном используемая для охлаждения горячих слитков в обычные слитки. Тем не менее, он также может охлаждать другие вещества, к примеру воду. gregtech.multiblock.implosion_compressor.description=Детонационный компрессор - это многоблочная структура, в которой используются взрывчатые вещества для превращения пыли в соответствующие камни. gregtech.multiblock.pyrolyse_oven.description=Пиролизная печь - это многоблочная структура, используемая для пиролиза древесины в древесный уголь и креозот, либо в золу и тяжелую нефть. gregtech.multiblock.cracker.description=Крекинговая установка - это многоблочная структура, используемая для высокотемпературной переработки нефти и её фракций с целью получения продуктов меньшей молекулярной массы. @@ -111,8 +111,8 @@ gregtech.multiblock.fusion_reactor.uv.description=Термоядерный ре gregtech.multiblock.fusion_reactor.heat=Нагрев: %d gregtech.multiblock.large_chemical_reactor.description=Многоблочная версия химического реактора выполняющий операции в больших объёмах с удвоенной эффективностью. Ускорение умножает скорость и энергию на 4. Для мультиблочной структуры требуется ровно 1 блок купроникелевой катушки, который должен быть размещен рядом с корпусом ПТФЭ трубы, расположенным в центре. gregtech.multiblock.primitive_water_pump.description=Примитивная водяная помпа — это многоблочная структура до Паровой Эпохи, который собирает воду раз в секунду, в зависимости от биома, в котором он находится. Он может использовать насос, выходной люк ULV или LV, увеличивая кол-во воды от уровня. Выполняется по формуле: Коэф. биома * Множитель люка. -gregtech.multiblock.primitive_water_pump.extra1=Коэф. биома:/n Океан, Река: 1000 Л/с/n Болото: 800 Л/с/n Джунгли: 350 Л/с/n Снежный: 300 Л/с/н Равнины, Лес: 250 Л/с/n Тайга : 175 Л/с/n Пляж: 170 Л/с/n Другое: 100 Л/с -gregtech.multiblock.primitive_water_pump.extra2=Множители люка:/n Люк насоса: 1x/n Выходной люк ULV: 2x/n LV Выходной люк: 4xn/nВо время дождя в биомах работы насоса добыча воды будет увеличена на 50%%. +gregtech.multiblock.primitive_water_pump.extra1=Коэф. биома:/n Океан, Река: 1000 Л/с/n Болото: 800 Л/с/n Джунгли: 350 Л/с/n Снежный: 300 Л/с/n Равнины, Лес: 250 Л/с/n Тайга: 175 Л/с/n Пляж: 170 Л/с/n Другое: 100 Л/с +gregtech.multiblock.primitive_water_pump.extra2=Множители люка:/n Люк насоса: 1x/n ULV Выходной люк : 2x/n LV Выходной люк: 4x/nВо время дождя в биомах работы насоса добыча воды будет увеличена на 50%%. gregtech.multiblock.processing_array.description=Массив машин объединяет до 16 одноблочных машин в одном многоблоке. gregtech.multiblock.advanced_processing_array.description=Массив машин объединяет до 64 одноблочных машин в одном многоблоке. item.invalid.name=Недопустимый предмет @@ -159,7 +159,7 @@ metaitem.power_unit.mv.name=Блок питания (§bMV§r) metaitem.power_unit.hv.name=Блок питания (§6HV§r) metaitem.power_unit.ev.name=Блок питания (§5EV§r) metaitem.power_unit.iv.name=Блок питания (§1IV§r) -metaitem.nano_saber.name=Нано-cабля +metaitem.nano_saber.name=Нано-сабля metaitem.nano_saber.tooltip=Ryujin no ken wo kurae! metaitem.shape.mold.plate.name=Форма (Пластина) metaitem.shape.mold.plate.tooltip=Форма для изготовления пластин @@ -237,8 +237,8 @@ metaitem.shape.extruder.gear.name=Форма экструдера (Шестер metaitem.shape.extruder.gear.tooltip=Форма экструдера для изготовления шестерней metaitem.shape.extruder.bottle.name=Форма экструдера (Бутылка) metaitem.shape.extruder.bottle.tooltip=Форма экструдера для изготовления бутылок -metaitem.shape.extruder.gear_small.name=Форма экструдера (маленькая шестеренка) -metaitem.shape.extruder.gear_small.tooltip=Форма экструдера для производства маленьких шестереней +metaitem.shape.extruder.gear_small.name=Форма экструдера (Маленькая шестеренка) +metaitem.shape.extruder.gear_small.tooltip=Форма экструдера для производства маленьких шестерней metaitem.shape.extruder.foil.name=Форма экструдера (Фольга) metaitem.shape.extruder.foil.tooltip=Форма экструдера для производства фольги из неметаллов metaitem.shape.extruder.rod_long.name=Форма экструдера (Длинный прут) @@ -485,7 +485,7 @@ metaitem.glass_lens.yellow.name=Стеклянная линза (Желтый) metaitem.glass_lens.lime.name=Стеклянная линза (Лаймовый) metaitem.glass_lens.pink.name=Стеклянная линза (Розовый) metaitem.glass_lens.gray.name=Стеклянная линза (Серый) -metaitem.glass_lens.light_gray.name=Стеклянная линза (Cветло-серый) +metaitem.glass_lens.light_gray.name=Стеклянная линза (Светло-серый) metaitem.glass_lens.cyan.name=Стеклянная линза (Бирюзовый) metaitem.glass_lens.purple.name=Стеклянная линза (Фиолетовый) metaitem.glass_lens.blue.name=Стеклянная линза (Синий) @@ -507,7 +507,7 @@ metaitem.wafer.silicon.name=Кремниевая пластина metaitem.wafer.silicon.tooltip=Необработанная схема metaitem.wafer.phosphorus.name=Пластина легированная фосфором metaitem.wafer.phosphorus.tooltip=Необработанная схема -metaitem.wafer.naquadah.name=Плаcтина легированная наквадой +metaitem.wafer.naquadah.name=Пластина легированная наквадой metaitem.wafer.naquadah.tooltip=Необработанная схема metaitem.wafer.neutronium.name=Пластина легированная нейтронием metaitem.wafer.neutronium.tooltip=Необработанная схема @@ -581,15 +581,15 @@ metaitem.wafer.integrated_logic_circuit.tooltip=Необработанная и metaitem.wafer.central_processing_unit.name=Пластина процессора metaitem.wafer.central_processing_unit.tooltip=Необработанная заготовка процессора metaitem.wafer.high_power_integrated_circuit.name=Пластина HPIC -metaitem.wafer.high_power_integrated_circuit.tooltip=Необработанная высоковольтажная микросхема +metaitem.wafer.high_power_integrated_circuit.tooltip=Необработанная микросхема высокого напряжения metaitem.wafer.ultra_high_power_integrated_circuit.name=Пластина UHPIC -metaitem.wafer.ultra_high_power_integrated_circuit.tooltip=Необработанная сверхвысоковольтажная микросхема +metaitem.wafer.ultra_high_power_integrated_circuit.tooltip=Необработанная микросхема сверхвысокого напряжения metaitem.wafer.nand_memory_chip.name=Пластина чипа NAND-памяти metaitem.wafer.nand_memory_chip.tooltip=Необработанная логическая схема metaitem.wafer.ultra_low_power_integrated_circuit.name=Пластина ULPIC -metaitem.wafer.ultra_low_power_integrated_circuit.tooltip=Необработанная микросхема сверхнизкого вольтажа +metaitem.wafer.ultra_low_power_integrated_circuit.tooltip=Необработанная микросхема сверхнизкого напряжения metaitem.wafer.low_power_integrated_circuit.name=Пластина LPIC -metaitem.wafer.low_power_integrated_circuit.tooltip=Необработанная низковольтажная микросхема +metaitem.wafer.low_power_integrated_circuit.tooltip=Необработанная микросхема низкого напряжения metaitem.wafer.power_integrated_circuit.name=Пластина PIC metaitem.wafer.power_integrated_circuit.tooltip=Необработанная силовая микросхема metaitem.wafer.nano_central_processing_unit.name=Пластина нано-процессора @@ -634,9 +634,9 @@ metaitem.plate.nano_central_processing_unit.tooltip=Центральный на metaitem.plate.nor_memory_chip.name=NOR схема metaitem.plate.nor_memory_chip.tooltip=NOR логическая схема metaitem.plate.ultra_low_power_integrated_circuit.name=ULPIC -metaitem.plate.ultra_low_power_integrated_circuit.tooltip=Сверхнизковольтный IC +metaitem.plate.ultra_low_power_integrated_circuit.tooltip=IC сверхнизкого напряжения metaitem.plate.low_power_integrated_circuit.name=LPIC -metaitem.plate.low_power_integrated_circuit.tooltip=Маловольтажный IC +metaitem.plate.low_power_integrated_circuit.tooltip=IC низкого напряжения metaitem.plate.power_integrated_circuit.name=PIC metaitem.plate.power_integrated_circuit.tooltip=Силовая IC metaitem.plate.qbit_central_processing_unit.name=Кубитный процессор @@ -694,7 +694,7 @@ metaitem.circuit.quantum_processor.name=Квантовый процессор metaitem.circuit.quantum_processor.tooltip=Квантовые вычисления оживают!/n§aEV уровень metaitem.circuit.quantum_assembly.name=Квантовый вычислительный блок metaitem.circuit.quantum_assembly.tooltip=Квантовые вычисления оживают!/n§aIV уровень -metaitem.circuit.quantum_computer.name=Квантовый cуперкомпьютер +metaitem.circuit.quantum_computer.name=Квантовый суперкомпьютер metaitem.circuit.quantum_computer.tooltip=Квантовые вычисления оживают!/n§aLuV уровень metaitem.circuit.quantum_mainframe.name=Квантовый мейнфрейм metaitem.circuit.quantum_mainframe.tooltip=Квантовые вычисления оживают!/n§aZPM уровень @@ -846,7 +846,7 @@ item.gt.tool.behavior.shield_disable=§7Брут: §fИгнорирует щит item.gt.tool.behavior.relocate_mining=§2Магнитный: §fПеремещает добытые блоки item.gt.tool.behavior.aoe_mining=§5Добыча по области: §f%sx%sx%s item.gt.tool.behavior.ground_tilling=§eФермер: Вспашка земли -item.gt.tool.behavior.grass_path=§eДекоратор:Создаёт тропу +item.gt.tool.behavior.grass_path=§eДекоратор: §fСоздаёт тропу item.gt.tool.behavior.rail_rotation=§eЖелезнодорожник: §fВращает рельсы item.gt.tool.behavior.crop_harvesting=§aКомбайн: §fСбор урожая item.gt.tool.behavior.plunger=§9Сантехник: §fОткачивает жидкости @@ -1054,7 +1054,7 @@ metaitem.blacklight.tooltip=Источник длинноволнового §d gui.widget.incrementButton.default_tooltip=Удерживайте Shift, Ctrl или оба, чтобы изменить кол-во gui.widget.recipeProgressWidget.default_tooltip=Показать рецепт gregtech.recipe_memory_widget.tooltip.2=§7Нажмите Shift, чтобы заблокировать/разблокировать этот рецепт -gregtech.recipe_memory_widget.tooltip.1=§7Щелкните левой кнопкой мыши, чтобы автоматически добавить этот рецепт в сетку крафта +gregtech.recipe_memory_widget.tooltip.1=§7Щелкните левой кнопкой мыши, чтобы автоматически добавить этот рецепт в Сетку создания cover.filter.blacklist.disabled=Белый список cover.filter.blacklist.enabled=Черный список cover.ore_dictionary_filter.title=Фильтр по словарю руд @@ -1315,7 +1315,7 @@ gregtech.material.hydrogen=Водород gregtech.material.helium=Гелий gregtech.material.helium_3=Гелий-3 gregtech.material.indium=Индий -gregtech.material.iodine=Иод +gregtech.material.iodine=Йод gregtech.material.iridium=Иридий gregtech.material.iron=Железо gregtech.material.krypton=Криптон @@ -1494,7 +1494,7 @@ gregtech.material.vanadium_gallium=Ванадий-Галлий gregtech.material.wrought_iron=Кованое железо gregtech.material.wulfenite=Вульфенит gregtech.material.yellow_limonite=Желтый лимонит -gregtech.material.yttrium_barium_cuprate=Купрат иттрий-барийя +gregtech.material.yttrium_barium_cuprate=Оксид иттрия-бария-меди gregtech.material.nether_quartz=Адский кварц gregtech.material.certus_quartz=Истинный кварц gregtech.material.quartzite=Кварцит @@ -1556,7 +1556,7 @@ gregtech.material.nitric_acid=Азотная кислота gregtech.material.sulfuric_acid=Серная кислота gregtech.material.phosphoric_acid=Фосфорная кислота gregtech.material.sulfur_trioxide=Триоксид серы -gregtech.material.sulfur_dioxide=Дииоксид серы +gregtech.material.sulfur_dioxide=Диоксид серы gregtech.material.carbon_monoxide=Монооксид углерода gregtech.material.hypochlorous_acid=Соляная кислота gregtech.material.ammonia=Аммиак @@ -1613,7 +1613,7 @@ gregtech.material.polyvinyl_acetate=Поливинилацетат gregtech.material.reinforced_epoxy_resin=Укрепленная эпоксидная смола gregtech.material.polyvinyl_chloride=Поливинилхлорид (ПВХ) gregtech.material.polyphenylene_sulfide=Полифениленсульфид -gregtech.material.glyceryl_trinitrate=Глицерил тринитрат +gregtech.material.glyceryl_trinitrate=Нитроглицерин gregtech.material.polybenzimidazole=Полибензимидазол (ПБИ) gregtech.material.polydimethylsiloxane=Полидиметилсилоксан gregtech.material.plastic=Полиэтилен @@ -1627,7 +1627,7 @@ gregtech.material.monochloramine=Хлорамин gregtech.material.chloroform=Хлороформ gregtech.material.cumene=Кумола gregtech.material.tetrafluoroethylene=Тетрафторэтилен -gregtech.material.chloromethane=Хлорометан +gregtech.material.chloromethane=Хлорметан gregtech.material.allyl_chloride=Аллилхлорид gregtech.material.isoprene=Изопрен gregtech.material.propane=Пропан @@ -1763,7 +1763,7 @@ gregtech.material.coal_gas=Угольный газ gregtech.material.coal_tar=Каменноугольная смола gregtech.material.gunpowder=Порох gregtech.material.oilsands=Нефтеносный песок -gregtech.material.rare_earth=Редкая земля +gregtech.material.rare_earth=Редкоземельные элементы gregtech.material.stone=Камень gregtech.material.lava=Лава gregtech.material.glowstone=Светокамень @@ -1783,9 +1783,9 @@ gregtech.material.wood=Дерево gregtech.material.treated_wood=Обработанное дерево gregtech.material.paper=Бумага gregtech.material.fish_oil=Рыбий жир -gregtech.material.ruby_slurry=Рубиновый шлам -gregtech.material.sapphire_slurry=Сапфирный шлам -gregtech.material.green_sapphire_slurry=Шлам зелёного сапфира +gregtech.material.ruby_slurry=Рубиновая суспензия +gregtech.material.sapphire_slurry=Сапфировая суспензия +gregtech.material.green_sapphire_slurry=Суспензия зелёного сапфира gregtech.material.dye_black=Черный краситель gregtech.material.dye_red=Красный краситель gregtech.material.dye_green=Зеленый краситель @@ -1918,12 +1918,12 @@ gregtech.material.maximum=Максимальный item.gregtech.material.nether_quartz.oreNetherrack=Кварцевая руда Нижнего мира item.gregtech.material.gunpowder.dustTiny=Крошечная кучка пороха item.gregtech.material.gunpowder.dustSmall=Маленькая кучка пороха -item.gregtech.material.paper.dustTiny=Крошечная куча целюлозы -item.gregtech.material.paper.dustSmall=Маленькая кучка целюлозы -item.gregtech.material.paper.dust=Целюлоза -item.gregtech.material.rare_earth.dustTiny=Крошечная кучка редкой земли -item.gregtech.material.rare_earth.dustSmall=Маленькая кучка редкой земли -item.gregtech.material.rare_earth.dust=Редкая земля +item.gregtech.material.paper.dustTiny=Крошечная куча целлюлозы +item.gregtech.material.paper.dustSmall=Маленькая кучка целлюлозы +item.gregtech.material.paper.dust=Целлюлоза +item.gregtech.material.rare_earth.dustTiny=Крошечная кучка редкоземельных элементов +item.gregtech.material.rare_earth.dustSmall=Маленькая кучка редкоземельных элементов +item.gregtech.material.rare_earth.dust=Редкоземельные элементы item.gregtech.material.ash.dustTiny=Крошечная кучка золы item.gregtech.material.ash.dustSmall=Маленькая кучка золы item.gregtech.material.ash.dust=Зола @@ -1931,7 +1931,7 @@ item.gregtech.material.bone.dustTiny=Крошечная кучка костно item.gregtech.material.bone.dustSmall=Маленькая кучка костной муки item.gregtech.material.bone.dust=Костная пыль item.gregtech.material.cassiterite_sand.crushedCentrifuged=Центрифугированный касситеритовый песок -item.gregtech.material.cassiterite_sand.crushedPurified=Очищеный касситеритовый песок +item.gregtech.material.cassiterite_sand.crushedPurified=Очищенный касситеритовый песок item.gregtech.material.cassiterite_sand.crushed=Дробленный касситеритовый песок item.gregtech.material.cassiterite_sand.dustTiny=Крошечная кучка касситеритного песка item.gregtech.material.cassiterite_sand.dustSmall=Маленькая кучка касситеритного песка @@ -1950,12 +1950,12 @@ item.gregtech.material.sugar.gem=Сахарный кубик item.gregtech.material.rock_salt.dustTiny=Крошечная кучка каменной соли item.gregtech.material.rock_salt.dustSmall=Маленькая кучка каменной соли item.gregtech.material.rock_salt.dustImpure=Грязная кучка каменной соли -item.gregtech.material.rock_salt.dustPure=Очищеный кучка каменной соли +item.gregtech.material.rock_salt.dustPure=Очищенная кучка каменной соли item.gregtech.material.rock_salt.dust=Каменная соль item.gregtech.material.salt.dustTiny=Крошечная кучка соли item.gregtech.material.salt.dustSmall=Маленькая кучка соли item.gregtech.material.salt.dustImpure=Грязная кучка соли -item.gregtech.material.salt.dustPure=Очищеный кучка соли +item.gregtech.material.salt.dustPure=Очищенная кучка соли item.gregtech.material.salt.dust=Кучка соли item.gregtech.material.wood.dustTiny=Крошечная кучка древесных опилок item.gregtech.material.wood.dustSmall=Маленькая кучка древесных опилок @@ -1997,26 +1997,26 @@ item.gregtech.material.glauconite_sand.dustSmall=Маленькая кучка item.gregtech.material.glauconite_sand.dustTiny=Крошечная кучка глауконитового песка item.gregtech.material.bentonite.crushed=Измельченный бентонит item.gregtech.material.bentonite.crushedCentrifuged=Центрифугированный бентонит -item.gregtech.material.bentonite.crushedPurified=Очищеный бентонит +item.gregtech.material.bentonite.crushedPurified=Очищенный бентонит item.gregtech.material.bentonite.dustImpure=Грязная кучка бентонита -item.gregtech.material.bentonite.dustPure=Очищеный кучка бентонита +item.gregtech.material.bentonite.dustPure=Очищенная кучка бентонита item.gregtech.material.bentonite.dustSmall=Маленькая кучка бентонита item.gregtech.material.bentonite.dustTiny=Крошечная кучка бентонита item.gregtech.material.bentonite.dust=Бентонит item.gregtech.material.fullers_earth.dustSmall=Маленькая кучка смектической глины -item.gregtech.material.fullers_earth.dustTiny=Крошечная кучка cмектической глины +item.gregtech.material.fullers_earth.dustTiny=Крошечная кучка смектической глины item.gregtech.material.fullers_earth.dust=Смектическая глина item.gregtech.material.pitchblende.crushed=Измельчённый уранит item.gregtech.material.pitchblende.crushedCentrifuged=Центрифугированный уранит -item.gregtech.material.pitchblende.crushedPurified=Очищеный уранит +item.gregtech.material.pitchblende.crushedPurified=Очищенный уранит item.gregtech.material.pitchblende.dustImpure=Грязная кучка уранита -item.gregtech.material.pitchblende.dustPure=Очищеный кучка уранита +item.gregtech.material.pitchblende.dustPure=Очищенная кучка уранита item.gregtech.material.pitchblende.dustSmall=Маленькая кучка уранита item.gregtech.material.pitchblende.dustTiny=Крошечная кучка уранита item.gregtech.material.pitchblende.dust=Уранит item.gregtech.material.talc.crushed=Дробленный тальк item.gregtech.material.talc.crushedCentrifuged=Центрифугированный тальк -item.gregtech.material.talc.crushedPurified=Очищеный тальк +item.gregtech.material.talc.crushedPurified=Очищенный тальк item.gregtech.material.talc.dustImpure=Грязная кучка талька item.gregtech.material.talc.dustPure=Очищеная кучка талька item.gregtech.material.talc.dustSmall=Маленькая кучка талька @@ -2204,7 +2204,7 @@ metaitem.item_magnet.lv.name=Магнит (§7LV§r) metaitem.item_magnet.hv.name=Магнит (§6HV§r) behavior.item_magnet.enabled=§aМагнитное поле включено behavior.item_magnet.disabled=§cМагнитное поле отключено -behavior.data_item.assemblyline.title=§nДанные для Сборочного конвеера: +behavior.data_item.assemblyline.title=§nДанные для Сборочного конвейера: behavior.data_item.assemblyline.data=- §a%s metaitem.rubber_wood_boat.name=Каучуковая лодка metaitem.treated_wood_boat.name=Обработанная деревянная лодка @@ -3781,8 +3781,8 @@ gregtech.machine.battery_buffer.opv.16.name=Батарейный буфер (16 gregtech.machine.battery_buffer.max.4.name=Батарейный буфер (4 ячейки §cMAX§r) gregtech.machine.battery_buffer.max.8.name=Батарейный буфер (8 ячеек §cMAX§r) gregtech.machine.battery_buffer.max.16.name=Батарейный буфер (16 ячеек §cMAX§r) -gregtech.battery_buffer.average_output=Выход в среднем: %s EU/t -gregtech.battery_buffer.average_input=Ввод в среднем: %s EU/t +gregtech.battery_buffer.average_output=Сред. вывод: %s EU/t: %s EU/t +gregtech.battery_buffer.average_input=Сред. ввод: %s EU/t # Transformers gregtech.machine.transformer.description=Преобразует энергию между уровнями напряжения @@ -3822,20 +3822,20 @@ gregtech.machine.transformer.adjustable.uev.name=Силовой трансфор gregtech.machine.transformer.adjustable.uiv.name=Силовой трансформатор (§2UIV§r) gregtech.machine.transformer.adjustable.uxv.name=Силовой трансформатор (§eUXV§r) gregtech.machine.transformer.adjustable.opv.name=Силовой трансформатор (§9OpV§r) -gregtech.machine.transformer.hi_amp.ulv.name=Высоковольтажный трансформатор (§8ULV§r) -gregtech.machine.transformer.hi_amp.lv.name=Высоковольтажный трансформатор (§7LV§r) -gregtech.machine.transformer.hi_amp.mv.name=Высоковольтажный трансформатор (§bMV§r) -gregtech.machine.transformer.hi_amp.hv.name=Высоковольтажный трансформатор (§6HV§r) -gregtech.machine.transformer.hi_amp.ev.name=Высокоамперный трансформатор (§5EV§r) -gregtech.machine.transformer.hi_amp.iv.name=Высокоамперный трансформатор (§1IV§r) -gregtech.machine.transformer.hi_amp.luv.name=Высокоамперный трансформатор (§dLuV§r) -gregtech.machine.transformer.hi_amp.zpm.name=Высокоамперный трансформатор (§fZPM§r) -gregtech.machine.transformer.hi_amp.uv.name=Высокоамперный трансформатор (§3UV§r) -gregtech.machine.transformer.hi_amp.uhv.name=Высокоамперный трансформатор (§4UHV§R) -gregtech.machine.transformer.hi_amp.uev.name=Высокоамперный трансформатор (§aUEV§r) -gregtech.machine.transformer.hi_amp.uiv.name=Высоковольтажный трансформатор (§2UIV§r) -gregtech.machine.transformer.hi_amp.uxv.name=Высоковольтажный трансформатор (§eUXV§r) -gregtech.machine.transformer.hi_amp.opv.name=Высоковольтажный трансформатор (§9OpV§r) +gregtech.machine.transformer.hi_amp.ulv.name=Высокотоковый трансформатор (§8ULV§r) +gregtech.machine.transformer.hi_amp.lv.name=Высокотоковый трансформатор (§7LV§r) +gregtech.machine.transformer.hi_amp.mv.name=Высокотоковый трансформатор (§bMV§r) +gregtech.machine.transformer.hi_amp.hv.name=Высокотоковый трансформатор (§6HV§r) +gregtech.machine.transformer.hi_amp.ev.name=Высокотоковый трансформатор (§5EV§r) +gregtech.machine.transformer.hi_amp.iv.name=Высокотоковый трансформатор (§1IV§r) +gregtech.machine.transformer.hi_amp.luv.name=Высокотоковый трансформатор (§dLuV§r) +gregtech.machine.transformer.hi_amp.zpm.name=Высокотоковый трансформатор (§fZPM§r) +gregtech.machine.transformer.hi_amp.uv.name=Высокотоковый трансформатор (§3UV§r) +gregtech.machine.transformer.hi_amp.uhv.name=Высокотоковый трансформатор (§4UHV§R) +gregtech.machine.transformer.hi_amp.uev.name=Высокотоковый трансформатор (§aUEV§r) +gregtech.machine.transformer.hi_amp.uiv.name=Высокотоковый трансформатор (§2UIV§r) +gregtech.machine.transformer.hi_amp.uxv.name=Высокотоковый трансформатор (§eUXV§r) +gregtech.machine.transformer.hi_amp.opv.name=Высокотоковый трансформатор (§9OpV§r) # Diodes gregtech.machine.diode.message=Макс. пропускная способность: %s @@ -4211,7 +4211,7 @@ gregtech.advancement.low_voltage.86_electrocution_death.name=Надо было gregtech.advancement.low_voltage.86_electrocution_death.desc=Прикосновение к неизолированному проводу убило вас. gregtech.advancement.low_voltage.88_first_cover_place.name=Первый из многих gregtech.advancement.low_voltage.88_first_cover_place.desc=Установите первое улучшение для машины. -gregtech.advancement.root_mv.name=Средний вольтаж +gregtech.advancement.root_mv.name=Среднее напряжение gregtech.advancement.root_mv.desc=Получите алюминий слиток. gregtech.advancement.medium_voltage.31_mv_energy_hatch.name=Улучшите вашу ЭДП gregtech.advancement.medium_voltage.31_mv_energy_hatch.desc=Создайте энергетический входной разъем (§bMV§r). @@ -4231,7 +4231,7 @@ gregtech.advancement.medium_voltage.38_super_chest.name=Новое хранил gregtech.advancement.medium_voltage.38_super_chest.desc=Соберите Супер сундук I. gregtech.advancement.medium_voltage.39_super_tank.name=Куда делся Океан? gregtech.advancement.medium_voltage.39_super_tank.desc=Соберите Супер резервуар I. -gregtech.advancement.root_hv.name=Высокий вольтаж +gregtech.advancement.root_hv.name=Высокое напряжение gregtech.advancement.root_hv.desc=Сделайте слиток нержавеющей стали. gregtech.advancement.high_voltage.40_workstation.name=Суперкомпьютеры gregtech.advancement.high_voltage.40_workstation.desc=Получите суперкомпьютер. @@ -4253,7 +4253,7 @@ gregtech.advancement.high_voltage.84_rotor_holder_open.name=Болезненны gregtech.advancement.high_voltage.84_rotor_holder_open.desc=Умереть, открыв вращающийся держатель ротора. gregtech.advancement.high_voltage.89_fluid_pipe_death_cold.name=Леденящий холод! gregtech.advancement.high_voltage.89_fluid_pipe_death_cold.desc=Умрите от жидкостной трубы, полной холодной жидкости. -gregtech.advancement.root_ev.name=Экстремальный вольтаж +gregtech.advancement.root_ev.name=Экстремальное напряжение gregtech.advancement.root_ev.desc=Охладите горячий титановый слиток. gregtech.advancement.extreme_voltage.47_nichrome_coil.name=Улучшите ваши катушки до уровня III gregtech.advancement.extreme_voltage.47_nichrome_coil.desc=Сделайте нихромовые катушки @@ -4267,7 +4267,7 @@ gregtech.advancement.extreme_voltage.51_large_combustion_engine.name=Больш gregtech.advancement.extreme_voltage.51_large_combustion_engine.desc=Соберите большой дизельный генератор, снабдите его смазкой и ускорьте кислородом. gregtech.advancement.extreme_voltage.52_soc_wafer.name=Пластина СНК gregtech.advancement.extreme_voltage.52_soc_wafer.desc=Сделайте Пластину СНК для более дешёвого производства микропроцессоров и интегральных микросхем. -gregtech.advancement.root_iv.name=Безумный вольтаж +gregtech.advancement.root_iv.name=Безумное напряжение gregtech.advancement.root_iv.desc=Охладите горячую вольфрамовую сталь. gregtech.advancement.insane_voltage.53_plutonium_239.name=Плутоний-239 gregtech.advancement.insane_voltage.53_plutonium_239.desc=Получите Плутоний-239 как источник Радона. @@ -4317,7 +4317,7 @@ gregtech.advancement.zero_point_module.80_hpca.name=Всё что надо дл gregtech.advancement.zero_point_module.80_hpca.desc=Соберите высокопроизводительный вычислительный массив. gregtech.advancement.zero_point_module.81_research_station.desc=Соберите Станцию исследований. gregtech.advancement.zero_point_module.81_research_station.name=Больше сложных вычислений -gregtech.advancement.root_uv.name=Предельный вольтаж +gregtech.advancement.root_uv.name=Предельное напряжение gregtech.advancement.root_uv.desc=Получите тританий. gregtech.advancement.ultimate_voltage.74_wetware_mainframe.name=Органический мейнфрейм gregtech.advancement.ultimate_voltage.74_wetware_mainframe.desc=Получите органический мейнфрейм. @@ -4341,7 +4341,7 @@ behaviour.paintspray.solvent.tooltip=Может удалить цвет с ве behaviour.paintspray.white.tooltip=Может окрасить в Белый behaviour.paintspray.orange.tooltip=Может окрасить в Оранжевый behaviour.paintspray.magenta.tooltip=Может окрасить в Пурпурный -behaviour.paintspray.lightBlue.tooltip=Может окрасить в Cветло-синий +behaviour.paintspray.lightBlue.tooltip=Может окрасить в Светло-синий behaviour.paintspray.yellow.tooltip=Может окрасить в Желтый behaviour.paintspray.lime.tooltip=Может окрасить в Лаймовый behaviour.paintspray.pink.tooltip=Может окрасить в Розовый @@ -4382,7 +4382,7 @@ gregtech.machine.large_chemical_reactor.name=Большой химический gregtech.machine.large_combustion_engine.name=Большой дизельный генератор gregtech.machine.extreme_combustion_engine.name=Улучшенный дизельный генератор gregtech.machine.large_combustion_engine.tooltip.boost_regular=Подавайте §f20 Л/с§7 кислорода для получения до §f%s§7 EU/t при §а2x§7 расходе топлива. -gregtech.machine.large_combustion_engine.tooltip.boost_extreme=Подавайте §e80 л/с§7 жидкого кислорода для получения до §f%s§7 EU/t при §а2x§7 расходе топлива. +gregtech.machine.large_combustion_engine.tooltip.boost_extreme=Подавайте §e80 Л/с§7 жидкого кислорода для получения до §f%s§7 EU/t при §а2x§7 расходе топлива. gregtech.machine.large_turbine.steam.name=Большая паровая турбина gregtech.machine.large_turbine.gas.name=Большая газовая турбина gregtech.machine.large_turbine.plasma.name=Большая плазменная турбина @@ -4402,7 +4402,7 @@ gregtech.machine.fusion_reactor.overclocking=Ускорение требует gregtech.machine.miner.lv.name=Обычный шахтер gregtech.machine.miner.mv.name=Улучшенный шахтер gregtech.machine.miner.hv.name=Улучшенный шахтер II -gregtech.machine.miner.tooltip=Добывает руды ТОЛЬКО ниже шахтера! Начинет работу в §f%sx%s §7области +gregtech.machine.miner.tooltip=Добывает руды ТОЛЬКО ниже шахтера! Начнет работу в §f%sx%s §7области gregtech.machine.miner.per_block=§7тратит §f%,dсек §7на блок gregtech.machine.large_miner.ev.name=Обычная буровая установка gregtech.machine.large_miner.iv.name=Улучшенная буровая установка @@ -4441,14 +4441,14 @@ gregtech.machine.cleanroom.tooltip.8=Подавайте питание чере gregtech.machine.cleanroom.tooltip.9=Отправляйте предметы и жидкости с помощью §fСквозных люков§7в стенах. gregtech.machine.cleanroom.tooltip.ae2.channels=Отправляйте до §f8 AE2 каналов §7через §fОболочку§7 в стенах. gregtech.machine.cleanroom.tooltip.ae2.no_channels=Отправляйте §aAE2 сеть§7 через §fОболочку§7 в стенах. -gregtech.multiblock.cleanroom.dirty_state=Статус: §4ЗАГРЯЗНЕНА -gregtech.multiblock.cleanroom.clean_state=Статус: §aЧИСТАЯ +gregtech.multiblock.cleanroom.dirty_state=ЗАГРЯЗНЕНА (%s%%) +gregtech.multiblock.cleanroom.clean_state=ЧИСТАЯ (%s%%) gregtech.machine.charcoal_pile.name=Воспламенитель угольной ямы -gregtech.machine.charcoal_pile.tooltip.1=§cПережигает§7 древесину в §aДревеный уголь§7. +gregtech.machine.charcoal_pile.tooltip.1=§cПережигает§7 древесину в §aДревесный уголь§7. gregtech.machine.charcoal_pile.tooltip.2=Щелкните правой кнопкой мыши предметом, зажигающим огонь, чтобы начать. gregtech.machine.charcoal_pile.tooltip.3=Прожиг происходит на расстоянии до §b9x4x9§7 под ним. gregtech.machine.charcoal_pile.tooltip.4=Древесина не должна подвергаться воздействию §eВоздуха§7! -gregtech.multiblock.charcoal_pile.description=Пережигает древесину в Древеный уголь.\n\nПол ямы должен быть сделан из кирпича, а для стен и крыши можно использовать любой блок земли. Внутри ямы не должно быть воздуха.\n\nБольшие ямы требуют больше времени для обработки древесины, но более эффективны. +gregtech.multiblock.charcoal_pile.description=Пережигает древесину в Древесный уголь.\n\nПол ямы должен быть сделан из кирпича, а для стен и крыши можно использовать любой блок земли. Внутри ямы не должно быть воздуха.\n\nБольшие ямы требуют больше времени для обработки древесины, но более эффективны. gregtech.machine.data_bank.name=Хранилище Данных gregtech.machine.data_bank.tooltip.1=Твой личный NAS gregtech.machine.data_bank.tooltip.2=Массовое хранение данных. Передача только по оптическим кабелям. @@ -4483,7 +4483,7 @@ gregtech.machine.high_performance_computing_array.name=Высокопроизв gregtech.machine.high_performance_computing_array.tooltip.1=Просто самый обычный Суперкомпьютер gregtech.machine.high_performance_computing_array.tooltip.2=Используется для генерации §fВычислений§7 (и тепла). gregtech.machine.high_performance_computing_array.tooltip.3=Требуются компоненты HPCA для создания §fCWU/t§7 (Вычислительные Рабочие Единицы). -gregtech.multiblock.high_performance_computing_array.description=Высокопроизводительный Вычислительный Массив (HPCA) представляет собой многоблочную структуру, используемую для создания Вычислительные Рабочие Единицы (CWU/t) для более Сложных Данных Исследования Cборочной Линии. Структура имеет гибкую область 3x3, которая может быть заполнена компонентами HPCA любым способом. Различные компоненты могут обеспечивать разное ко-во вычислений, охлаждения, а также затрат на энергию, стоимость охлаждающей жидкости и производство тепла. При использовании с компонентом моста HPCA может подключаться к сетевым коммутаторам для объединения и маршрутизации вычислений из нескольких источников в одно или несколько мест назначения. +gregtech.multiblock.high_performance_computing_array.description=Высокопроизводительный Вычислительный Массив (HPCA) представляет собой многоблочную структуру, используемую для создания Вычислительные Рабочие Единицы (CWU/t) для более Сложных Данных Исследования Cборочной Линии. Структура имеет гибкую область 3x3, которая может быть заполнена компонентами HPCA любым способом. Различные компоненты могут обеспечивать разное кол-во вычислений, охлаждения, а также затрат на энергию, стоимость охлаждающей жидкости и производство тепла. При использовании с компонентом моста HPCA может подключаться к сетевым коммутаторам для объединения и маршрутизации вычислений из нескольких источников в одно или несколько мест назначения. gregtech.machine.central_monitor.name=Центральный монитор gregtech.multiblock.central_monitor.low_power=Недостаточно энергии gregtech.multiblock.central_monitor.height=Высота экрана: @@ -4525,7 +4525,7 @@ gregtech.machine.large_turbine.steam.tooltip=Не суй свою голову gregtech.machine.large_turbine.gas.tooltip=Не Реактивный двигатель gregtech.machine.large_turbine.plasma.tooltip=Вытягиватель энергии из Плазмы gregtech.machine.large_boiler.bronze.tooltip=Нужно больше ПАРА! -gregtech.machine.large_boiler.steel.tooltip=Сжигатель древесного уголя +gregtech.machine.large_boiler.steel.tooltip=Сжигатель древесного угля gregtech.machine.large_boiler.titanium.tooltip=Где найти Магическое Супер-Топливо? gregtech.machine.large_boiler.tungstensteel.tooltip=Как вообще заправлять эту штуку? gregtech.machine.coke_oven.tooltip=Создание лучшего топлива для Стали и Энергии @@ -4742,7 +4742,7 @@ gregtech.machine.computation_hatch.receiver.tooltip=Вход Данных Выч gregtech.machine.research_station.object_holder.name=Держатель объекта gregtech.machine.research_station.object_holder.tooltip=Улучшенный держатель объекта для Станций исследований gregtech.machine.fluid_tank.max_multiblock=Максимальный размер: %,dx%,dx%,d -gregtech.machine.fluid_tank.fluid=Содержит %s mB %s +gregtech.machine.fluid_tank.fluid=Содержит %s мВ %s gregtech.machine.me_export_fluid_hatch.name=ME Выходной жидкостный люк gregtech.machine.me_export_item_bus.name=ME Выходной предметный люк gregtech.machine.me_import_fluid_hatch.name=ME Накопительный жидкостный люк @@ -4776,7 +4776,7 @@ gregtech.universal.tooltip.fluid_storage_capacity=§9Объем жидкости gregtech.universal.tooltip.fluid_storage_capacity_mult=§9Объем жидкости: §f%,d §7Хранилища, §f%,d Л §7каждое gregtech.universal.tooltip.fluid_stored=§dОбъем жидкости: §f%s, %,d Л gregtech.universal.tooltip.fluid_transfer_rate=§bСкорость передачи: §f%,d Л/т -gregtech.universal.tooltip.parallel=§dПаралеллей: §f%d +gregtech.universal.tooltip.parallel=§dПараллелей: §f%d gregtech.universal.tooltip.working_area=§bРабочая область: §f%,dx%,d gregtech.universal.tooltip.working_area_max=§bМакс. рабочая область: §f%,dx%,d gregtech.universal.tooltip.working_area_chunks_max=§bMax Working Area: §f%,dx%,d Chunks @@ -4794,7 +4794,7 @@ gregtech.block.tooltip.no_mob_spawning=§bМонстры не могут поя gregtech.recipe.total=Всего: %d EU gregtech.recipe.eu=Потребление: %d EU/т (%s§r) gregtech.recipe.eu_inverted=Производство: %d EU/т -gregtech.recipe.duration=Длительность: %s secs +gregtech.recipe.duration=Длительность: %s сек gregtech.recipe.amperage=Сила тока: %d gregtech.recipe.not_consumed=Не расходуется gregtech.recipe.chance=Шанс: %s%% +%s%%/уровень @@ -4807,9 +4807,9 @@ gregtech.recipe.cleanroom.display_name=Чистая комната gregtech.recipe.cleanroom_sterile.display_name=Стерильная чистая комната gregtech.recipe.research=Требует Исследование gregtech.recipe.computation_per_tick=Мин. Вычисления: %,d CWU/t -gregtech.fluid.click_to_fill=§7Нажмите с хралищем для жидкости, чтобы §bзаполнить §7резервуар. +gregtech.fluid.click_to_fill=§7Нажмите с хранилищем для жидкости, чтобы §bзаполнить §7резервуар. gregtech.fluid.click_to_empty=§7Нажмите с хралищем для жидкости, чтобы §cопустошить §7резервуар. -gregtech.fluid.click_combined=§7Нажмите с хралищем для жидкости, чтобы §bзаполнить §7или §cопустошить §7резервуар. +gregtech.fluid.click_combined=§7Нажмите с хранилищем для жидкости, чтобы §bзаполнить §7или §cопустошить §7резервуар. gregtech.tool_action.show_tooltips=Зажмите SHIFT для Информации о Инструменте gregtech.tool_action.screwdriver.auto_output=§8Используйте отвертку, чтобы переключить Авто-Вывод gregtech.tool_action.screwdriver.toggle_mode_covers=§8Используйте отвертку, чтобы переключить Режим или настроить улучшения @@ -4851,7 +4851,7 @@ gregtech.gui.fluid_auto_output.tooltip.disabled=Авто. вывод жидко gregtech.gui.item_auto_output.tooltip.enabled=Авто. вывод предметов включен gregtech.gui.item_auto_output.tooltip.disabled=Авто. вывод предметов отключен gregtech.gui.charger_slot.tooltip=§fСлот двухстороннего питания§r/n§7Может потреблять энергию от %s §7аккумуляторов либо-же отдавать -gregtech.gui.configurator_slot.tooltip=§fСлот Конфигурации§r\n§aУстановить Значение: §f%d§7\n\n§7ЛКМ/ПКМ/Прокрутка для переключения по листу\n§7Shift-ЛКМ чтобы выбрать селектор\n§7Shift-ПКМ для очистка +gregtech.gui.configurator_slot.tooltip=§fСлот Конфигурации§r/n§aУстановленное значение: §f%d§7/n/n§7ЛКМ/ПКМ/Прокрутка для переключения по листу/n§7Shift-ЛКМ чтобы выбрать селектор/n§7Shift-ПКМ для очистки gregtech.gui.fluid_lock.tooltip.enabled=Блокировка жидкости включена gregtech.gui.fluid_lock.tooltip.disabled=Блокировка жидкости выключена gregtech.gui.fluid_voiding.tooltip.enabled=Удаление избытков жидкости Включен @@ -4874,7 +4874,7 @@ gregtech.jei.ore.surface_rock_2=Их можно разбить на 3 Кроше gregtech.jei.ore.biome_weighting_title=§dОбщий вес модифицированного биома gregtech.jei.ore.biome_weighting=§d%s Объем: §3%d gregtech.jei.ore.biome_weighting_no_spawn=%s Объем: Не может появиться -gregtech.jei.ore.ore_weight=Обьём в жиле: %d%% +gregtech.jei.ore.ore_weight=Объем в жиле: %d%% gregtech.jei.ore.primary_1=Верхняя руда gregtech.jei.ore.primary_2=Появляется в верхних %d слоях жилы gregtech.jei.ore.secondary_1=Нижняя руда @@ -4903,10 +4903,10 @@ gregtech.jei.materials.average_neutrons=Ср. кол-во нейтронов: %, gregtech.jei.materials.average_protons=Ср. кол-во протонов: %,d gregtech.item_filter.empty_item=Пусто (нет предмета) gregtech.item_filter.footer=§eНажмите с предметом, чтобы переопределить -gregtech.cable.voltage=§aВольтаж: §f%,d §f(%s§f) +gregtech.cable.voltage=§Напряжение: §f%,d §f(%s§f) gregtech.cable.amperage=§eСила тока: §f%,d gregtech.cable.loss_per_block=§cПотеря за блок: §f%,d§f ЕУ-Вольт -gregtech.cable.superconductor=§d%s Суперпроводник +gregtech.cable.superconductor=§d%s Сверхпроводник gregtech.fluid_pipe.max_temperature=Максимальная температура: §f%,d K gregtech.fluid_pipe.channels=§eКаналов: §f%d gregtech.fluid_pipe.plasma_proof=§6Может хранить все виды Плазмы @@ -4938,7 +4938,7 @@ gregtech.multiblock.universal.problem.wire_cutter=%s§7Проводка пере gregtech.multiblock.universal.problem.crowbar=%s§7Что-то попало внутрь. (§aМонтировка§7) gregtech.multiblock.universal.muffler_obstructed=Что то мешает Люку глушителя. gregtech.multiblock.universal.distinct_enabled=Раздельные люки: §aВключено§r/nКаждый входной люк будет рассматриваться отдельно друг от друга для поиска рецепта. Полезно, например, для форм экструдера, лазерных линз и т.д. -gregtech.multiblock.universal.distinct_disabled=Раздельные люки: §aВsключено§r/nКаждый входной люк будет рассматриваться как комбинированный ввод для поиска рецепта. +gregtech.multiblock.universal.distinct_disabled=Раздельные люки: §aВключено§r/nКаждый входной люк будет рассматриваться как комбинированный ввод для поиска рецепта. gregtech.multiblock.universal.distinct_not_supported=Эту структура не поддерживает Раздельные Люки gregtech.multiblock.universal.no_flex_button=Эта структура не имеет дополнительных функций с этой кнопкой. gregtech.multiblock.parallel=Макс. Параллелей: %s @@ -4947,7 +4947,7 @@ gregtech.multiblock.multiple_recipemaps.tooltip=Нажмите отвёртко gregtech.multiblock.multiple_recipemaps_recipes.tooltip=Режим машин: §e%s§r gregtech.multiblock.multiple_recipemaps.switch_message=Для переключения режимов машина должна быть выключена! gregtech.multiblock.energy_stored=Энергия: %s EU / %s EU -gregtech.multiblock.preview.zoom=Используйте колёсико мыши или Shift+RMB для масштаба +gregtech.multiblock.preview.zoom=Используйте колёсико мыши или Shift+ПКМ для масштаба gregtech.multiblock.preview.rotate=Нажмите и вращайте для поворота gregtech.multiblock.preview.select=Правой кнопкой по блоку вы можете посмотреть варианты gregtech.multiblock.pattern.error_message_header=Возможная ошибка структуры: @@ -4971,16 +4971,16 @@ gregtech.multiblock.blast_furnace.max_temperature=Максимальная те gregtech.multiblock.multi_furnace.heating_coil_discount=EU усиление нагревательной катушки: %sx gregtech.multiblock.distillation_tower.distilling_fluid=Дистилляция %s gregtech.multiblock.large_combustion_engine.no_lubricant=Нет Смазки. -gregtech.multiblock.large_combustion_engine.lubricant_amount=Кол-во смазки: %smB -gregtech.multiblock.large_combustion_engine.oxygen_amount=Кол-во кислорода: %smB -gregtech.multiblock.large_combustion_engine.liquid_oxygen_amount=Кол-во жид. кислорода: %smB +gregtech.multiblock.large_combustion_engine.lubricant_amount=Кол-во смазки: %s +gregtech.multiblock.large_combustion_engine.oxygen_amount=Кол-во кислорода: %s +gregtech.multiblock.large_combustion_engine.liquid_oxygen_amount=Кол-во жид. кислорода: %s gregtech.multiblock.large_combustion_engine.oxygen_boosted=§bКислород добавлен. -gregtech.multiblock.large_combustion_engine.liquid_oxygen_boosted=§bЖидкий кислород добавлен. +gregtech.multiblock.large_combustion_engine.liquid_oxygen_boosted=§bЖид. кислород добавлен. gregtech.multiblock.large_combustion_engine.supply_oxygen_to_boost=Принимает кислород для ускорения. -gregtech.multiblock.large_combustion_engine.supply_liquid_oxygen_to_boost=Принимает жидкий кислород для ускорения. +gregtech.multiblock.large_combustion_engine.supply_liquid_oxygen_to_boost=Принимает жид. кислород для ускорения. gregtech.multiblock.large_combustion_engine.obstructed=Что-то мешает воздухозаборнику двигателя. -gregtech.multiblock.turbine.fuel_amount=Топлива: %smB (%s) -gregtech.multiblock.turbine.rotor_speed=Скорость: %s/%s об/мин +gregtech.multiblock.turbine.fuel_amount=Топлива: %sмВ (%s) +gregtech.multiblock.turbine.rotor_speed=Скорость: %s gregtech.multiblock.turbine.rotor_durability=Прочность ротора: %s gregtech.multiblock.turbine.rotor_durability_low=Прочность ротора низкая! gregtech.multiblock.turbine.no_rotor=Нет Ротора в Держателе ротора. @@ -5042,15 +5042,15 @@ gregtech.multiblock.hpca.warning_temperature_active_cool=Полное испол gregtech.multiblock.hpca.warning_structure_header=Подсказки по структуре: gregtech.multiblock.hpca.warning_multiple_bridges=- Множество мостов в структуре (не дают дополнительных преимущество) gregtech.multiblock.hpca.warning_no_computation=- Не проводятся вычисления -gregtech.multiblock.hpca.warning_low_cooling=- Не достаточно хладогента -gregtech.command.usage=Применение: /gregtech +gregtech.multiblock.hpca.warning_low_cooling=- Не достаточно хладагента +gregtech.command.usage=Применение: /gregtech gregtech.command.worldgen.usage=Применение: /gregtech worldgen gregtech.command.worldgen.reload.usage=Применение: /gregtech worldgen reload gregtech.command.worldgen.reload.success=Генератор мира успешно перезагрузился из настроек. gregtech.command.worldgen.reload.failed=Перезагрузка генератора мира окончилась ошибкой. Проверьте ошибки в консоли. gregtech.command.hand.usage=Применение: /gregtech hand gregtech.command.hand.item_id=Предмет: %s (Метаданные: %d) -gregtech.command.hand.electric=Информация о заряде: %d / %d Уровень вольтажа: %d; Это батарея: %s +gregtech.command.hand.electric=Информация о заряде: %d / %d Уровень напряжения: %d; Это батарея: %s gregtech.command.hand.fluid=Информация о жидкости: %d / %d мВ; Можно залить: %s; Можно слить: %s gregtech.command.hand.fluid2=ID жидкости: gregtech.command.hand.material=ID материала: @@ -5076,10 +5076,10 @@ gregtech.creative.chest.item=Предмет gregtech.creative.chest.ipc=Предметов за цикл gregtech.creative.chest.tpc=Тиков в цикле gregtech.creative.tank.fluid=Жидкость -gregtech.creative.tank.mbpc=mB за цикл +gregtech.creative.tank.mbpc=мВ за цикл gregtech.creative.tank.tpc=Тиков в цикле gregtech.creative.energy.amperage=Сила тока -gregtech.creative.energy.voltage=Вольтаж +gregtech.creative.energy.voltage=Напряжение gregtech.creative.activity.on=Включить gregtech.creative.activity.off=Выключить gregtech.terminal.app_name.items=Учебник по предметам @@ -5121,7 +5121,7 @@ texture.modify_gui_texture.missing=Отсутствует текстура texture.url_texture.fail=Загрузка не удалась terminal.hw.battery=Аккумулятор terminal.hw.device=Устройство -terminal.os.shutdown_confirm=Завершение работы (Нажмите ESC что-бы завершить) +terminal.os.shutdown_confirm=Завершение работы (Нажмите ESC чтобы завершить) terminal.os.hw_demand=Нет нужного оборудования: terminal.system_call.null=NULL terminal.system_call.call_menu=Боковая панель @@ -5305,7 +5305,7 @@ gregtech.subtitle.tick.forge_hammer=Кувалда крушит gregtech.subtitle.tick.macerator=Предмет измельчается gregtech.subtitle.tick.chemical_reactor=Химикаты реагируют gregtech.subtitle.tick.assembler=Предмет собирается -gregtech.subtitle.tick.centrifuge=Предметы расщипляются +gregtech.subtitle.tick.centrifuge=Предметы расщепляются gregtech.subtitle.tick.compressor=Предмет сжимается gregtech.subtitle.tick.electrolyzer=Элементы электризуются gregtech.subtitle.tick.mixer=Пыль смешивается @@ -5327,7 +5327,7 @@ gregtech.subtitle.use.soft_hammer=Блок размолот gregtech.subtitle.use.drill=Бур засверлил gregtech.subtitle.use.plunger=Вантуз пробил gregtech.subtitle.use.file=Напильник отшлифовал -gregtech.subtitle.use.saw=Дерево рапилилось +gregtech.subtitle.use.saw=Дерево распилилось gregtech.subtitle.use.screwdriver=Болт закрутился gregtech.subtitle.use.chainsaw=Бензопила рычит gregtech.subtitle.use.wirecutter=Щелчок проводов @@ -5554,7 +5554,7 @@ tile.studs.silver.name=Светло-серая перегородка tile.studs.cyan.name=Бирюзовая перегородка tile.studs.purple.name=Фиолетовая перегородка gregtech.scanner.copy_stick_from=§oСкопировать Флешку -gregtech.scanner.copy_stick_to=§oСкопирова в Флешку +gregtech.scanner.copy_stick_to=§oСкопировать в Флешку gregtech.scanner.copy_stick_empty=§oПустая флешка gregtech.material.rtm_alloy=РВМ Сплав tile.metal_sheet.red.name=Красный лист металла @@ -5571,9 +5571,9 @@ tile.large_metal_sheet.green.name=Крупный зеленый лист мет gregtech.machine.alarm.name=Тревога gregtech.machine.world_accelerator.mv.tooltip=Тик ускоряет блоки gregtech.machine.world_accelerator.ev.tooltip=Тик ускоряет блоки -gregtech.machine.world_accelerator.iv.tooltip=Время в §mБутылке§r§7 Блоке -gregtech.machine.world_accelerator.luv.tooltip=Время в §mБутылке§r§7 Блоке -gregtech.machine.world_accelerator.zpm.tooltip=Время в §mБутылке§r§7 Блоке +gregtech.machine.world_accelerator.iv.tooltip=Время в §mБутылке§r§7 в Блоке +gregtech.machine.world_accelerator.luv.tooltip=Время в §mБутылке§r§7 в Блоке +gregtech.machine.world_accelerator.zpm.tooltip=Время в §mБутылке§r§7 в Блоке gregtech.machine.world_accelerator.uv.tooltip=Временная аномалия tile.wire_coil.rtm_alloy.name=Катушка из РВМ Сплава tile.metal_sheet.green.name=Зеленый лист металла @@ -5722,8 +5722,8 @@ gregtech.multiblock.fluid_rig.fluid_amount=Скорость добычи: %s gregtech.multiblock.fluid_rig.vein_depletion=Размер: %s gregtech.multiblock.fluid_rig.vein_depleted=Жила опустошена. gregtech.multiblock.miner.drilling=Бурение. -gregtech.multiblock.hpca.info_max_cooling_demand=Потребность в хладогенте: %s -gregtech.multiblock.hpca.info_max_coolant_required=Хладогента требуется: %s +gregtech.multiblock.hpca.info_max_cooling_demand=Потребность в хладагенте: %s +gregtech.multiblock.hpca.info_max_coolant_required=Хладагента требуется: %s gregtech.multiblock.hpca.info_coolant_name=Хладоген (ПХД) gregtech.multiblock.hpca.info_bridging_enabled=Мост Включен gregtech.multiblock.hpca.info_bridging_disabled=Мост Выключен @@ -5746,11 +5746,11 @@ item.gt.comb.ash.name=Пепельные соты item.gt.comb.biomass.name=Соты биомассы item.gt.comb.energy.name=Энергетические соты item.gt.comb.lapotron.name=Лапотронные соты -item.gt.comb.stainlesssteel.name=Соты нержавеки +item.gt.comb.stainlesssteel.name=Соты нержавейки item.gt.comb.stone.name=Каменные соты item.gt.comb.certus.name=Кварцевые соты item.gt.comb.redstone.name=Редстоун соты -item.gt.comb.rareearth.name=Соты редкой земли +item.gt.comb.rareearth.name=Соты редкоземельных элементов item.gt.comb.ruby.name=Рубиновые соты item.gt.comb.sapphire.name=Сапфировые соты item.gt.comb.diamond.name=Алмазные соты @@ -5815,7 +5815,7 @@ for.bees.species.lead=Свинцовая for.bees.species.iron=Железная for.bees.species.nickel=Никелевая for.bees.species.zinc=Цинковая -for.bees.species.silver=Серебрянная +for.bees.species.silver=Серебряная for.bees.species.gold=Золотая for.bees.species.arsenic=Мышьяковая for.bees.species.titanium=Титановая @@ -5871,7 +5871,7 @@ gregtech.veins.ore.raw_oil_sphere=Залежь нефти gregtech.veins.fluid.natural_gas_nether=Залежь природного газа Нижнего мира gregtech.multiblock.multi_furnace.heating_coil_discount_hover=Множитель энергопотребления задается уровнем катушки gregtech.multiblock.large_combustion_engine.liquid_oxygen_boost_disallowed=Улучшите выходной разъем, чтобы включить жидкостный форсаж. -gregtech.multiblock.hpca.info_max_cooling_available=Хладогента доступно: %s +gregtech.multiblock.hpca.info_max_cooling_available=Хладагента доступно: %s gregtech.creative.energy.sink=Разряд metaitem.electrode.copper.name=Медный электрод item.gt.tool.behavior.scoop=§dЛовец: §fЛовит бабочек при ЛКМ @@ -5881,7 +5881,7 @@ item.gt.comb.lapis.name=Ляписовые соты item.gt.comb.emerald.name=Изумрудные соты item.gt.comb.tin.name=Оловянные соты item.gt.comb.steel.name=Стальные соты -item.gt.comb.silver.name=Серебрянные соты +item.gt.comb.silver.name=Серебряные соты item.gt.comb.magnesium.name=Магниевые соты item.gt.comb.molybdenum.name=Молибденовые соты item.gt.comb.uranium.name=Урановые соты @@ -5929,16 +5929,19 @@ cover.bucket.mode.milli_bucket_exact=Л option.gregtech.converter=Энерго-преобразователи option.gregtech.energy=Энергохранилища option.gregtech.block_lamp=Лампы -option.gregtech.maintenance=Неисправености +option.gregtech.maintenance=Неисправности option.gregtech.block_ore=Блоки руды option.gregtech.controllable=Управляемые машины option.gregtech.multiblock=Мультиблочные структуры -cover.conveyor.distribution.name=Режим распространения +cover.conveyor.distribution.name=Режим распределения cover.bucket.mode.milli_bucket_rate=Л/с gregtech.machine.me.stocking_item.tooltip=Извлекает предметы непосредственно из сети ME gregtech.machine.me_import_item_hatch.configs.tooltip=Держит 16 предметов в наличии tile.gt_explosive.breaking_tooltip=При обычной добыче взрывается, добудьте с SHIFT, чтобы забрать обратно gregtech.machine.me.stocking_fluid.tooltip=Извлекает жидкости непосредственно из сети ME +gregtech.machine.me.copy_paste.tooltip=ЛКС с Флешкой для копирования, ПКМ для применения +gregtech.machine.me.import_copy_settings=Настройки сохранены в Флешку +gregtech.machine.me.import_paste_settings=Настройки из Флешки применены gregtech.machine.me.fluid_import.data_stick.name=§oНастройки ME Накопительного жидкостного люка gregtech.recipe.dimensions_blocked=Заблокированные измерения: %s gregtech.gui.item_auto_input.tooltip.enabled=Авто. ввод предметов включен @@ -5953,9 +5956,9 @@ tile.gt_explosive.lighting_tooltip=Нельзя зажечь с помощью gregtech.multiblock.power_substation.average_in_hover=Средний приход EU/t в внутреннее хранилище вашей Силовой Подстанции gregtech.machine.me.stocking_item.tooltip.2=Авто-вытягивание из МЕ сети будет автоматически пополнять первые 16 предметов в МЕ сети, обновляясь раз в 5 сек. gregtech.machine.me.stocking_fluid.tooltip.2=Авто-вытягивание из МЕ сети будет автоматически пополнять первые 16 слотов жидкости в МЕ сети, обновляясь раз в 5 сек. -gregtech.gui.config_slot.auto_pull_managed=§4Отключено:§7 Управляется Авто-вытягивание +gregtech.gui.config_slot.auto_pull_managed=§4Отключено:§7 Управляется Авто-вытягиванием tile.itnt.drops_tooltip=Намного мощнее, чем TNT. Все взорванные блоки выпадают как предметы -gregtech.multiblock.cleanroom.low_tier=Уровень вольтажа слишком низкий, требуется %s или выше! +gregtech.multiblock.cleanroom.low_tier=Уровень напряжения слишком низкий, требуется %s или выше! gregtech.gui.item_auto_input.tooltip.disabled=Авто. ввод предметов выключен gregtech.gui.me_bus.extra_slot=Доп. Слот/n§7Вложите доп. предмет для рецептов, например Линзы или Формы gregtech.multiblock.power_substation.average_in=Сред. вход. EU: %s @@ -5983,3 +5986,70 @@ gregtech.machine.me.stocking_auto_pull_enabled=Авто-вытягивание cover.machine_controller.this_cover=§cЭто улучшение cover.machine_controller.cover_not_controllable=§cНет управляемых улучшений cover.machine_controller.control=Управление: +gregtech.material.ilmenite_slag=Ильменитовый шлак +gregtech.material.zirconia=Оксид циркония +gregtech.command.datafix.usage=Применение: /gregtech datafix +gregtech.material.decalcified_bauxite_sludge=Декальцинированный шлам боксита +gregtech.material.zircon=Циркон +gregtech.material.zirconium_tetrachloride=Тетрахлорид циркония +gregtech.material.hafnia=Гафнии +gregtech.material.hafnium_tetrachloride=Тетрахлорид гафния +gregtech.material.zircaloy_4=Циркалой-4 +gregtech.material.inconel_718=Инконель-718 +gregtech.material.bauxite_sludge=Шлам боксита +gregtech.material.bauxite_slurry=Бокситовая суспензия +gregtech.material.cracked_bauxite_slurry=Бокситовая суспензия прошедшая крекинг +gregtech.material.bauxite_slag=Бокситовый шлак +gregtech.command.datafix.bqu.usage=Применение: /gregtech datafix bqu [confirm] +gregtech.command.datafix.bqu.backup=Скопируйте ваши сохранения и папку настроек BQu, а после перезапустите с 'confirm' аргументов +gregtech.command.datafix.bqu.start=Начинается перенос BQu Базы данных Квестов... +gregtech.command.datafix.bqu.complete=Закончен перенос Базы данных Квестов +gregtech.command.datafix.bqu.failed=Перенос Базы данных Квестов был произведен с ошибкой. Восстановите ваши сохранения! +behavior.tricorder.mte_owner=Владелец: %s +behavior.tricorder.mte_owner_offline=Владелец Не в сети или Не в этом мире! +behavior.tricorder.mte_owner_null=Это установлено не игроком! +cover.ender_fluid_link.transfer_unit=Л/т +cover.generic.ender.known_channels=Известные каналы +cover.generic.ender.open_selector=Открыть выбор +cover.generic.ender.set_description.tooltip=Описание +cover.generic.ender.set_description.title=Описание [%s] +cover.generic.ender.delete_entry=Удалить запись +gregtech.machine.me.extra_connections.disabled=Разрешить соединения только с лицевой стороны +gregtech.machine.me.extra_connections.enabled=Разрешить соединения со всех сторон +gregtech.waila.energy_input=Вход: %s EU/т +gregtech.waila.energy_output=Выход: %s EU/т +gregtech.battery_buffer.average_input.top=Ввод: %s +gregtech.battery_buffer.average_output.top=Выход: %s +gregtech.multiblock.active_transformer.max_in=Макс. вход: %s +gregtech.multiblock.active_transformer.max_out=Макс. выход: %s +gregtech.multiblock.active_transformer.average_io=Сред. Вх./Вых.: %s +gregtech.machine.me.extra_connections.tooltip=ПКМ с кусачками, чтобы разрешить подключение к AE2 с любых сторон +gregtech.waila.active_transformer.average_io=Сред. Вх./Вых.: %s EU/т +gregtech.top.quantum_controller.no_hatches=§cНет подключенных энергетических разъемов +behavior.tricorder.quantum_storage.usage=Используется %s EU/т Квантовым контроллером +gregtech.machine.super_tank.ulv.name=Простой резервуар I +gregtech.jei.ct_recipe.tooltip=CraftTweaker рецепт +gregtech.machine.super_chest.ulv.name=Простой сундук I +gregtech.machine.quantum_storage_extender.tooltip=Расширяет сеть квантового хранилища к другим сундукам/резервуарам +gregtech.machine.quantum_storage_controller.tooltip=Сердце сети квантового хранилища/nПодключите Энергетические разьемы для включения Сети квантового хранилища +gregtech.jei.gs_recipe.tooltip=GroovyScript рецепт +gregtech.top.quantum_status.label=Статус: +gregtech.top.quantum_status.powered=§bВ сети +gregtech.top.quantum_status.connected=§сНе в сети +gregtech.top.quantum_status.disconnected=Не подключено +gregtech.top.quantum_controller.no_power=§сНет энергии +gregtech.jei.remove_recipe.tooltip=Копирует фрагмент %s, чтобы удалить этот рецепт +gregtech.top.steam_cooling_down=Охлаждение +behavior.tricorder.quantum_controller.usage=Используется: %s EU/т (%s) +behavior.tricorder.quantum_controller.connected_items=Подключено хранилищ: %s +behavior.tricorder.quantum_controller.connected_fluids=Подключено резервуаров: %s +gregtech.machine.quantum_storage_controller.name=Контроллер квантового хранилища +gregtech.machine.quantum_storage_proxy.name=Прокси квантового хранилища +gregtech.machine.quantum_storage_proxy.tooltip=Прокси разьем квантового хранилища +gregtech.machine.quantum_storage_extender.name=Расширитель квантового хранилища +gregtech.machine.quantum_storage.connected=Подключено к Квантовому контроллеру в [%d, %d, %d]/n/nНажмите, чтобы выделить контроллер +gregtech.machine.quantum_storage.disconnected=Не подключено +cover.filter.allow_flow.tooltip=По умолчанию предметы/жидкости могут перемещаться\nтолько в направлении фильтра в соответствии с его настройками.\n\nЕсли включено, предметы/жидкости могут проходить\nбез фильтрации в противоположном направлении от этого фильтра. +cover.generic.disabled=Выключено +cover.generic.enabled=Включено +cover.filter.allow_flow.label=Разрешено diff --git a/src/main/resources/assets/gregtech/lang/uk_ua.lang b/src/main/resources/assets/gregtech/lang/uk_ua.lang new file mode 100644 index 00000000000..972e9e985bb --- /dev/null +++ b/src/main/resources/assets/gregtech/lang/uk_ua.lang @@ -0,0 +1,1721 @@ + + +death.attack.heat=%s зварили живцем +death.attack.chemical=%s потрапив у хімічний інцидент +death.attack.electric=%s був убитий струмом +death.attack.radiation=%s тепер світиться від радості +death.attack.turbine=%s засунув голову в турбіну +death.attack.explosion=%s вибухнув +death.attack.explosion.player=%s вибухнув з допомогою %s +death.attack.heat.player=%s був зварений живцем з допомогою %s +death.attack.shovel=%s було викопано з допомогою %s +death.attack.axe=%s було порубано на шматки з допомогою %s +death.attack.hammer=%s був розчавлений з допомогою %s +death.attack.mallet=%s був забитий до смерті з допомогою %s +death.attack.mining_hammer=%s був помилково прийнятий за руду %s +death.attack.wrench=%s вдарив %s гайковим ключем! +death.attack.frost=%s досліджував кріогенні технології +death.attack.mortar=%s було розтерто на порох з допомогою %s +death.attack.wire_cutter=кабель життєзабезпечення %s був перерізаний %s +death.attack.knife=%s був ніжно вдарений ножем з допомогою %s +death.attack.drill_lv=%s був пробурений при напрузі 32V з допомогою %s +death.attack.wrench_iv=До планів %s несподівано був доданий гайковий ключ %s +death.attack.buzzsaw=%s був розпиляний з допомогою %s +enchantment.disjunction=Роз'єднання +gregtech.machine.steam_grinder.name=Парова дробарка +death.attack.drill_hv=%s був пробурений при напрузі 512V з допомогою %s +death.attack.drill_iv=%s був пробурений при напрузі 8192V з допомогою %s +death.attack.chainsaw_lv=%s був розпиляний з допомогою %s +gregtech.multiblock.steam.low_steam=Не вистачає пари для роботи! +gregtech.machine.steam_hatch.name=Паровий люк +gregtech.multiblock.steam.steam_stored=Пар: %s +gregtech.machine.steam.steam_hatch.tooltip=§eМожливі рідини: §fПар +gregtech.machine.steam_import_bus.name=Парова вхідна шина +gregtech.machine.steam_export_bus.name=Парови вихідна шина +gregtech.machine.steam_oven.name=Парова мультиплавильна піч +gregtech.multiblock.require_steam_parts=Потребує парові люки та шини! +gregtech.multiblock.steam_.duration_modifier=Потребує в §f1.5x §7більше часу, не залежить від кількості предметів. +gregtech.top.energy_production=Виготовляє +gregtech.top.transform_down=Знижувати +gregtech.top.transform_input=Вхід: +gregtech.top.transform_output=Вихід: +gregtech.top.steam_heating_up=Нагрівання: +gregtech.top.steam_no_water=Немає води +gregtech.top.convert_fe=Конвертація §cFE§r -> §eEU§r +gregtech.top.invalid_structure=Структура незавершена +gregtech.top.obstructed_structure=Структура заблокована +gregtech.top.maintenance_fixed=Технічне обслуговування непотрібне +gregtech.top.maintenance.wrench=Труба ослаблена +gregtech.top.maintenance.screwdriver=Гвинти ослаблені +gregtech.top.maintenance.hard_hammer=Обшивка має вм'ятини +gregtech.top.maintenance.crowbar=Щось там не повинно бути +gregtech.top.mode.export=Експортуємо +gregtech.top.unit.items=Предмети +gregtech.top.unit.fluid_milibuckets=МЛ +gregtech.top.unit.fluid_buckets=Л +gregtech.top.block_drops=Випадає +gregtech.top.ld_pipe_incomplete=Незавершений трубопровід +gregtech.top.ld_pipe_length=Довжина: +option.gregtech.converter=Енергетичні конвертори +option.gregtech.diode=Діоди +option.gregtech.energy=Енергосховища +option.gregtech.block_lamp=Лампи +option.gregtech.multi_recipemap=Режими роботи +option.gregtech.multiblock=Багатоблочні конструкції +option.gregtech.primitive_pump=Примітивний насос +option.gregtech.transformer=Трансформатори +gregtech.waila.progress_idle=Холостий +gregtech.waila.progress_sec=Прогрес: %d s / %d s +gregtech.waila.progress_computation=Розрахунок: %s / %s +gregtech.multiblock.title=Схема багатоблокової структури +gregtech.multiblock.assembly_line.description=Складальна лінія - це велика багатоблочна конструкція, що складається з 5 до 16 "шматочків". Теоретично, це велика складальна машина, що використовується для виготовлення покращених компонентів. +gregtech.multiblock.fusion_reactor.uv.description=Термоядерний реактор модель 3 - це велика багатоблочна конструкція, яка використовується для злиття елементів у більш важкі. Може використовувати лише енергетичні люки типу UV. З кожним люком буфер енергії збільшується на 40 млн EU, і має максимум у 640 млн EU. +gregtech.multiblock.fusion_reactor.heat=Тепло: %s +metaitem.coin.doge.name=Догкоін +metaitem.shape.empty.name=Порожня форма +metaitem.dynamite.name=Динаміт +metaitem.power_unit.lv.name=Блок живлення (LV) +metaitem.power_unit.mv.name=Блок живлення (MV) +metaitem.power_unit.hv.name=Блок живлення (HV) +metaitem.nano_saber.name=Наношабля +metaitem.nano_saber.tooltip=Ryujin no ken wo kurae! +metaitem.shape.mold.plate.tooltip=Форма для виготовлення пластин +metaitem.shape.mold.plate.name=Форма (Пластина) +metaitem.shape.mold.gear.tooltip=Форма для виготовлення шестерень +metaitem.shape.mold.gear.name=Форма (Шестерня) +metaitem.shape.mold.bottle.name=Форма (Пляшка) +metaitem.shape.mold.bottle.tooltip=Форма для виготовлення пляшок +metaitem.shape.mold.ingot.name=Форма (Злиток) +metaitem.shape.mold.ball.name=Форма (Куля) +metaitem.shape.mold.ball.tooltip=Форма для виготовлення куль +metaitem.shape.mold.block.name=Форма (Блок) +metaitem.shape.mold.nugget.name=Форма (самородки) +metaitem.shape.mold.cylinder.name=Форма (Циліндр) +metaitem.shape.mold.name.name=Форма (Назва) +metaitem.shape.mold.cylinder.tooltip=Форма для формування циліндрів +metaitem.shape.mold.gear.small.tooltip=Форма для виготовлення малих шестерень +metaitem.shape.mold.rotor.name=Форма (Ротор) +metaitem.shape.extruder.plate.name=Форма екструдера (пластина) +metaitem.shape.extruder.plate.tooltip=Форма екструдера для виготовлення пластин +metaitem.shape.extruder.bolt.name=Форма екструдера (Болт) +metaitem.shape.extruder.ring.tooltip=Форма екструдера для виготовлення кілець +metaitem.shape.extruder.cell.name=Форма екструдера (Капсула) +metaitem.shape.extruder.casing.name=Форма екструдера (Корпус) +metaitem.shape.extruder.pipe.tiny.name=Форма екструдера (Крихітна трубка) +metaitem.shape.extruder.pipe.small.name=Форма екструдера (маленька труба) +metaitem.shape.extruder.pipe.normal.tooltip=Форма екструдера для виготовлення труб +metaitem.shape.extruder.pipe.large.name=Форма екструдера (Велика труба) +metaitem.shape.extruder.pipe.huge.tooltip=Форма екструдера для виготовлення величезних труб +metaitem.shape.extruder.block.name=Форма екструдера (Блок) +metaitem.shape.extruder.block.tooltip=Форма екструдера для виготовлення блоків +metaitem.shape.extruder.shovel.tooltip=Форма екструдера для виготовлення лопат +metaitem.shape.extruder.hoe.name=Форма екструдера (Головка мотики) +metaitem.shape.extruder.hoe.tooltip=Форма екструдера для виготовлення мотик +metaitem.shape.extruder.saw.name=Форма екструдера (Пильний диск) +metaitem.shape.extruder.saw.tooltip=Форма екструдера для виготовлення пилок +metaitem.shape.extruder.gear.name=Форма екструдера (Шестерня) +death.attack.pickaxe=мізки %s було вибито з допомогою %s +death.attack.hoe=%s був проораний з допомогою %s +death.attack.wrench_hv=Труби %s були послаблені з допомогою %s +gregtech.multiblock.steam_grinder.description=Багатоблочний подрібнювач парової епохи. Для побудови потрібно щонайменше 14 бронзових корпусів. Не може використовувати звичайні вхідні/вихідні шини, або рідині люки. Може використовувати тільки парові люки. +gregtech.multiblock.steam_oven.description=Мультиплавильна піч парової епохи. Для побудови потрібно щонайменше 6 бронзових корпусів. Не може використовувати звичайні вхідні/вихідні шини, або рідині люки. Може використовувати тільки парові люки. Паровий люк має бути на першому рівні, та не має бути більше одного. +gregtech.top.working_disabled=Робота призупинена +gregtech.top.transform_up=Підвищує +gregtech.top.convert_eu=Конвертація §eEU§r -> §cFE§r +gregtech.top.valid_structure=Структура завершена +gregtech.top.maintenance.wire_cutter=Дроти перегоріли +gregtech.top.mode.import=Імпортуємо +gregtech.top.ld_pipe_no_network=Не знайдено жодного трубопроводу +gregtech.top.ld_pipe_connected=Трубопровід під'єднано +gregtech.top.ld_pipe_output=Вихід +gregtech.top.ld_pipe_input_endpoint=Кінцева точка входу: +gregtech.top.ld_pipe_output_endpoint=Кінцева точка виходу: +option.gregtech.controllable=Керовані машини +option.gregtech.maintenance=Проблеми з технічним обслуговуванням +option.gregtech.recipe_logic=Рецепти +option.gregtech.steam_boiler=Парові котли +gregtech.waila.energy_stored=Енергія: %s EU / %s EU +death.attack.spade=%s був розкопаний з допомогою %s +death.attack.screwdriver_lv=Гвинти %s були відкручені з допомогою %s +gregtech.top.energy_consumption=Використовує +gregtech.top.maintenance_broken=Технічне обслуговування потрібне +gregtech.top.maintenance.soft_mallet=Щось заклинило +gregtech.top.primitive_pump_production=Виробництво: +gregtech.top.filter.label=Фільтр: +gregtech.top.link_cover.color=Колір: +gregtech.top.ld_pipe_input=Вхід +option.gregtech.block_ore=Рудні блоки +option.gregtech.workable=Механізми +gregtech.waila.progress_tick=Прогрес: %d t / %d t +gregtech.machine.steam_bus.tooltip=Не працює з не паровими багатоблочними конструкціями +metaitem.shape.mold.name.tooltip=Форма для іменування предметів у формувальному пресі (перейменувати форму за допомогою ковадла) +metaitem.shape.mold.gear.small.name=Форма (Мала шестерня) +metaitem.shape.mold.rotor.tooltip=Форма для виготовлення роторів +metaitem.shape.extruder.rod.name=Форма екструдера (Cтержень) +metaitem.shape.extruder.ingot.tooltip=Форма екструдера для, зачекайте, хіба ми не можемо просто використовувати піч? +metaitem.shape.extruder.wire.tooltip=Форма екструдера для виготовлення дротів +metaitem.shape.extruder.pipe.tiny.tooltip=Форма екструдера для виготовлення крихітних труб +metaitem.shape.extruder.pipe.small.tooltip=Форма екструдера для виготовлення малих труб +metaitem.shape.extruder.pipe.normal.name=Форма екструдера (Труба) +metaitem.shape.extruder.pipe.large.tooltip=Форма екструдера для виготовлення великих труб +metaitem.shape.extruder.pipe.huge.name=Форма екструдера (Величезна труба) +metaitem.shape.extruder.sword.tooltip=Форма екструдера для виготовлення мечів +metaitem.shape.extruder.pickaxe.name=Форма екструдера (Головка кайла) +metaitem.shape.extruder.pickaxe.tooltip=Форма екструдера для виготовлення кайла +gregtech.multiblock.primitive_blast_furnace.bronze.description=Примітивна доменна піч (ПДП) це багатоблочна структура, що використовуєть для виготовлення сталі на початку гри. Хоча вона і не дуже швидка, вона забезпечить вам сталь для перших кроків. +gregtech.multiblock.coke_oven.description=Коксова піч - це багатоблочна конструкція, яка використовується для отриманя коксу та креозоту на початку гри. Вона не потребує палива і має внутрішній резервуар на 32 відра креозоту. Доступ до інвентарю можна отримати через люк коксової печі. +gregtech.multiblock.vacuum_freezer.description=Вакуумна морозильна камера - це багатоблочна структура, яка в більшості випадків використовується для охолоджування гарячих злитків до їхньоніх звичайних температур. Також може заморожувати інші речовини, до прикладу вода. +gregtech.multiblock.implosion_compressor.description=Імплохійний компресор - це багатоблочна структура яка використовує вибухівки щоб перетворити пил на відповідні дорогоцінні камені. +gregtech.multiblock.pyrolyse_oven.description=Піролізна піч - це багатоблочна конструкція, яка використовується для перетворення колод на деревне вугілля та креозот, або золу та тяжку нафту. +gregtech.multiblock.cracker.description=Крекінгова установка - це багатоблочна конструкція, яка використовується для перетворення легкого та важкаго палина на їхні потріскані варіанти. +gregtech.multiblock.large_combustion_engine.description=Великий двигун внутрішнього згоряння - це багатоблочна конструкція, яка діє як генератор внетрішнього згоряння для вироблення EV енергіє. +metaitem.shape.mold.anvil.name=Форма (Ковадло) +metaitem.shape.mold.anvil.tooltip=Форма для формування ковадла +metaitem.shape.extruder.rod.tooltip=Форма екструдера для виготовлення стержнів +metaitem.shape.extruder.bolt.tooltip=Форма екструдера для виготовлення болтів +metaitem.shape.extruder.ring.name=Форма екструдера (Кільце) +metaitem.shape.extruder.cell.tooltip=Форма екструдера для виготовлення капсул +metaitem.shape.extruder.ingot.name=Форма екструдера (злиток) +metaitem.shape.extruder.wire.name=Форма екструдера (Дріт) +metaitem.shape.extruder.casing.tooltip=Форма екструдера для виготовлення корпусів +metaitem.shape.extruder.sword.name=Форма екструдера (Лезо меча) +metaitem.shape.extruder.shovel.name=Форма екструдера (Головка лопати) +metaitem.shape.extruder.axe.name=Форма екструдера (Головка сокири) +metaitem.shape.extruder.axe.tooltip=Форма екструдера для виготовлення сокир +death.attack.file=%s був заокруглений до сметрі з допомогою %s +death.attack.drill_ev=%s був пробурений при напрузі 2048V з допомогою %s +death.attack.butchery_knife=%s був перетворений у фарш з допомогою %s +death.attack.drill_mv=%s був пробурений при напрузі 128V з допомогою %s +death.attack.wrench_lv=Труби %s були ослаблені з допомогою %s +gregtech.multiblock.large_turbine.description=Великі турбіни - це багатоблочна конструкція яка генерую електроенергію з пари, газів, і плазми шляхом обертання ротора турбіни. Вихід енергії залежить від ефективності ротора та поточної швидкості турбіни. У центрі конструкції використовуються корпуси коробки передач. +metaitem.shape.extruder.hammer.name=Форма екструдера (Молоткова головка) +metaitem.shape.extruder.hammer.tooltip=Форма екструдера для виготовлення молотків +metaitem.shape.extruder.file.tooltip=Форма екструдера для воготовлення напилка +metaitem.shape.extruder.file.name=Форма екструдера (Головка напилка) +metaitem.shape.extruder.gear.tooltip=Форма екструдера для виготовлення шестерень +metaitem.shape.extruder.bottle.name=Форма екструдера (Пляшка) +death.attack.scythe=Душу %s було викрадено з допомогою %s +gregtech.multiblock.extreme_combustion_engine.description=Екстремальний двигун внутрішнього згорання - це багатоблочна конструкція, яка діє як генератор згоряння для IV рівня напруги. +gregtech.multiblock.distillation_tower.description=Дистиляціна вежа - це багатоблочана конструкція, яка використовується для перегонки різних видів нафти та деяких побічних продуктів. Кожен шар починаючи з другого повинен мати рівно один вихідний люк. Нижній шар може виводити продукти і вводити рідини в будь-якому положенні. +gregtech.multiblock.electric_blast_furnace.description=Електрична доменна піч (ЕДП) - це багатоблочна конструкція, яка використовується для виплавки сплавів, готових металів та переробки сирих. Вона необхідна для отримання високоякісних сплавів і металів, таких як алюміній, нержавіюча сталь, титат і сплав наквади. +gregtech.multiblock.multi_furnace.description=Мультиплавильна піч - це багатоблочна конструкція, яка використовується для виплавлення великої кількості предметів. Різні рівні котушок забезпечують підвищення швидкості та енергоефективності. 32 - це базова кількість предметів, що виплавляються за операцію, яке можна збільшити, використовуючи котушки вищого рівня. +gregtech.multiblock.large_boiler.description=Великі котли - це багатоблочна структура, яка виробляє пар за допомогою енергії та води. Джерелом енергії є будь-яке тверде паливо з певним часом горіння або дизельне/напіврідке паливо. Може бути сповільнене заради зменшення кількості пари та потрібного палива. +gregtech.multiblock.fusion_reactor.luv.description=Термоядерний реактор модель 1 - це велика багатоблочна конструкція, яка використовується для злиття елементів у більш важкі. Може використовувати лише енергетичні люки типу LuV, ZPM, і UV. З кожним люком буфер енергії збільшується на 10 млн EU, і має максимум у 160 млн EU. +gregtech.multiblock.fusion_reactor.zpm.description=Термоядерний реактор модель 2 - це велика багатоблочна конструкція, яка використовується для злиття елементів у більш важкі. Може використовувати лише енергетичні люки типу ZPM і UV. З кожним люком буфер енергії збільшується на 20 млн EU, і має максимум у 320 млн EU. +gregtech.multiblock.large_chemical_reactor.description=Великий хімічний реактор виконує хімічні реакції зі 100%% енергоефективністю. Розгін збільшує швидкість і евергію в 4 рази. Багатоблочна конструкція потребує рівно 1 купронікелевий блок, який повинен бути розміщений поруч з копрусом ПТФЕ труби, розташованим в центрі. +metaitem.credit.platinum.tooltip=512 Кредитів +metaitem.credit.osmium.tooltip=4096 Кредити +metaitem.credit.naquadah.name=Наквадовий Кредит +metaitem.coin.gold.ancient.name=Старовинна золота монета +metaitem.coin.gold.ancient.tooltip=Знайдено в стародавніх руїнах +metaitem.power_unit.iv.name=Блок живлення (IV) +metaitem.shape.mold.casing.tooltip=Форма для виготовлення корпусів +metaitem.shape.mold.block.tooltip=Форма для виготовлення блоків +gregtech.multiblock.primitive_water_pump.description=Примітивна водяна помпа - це багатоблочна конструкція до парової ери, яка збирає води один раз на секунду, залежно в якому біома. Вона може використовувати помповий, ULV або LV вихідний люк, збільшуючи кількість води на рівень. Розраховується за формулою: коефіцієнь біома * множник люка +metaitem.credit.osmium.name=Осмійські Кредит +metaitem.credit.naquadah.tooltip=32768 Кредити +metaitem.credit.neutronium.name=Нейтронний кредит +metaitem.credit.neutronium.tooltip=262144 Кредити +metaitem.coin.chocolate.name=Шоколадна монетка +metaitem.coin.chocolate.tooltip=Загорнутий у золото +metaitem.shape.empty.tooltip=Сировина для виготовлення прес-форм та екструзійних форм +metaitem.power_unit.ev.name=Блок живлення (EV) +metaitem.shape.mold.credit.name=Форма (Монета) +metaitem.shape.mold.credit.tooltip=Безпечна форма для виготовлення монет (не загуби!) +metaitem.shape.mold.casing.name=Форма (Корпус) +metaitem.shape.mold.ingot.tooltip=Форма для виготовлення злитків +metaitem.shape.mold.nugget.tooltip=Форма для виготовлення самородків +gregtech.multiblock.primitive_water_pump.extra2=Множники люків:/n Люк насоса: 1x/n Вихідний люк ULV: 2x/n Вихідний люк LV: 4x/n/nПід час дощу в біомі насоса загальне виробництво води збільшується на 50%%. +gregtech.multiblock.processing_array.description=Оброблювальний масив об'єднує до 16 одноблочних машин в один мультиблок, що значно полегшує автоматизацію. +item.invalid.name=Некоректний предмет +fluid.empty=Порожньо +gregtech.tooltip.hold_shift=Утримуйте SHIFT, щоб дізнатися більше +gregtech.tooltip.hold_ctrl=Утримуйте CTRL, щоб дізнатися більше +gregtech.tooltip.tool_fluid_hold_shift=Утримуйте SHIFT, щоб відобразити інформацію про рідину та інструмент +metaitem.generic.fluid_container.tooltip=%,d/%,dЛ %s +metaitem.generic.electric_item.tooltip=%,d/%,d EU - Рівень %s +metaitem.electric.discharge_mode.enabled=§eУвімкнено режим розрядки +metaitem.dust.tooltip.purify=Киньте в Казан, щоб отримати чистий пил +metaitem.int_circuit.configuration=§aНалаштоване значення: §f%d§7 +metaitem.credit.copper.tooltip=0.125 Кредитів +metaitem.credit.silver.name=Срібний кредит +metaitem.credit.silver.tooltip=8 кредитів +metaitem.credit.gold.name=Золотий кредит +metaitem.credit.gold.tooltip=64 Кредитів +metaitem.credit.platinum.name=Платиновий кредит +metaitem.shape.extruder.rod_long.tooltip=Форма екструдера для виготовлення довгих стержнів +metaitem.shape.extruder.rod_long.name=Форма екструдера (Довгий стержень) +metaitem.spray.empty.name=Балончик (порожній) +metaitem.spray.empty.tooltip=Можна наповнювати спреями різних кольорів + +# Fluid Cells +metaitem.fluid_cell.empty=Порожньо +metaitem.fluid_cell.name=%s Капсула +metaitem.fluid_cell.universal.name=%s Універсальна капсула +metaitem.large_fluid_cell.steel.name=%s Сталева капсула +metaitem.fluid_cell.glass_vial.name=%s Пробірка +metaitem.large_fluid_cell.titanium.name=%s Титанова капсула +metaitem.spray.solvent.name=Балончик (розчинник) +metaitem.spray.can.dyes.orange.name=Балончик (помаранчевий) +metaitem.spray.can.dyes.purple.name=Балончик (фіолетовий) +metaitem.tool.matches.name=Сірник +metaitem.tool.lighter.platinum.name=Платинова запальничка +metaitem.battery.hull.hv.name=Великий корпус батареї +metaitem.battery.hull.ev.name=Малий корпус ванадієвої батареї +metaitem.battery.hull.zpm.name=Корпус середньої наквадівої батареї +metaitem.battery.hull.zpm.tooltip=Порожній §fZPM §7корпус батареї +metaitem.battery.hull.uv.name=Корпус великої наквадівої батареї +metaitem.battery.hull.uv.tooltip=Порожній §3UV §7корпус батареї +metaitem.battery.charge_time=§aЗберігає %,d%s електроенергії +metaitem.battery.charge_unit.minute=хв +metaitem.battery.charge_unit.hour=год +metaitem.battery.re.ulv.tantalum.name=Танталовий конденсатор +metaitem.battery.re.lv.cadmium.name=Маленька кадмієва батарея +metaitem.battery.re.lv.cadmium.tooltip=Багаторазова батарея +metaitem.battery.re.lv.lithium.name=Маленька літієва батарея +metaitem.battery.re.mv.cadmium.tooltip=Багаторазова батарея +metaitem.battery.re.mv.sodium.tooltip=Багаторазова батарея +metaitem.battery.re.hv.cadmium.name=Велика кадмієва батарея +metaitem.battery.re.hv.cadmium.tooltip=Багаторазова батарея +metaitem.battery.re.hv.lithium.name=Велика літієва батарея +metaitem.battery.re.hv.sodium.name=Велика натрієва батарея +metaitem.battery.ev.vanadium.name=Маленька ванадієва батарея +metaitem.battery.iv.vanadium.name=Середня ванадієва батарея +metaitem.battery.luv.vanadium.name=Велика ванадієва батарея +metaitem.battery.luv.vanadium.tooltip=Багаторазова батарея +metaitem.battery.uv.naquadria.name=Велика наквадрієва батарея +metaitem.energy_crystal.name=Енергетичний кристал +metaitem.energy.lapotronic_orb.tooltip=Багаторазова батарея +metaitem.energy.lapotronic_orb_cluster.name=Лапотронний кластер енергетичних куль +metaitem.energy.module.name=Енергетичний модуль +metaitem.energy.cluster.name=Енергетичний кластер +metaitem.max.battery.tooltip=Зарядіть це, щоб виграти Minecraft +metaitem.electric.motor.luv.name=Електродвигун LuV +metaitem.electric.motor.zpm.name=Електродвигун ZPM +metaitem.electric.motor.uev.name=Електродвигун UEV +metaitem.electric.motor.uxv.name=Електродвигун UXV +metaitem.electric.pump.ev.name=Електронасос EV +metaitem.electric.pump.iv.name=Електронасос IV +metaitem.electric.pump.uev.name=Електронасос UEV +metaitem.electric.pump.uxv.name=Електронасос UXV +metaitem.fluid.regulator.lv.name=Регулятор рідини LV +metaitem.fluid.regulator.mv.name=Регулятор рідини MV +metaitem.fluid.regulator.luv.name=Регулятор рідини LuV +metaitem.fluid.regulator.uv.name=Регулятор рідини UV +metaitem.conveyor.module.lv.name=Конвеєрний модуль LV +metaitem.conveyor.module.mv.name=Конвеєрний модуль MV +metaitem.conveyor.module.ev.name=Конвеєрний модуль EV +metaitem.conveyor.module.zpm.name=Конвеєрний модуль ZPM +metaitem.conveyor.module.uhv.name=Конвеєрний модуль UHV +metaitem.conveyor.module.uiv.name=Конвеєрний модуль UIV +metaitem.conveyor.module.uxv.name=Конвеєрний модуль UXV +metaitem.conveyor.module.opv.name=Конвеєрний модуль OpV +metaitem.electric.piston.lv.name=Електричний поршень LV +metaitem.electric.piston.mv.name=Електричний поршень MV +metaitem.electric.piston.ev.name=Електричний поршень EV +metaitem.electric.piston.iv.name=Електричний поршень IV +metaitem.electric.piston.luv.name=Електричний поршень LuV +metaitem.electric.piston.zpm.name=Електричний поршень ZPM +metaitem.electric.piston.uhv.name=Електричний поршень UHV +metaitem.electric.piston.uev.name=Електричний поршень UEV +metaitem.electric.piston.uiv.name=Електричний поршень UIV +metaitem.electric.piston.uxv.name=Електричний поршень UXV +metaitem.electric.piston.opv.name=Електричний поршень OpV +metaitem.robot.arm.mv.name=Роботизована рука MV +metaitem.robot.arm.hv.name=Роботизована рука HV +metaitem.robot.arm.iv.name=Роботизована рука IV +metaitem.robot.arm.luv.name=Роботизована рука LuV +metaitem.robot.arm.uv.name=Роботизована рука UV +metaitem.robot.arm.uhv.name=Роботизована рука UHV +metaitem.robot.arm.uiv.name=Роботизована рука UIV +metaitem.robot.arm.opv.name=Роботизована рука OpV +metaitem.field.generator.mv.name=Генератор поля MV +metaitem.field.generator.ev.name=Генератор поля EV +metaitem.field.generator.iv.name=Генератор поля IV +metaitem.field.generator.luv.name=Генератор поля LuV +metaitem.field.generator.zpm.name=Генератор поля ZPM +metaitem.field.generator.uhv.name=Генератор поля UHV +metaitem.field.generator.uev.name=Генератор поля UEV +metaitem.field.generator.uiv.name=Генератор поля UIV +metaitem.emitter.mv.name=Випромінювач MV +metaitem.emitter.ev.name=Випромінювач EV +metaitem.emitter.iv.name=Випромінювач IV +metaitem.emitter.luv.name=Випромінювач LuV +metaitem.emitter.zpm.name=Випромінювач ZPM +metaitem.emitter.uev.name=Випромінювач UEV +metaitem.emitter.uxv.name=Випромінювач UXV +metaitem.emitter.opv.name=Випромінювач OpV +metaitem.sensor.lv.name=Сенсор LV +metaitem.sensor.mv.name=Сенсор MV +metaitem.sensor.ev.name=Сенсор EV +metaitem.sensor.iv.name=Сенсор IV +metaitem.sensor.luv.name=Сенсор LuV +metaitem.sensor.zpm.name=Сенсор ZPM +metaitem.sensor.uv.name=Сенсор UV +metaitem.sensor.uhv.name=Сенсор UHV +metaitem.sensor.uev.name=Сенсор UEV +metaitem.sensor.uiv.name=Сенсор UIV +metaitem.sensor.opv.name=Сенсор OpV +metaitem.tool.datastick.name=Накопичувач даних +metaitem.tool.datastick.tooltip=Сховище для простих даних +metaitem.tool.dataorb.name=Сфера даних +metaitem.tool.datamodule.name=Модуль даних +metaitem.circuit.integrated.name=Запрограмована схема +metaitem.circuit.integrated.tooltip=ПКМ щоб відкрити графічний інтерфейс/n/nShift-ПКМ по машині/nзі схемою в руці/nщоб запрограмувати машину./n +metaitem.circuit.integrated.gui=Конфігурація схеми +item.glass.lens=Скляна лінза (Біла) +metaitem.glass_lens.orange.name=Скляна лінза (Помаранчева) +metaitem.glass_lens.magenta.name=Скляна лінза (Пурпурна) +metaitem.glass_lens.pink.name=Скляна лінза (Рожева) +metaitem.glass_lens.yellow.name=Скляна лінза (Жовта) +metaitem.glass_lens.light_gray.name=Скляна лінза (Світло-сіра) +metaitem.glass_lens.cyan.name=Скляна лінза (Блакитна) +metaitem.glass_lens.purple.name=Скляна лінза (Фіолетова) +metaitem.glass_lens.green.name=Скляна лінза (Зелена) +metaitem.glass_lens.red.name=Скляна лінза (Червона) +metaitem.glass_lens.black.name=Скляна лінза (Чорна) + +#CIRCUITS LOCALIZATION +metaitem.boule.silicon.name=Монокристалічний кремній +metaitem.boule.phosphorus.tooltip=Необроблена схема +metaitem.boule.naquadah.tooltip=Необроблена схема +metaitem.boule.neutronium.tooltip=Необроблена схема +metaitem.wafer.phosphorus.tooltip=Необроблена схема +metaitem.board.epoxy.tooltip=Покращена плата +metaitem.board.fiber_reinforced.tooltip=Екстремально гарна плата +metaitem.board.multilayer.fiber_reinforced.name=Багато рівнева посилена волокном друкована плата +metaitem.board.fiber_reinforced.name=Посилена волокном друкована плата +metaitem.board.multilayer.fiber_reinforced.tooltip=Відмінна плата +metaitem.board.wetware.name=Друкована плата зі системою життєзабезпечення +metaitem.board.wetware.tooltip=Плата, яка зберігає життя +metaitem.circuit_board.basic.name=Друкована плата +metaitem.circuit_board.basic.tooltip=Базова друкована плата +metaitem.circuit_board.good.name=Гарна друкована плата +metaitem.circuit_board.good.tooltip=Гарна друкована плата +metaitem.circuit_board.plastic.name=Пластикова друкована плата +metaitem.circuit_board.plastic.tooltip=Гарна друкована плата +metaitem.circuit_board.advanced.name=Покращена друкована плата +metaitem.circuit_board.advanced.tooltip=Покращена друкована плата +metaitem.circuit_board.extreme.name=Екстремально гарна друкована плата +metaitem.circuit_board.extreme.tooltip=Більш покращена друкована плата +metaitem.circuit_board.elite.tooltip=Відмінна друкована плата +metaitem.circuit.vacuum_tube.name=Вакумна лампа +metaitem.component.diode.name=Діод +metaitem.component.diode.tooltip=Базовий електричний компонент +metaitem.component.resistor.name=Резистор +metaitem.component.resistor.tooltip=Базовий електричний компонент +metaitem.component.transistor.name=Транзистор +metaitem.component.capacitor.name=Конденсатор +metaitem.component.glass.tube.name=Скляна трубка +metaitem.component.inductor.name=Індуктор +metaitem.component.inductor.tooltip=Мала котушка +metaitem.component.smd.diode.name=SMD Діод +metaitem.component.smd.capacitor.name=SMD Конденсатор +metaitem.component.smd.capacitor.tooltip=Електричний компонент +metaitem.component.smd.transistor.tooltip=Електричний компонент +metaitem.component.smd.resistor.name=SMD Резистор +metaitem.component.smd.resistor.tooltip=Електричний компонент +metaitem.component.smd.inductor.name=SMD Індуктор +metaitem.component.smd.inductor.tooltip=Електричний компонент +metaitem.component.advanced_smd.diode.name=Покращений SMD Діод +metaitem.component.advanced_smd.capacitor.name=Покращений SMD Конденсатор +metaitem.component.advanced_smd.capacitor.tooltip=Покращений електричний компонент +metaitem.component.advanced_smd.transistor.name=Покращений SMD Транзистор +metaitem.component.advanced_smd.resistor.name=Покращений SMD Резистор +metaitem.component.advanced_smd.resistor.tooltip=Покращений електричний компонент +metaitem.component.advanced_smd.inductor.name=Покращений SMD Індуктор +metaitem.component.advanced_smd.inductor.tooltip=Покращений електричний компонент +metaitem.wafer.advanced_system_on_chip.name=Пластина ASoC +metaitem.wafer.advanced_system_on_chip.tooltip=Необроблена покращена схема +metaitem.wafer.central_processing_unit.tooltip=Необроблений модуль обробки +metaitem.credit.cupronickel.name=Купронікелевий кредит +metaitem.credit.cupronickel.tooltip=1 Кредит +metaitem.electric.discharge_mode.tooltip=Використовуйте затиснувши кнопку Присісти для перемикання режиму розрядки +metaitem.crushed.tooltip.purify=Киньте в казан, щоб отримати очищену руду +metaitem.shape.extruder.rotor.name=Форма екструдера (Ротор) +metaitem.shape.extruder.rotor.tooltip=Форма екструдера для виготовлення роторів +metaitem.credit.copper.name=Мідний кредит +gregtech.multiblock.primitive_water_pump.extra1=Коефіцієнт біома:/n Океан, річка: 1000 л/с/n Болото: 800 л/с/n Джунглі: 350 л/с/n Засніжені: 300 л/с/n Рівнина, ліс: 250 л/с/n Тайга: 175 л/с/n Пляж: 170 Л/с/n Інше: 100 л/с +gregtech.multiblock.advanced_processing_array.description=Оброблювальний масив об'єднує до 64 одноблочних машин в один мультиблок, що значно полегшує автоматизацію. +gregtech.tooltip.fluid_pipe_hold_shift=Утримуйте SHIFT, щоб відобразити інформацію про рідину +metaitem.electric.discharge_mode.disabled=§eВимкнено режим розряду +metaitem.shape.extruder.bottle.tooltip=Форма екструдера для виготовлення пляшок +metaitem.shape.extruder.gear_small.tooltip=Форма екструдера для виготовлення малих шестерень +metaitem.shape.extruder.foil.name=Форма екструдера (Фольга) +metaitem.shape.extruder.gear_small.name=Форма екструдера (Мала шестерня) +metaitem.shape.extruder.foil.tooltip=Форма екструдера для виготовлення фольги з неметалів +metaitem.plant.ball.name=Кулька біомаси +metaitem.fluid_cell.universal.empty=Порожньо +metaitem.large_fluid_cell.aluminium.name=%s Алюмінієва капсула +metaitem.large_fluid_cell.stainless_steel.name=%s Капсула з нержавіючої сталі +metaitem.large_fluid_cell.tungstensteel.name=%s Вольфрамова капсула +metaitem.spray.can.dyes.white.name=Балончик (білий) +metaitem.spray.can.dyes.magenta.name=Балончик (пурпурний) +metaitem.spray.can.dyes.yellow.name=Балончик (жовтий) +metaitem.spray.can.dyes.lime.name=Балончик (лайм) +metaitem.spray.can.dyes.pink.name=Балончик (рожевий) +metaitem.spray.can.dyes.gray.name=Балончик (сірий) +metaitem.spray.can.dyes.silver.name=Балончик (світло-сірий) +metaitem.spray.can.dyes.cyan.name=Балончик (блакитний) +metaitem.spray.can.dyes.blue.name=Балончик (синій) +metaitem.spray.can.dyes.brown.name=Балончик (коричневий) +metaitem.spray.can.dyes.green.name=Балончик (зелений) +metaitem.spray.can.dyes.red.name=Балончик (червоний) +metaitem.spray.can.dyes.black.name=Балончик (чорний) +metaitem.tool.matchbox.name=Сірникова коробка +metaitem.tool.matchbox.tooltip=Це не автомобіль +metaitem.tool.lighter.platinum.tooltip=На ньому викарбувано відомого майстра жартів +metaitem.battery.hull.lv.tooltip=Порожній §7LV §7корпус батареї +metaitem.battery.hull.mv.tooltip=Порожній §bMV §7корпус батареї +metaitem.tool.lighter.invar.name=Запальничка + + +metaitem.battery.hull.lv.name=Малий корпус батареї +metaitem.battery.hull.mv.name=Середній корпус батареї +metaitem.battery.hull.hv.tooltip=Великий §6HV §7корпус батареї +metaitem.battery.hull.iv.name=Корпус середньої ванадієвої батареї +metaitem.battery.hull.iv.tooltip=Порожній §1IV §7корпус батареї +metaitem.battery.re.ulv.tantalum.tooltip=Багаторазова батарея +metaitem.battery.re.lv.sodium.tooltip=Багаторазова батарея +metaitem.battery.re.mv.cadmium.name=Середня кадмієва батарея +metaitem.battery.re.hv.lithium.tooltip=Багаторазова батарея +metaitem.battery.re.hv.sodium.tooltip=Багаторазова батарея +metaitem.battery.ev.vanadium.tooltip=Багаторазова батарея +metaitem.battery.iv.vanadium.tooltip=Багаторазова батарея +metaitem.battery.zpm.naquadria.name=Середня наквадрієва батарея +metaitem.battery.zpm.naquadria.tooltip=Багаторазова батарея +metaitem.battery.hull.ev.tooltip=Порожній §5EV §7корпус батареї +metaitem.battery.hull.luv.name=Великий ванадієвий корпус батареї +metaitem.battery.hull.luv.tooltip=Порожній §dLuV §7корпус батареї +metaitem.battery.charge_unit.second=сек +metaitem.battery.re.lv.lithium.tooltip=Багаторазова батарея +metaitem.battery.re.lv.sodium.name=Маленька натрієва батарея +metaitem.battery.re.mv.lithium.name=Середня літієва батарея +metaitem.battery.re.mv.lithium.tooltip=Багаторазова батарея +metaitem.battery.re.mv.sodium.name=Середня натрієва батарея +metaitem.battery.uv.naquadria.tooltip=Багаторазова батарея +metaitem.energy_crystal.tooltip=Багаторазова батарея +metaitem.lapotron_crystal.name=Лапотроний кристал +metaitem.lapotron_crystal.tooltip=Багаторазова батарея +metaitem.energy.lapotronic_orb_cluster.tooltip=Багаторазова батарея +metaitem.zpm.name=Модуль нульової точки +metaitem.energy.cluster.tooltip=Багаторазова батарея +metaitem.max.battery.name=Досконала батарея +metaitem.electric.motor.iv.name=Електродвигун IV +metaitem.energy.lapotronic_orb.name=Лапотронічна енергетична куля +metaitem.energy.module.tooltip=Багаторазова батарея +metaitem.fluid.regulator.tooltip=Обмежує §fРідини§7 до певної кількості, працює як §fПокращення§7. +metaitem.electric.pump.tooltip=Переводить §fРідини§7 з одинаковою швидкістю, працює як §fПокращення§7. +metaitem.electric.motor.lv.name=Електродвигун LV +metaitem.electric.motor.mv.name=Електродвигун MV +metaitem.electric.motor.hv.name=Електродвигун HV +metaitem.electric.motor.ev.name=Електродвигун EV +metaitem.electric.motor.uhv.name=Електродвигун UHV +metaitem.electric.motor.uiv.name=Електродвигун UIV +metaitem.electric.motor.opv.name=Електродвигун OpV +metaitem.electric.pump.lv.name=Електронасос LV +metaitem.electric.pump.hv.name=Електронасос HV +metaitem.electric.pump.uhv.name=Електронасос UHV +metaitem.fluid.regulator.hv.name=Регулятор рідини HV +metaitem.fluid.regulator.ev.name=Регулятор рідини EV +metaitem.conveyor.module.hv.name=Конвеєрний модуль HV +metaitem.conveyor.module.iv.name=Конвеєрний модуль IV +metaitem.conveyor.module.uev.name=Конвеєрний модуль UEV +metaitem.conveyor.module.tooltip=Передає §fПредмети§7 з одинаковою швидкістю, працює як §fПокращення§7. +metaitem.electric.piston.hv.name=Електричний поршень HV +metaitem.electric.piston.uv.name=Електричний поршень UV +metaitem.robot.arm.uxv.name=Роботизована рука UXV +metaitem.field.generator.lv.name=Генератор поля LV +metaitem.field.generator.uxv.name=Генератор поля UXV +metaitem.emitter.lv.name=Випромінювач LV +metaitem.electric.motor.uv.name=Електродвигун UV +metaitem.electric.pump.mv.name=Електронасос MV +metaitem.electric.pump.luv.name=Електронасос LuV +metaitem.electric.pump.zpm.name=Електронасос ZPM +metaitem.electric.pump.uv.name=Електронасос UV +metaitem.electric.pump.uiv.name=Електронасос UIV +metaitem.electric.pump.opv.name=Електронасос OpV +metaitem.fluid.regulator.iv.name=Регулятор рідини IV +metaitem.fluid.regulator.zpm.name=Регулятор рідини ZPM +metaitem.conveyor.module.luv.name=Конвеєрний модуль LuV +metaitem.conveyor.module.uv.name=Конвеєрний модуль UV +metaitem.robot.arm.lv.name=Роботизована рука LV +metaitem.robot.arm.ev.name=Роботизована рука EV +metaitem.robot.arm.zpm.name=Роботизована рука ZPM +metaitem.robot.arm.uev.name=Роботизована рука UEV +metaitem.robot.arm.tooltip=Обмежує §fПредмети§7 до певної кількості, працює як §fПокращення§7. +metaitem.field.generator.hv.name=Генератор поля HV +metaitem.field.generator.uv.name=Генератор поля UV +metaitem.field.generator.opv.name=Генератор поля OpV +metaitem.emitter.hv.name=Випромінювач HV +metaitem.emitter.uv.name=Випромінювач UV +metaitem.emitter.uiv.name=Випромінювач UIV +metaitem.tool.dataorb.tooltip=Сховище для складних даних +metaitem.tool.datamodule.tooltip=Сховище для неймовірно складних даних/n§cМоже бути прочитане лише банком даних +metaitem.emitter.uhv.name=Випромінювач UHV +metaitem.sensor.hv.name=Сенсор HV +metaitem.sensor.uxv.name=Сенсор UXV +metaitem.board.epoxy.name=Епоксидна друкована плата +metaitem.glass_lens.light_blue.name=Скляна лінза (Світло-блакитна) +metaitem.circuit.integrated.jei_description=JEI показує рецепти тільки для даної конфігурації.\n\nВи можете вибрати конфігурацію у графічному інтерфейсі схеми. +metaitem.spray.can.dyes.light_blue.name=Балончик (світло-синій) +metaitem.glass_lens.blue.name=Скляна лінза (Синя) +metaitem.boule.silicon.tooltip=Необроблена схема +metaitem.wafer.silicon.tooltip=Необроблена схема +metaitem.wafer.phosphorus.name=Пластина легована фосфором +metaitem.wafer.naquadah.name=Пластина легована наквадою +metaitem.boule.naquadah.name=Монокристалічний кремній легований наквадою +metaitem.board.plastic.name=Пластмасова друкована плата +metaitem.circuit_board.elite.name=Відмінна друкована плата +metaitem.circuit_board.wetware.tooltip=Плата, яка зберігає життя +metaitem.circuit.vacuum_tube.tooltip=Технічно це діод/n рівень §cULV +metaitem.component.transistor.tooltip=Базовий електричний компонент +metaitem.glass_lens.lime.name=Glass Lens (Лаймова) +metaitem.glass_lens.gray.name=Скляна лінза (Сіра) +metaitem.glass_lens.brown.name=Скляна лінза (Коричнева) +metaitem.boule.phosphorus.name=Монокристалічний кремній легований фосфором +metaitem.wafer.silicon.name=Кремнієва Пластина +metaitem.wafer.naquadah.tooltip=Необроблена схема +metaitem.wafer.neutronium.name=Пластина легована нейтронами +metaitem.boule.neutronium.name=Монокристалічний кремній легований нейтронами +metaitem.wafer.neutronium.tooltip=Необроблена схема +metaitem.board.coated.name=Друкована плата з покриттям +metaitem.board.coated.tooltip=Плата з покриттям +metaitem.board.phenolic.name=Фенольна друкована плата +metaitem.board.phenolic.tooltip=Гарна плата +metaitem.board.plastic.tooltip=Гарна плата +metaitem.component.capacitor.tooltip=Базовий електричний компонент +metaitem.component.smd.diode.tooltip=Електричний компонент +metaitem.component.smd.transistor.name=SMD Транзистор +metaitem.component.advanced_smd.diode.tooltip=Покращений електричний компонент +metaitem.component.advanced_smd.transistor.tooltip=Покращений електричний компонент +metaitem.wafer.highly_advanced_system_on_chip.tooltip=Необроблена високотехнологічна схема +metaitem.wafer.high_power_integrated_circuit.tooltip=Необроблена схема високої потужності +metaitem.wafer.central_processing_unit.name=Процесорна пластина +metaitem.petri_dish.name=Чашка Петрі +metaitem.duct_tape.name=Покращена армована клейка стрічка FAL-84 +metaitem.basic_tape.tooltip=Недостатньо міцна для вирішення механічних проблем +metaitem.gravistar.tooltip=Доскональна пекельна зірка +metaitem.carbon.mesh.name=Сітка з вуглецевого волокна +metaitem.carbon.plate.name=Вуглецева пластина +metaitem.minecart_wheels.steel.tooltip=Щоб все їхало за планом +metaitem.wafer.ultra_high_power_integrated_circuit.name=Пластина UHPIC +metaitem.wafer.ultra_high_power_integrated_circuit.tooltip=Необроблена схема надвисокої напруги +metaitem.wafer.nand_memory_chip.name=Пластина NAND +metaitem.wafer.nand_memory_chip.tooltip=Необроблений логічний вентиль +metaitem.wafer.ultra_low_power_integrated_circuit.name=Пластина ULPIC +metaitem.wafer.ultra_low_power_integrated_circuit.tooltip=Необроблена схема наднизької напруги +metaitem.wafer.low_power_integrated_circuit.name=Пластина LPIC +metaitem.wafer.low_power_integrated_circuit.tooltip=Необроблена схема низької напруги +metaitem.wafer.power_integrated_circuit.name=Пластина PIC +metaitem.wafer.power_integrated_circuit.tooltip=Необлена схема напруги +metaitem.wafer.nano_central_processing_unit.name=Пластина нанопроцесора +metaitem.wafer.nor_memory_chip.name=Пластина NOR +metaitem.wafer.nor_memory_chip.tooltip=Необроблений логічний вентиль +metaitem.wafer.random_access_memory.name=Пластина RAM +metaitem.wafer.random_access_memory.tooltip=Необроблена пам'ять +metaitem.wafer.system_on_chip.name=Пластина SoC +metaitem.wafer.simple_system_on_chip.name=Проста пластина SoC +metaitem.wafer.simple_system_on_chip.tooltip=Необроблена проста схема +metaitem.engraved.crystal_chip.name=Гравірований кришталевий чіп +metaitem.engraved.crystal_chip.tooltip=Потрібен для схем +metaitem.crystal.raw.name=Необроблений кришталевий чіп +metaitem.crystal.raw_chip.name=Частини необробленого криштального чіпа +metaitem.engraved.lapotron_chip.name=Гравірований лапотроний криштальний чіп +metaitem.crystal.central_processing_unit.name=Криштальний CPU +metaitem.crystal.central_processing_unit.tooltip=Криштальний модуль обробки +metaitem.crystal.system_on_chip.name=Криштальний SoC +metaitem.crystal.system_on_chip.tooltip=Криштальна система на чіпі +metaitem.plate.advanced_system_on_chip.name=ПСнЧ +metaitem.plate.highly_advanced_system_on_chip.name=ВТСнЧ +metaitem.plate.highly_advanced_system_on_chip.tooltip=Високотехнологічна система на чіпі +metaitem.plate.integrated_logic_circuit.name=Вбудована схема +metaitem.plate.integrated_logic_circuit.tooltip=Вбудована логічна схема +metaitem.plate.central_processing_unit.name=ЦП +metaitem.plate.central_processing_unit.tooltip=Центральний процесор +metaitem.plate.high_power_integrated_circuit.name=HPIC +metaitem.plate.high_power_integrated_circuit.tooltip=Вбудована схема високої напруги +metaitem.plate.ultra_high_power_integrated_circuit.tooltip=Вбудована схема надвисокої напруги +metaitem.plate.ultra_high_power_integrated_circuit.name=ВСНВН +metaitem.plate.nand_memory_chip.name=NAND +metaitem.plate.nand_memory_chip.tooltip=Логічний вентиль NAND +metaitem.plate.nano_central_processing_unit.name=Нано ЦП +metaitem.plate.nano_central_processing_unit.tooltip=Нанопроцесор +metaitem.plate.nor_memory_chip.name=NOR +metaitem.plate.nor_memory_chip.tooltip=Логічний вентиль NOR +metaitem.circuit.good_electronic.name=Гарна електрична схема +metaitem.circuit.good_electronic.tooltip=Твоя друга схема/n§cРівень MV +metaitem.plate.ultra_low_power_integrated_circuit.tooltip=Вбудована схема наднизької напруги +metaitem.plate.low_power_integrated_circuit.name=ВСНН +metaitem.plate.ultra_low_power_integrated_circuit.name=ВСННН +metaitem.plate.low_power_integrated_circuit.tooltip=Вбудована схема низької напруги +metaitem.plate.power_integrated_circuit.name=ВСН +metaitem.plate.power_integrated_circuit.tooltip=Вбудована схема напруги +metaitem.plate.random_access_memory.name=RAM +metaitem.plate.random_access_memory.tooltip=Пам'ять з довільним доступом +metaitem.plate.system_on_chip.name=СнЧ +metaitem.plate.system_on_chip.tooltip=Система на чіпі +metaitem.plate.simple_system_on_chip.name=Проста СнЧ +metaitem.plate.simple_system_on_chip.tooltip=Проста система на чіпі + + +# T1: Electronic +metaitem.circuit.electronic.name=Проста електрична схема +metaitem.circuit.electronic.tooltip=Твоя перша схема/n§cРівень LV + +# T2: Integrated +metaitem.circuit.basic_integrated.name=Вбудована логічна схема +metaitem.circuit.basic_integrated.tooltip=Менша та більш потужна/n§6Рівень LV +metaitem.circuit.good_integrated.name=Гарна вбудована схема +metaitem.circuit.good_integrated.tooltip=Менша та більш потужна/n§6Рівень MV +metaitem.circuit.advanced_integrated.name=Покращена вбудована схема +metaitem.circuit.advanced_integrated.tooltip=Менша та більш потужна/n§6Рівень HV + +# Misc +metaitem.circuit.nand_chip.name=Чіп NAND +metaitem.circuit.nand_chip.tooltip=Передова проста схема/n§6Рівень ULV +metaitem.circuit.microprocessor.name=Мікропроцесор +metaitem.circuit.microprocessor.tooltip=Передова базова схема/n§eРівень LV + +# T3: Processor +metaitem.circuit.processor.name=Вбудований процесор +metaitem.circuit.processor.tooltip=Дивовижна швидкість обчислення!/n§eРівень MV +metaitem.circuit.assembly.name=Обчислювальний процесор +metaitem.circuit.assembly.tooltip=Дивовижна швидкість обчислення!/n§eРівень HV +metaitem.circuit.workstation.name=Суперкомп'ютер +metaitem.circuit.workstation.tooltip=Дивовижна швидкість обчислення!/n§eРівень EV +metaitem.circuit.mainframe.name=Основний каркас +metaitem.circuit.mainframe.tooltip=Дивовижна швидкість обчислення!/n§eРівень IV + +# T4: Nano +metaitem.circuit.nano_processor.name=Нанопроцесор +metaitem.circuit.nano_processor.tooltip=Менше, ніж будь-коли/n§bРівень HV +metaitem.circuit.nano_assembly.name=Обчислювальний нанопроцесор +metaitem.circuit.nano_assembly.tooltip=Менше, ніж будь-коли/n§bРівень EV +metaitem.circuit.nano_computer.name=Наносуперкомп'ютер +metaitem.circuit.nano_computer.tooltip=Менше, ніж будь-коли/n§bРівень IV +metaitem.circuit.nano_mainframe.name=Основний каркас нанопроцесора +metaitem.circuit.nano_mainframe.tooltip=Менше, ніж будь-коли/n§bРівень LuV + +# T5: Quantum +metaitem.circuit.quantum_processor.name=Квантовий процесор +metaitem.circuit.quantum_processor.tooltip=Квантові обчислення втілюються в життя!/n§aРівень EV +metaitem.circuit.quantum_assembly.name=Обчислювальний квантовий процесор +metaitem.circuit.quantum_assembly.tooltip=Квантові обчислення втілюються в життя!/n§aРівень IV +metaitem.circuit.quantum_computer.name=Квантовий суперкомп'ютер +metaitem.circuit.quantum_computer.tooltip=Квантові обчислення втілюються в життя!/n§aРівень LuV +metaitem.circuit.quantum_mainframe.name=Основний каркас квантового процесора +metaitem.circuit.quantum_mainframe.tooltip=Квантові обчислення втілюються в життя!/n§aРівень ZPM + +# T6: Crystal +metaitem.circuit.crystal_processor.name=Криштальний процесор +metaitem.circuit.crystal_processor.tooltip=Використання переваг гравіювання на кришталі/n§9Рівень IV +metaitem.circuit.crystal_assembly.name=Обчислювальний криштальний процесор +metaitem.circuit.crystal_assembly.tooltip=Використання переваг гравіювання на кришталі/n§9Рівень LuV +metaitem.circuit.crystal_computer.name=Криштальний суперкомп'ютер +metaitem.circuit.crystal_computer.tooltip=Використання переваг гравіювання на кришталі/n§9Рівень ZPM +metaitem.circuit.crystal_mainframe.name=Основний каркас криштального процесора +metaitem.circuit.crystal_mainframe.tooltip=Використання переваг гравіювання на кришталі/n§9Рівень UV + +# T7: Wetware +metaitem.circuit.wetware_processor.name=Органічний процесор +metaitem.circuit.wetware_processor.tooltip=У тебе таке відчуття, ніби воно спостерігає за тобою./n§4РівеньLuV +metaitem.circuit.wetware_assembly.name=Обчислювальний органічний процесор +metaitem.circuit.wetware_assembly.tooltip=Зможе запустити Minecraft/n§4Рівень ZPM +metaitem.circuit.wetware_computer.name=Органічний суперкомп'ютер +metaitem.circuit.wetware_mainframe.name=Основний каркас органічного процесора +metaitem.circuit.wetware_computer.tooltip=Ідеальне поєднання плоті та машини/n§4Рівень UV +metaitem.circuit.wetware_mainframe.tooltip=Потужне, але чи сможе воно запустити Crysis?/n§4Рівень UHV +metaitem.stem_cells.name=Cтовбурові клітини +metaitem.stem_cells.tooltip=Сирий інтелект +metaitem.processor.neuro.name=Нейроний модуль обробки +metaitem.processor.neuro.tooltip=Нейроний процесор +metaitem.petri_dish.tooltip=Для вирощування клітин +metaitem.bio_chaff.name=Біологічна маса +metaitem.carbon.fibers.name=Сире вуглецеве волокно +metaitem.neutron_reflector.name=Іридієвий нейтронний відбивач +metaitem.neutron_reflector.tooltip=Незламний +metaitem.duct_tape.tooltip=Якщо ви не можете виправити це за допомогою цього, використайте більше! +metaitem.basic_tape.name=Стрічка +metaitem.component.grinder.diamond.name=Алмазна шліфувальна головка +metaitem.component.grinder.tungsten.name=Вольфрамова шліфувальна головка +metaitem.minecart_wheels.iron.name=Залізні колеса вагонетки +metaitem.minecart_wheels.iron.tooltip=Щоб все їхало за планом +metaitem.minecart_wheels.steel.name=Стальні колеса вагонетки +metaitem.quantumeye.name=Квантове око +metaitem.quantumeye.tooltip=Вдосконалене око енду +metaitem.quantumstar.name=Квантова зірка +metaitem.quantumstar.tooltip=Вдосконалена пекельна зірка +metaitem.gravistar.name=Гравітаційна зірка +metaitem.item_filter.name=Фільтр предметів +metaitem.wafer.system_on_chip.tooltip=Необроблена базова схема +metaitem.wafer.nano_central_processing_unit.tooltip=Необроблема наносхема +metaitem.crystal.raw_chip.tooltip=Частини необробленого криштального процесора +metaitem.plate.advanced_system_on_chip.tooltip=Покращена система на чіпі +metaitem.crystal.raw.tooltip=Необроблений кришталевий процесор +metaitem.fluid_filter.name=Фільтр рідини +metaitem.ore_dictionary_filter.name=Фільтр руди +metaitem.fluid_filter.tooltip=Фільтрує §fРідини§7 працює як §fПокращення§7./nМожна виковистовувати для покращення §fЕлектронасоса§7 і §fРегулятора рідини§7. +metaitem.smart_item_filter.name=Розумний фільтр предметів +behaviour.filter_ui_manager=§fПКМ§7 для налаштувань, §fShift ПКМ§7 для очищення налаштувань +metaitem.cover.controller.name=Контролер машини +metaitem.cover.activity.detector.tooltip=Видає §fСтатус роботи§7 у вигляді сигналу Редстоуна, працює як §fПокращення§7. +metaitem.cover.fluid.detector.tooltip=Видає §fКількість рідини§7 у вигляді сигналу Редстоуна, працює як §fПокращення§7. +metaitem.cover.item.detector.tooltip=Видає §fКількість предметів§7 у вигляді сигналу Редстоуна, працює як §fПокращення§7. +metaitem.cover.activity.detector.name=Датчик активності +metaitem.cover.fluid.detector.name=Датчик рідини +metaitem.cover.fluid.detector.advanced.name=Покращений датчик рідини +metaitem.cover.item.detector.name=Датчик предметів +metaitem.cover.item.detector.advanced.name=Покращений датчик предметів +metaitem.cover.fluid.voiding.name=Видалятор рідини +metaitem.cover.fluid.voiding.tooltip=Видаляє §fРідини§7, працює як §fПокращення§7./nАктивується за допомогою §fМ'якої киянки§7 після розміщення. +metaitem.cover.fluid.voiding.advanced.name=Покращення видалятор рідини +metaitem.cover.item.voiding.name=Видалятор предметів +metaitem.cover.item.voiding.tooltip=Видаляє §fПредмети§7 працює як §fПокращення§7./nАктивується за допомогою §fМ'якої киянки§7 після розміщення. +metaitem.cover.item.voiding.advanced.name=Покращений видалятор предметів +metaitem.cover.storage.name=Сховище (Покращення) +metaitem.cover.energy.detector.advanced.name=Покращений датчик енергії +metaitem.cover.maintenance.detector.tooltip=Видає §fПотребу в технічного обслуговування§7 у вигляді сигналу Редстоуна, працює як §fПокращення§7. +metaitem.cover.facade.name=Фасад (%s) +metaitem.cover.screen.name=Комп'ютерний монітор +metaitem.cover.screen.tooltip=Показує §fДані§7, працює як §fПокращення§7. +metaitem.cover.crafting.name=Верстак (Покращення) +metaitem.cover.shutter.name=Затворний модуль (Покращення) +metaitem.cover.shutter.tooltip=§fБлокує передачу§7 через сторону на якій знаходиться, працює як §fПокращення§7. +metaitem.cover.solar.panel.ulv.name=Сонячна панель ультранизької напруги +metaitem.cover.solar.panel.mv.name=Сонячна панель середньої напруги (Покращення) +metaitem.cover.solar.panel.hv.name=Сонячна панель високої напруги (Покращення) +metaitem.cover.solar.panel.iv.name=Сонячна панель шаленої напруги (Покращення) +metaitem.cover.solar.panel.luv.name=Сонячна панель сміховинної напруги (Покращення) +metaitem.cover.solar.panel.uv.name=Сонячна панель кінцевої напруги (Покращення) +metaitem.cover.solar.panel.tooltip.1=Нехай Сонце буде з вами. +metaitem.cover.infinite_water.name=Нескінченне джерело води (Покращення) +metaitem.cover.infinite_water.tooltip.1=Наповнює контейнери §9Водою§7, працює як §fПокращення§7. +metaitem.cover.ender_fluid_link.name=Рідкий безтрубний зв'язок (Покращення) +metaitem.gelled_toluene.tooltip=Сира вибухівка +metaitem.bottle.purple.drink.name=Фіолетовий напій +metaitem.bottle.purple.drink.tooltip=Як щодо лимонаду? Або холодного чаю? А у мене є фіолетовий напій! +metaitem.dye.black.name=Чорний барвник +metaitem.dye.red.name=Червоний барвник +metaitem.dye.green.name=Зелений барвник +metaitem.dye.blue.name=Синій барвник +metaitem.dye.purple.name=Фіолетовий барвник +metaitem.dye.cyan.name=Блакитний барвник +metaitem.dye.silver.name=Світло-сірий барвник +metaitem.dye.gray.name=Сірий барвник +metaitem.dye.lime.name=Лаймовий барвник +metaitem.dye.magenta.name=Пурпурний барвник +metaitem.dye.orange.name=Помаранчевий барвник +metaitem.dye.white.name=Білий барвник +metaitem.tool_parts_box.name=Ящик для інструментів +metaitem.foam_sprayer.name=Розпилювач піни +metaitem.energium_dust.name=Енергітичний пил +metaitem.compressed.clay.name=Спресована глина +metaitem.compressed.fireclay.name=Спресована шамотна глина +metaitem.brick.fireclay.name=Цегла з шамотної глина +metaitem.brick.fireclay.tooltip=Термостійка +metaitem.brick.coke.name=Цегла для коксових печей +metaitem.wooden_form.empty.name=Порожня дерев'яна форма +item.gt.tool.replace_tool_head=Створіть нову головку інструменту, щоб замінити її +item.gt.tool.usable_as=Використовується як: §f%s +item.gt.tool.behavior.tree_felling=§4Лісоруб: §fРубка дерев +item.gt.tool.behavior.shield_disable=§cБрут: §fВідключає щити +item.gt.tool.behavior.ground_tilling=§eФермер: §fОбробляє землю +item.gt.tool.behavior.rail_rotation=§eЗалізничний інженер: §fОбертає рейки +item.gt.tool.behavior.block_rotation=§2Механік: §fОбертає блоки +gt.tool.class.sword=Меч +gt.tool.class.pickaxe=Кайло +gt.tool.class.shovel=Лопата +gt.tool.class.axe=Сокира +gt.tool.class.hoe=Мотика +gt.tool.class.saw=Пила +gt.tool.class.hammer=Молот +gt.tool.class.mallet=Киянка +gt.tool.class.wrench=Гайковий ключ +gt.tool.class.file=Напилок +gt.tool.class.crowbar=Лом +gt.tool.class.screwdriver=Викрутка +gt.tool.class.mortar=Ступка +gt.tool.class.scythe=Коса +gt.tool.class.shears=Ножиці +gt.tool.class.knife=Ніж +gt.tool.class.plunger=Вантуз +item.gt.tool.sword.name=Меч (%s) +item.gt.tool.pickaxe.name=Кайло (%s) +item.gt.tool.shovel.name=Лопата (%s) +item.gt.tool.axe.name=Сокира (%s) +item.gt.tool.hoe.name=Мотика (%s) +item.gt.tool.saw.name=Пила (%s) +item.gt.tool.hammer.name=Молот (%s) +item.gt.tool.mallet.name=М'яка киянка (%s) +item.gt.tool.mallet.tooltip=§8Зупиняє/запускає техніку +item.gt.tool.wrench.name=Гайковий ключ %s +item.gt.tool.file.name=Напилок (%s) +item.gt.tool.crowbar.name=Лом (%s) +item.gt.tool.crowbar.tooltip=§8Знімає покращення +item.gt.tool.screwdriver.name=Викрутка (%s) +item.gt.tool.screwdriver.tooltip=§8Налаштовує покращення та машини +item.gt.tool.mortar.name=Ступка (%s) +item.gt.tool.wire_cutter.name=Кусачки (%s) +item.gt.tool.butchery_knife.name=Тесак (%s) +item.gt.tool.butchery_knife.tooltip=§8Має низьку швидкість атаки +item.gt.tool.scythe.name=Коса (%s) +item.gt.tool.rolling_pin.name=Качалка (%s) +item.gt.tool.drill_lv.name=%s Бур (LV) +item.gt.tool.drill_hv.name=%s Бур (HV) +item.gt.tool.drill_ev.name=%s Бур (EV) +item.gt.tool.drill_iv.name=%s Бур (IV) +item.gt.tool.mining_hammer.name=%s Гірський молот +item.gt.tool.spade.tooltip=§8Видобуває велику площу за один раз (якщо тільки ви не присідаєте) +item.gt.tool.chainsaw_lv.name=%s Бензопила (LV) +item.gt.tool.chainsaw_mv.name=%s Бензопила (MV) +item.gt.tool.chainsaw_hv.name=%s Бензопила (HV) +item.gt.tool.wrench_lv.tooltip=§8Утримуйте ЛКМ, щоб демонтувати машини +item.gt.tool.wrench_iv.tooltip=§8Утримуйте ЛКМ, щоб демонтувати машини +item.gt.tool.buzzsaw.name=%s Циркулярна пила (LV) +item.gt.tool.screwdriver_lv.name=%s Викрутка (LV) +item.gt.tool.screwdriver_lv.tooltip=§8Налаштовує покращення та машини +item.gt.tool.plunger.name=%s Вантуз +item.gt.tool.plunger.tooltip=§8Видаляє рідини з машин +item.gt.tool.wire_cutter_lv.name=%s Кусачки (LV) +item.gt.tool.wire_cutter_hv.name=%s Кусачки (HV) +item.gt.tool.tooltip.general_uses=§bМіцність: %s +item.gt.tool.tooltip.attack_damage=§cШкода від атаки: %s +item.gt.tool.tooltip.attack_speed=§9Швидкість атаки: %s +item.gt.tool.tooltip.mining_speed=§dШвидкість видобутку: %s +item.gt.tool.tooltip.harvest_level_extra=§eРівень збору: %s §f(%s§f) +item.gt.tool.harvest_level.0=§8Дерево +item.gt.tool.harvest_level.2=§aЗалізо +item.gt.tool.harvest_level.3=§bАлмаз +item.gt.tool.harvest_level.4=§dУльтімет +item.gt.tool.harvest_level.5=§9Дюранієвий +item.gt.tool.harvest_level.6=§cНейтроній +item.gt.tool.tooltip.repair_info=Утримуйте клавішу SHIFT, щоб показати інформацію про ремонт +item.gt.tool.tooltip.repair_material=Ремонтується з допомогою: §a%s +item.gt.tool.aoe.rows=Ряди +item.gt.tool.aoe.columns=Колонки +item.gt.tool.aoe.layers=Шари +metaitem.turbine_rotor.name=%s Ротор турбіни +metaitem.turbine_rotor.tooltip=Ротори турбін для вашої електростанції +metaitem.clipboard.name=Блокнот +metaitem.clipboard.tooltip=Можна писати (без будь-якого інструменту для письма). Клацніть ПКМ на стіні, щоб розмістити, і клацніть Shift-ПКМ, щоб підібрати + + +metaitem.behavior.mode_switch.tooltip=SHIFT-ПКМ для змінення режиму +metaitem.behavior.mode_switch.mode_switched=§eРежим змінено на: %s +metaitem.behavior.mode_switch.current_mode=Режим: %s +metaitem.tool.tooltip.primary_material=§fМатеріал: §e%s +metaitem.tool.tooltip.durability=§fМіцність: §a%,d / %,d +metaitem.tool.tooltip.rotor.efficiency=Ефективність турбіни: §9%,d%% +metaitem.tool.tooltip.rotor.power=Потужність турбіни: §9%,d%% +metaitem.voltage_coil.ulv.name=Котушка (ULV) +metaitem.voltage_coil.ulv.tooltip=Примітивна котушка +metaitem.voltage_coil.lv.name=Котушка (LV) +metaitem.voltage_coil.lv.tooltip=Базова котушка +metaitem.voltage_coil.mv.name=Котушка середньої напруги +metaitem.voltage_coil.mv.tooltip=Гарна котушка +metaitem.voltage_coil.hv.name=Котушка високої напруги +metaitem.voltage_coil.hv.tooltip=Покращена котушка +metaitem.voltage_coil.ev.name=Котушка екстремальної напруги +metaitem.voltage_coil.ev.tooltip=Екстремально гарна котушка +metaitem.voltage_coil.iv.name=Котушка шаленої напруги +metaitem.voltage_coil.iv.tooltip=Відмінна котушка +metaitem.voltage_coil.luv.name=Котушка сміховинної напруги +metaitem.voltage_coil.luv.tooltip=Відмінна котушка V2 +metaitem.voltage_coil.zpm.name=Котушка (ZPM) +metaitem.voltage_coil.zpm.tooltip=Відмінна котушка V3 +metaitem.voltage_coil.uv.name=Котушка (UV) +metaitem.voltage_coil.uv.tooltip=Доскональна котушка +metaitem.voltage_coil.uhv.name=Котушка (UHV) +metaitem.voltage_coil.uhv.tooltip=Ідеальна котушка +metaitem.voltage_coil.uev.name=Котушка (UEV) +metaitem.voltage_coil.uev.tooltip=Нереальна котушка +metaitem.voltage_coil.uiv.name=Котушка (UIV) +metaitem.voltage_coil.uiv.tooltip=Бездоганна котушка V2 +metaitem.voltage_coil.uxv.name=Котушка (UXV) +metaitem.voltage_coil.uxv.tooltip=Бездоганна котушка V3 +metaitem.voltage_coil.opv.name=Котушка (OpV) +metaitem.voltage_coil.opv.tooltip=Бездоганна котушка V4 +metaitem.voltage_coil.max.name=Катушка (MAX) +metaitem.voltage_coil.max.tooltip=Максимальна котушка +metaitem.liquid_fuel_jetpack.name=Реактивний ранець на рідкому паливі +metaitem.liquid_fuel_jetpack.tooltip=Використовує паливо для тяги +metaitem.electric_jetpack.name=Реактивний ранець з електричним двигуном +metaitem.nightvision_goggles.name=Окуляри нічного бачення +metaitem.nms.leggings.name=NanoMuscle™ Штани +metaitem.nms.boots.name=NanoMuscle™ Чоботи +metaitem.nms.helmet.name=NanoMuscle™ Шолом +metaitem.nms.advanced_chestplate.name=Покращений NanoMuscle™ Нагрудник +metaitem.qts.chestplate.name=QuarkTech™ Нагрудник +metaitem.item_filter.tooltip=Фільтрує §fПредмети§7 працює як §fПокращення§7./nМожна виковистовувати для покращення §fКонвеєрного модуля§7 і §fРоботизованої руки§7. +metaitem.smart_item_filter.tooltip=Фільтрує §fПредмети§7 за допомогою §fРецептів машин§7 працює як §fПокращення§7./nМожна виковистовувати для покращення §fКонвеєрного модуля§7 і §fРоботизованої руки§7. +metaitem.qts.helmet.name=QuarkTech™ Шолом +metaitem.qts.advanced_chestplate.name=Покращений QuarkTech™ Нагрудник +metaitem.gravitation_engine.name=Модуль гравітаційного двигуна +metaitem.tool.multiblock_builder.name=Конструктор багатоблочних конструкцій +metaitem.tool.multiblock_builder.tooltip=Для налагодження та автоматичної збірки ваших багатоблочних конструкцій! +metaitem.ore_dictionary_filter.tooltip=Фільтрує §fПредмети§7 з допомогою §fСловника руд§7 працює як §fПокращення§7./nМожна виковистовувати для покращення §fКонвеєрного модуля§7 і §fРоботизованої руки§7. +metaarmor.nms.nightvision.enabled=NanoMuscle™ Костюм: Увімкнено нічне бачення +metaarmor.nms.nightvision.disabled=NanoMuscle™ Костюм: Вимкнено нічне бачення +metaitem.cover.controller.tooltip=§fВКЛ/ВИКЛ§7 машину працює як §fПокращення§7. +metaitem.cover.activity.detector_advanced.tooltip=Видає §fПрогрес роботи§7 у вигляді сигналу Редстоуна, працює як §fПокращення§7. +metaitem.cover.item.detector.advanced.tooltip=Видає §fСтатус зберігання предметів§7 у вигляді сигналу Редстоуна, працює як §fПокращення§7, з можливістю контролювати з допомогою §fРедстоун трігеру§7. +metaitem.cover.energy.detector.advanced.tooltip=Дає §fРедстоун трігеру§7 контроль за §fСтатусом енергії§7 за допомогою Редстоуну, працює як §fПокращення§7. +metaitem.cover.energy.detector.name=Датчик енергії +metaarmor.nms.nightvision.error=NanoMuscle™ Костюм: §cНедостатньо енергії! +metaarmor.qts.nightvision.enabled=QuarkTech™ Костюм: Увімкнено нічне бачення +metaitem.cover.fluid.detector.advanced.tooltip=Видає §fСтатус зберігання рідини§7 у вигляді сигналу Редстоуна, працює як §fПокращення§7, з можливістю контролювати з допомогою §fРедстоун трігеру§7. +metaitem.cover.energy.detector.tooltip=Видає §fКількість енергії§7 у вигляді сигналу Редстоуна, працює як §fПокращення§7. +metaitem.cover.fluid.voiding.advanced.tooltip=Видаляє §fРідини§7, з контролем кількості, працює як §fПокращення§7./nАктивується за допомогою §fМ'якої киянки§7 після розміщення. +metaarmor.qts.nightvision.disabled=QuarkTech™ Костюм: Вимкнено нічне бачення +metaarmor.jetpack.hover.enable=Реактивний ранець: Увімкнено режим зависання +metaarmor.jetpack.hover.disable=Реактивний ранець: Вимкнено режим зависання +metaarmor.jetpack.emergency_hover_mode=Аварійний режим зависання увімкнено! +metaarmor.nms.share.enable=NanoMuscle™ Костюм: Зарядку ввімкнено +metaarmor.nms.share.disable=NanoMuscle™ Костюм: Зарядку вимкнено +metaarmor.nms.share.error=NanoMuscle™ Костюм: §cНе вистачає енергії для зарядки! +metaarmor.qts.share.enable=QuarkTech™ Костюм: Зарядку ввімкнено +metaarmor.qts.share.disable=QuarkTech™ Костюм: Зарядку вимкнено +metaarmor.qts.share.error=QuarkTech™ Костюм: §cНе вистачає енергії для зарядки! +metaarmor.message.nightvision.enabled=§bНічне бачення: §aУвімкнено +metaarmor.message.nightvision.disabled=§bНічне бачення: §cВимкнено +metaarmor.message.nightvision.error=§cНедостатньо енергії! +metaarmor.tooltip.stepassist=Забезпечує крокову допомогу +metaarmor.tooltip.speed=Збільшує швидкість бігу +metaarmor.tooltip.jump=Збільшує висоту та дистанцію стрибків +metaarmor.tooltip.falldamage=Обнуляє шкоду від падіння +metaarmor.tooltip.potions=Обнуляє шкідливі ефекти +metaarmor.tooltip.burning=Обнуляє горіння +metaarmor.tooltip.breath=Поповнює шкалу підводого дихання +metaarmor.tooltip.autoeat=Поповнює запаси їжі, використовуючи їжу з інвентарю +metaarmor.hud.status.enabled=§aУВІМК +metaarmor.hud.status.disabled=§cВИМК +metaarmor.hud.energy_lvl=Рівень енергії: %s +metaarmor.hud.fuel_lvl=Рівень палива: %s +metaarmor.hud.hover_mode=Режим зависання: %s +mataarmor.hud.supply_mode=Режим постачання: %s +metaarmor.energy_share.error=Енергопостачання: §cНе вистачає потужності для зарядки приладів! +metaarmor.energy_share.enable=Енергопостачання: Увімкнено заряджання приладів +metaarmor.energy_share.disable=Енергопостачання: Вимкнено зарядку пристроїв +metaarmor.energy_share.tooltip=Режим постачання: %s +metaarmor.energy_share.tooltip.guide=Щоб змінити режим, клацніть SHIFT-ПКМ, утримуючи предмет +metaitem.record.sus.name=Музичний диск +metaitem.record.sus.tooltip=§7Leonz - Among Us Drip +metaitem.nan.certificate.name=Сертифікат про те, що ви більше не новачок +metaitem.nan.certificate.tooltip=Виклик прийнято! +metaitem.fertilizer.name=Добриво +metaitem.blacklight.name=Чорне світло +metaitem.blacklight.tooltip=Довгохвильове §dУльтрафіолетове§7 джерело світла +gui.widget.incrementButton.default_tooltip=Утримуйте Shift, Ctrl або обидві клавіші, щоб змінити кількість +gui.widget.recipeProgressWidget.default_tooltip=Показати рецепти +gregtech.recipe_memory_widget.tooltip.1=§7Клікніть лівою кнопкою миші, щоб автоматично внести цей рецепт до сітки крафтингу +cover.filter.blacklist.disabled=Білий список +cover.filter.blacklist.enabled=Чорний список +cover.ore_dictionary_filter.title=Фільтр руди за словником +cover.ore_dictionary_filter.match_all=Відповідає всім: %s +cover.ore_dictionary_filter.case_sensitive=Чутливість до регістру: %s +cover.ore_dictionary_filter.test_slot.info=Вставте елемент, щоб перевірити, чи відповідає він виразу фільтра +cover.ore_dictionary_filter.test_slot.matches=§a* %s +cover.ore_dictionary_filter.test_slot.matches_not=§c* %s +cover.ore_dictionary_filter.test_slot.no_oredict.matches=§a(Немає словника руд) +cover.ore_dictionary_filter.test_slot.no_oredict.matches_not=§c(Немає словника руд) +cover.ore_dictionary_filter.status.err=§c%s помилка(и) +cover.ore_dictionary_filter.status.err_warn=§c%s помилок та %s попереджень +cover.ore_dictionary_filter.status.warn=§7%s попереджень +cover.ore_dictionary_filter.status.no_issues=§aБез проблем +cover.ore_dictionary_filter.status.explain=Пояснення рудного фільтра: +cover.ore_dictionary_filter.button.case_sensitive.disabled=Нечутливий до регістру +cover.ore_dictionary_filter.button.case_sensitive.enabled=Чутливий до регістру +cover.ore_dictionary_filter.preview.next=... за яким слідує +cover.ore_dictionary_filter.preview.match='%s' +cover.ore_dictionary_filter.preview.match.not=не '%s' +cover.ore_dictionary_filter.preview.char=1 символ +cover.ore_dictionary_filter.preview.char.not=або більше ніж 1 символабо нічого +cover.ore_dictionary_filter.preview.chars=%s символів +cover.ore_dictionary_filter.preview.chars.not=або більше ніж або менше %s символів +cover.ore_dictionary_filter.preview.chars_or_more=%s чи більше символів +cover.ore_dictionary_filter.preview.chars_or_more.not=менше ніж %s символів +cover.ore_dictionary_filter.preview.group=не: +cover.ore_dictionary_filter.preview.or=один з... +cover.ore_dictionary_filter.preview.nor=будьщо, що не є одним із... +cover.ore_dictionary_filter.preview.or.entry= +cover.ore_dictionary_filter.preview.or.entry.start= +metaitem.cover.item.voiding.advanced.tooltip=Видаляє §fПредмети§7, з контролем кількості, працює як §fПокращення§7./nАктивується за допомогою §fМ'якої киянки§7 після розміщення. +metaitem.cover.storage.tooltip=Невеликий сховище для зберігання дрібниць +metaitem.cover.maintenance.detector.name=Датчик потреби технічного обслуговування +metaitem.cover.activity.detector_advanced.name=Покращений датчик активності +metaitem.cover.facade.tooltip=Декоративне оздоблення §fПокращення§7. +metaitem.cover.crafting.tooltip=§fПокращений верстак§7 на машині, працює як §fПокращення§7. +metaitem.cover.solar.panel.name=Сонячна панель (Покращення) +metaitem.cover.solar.panel.lv.name=Сонячна панель низької напруги (Покращення) +metaitem.cover.solar.panel.ev.name=Сонячна панель екстремальної напруги (Покращення) +metaitem.cover.solar.panel.zpm.name=Сонячна панель модуля нульової точки (Покращення) +metaitem.cover.solar.panel.tooltip.2=Виробляє §fЕнергію§7 з §eСонця§7, працює як §fПокращення§7. +metaitem.dye.pink.name=Рожевий барвник +metaitem.dye.yellow.name=Жовтий барвник +metaitem.dye.light_blue.name=Світло-синій барвник +metaitem.foam_sprayer.tooltip=Розпилює будівельну піну/nВикористовується на рамі для запінення з'єднаних рам/nПіна може бути кольоровою +item.gt.tool.behavior.grass_path=§eЛандшафтник: §fСтворює доріжки +item.gt.tool.behavior.plunger=§9Сантехнік: §fЗливає рідини +gt.tool.class.wirecutter=Кусачки +item.gt.tool.hammer.tooltip=§8Подрібнює блоки під час їх збирання +item.gt.tool.knife.name=Ніж (%s) +metaitem.cover.ender_fluid_link.tooltip=Передає §fРідини§7 за допомогою §fБезтрубового §dЕндер§f зв'яку§7, працює як §fПокращення§7. +metaitem.dye.brown.name=Коричневий барвник +metaitem.tool_parts_box.tooltip=Містить деякі частини інструментів/nПКМ для відкриття +metaitem.compressed.coke_clay.name=Спресована коксова глина +metaitem.wooden_form.brick.name=Дерев'яна форма для цегли +item.gt.tool.behavior.silk_ice=§bЛьодоруб: §fШовковий дотик для льоду +item.gt.tool.behavior.relocate_mining=§2Магніт: §fПритягує видобуті блоки +item.gt.tool.behavior.damage_boost=§4Посилення шкоди: §fДодаткова шкода проти %s +gt.tool.class.butchery_knife=Тесак +item.gt.tool.wrench.tooltip=§8Утримуйте ліву кнопку миші, щоб демонтувати машини +item.gt.tool.drill_mv.name=%s Бур (MV) +item.gt.tool.wire_cutter_iv.name=%s Кусачки (IV) + + +item.gt.tool.tooltip.crafting_uses=§aЗалишилося застосувань: %s +item.gt.tool.harvest_level.1=§7Камінь +item.gt.tool.mining_hammer.tooltip=§8Видобуває велику площу за один раз (якщо тільки ви не присідаєте) +item.gt.tool.wrench_lv.name=%s Електроключ (LV) +item.gt.tool.wrench_hv.tooltip=§8Утримуйте ЛКМ, щоб демонтувати машини +item.gt.tool.buzzsaw.tooltip=§8Не підходить для добування блоків +item.gt.tool.tooltip.harvest_level=§eРівень збору: %s +metaitem.advanced_electric_jetpack.name=Покращений реактивний ранець +metaitem.nms.chestplate.name=NanoMuscle™ Нагрудник +metaitem.qts.leggings.name=QuarkTech™ Штани +metaarmor.qts.nightvision.error=QuarkTech™ Костюм: §cНедостатньо енергії! +gregtech.recipe_memory_widget.tooltip.2=§7Нажміть Shift, щоб заблокувати/розблокувати цей рецепт +metaitem.qts.boots.name=QuarkTech™ Чоботи +metaitem.tool.multiblock_builder.tooltip2=SHIFT-ПКМ по контролеру мультиблочної структури, щоб автоматично побудувати її +cover.item_filter.ignore_damage.disabled=Враховувати пошкодження +cover.ore_dictionary_filter.preview.and=все що... +cover.ore_dictionary_filter.preview.nand=все що не... +cover.ore_dictionary_filter.preview.and.entry= +cover.ore_dictionary_filter.preview.and.entry.start= +cover.ore_dictionary_filter.preview.xor=тільки одиз з... +cover.ore_dictionary_filter.preview.xnor=обидва чи нічого з... +cover.ore_dictionary_filter.preview.xor.entry= +cover.ore_dictionary_filter.preview.everything=будьщо +cover.ore_dictionary_filter.preview.impossible=(неможливо зрівняти) +cover.ore_dictionary_filter.preview.nonempty=щось +cover.ore_dictionary_filter.preview.empty=нічого +cover.ore_dictionary_filter.preview.error=ПОМИЛКА! +cover.ore_dictionary_filter.compile.eof=** Кінець рядка ** +cover.ore_dictionary_filter.compile.error.unexpected_eof=Несподіване закінчення виразу +cover.ore_dictionary_filter.compile.error.unexpected_token=Неочікуваний токен '%s' +cover.ore_dictionary_filter.compile.error.unexpected_token_after_eof=Неочікуваний токен '%s' після кінця виразу +cover.ore_dictionary_filter.compile.error.unexpected_compilation_flag=Прапори компіляції в середині виразу +cover.ore_dictionary_filter.compile.error.empty_compilation_flag=Прапори компіляції не задано +cover.ore_dictionary_filter.compile.error.unknown_compilation_flag=Невідомий прапор компіляції '%s' +cover.ore_dictionary_filter.compile.error.redundant_compilation_flag=Прапор компіляції '%s' написано двічі +cover.ore_dictionary_filter.compile.error.eof_after_escape=Кінець файлу після символу екранування ('') +cover.ore_dictionary_filter.compile.error.invalid_char=Неприпустимий символ U+%s('%s') +cover.ore_dictionary_filter.compile.warn.nested_negation=Вкладені заперечення можуть бути неінтуїтивно зрозумілими. Подумайте про використання груп ( () ) для усунення неоднозначності. +cover.ore_dictionary_filter.compile.warn.consecutive_negation=Послідовні заперечення можуть бути неінтуїтивно зрозумілими. Будь ласка, перевірте, чи бажаний результат оцінювання. +cover.fluid_filter.title=Фільтр для рідини +cover.fluid_filter.config_amount=Колесо прокрутки вгору збільшує кількість, вниз - зменшує./nShift[§6x10§r],Ctrl[§ex100§r],Shift+Ctrl[§ax1000§r]/nПКМ збільшує кількість, ЛКМ зменшує./nТримайте SHIFT щоб збільшити/зменшити вдвічі./nСКМ для очищення +cover.item_filter.title=Фільтр предметів +cover.filter.mode.title=Режим фільтрації +cover.filter.mode.filter_insert=Фільтрує вхідні предмети +cover.fluid_filter.mode.filter_fill=Фільтрує вхідні рідини +cover.fluid_filter.mode.filter_drain=Фільтрує вихідні рідини +cover.fluid_filter.mode.filter_both=Фільтрує рідини на виході та вході +cover.filter.mode.filter_extract=Фільтрує вихідні предмети +cover.filter.mode.filter_both=Фільтрує предмети на виході та вході +cover.item_filter.ignore_damage.enabled=Ігнорувати пошкодження +cover.item_filter.ignore_nbt.enabled=Ігнорувати NBT +cover.item_filter.ignore_nbt.disabled=Враховувати NBT +cover.item_filter.config_amount=Прокручування колесика вгору збільшує суму, вниз зменшує.\nShift[§6x4§r], Ctrl[§ex16§r], Alt[§ax64§r]\nПКМ щоб збільшити, ЛКМ щоб зменшити.\nShift-ЛКМ щоб очистити +cover.voiding.voiding_mode.void_any=Видаляти відповідності +cover.voiding.voiding_mode.void_overflow=Видаляти надлишки +cover.voiding.voiding_mode=Режим видалення +cover.fluid.voiding.title=Налаштування видалення рідини +cover.fluid.voiding.advanced.title=Покращені налаштування видалення рідини +cover.item.voiding.title=Налаштування видалення предметів +cover.item.voiding.advanced.title=Покращені налаштування видалення предметів +cover.voiding.label.disabled=Вимкнено +cover.voiding.label.enabled=Увімкнено +cover.voiding.message.disabled=Видалення вимкнено +cover.voiding.message.enabled=Видалення увімкнено +cover.shutter.message.disabled=Затвор вимкнено +cover.shutter.message.enabled=Затвор увімкнено +cover.smart_item_filter.title=Розумний фільтр предметів +cover.smart_item_filter.filtering_mode.electrolyzer=Електролізер +cover.smart_item_filter.filtering_mode.centrifuge=Центрифуга +cover.smart_item_filter.filtering_mode.sifter=Просіювач +cover.generic.transfer_mode=Режим передавання +cover.generic.manual_io=Ручний режим вводу-виводу +cover.generic.io=Режим вводу-виводу +cover.pump.mode=Режим насоса +cover.conveyor.title=Налаштування покращення конвеєра (%s) +cover.conveyor.transfer_rate=§7 предметів/сек +cover.conveyor.mode.export=Режим: Експорт +cover.conveyor.mode.import=Режим: Імпорт +cover.conveyor.distribution.name=Режим розповсюдження +cover.conveyor.distribution.round_robin=§bЦиклічне планування§r з пріоритетом\n§7Намагається розділити предмети порівну на всі інвентарні +cover.conveyor.distribution.first_insert=§bПерша вставка§r\n§7Вставить у перший знайдений інвентар +cover.conveyor.blocks_input.disabled=Якщо увімкнено, предмети не вставлятимуться, коли покращення встановлено для витягування предметів з інвентарю у трубу./n§cВимкнено +cover.universal.manual_import_export.mode.disabled=Ручний ввід/вивід: Вимкнено +cover.universal.manual_import_export.mode.filtered=Ручний ввід/вивід: Фільтрація +cover.conveyor.item_filter.title=Фільтр предметів +cover.conveyor.ore_dictionary.title=Назва за словником руд +cover.conveyor.ore_dictionary.title2=(використовуйте * для підстановки символів) +cover.robotic_arm.title=Налаштування роботизованої руки (%s) +cover.robotic_arm.exact=§7предмети +cover.robotic_arm.transfer_mode.transfer_any=Перемістити будь-яку к-сть +cover.robotic_arm.transfer_mode.transfer_exact=Перемістити рівно +cover.robotic_arm.transfer_mode.keep_exact=Дотримуватися рівно +cover.pump.title=Налаштування для покращення помпи (%s) +cover.pump.transfer_rate=%s +cover.pump.mode.export=Режим: Експорт +cover.pump.mode.import=Режим: Імпорт +cover.bucket.mode.bucket=Режим ковша: кЛ +cover.bucket.mode.milli_bucket=Режим ковша: Л +cover.bucket.mode.bucket_rate=кЛ/с +cover.bucket.mode.bucket_exact=кЛ +cover.bucket.mode.milli_bucket_rate=Л/с +cover.bucket.mode.milli_bucket_exact=Л +cover.smart_item_filter.filtering_mode.description=Виберіть Машину, яку розумний фільтр буде використовувати для фільтрації./nВін автоматично вибере правильні порції елементів для роботизованої руки. +cover.conveyor.distribution.round_robin_enhanced=§bЦиклічне планування§r\n§7Розподіляє предмети порівну на всі інвентарні +cover.voiding.voiding_mode.description=§eВидаляти відповідності§r вилучить все, що відповідає фільтру. /n§eВидаляти надлишки§r вилучить все, що відповідає фільтру, до вказаної суми. +cover.voiding.tooltip=§cУВАГА!§7 Встановлення цього параметра на «Увімкнено» означає, що рідини або предмети БУДУТЬ видалені. +cover.conveyor.blocks_input.enabled=Якщо увімкнено, предмети не вставлятимуться, коли покращення встановлено для витягування предметів з інвентарю у трубу./n§aУвімкнено +cover.universal.manual_import_export.mode.unfiltered=Ручний ввід/вивід: Без фільтрації +cover.universal.manual_import_export.mode.description=§eВимкнено§r - Предмети/рідини переміщуватимуться лише так, як зазначено в покращенні і її фільтрі. /n§eДозволити фільтровані§r - Придмети/рідини будуть переміщуватися незалежно від налаштувань покращення, якщо його фільтр збігається (якщо наявний). /n§eДозволити нефільтровані§r - Предмети/рідини будуть переміщуватися незалежно від налаштувань покращення. Фільтр застосовується до об'єктів, вставлених або витягнутих цим покращенням +cover.fluid_regulator.title=Налаштування регулятора рідини (%s) +cover.pump.fluid_filter.title=Фільтр для рідини +death.attack.crowbar=%s відчув себе комбайном після зустрічі з %s +item.gt.tool.wrench_iv.name=%s Електроключ (IV) +cover.ore_dictionary_filter.button.match_all.enabled=Всі записи зі словника руд +cover.fluid_regulator.keep_exact=Зберігати точно: %s +cover.machine_controller.mode.cover_down=Керувати покращенням (Знизу) +cover.machine_controller.mode.cover_up=Керувати покращенням (Зверху) +cover.machine_controller.mode.cover_south=Керувати покращенням (Південь) +cover.machine_controller.mode.cover_north=Керувати покращенням (Північ) +cover.machine_controller.mode.cover_east=Керувати покращенням (Схід) +cover.machine_controller.mode.cover_west=Керувати покращенням (Захід) +cover.machine_controller.this_cover=§cЦе покращення +cover.machine_controller.cover_not_controllable=§cНе кероване покращення +cover.machine_controller.machine_not_controllable=§cМашина не керована +cover.machine_controller.control=Керування: +cover.ender_fluid_link.title=Ендовий рідиний зв'язок +gregtech.waila.energy_output=Вихід: %s EU/t +metaitem.wafer.qbit_central_processing_unit.tooltip=Необроблена кубітня схема +metaitem.wafer.integrated_logic_circuit.name=ІС Пластина +metaitem.wafer.integrated_logic_circuit.tooltip=Необроблена інтегрована схема +metaitem.rubber_drop.name=Смола +metaitem.plant_ball.name=Рослинна куля +cover.ender_fluid_link.iomode.enabled=Вхід/Вихід Увімкнено +cover.ender_fluid_link.iomode.disabled=Вхід/Вихід Вимкнено +cover.generic.ender.known_channels=Відомі канали +cover.generic.ender.set_description.tooltip=Опис +cover.generic.ender.set_description.title=Опис [%s] +cover.generic.ender.delete_entry=Видалити запис +cover.generic.advanced_detector.latched=Замкнений +cover.generic.advanced_detector.continuous=Безперервний +cover.generic.advanced_detector.latch_label=Поведінка: +cover.advanced_energy_detector.label=Покращений датчик енергії +cover.advanced_energy_detector.min=Мінімум: +cover.advanced_energy_detector.inverted=Інвертований +cover.advanced_fluid_detector.max=Максимум рідини: +item.material.oreprefix.oreBasalt=%s (Базальтова руда) +item.material.oreprefix.oreSand=%s (Піщана руда) +item.material.oreprefix.oreRedSand=%s (Червона піщана руда) +item.material.oreprefix.oreNether=%s (Пекельна руда) +item.material.oreprefix.oreEndstone=%s (Ендова руда) +item.material.oreprefix.oreEnd=%s (Ендова руда) +gregtech.waila.energy_input=Вхід: %s EU/t +metaitem.wafer.highly_advanced_system_on_chip.name=Пластина HASoC +metaitem.gelled_toluene.name=Гелеподібний толуол +item.gt.tool.behavior.torch_place=§eСпелеолог: §fРозміщення смолоскипів на ПКМ +item.gt.tool.behavior.aoe_mining=§5Зона дії: §f%sx%sx%s +item.gt.tool.behavior.crop_harvesting=§aЖниварка: §fЗбирає врожай +cover.machine_controller.enable_with_redstone=Увімкнути від Редстоуну +cover.ender_fluid_link.incomplete_hex=Введений колір неповний!/nЙого буде застосовано після завершення (всі 8 шістнадцяткових цифр)/nЯкщо ви закриєте інтерфейс, правки буде втрачено! +cover.ender_fluid_link.transfer_unit=Л/t +cover.advanced_energy_detector.max=Максимум: +cover.advanced_fluid_detector.min=Мінімально рідини: +item.gt.tool.spade.name=Заступ (%s) +metaitem.battery.charge_detailed=%,d/%,d EU - Tier %s §7(§%c%,d%s залишилось§7) +metaitem.circuit_board.wetware.name=Відмінна друкована плата +metaitem.wafer.high_power_integrated_circuit.name=Пластина HPIC +metaitem.wafer.qbit_central_processing_unit.name=Пластина кубітного процесора +metaitem.plate.qbit_central_processing_unit.name=Кубітний процесор +metaitem.plate.qbit_central_processing_unit.tooltip=Кубітовий центральний процесор +item.gt.tool.scythe.tooltip=§8Зійде для косплею смерті +item.gt.tool.wrench_hv.name=%s Електроключ (HV) +metaarmor.hud.gravi_engine=Граві-двигун: %s +cover.ore_dictionary_filter.button.match_all.disabled=Будь-який запис зі словника руд +cover.fluid_regulator.supply_exact=Постачати точно: %s +cover.machine_controller.disable_with_redstone=Вимкнути від Редстоуну +cover.ender_fluid_link.private.tooltip.disabled=Перемкнути в режим приватного резервуара\nПриватний режим використовує гравця, який поставив покращення +cover.ender_fluid_link.private.tooltip.enabled=Перемкнути в режим публічного резервуара +cover.generic.advanced_detector.invert_label=Вивід редстоуна: +cover.generic.advanced_detector.invert_tooltip=Перемкніть, щоб інвертувати логіку редстоуна +cover.advanced_energy_detector.normal=Звичайний +cover.advanced_energy_detector.modes_label=Режим: +cover.advanced_energy_detector.mode_percent=Відсоток +item.material.oreprefix.oreMarble=%s (Мармурна руда) +item.material.oreprefix.ore=%s (Руда) +gt.tool.class.grafter=Щепальний ніж +item.material.oreprefix.oreNetherrack=%s (Пекельна руда) +gregtech.waila.active_transformer.average_io=Середній Вхід/Вихід: %s EU/t +metaitem.power_thruster.name=Силовий двигун +metaitem.power_thruster_advanced.name=Покращений силовий двигун +cover.machine_controller.mode.machine=Контролює машину +cover.ore_dictionary_filter.info=§bПриймає складні вирази\n§6a & b§r = AND\n§6a | b§r = OR\n§6a ^ b§r = XOR\n§6! abc§r = NOT\n§6( abc )§r для групування\n§6*§r для підстановочного символу (тобто 0 або більше символів)\n§6?§r для будь-якого 1 символу\n§6()§r для збігу з порожнім записом (включно з елементами, для яких немає словника руд)\n§bПриклад:\n§6dust*Gold | (plate* & !*Double*)\nПідходить для будь-якого золотого пилу всіх розмірів або для всіх пластин, але не для подвійних пластин +cover.robotic_arm.transfer_mode.description=§eПередача будь-чого§r - в цьому режимі, покращення передаватеме якомога більше елементів, що відповідають його фільтру./n§eПостачати рівно§r - в цьому режимі, покращення передаватеме пропорціями які вказані у слотах фільтра (або змінною під цією кнопкою для фільтра словника руд). Якщо кількість предметів менша за розмір порції, предмети не буде переміщено. Якщо є §bРозумний фільтр предметів§r, змінна під цією кнопкою діятиме як множник./n§eЗберігати рівно§r - в цьому режимі, покращення буде зберігати вказану кулькість предметів в інвентарі призначення, поставляючи додаткову кількість предметів, якщо потрібно./n§7Порада: ЛКМ/ПКМ по слотах фільтра, щоб змінити кількість предметів, використовуйте SHIFT, щоб змінити кількість швидше. +cover.fluid_regulator.transfer_mode.description=§eПередача будь-чого§r - в цьому режимі, покращення передаватеме якомога більше рідин, що відповідають його фільтру./n§eПостачати рівно§r - в цьому режимі, покращення передаватеме пропорціями які вказані у змінній під цією кнопкою. Якщо кількість рідини менша за розмір порції, рідину не буде переміщено./n§eЗберігати рівно§r - в цьому режимі, покращення буде зберігати вказану кулькість рідин в інвентарі призначення, поставляючи додаткову кількість рідин, якщо потрібно./n§7Порада: використовуйте SHIFT та ЛКМ/ПКМ щоб змінити кількість на 10, і CTRL щоб помножити на 100. +death.attack.screwdriver=%s крутив мізки %s останій раз! +item.material.oreprefix.oreBlackgranite=%s (Чорно-гранітова руда) +item.material.oreprefix.nugget=%s (Самородок) +item.material.oreprefix.plateDense=%s (Щільна пластина) +item.material.oreprefix.gear=%s (Шестерня) +item.material.oreprefix.pipeHugeRestrictive=%s (Величезна обмежувальна труба для предметів) +item.material.oreprefix.polymer.nugget=%s (Самородок) +item.material.oreprefix.polymer.plateDense=%s (Щільний лист) +item.material.oreprefix.polymer.plateDouble=%s (Подвійний лист) +item.material.oreprefix.polymer.dustTiny=%s (Крихітна купка) +item.material.oreprefix.polymer.dust=%s (Пил) +item.material.oreprefix.polymer.ingot=%s (Злиток) +gregtech.material.actinium=Актиній +gregtech.material.aluminium=Алюміній +cover.generic.ender.open_selector=Відкрити список записів +cover.advanced_energy_detector.modes_tooltip=Перемикання між використанням точних значень EU або відсотків для порівняння мін/макс з підключеним накопичувачем енергії. +cover.advanced_energy_detector.mode_eu=Точне значення +cover.advanced_fluid_detector.label=Покращений датчик рідини +cover.advanced_item_detector.label=Покращений датчик предметів +cover.advanced_item_detector.invert_tooltip=Перемкніть, щоб інвертувати логіку редстоуну/nЗа замовчуванням, редстоун видає сигнал коли предметів менше ніж мін, і зупиняє коли значення предметів більше ніж макс +cover.advanced_item_detector.max=Максимум предметів: +cover.advanced_item_detector.min=Мінімум предметів: +cover.storage.title=Сховище (Покращення) +item.material.oreprefix.oreRedgranite=%s (Червоно-гранітова руда) +item.material.oreprefix.oreGranite=%s (Гранітова руда) +item.material.oreprefix.oreDiorite=%s (Діоритова руда) +item.material.oreprefix.oreAndesite=%s (Андезитова руда) +item.material.oreprefix.crushedCentrifuged=%s (Центрифугований руда) +item.material.oreprefix.crushedPurified=%s (Очищена руда) +item.material.oreprefix.crushed=%s (Подрібнена руда) +item.material.oreprefix.ingotHot=%s (Гарячий зливок) +item.material.oreprefix.ingot=%s (Злиток) +item.material.oreprefix.gem=%s +item.material.oreprefix.gemChipped=%s (Самородок) +item.material.oreprefix.gemFlawed=%s (Неповноцінний) +item.material.oreprefix.gemFlawless=%s (Бездоганний) +item.material.oreprefix.gemExquisite=%s (Вишуканий) +item.material.oreprefix.dustTiny=%s (Крихітна купка пилу) +item.material.oreprefix.dustSmall=%s (Маленька купка пилу) +item.material.oreprefix.dustImpure=%s (Нечиста купка пилу) +item.material.oreprefix.dustPure=%s (Очищена купка пилу) +item.material.oreprefix.dust=%s (Пил) +item.material.oreprefix.plateDouble=%s (Подвійна пластина) +item.material.oreprefix.plate=%s (Пластина) +item.material.oreprefix.plank=%s (Дошки) +item.material.oreprefix.foil=%s (Фольга) +item.material.oreprefix.stick=%s (Стержень) +item.material.oreprefix.round=%s (Куля) +item.material.oreprefix.bolt=%s (Болт) +item.material.oreprefix.screw=%s (Гвинт) +item.material.oreprefix.ring=%s (Кільце) +item.material.oreprefix.springSmall=%s (Мала пружина) +item.material.oreprefix.wireFine=%s (Тонкий дріт) +item.material.oreprefix.rotor=%s (Ротор) +item.material.oreprefix.gearSmall=%s (Маленька шестерня) +item.material.oreprefix.lens=%s (Лінза) +item.material.oreprefix.toolHeadSword=%s (Лезо меча) +item.material.oreprefix.toolHeadPickaxe=%s (Головка кайла) +item.material.oreprefix.toolHeadShovel=%s (Головка лопати) +item.material.oreprefix.toolHeadAxe=%s (Головка сокири) +item.material.oreprefix.toolHeadHoe=%s (Головка мотики) +item.material.oreprefix.toolHeadScythe=%s (Лезо коси) +item.material.oreprefix.toolHeadFile=%s (Головка напилка) +item.material.oreprefix.toolHeadHammer=%s (Головка молотка) +item.material.oreprefix.toolHeadSaw=%s (Лезо пилки) +item.material.oreprefix.toolHeadBuzzSaw=%s (Лезо пили) +item.material.oreprefix.toolHeadScrewdriver=%s (Наконечник для викрутки) +item.material.oreprefix.toolHeadDrill=%s (Наконечник для бура) +item.material.oreprefix.toolHeadChainsaw=%s (Наконечник для бензопили) +item.material.oreprefix.toolHeadWrench=%s (Наконечник гайкового ключа) +item.material.oreprefix.turbineBlade=%s (Лопатка турбіни) +item.material.oreprefix.block=%s (Блок) +item.material.oreprefix.frameGt=%s (Каркас) +item.material.oreprefix.pipeTinyFluid=%s (Крихітна трубка для рідини) +item.material.oreprefix.pipeSmallFluid=%s (Маленька труба для рідини) +item.material.oreprefix.pipeNormalFluid=%s (Труба для рідини) +item.material.oreprefix.pipeLargeFluid=%s (Велика труба для рідини) +item.material.oreprefix.pipeQuadrupleFluid=%s (Четверна труба для рідини) +item.material.oreprefix.pipeNonupleFluid=%s (Дев'ятисекційна рідинна труба) +item.material.oreprefix.pipeTinyItem=%s (Крихітна труба для предметів) +item.material.oreprefix.pipeNormalItem=%s (Труба для предметів) +item.material.oreprefix.pipeLargeItem=%s (Велика труба для предметів) +item.material.oreprefix.pipeHugeItem=%s (Величезна труба для предметів) +item.material.oreprefix.pipeSmallRestrictive=%s (Маленька обмежувальна труба для предметів) +item.material.oreprefix.pipeNormalRestrictive=%s (Обмежувальна труба для предметів) +item.material.oreprefix.pipeLargeRestrictive=%s (Велика обмежувальна труба для предметів) +item.material.oreprefix.wireGtHex=%s (16x Дріт) +item.material.oreprefix.wireGtOctal=%s (8x Дріт) +item.material.oreprefix.wireGtQuadruple=%s (4x Дріт) +item.material.oreprefix.wireGtDouble=%s (2x Wire) +item.material.oreprefix.wireGtSingle=%s (1x Дріт) +item.material.oreprefix.cableGtHex=%s (16x Кабель) +item.material.oreprefix.cableGtOctal=%s (8x Cable) +item.material.oreprefix.cableGtQuadruple=%s (4x Кабель) +item.material.oreprefix.cableGtDouble=%s (2x Кабель) +item.material.oreprefix.cableGtSingle=%s (1x Кабель) +item.material.oreprefix.polymer.plate=%s (Лист) +item.material.oreprefix.polymer.foil=%s (Тонкий лист) +cover.generic.advanced_detector.latch_tooltip=Змінити поведінку редстоуна цього покращення. /n§eБезперервний§7 - За замовчуванням; значення менше мінімального виходу 0; значення більше максимального виходу 15; значення між мінімальним і максимальним виходом від 0 до 15 /n§eЗамкнений§7 - виводити 15, поки не перевищить макс, потім виводити 0, поки не стане менше мін +cover.advanced_energy_detector.invert_tooltip=Перемкніть, щоб інвертувати логіку редстоуну/nЗа замовчуванням, редстоун видає сигнал коли енергії менше ніж мін EU, і зупиняє коли значення енергії більше ніж макс EU +item.material.oreprefix.stickLong=%s (Довгий стержень) +item.material.oreprefix.pipeHugeFluid=%s (Величезна труба для рідини) +item.material.oreprefix.spring=%s (Пружина) +item.material.oreprefix.pipeSmallItem=%s (Маленька труба для предметів) +item.material.oreprefix.pipeTinyRestrictive=%s (Крихітна обмежувальна труба для предметів) +item.material.oreprefix.polymer.dustSmall=%s (Маленька купка) +gregtech.material.naquadah_enriched=Збагачений наквада +gregtech.material.praseodymium=Празеодим +gregtech.material.promethium=Прометій +gregtech.material.protactinium=Протактиній +gregtech.material.radon=Радон +gregtech.material.radium=Радій +gregtech.material.rhenium=Реній +gregtech.material.rhodium=Родій +gregtech.material.sodium=Натрій +gregtech.material.strontium=Стронцій +gregtech.material.sulfur=Сірка +gregtech.material.tantalum=Тантал +gregtech.material.technetium=Технецій +gregtech.material.tellurium=Телур +gregtech.material.uranium=Уран +gregtech.material.emerald=Смарагд +gregtech.material.deuterium=Дейтерій +gregtech.material.dubnium=Дубній +gregtech.material.dysprosium=Диспрозій +gregtech.material.einsteinium=Ейнштейній +gregtech.material.hydrogen=Водень +gregtech.material.helium=Гелій +gregtech.material.helium_3=Гелій-3 +gregtech.material.lead=Свинець +gregtech.material.lithium=Літій +gregtech.material.lutetium=Лютецій +gregtech.material.magnesium=Магній +gregtech.material.mendelevium=Менделевій +gregtech.material.manganese=Манґан +gregtech.material.mercury=Ртуть +gregtech.material.livermorium=Ліверморій +gregtech.material.meitnerium=Майтнерій +gregtech.material.moscovium=Московій +gregtech.material.molybdenum=Молібден +gregtech.material.oxygen=Кисень +gregtech.material.osmium=Осмій +gregtech.material.palladium=Паладій +gregtech.material.duranium=Дураніум +gregtech.material.trinium=Трініум +gregtech.material.almandine=Альмандин +gregtech.material.andradite=Андрадит +gregtech.material.annealed_copper=Відпалена мідь +gregtech.material.asbestos=Азбест +gregtech.material.ash=Попіл +gregtech.material.banded_iron=Стрічкове залізо +gregtech.material.battery_alloy=Батарейний сплав +gregtech.material.blue_topaz=Синій топаз +gregtech.material.bone=Кость +gregtech.material.brass=Латунь +gregtech.material.bronze=Бронза +gregtech.material.brown_limonite=Коричновий лімоніт +gregtech.material.calcite=Кальцит +gregtech.material.cinnabar=Кіновар +gregtech.material.water=Вода +gregtech.material.coal=Вугілля +gregtech.material.cobaltite=Кобальтин +gregtech.material.cooperite=Шелдоніт +gregtech.material.cupronickel=Купронікель +gregtech.material.dark_ash=Темний попіл +gregtech.material.diamond=Діамант +gregtech.material.electrum=Електрум +gregtech.material.galena=Галеніт +gregtech.material.garnierite=Гарнієрит +gregtech.creative.energy.voltage=Вольтаж +for.bees.species.clay=Глина +gregtech.jei.ct_recipe.tooltip=Рецепт CraftTweaker +gregtech.jei.gs_recipe.tooltip=Рецепт GroovyScript +gregtech.material.darmstadtium=Дармштадтій +gregtech.material.erbium=Ербій +gregtech.material.europium=Європій +gregtech.material.fermium=Фермій +gregtech.material.flerovium=Флеровій +gregtech.material.fluorine=Фтор +gregtech.material.francium=Францій +gregtech.material.gadolinium=Гадоліній +gregtech.material.gallium=Галій +gregtech.material.germanium=Германій +gregtech.material.gold=Золото +gregtech.material.hafnium=Гафній +gregtech.material.hassium=Гасій +gregtech.material.iodine=Йод +gregtech.material.iron=Залізо +gregtech.material.krypton=Криптон +gregtech.material.lanthanum=Лантан +gregtech.material.lawrencium=Лоуренсій +gregtech.material.neodymium=Неодим +gregtech.material.neon=Неон +gregtech.material.neptunium=Нептуній +gregtech.material.nickel=Нікель +gregtech.material.nihonium=Ніхоній +gregtech.material.oganesson=Оґанесон +gregtech.material.phosphorus=Фосфор +gregtech.material.polonium=Полоній +gregtech.material.platinum=Платина +gregtech.material.plutonium=Плутоній +gregtech.material.plutonium_239=Плутоній 239 +gregtech.material.plutonium_241=Плутоній 241 +gregtech.material.potassium=Калій +gregtech.material.roentgenium=Рентгеній +gregtech.material.rubidium=Рубідій +gregtech.material.ruthenium=Рутеній +gregtech.material.rutherfordium=Резерфордій +gregtech.material.samarium=Самарій +gregtech.material.scandium=Скандій +gregtech.material.seaborgium=Сіборгій +gregtech.material.selenium=Селен +gregtech.material.silicon=Кремній +gregtech.material.silver=Срібло +gregtech.material.tennessine=Теннессин +gregtech.material.terbium=Тербій +gregtech.material.thorium=Торій +gregtech.material.thallium=Талій +gregtech.material.thulium=Тулій +gregtech.material.tin=Олово +gregtech.material.titanium=Титан +gregtech.material.tritium=Тритій +gregtech.material.tungsten=Вольфрам +gregtech.material.uranium_235=Уран 235 +gregtech.material.uranium_238=Уран 238 +gregtech.material.vanadium=Ванадій +gregtech.material.xenon=Ксенон +gregtech.material.ytterbium=Ітербій +gregtech.material.yttrium=Ітрій +gregtech.material.zinc=Цинк +gregtech.material.zirconium=Цирконій +gregtech.material.naquadah=Наквада +gregtech.material.naquadria=Наквадрія +gregtech.material.neutronium=Нейтроній +gregtech.material.tritanium=Тританій +gregtech.material.cassiterite=Каситерит +gregtech.material.cassiterite_sand=Каситеритовий пісок +gregtech.material.chalcopyrite=Халькопірит +gregtech.material.charcoal=Деревне вугілля +gregtech.material.green_sapphire=Зелений сапфір +gregtech.material.grossular=Гросуляр +for.bees.species.nitrogen=Азот +metaitem.coin.doge.tooltip=Вау скільки коінів, як багато грошей кріпта пліз я дуже богатий вау +gregtech.material.holmium=Гольмій +gregtech.material.indium=Індій +gregtech.material.niobium=Ніобій +gregtech.material.chromite=Хроміт +gregtech.material.chromium_dioxide=Діоксид хрому +gregtech.material.liquid_oxygen=Рідкий кисень +gregtech.material.iridium=Ірідіум +gregtech.material.nitrogen=Азот +gregtech.material.nobelium=Нобелій +gregtech.material.americium=Америцій +gregtech.material.antimony=Стибій +gregtech.material.astatine=Астат +gregtech.material.bromine=Бром +gregtech.material.caesium=Цезій +gregtech.material.calcium=Кальцій +gregtech.material.californium=Каліфорній +gregtech.material.carbon=Вуглець +gregtech.material.cadmium=Кадмій +gregtech.material.cerium=Церій +gregtech.material.cobalt=Кобальт +gregtech.top.quantum_status.label=Статус: +gregtech.top.quantum_status.powered=§bОнлайн +gregtech.top.quantum_status.connected=§cНемає енергії +gregtech.top.quantum_status.disconnected=Не підключено +gregtech.top.quantum_controller.no_power=§cНемає енергії +gregtech.top.steam_cooling_down=Охолодження +gregtech.material.argon=Аргон +gregtech.material.arsenic=Арсен +gregtech.material.barium=Барій +gregtech.material.berkelium=Берклій +gregtech.material.beryllium=Берилій +gregtech.material.bismuth=Бісмут +gregtech.material.bohrium=Борій +gregtech.material.boron=Бор +gregtech.material.chlorine=Хлор +gregtech.material.chrome=Хром +gregtech.material.copernicium=Коперницій +gregtech.material.copper=Мідь +gregtech.material.curium=Кюрій +gregtech.material.magnalium=Магналій +gregtech.material.niobium_nitride=Нітрид ніобію +gregtech.material.kanthal=Канталь +gregtech.material.lazurite=Лазурит +gregtech.material.liquid_helium=Рідкий гелій +gregtech.material.magnesite=Магнезит +gregtech.material.magnetite=Магнетит +gregtech.material.molybdenite=Молібденіт +gregtech.material.nichrome=Ніхром +gregtech.material.niobium_titanium=Ніобій-Титан +gregtech.material.obsidian=Обсидіан +gregtech.material.phosphate=Фосфат +gregtech.material.ice=Лід +gregtech.material.ilmenite=Ільменіт +gregtech.material.rutile=Рутил +gregtech.material.bauxite=Боксити +gregtech.material.invar=Інвар +gregtech.material.sterling_silver=Стерлінгове срібло +gregtech.material.rose_gold=Рожеве золото +gregtech.material.black_bronze=Чорна бронза +gregtech.material.bismuth_bronze=Вісмутовая бронза +gregtech.material.biotite=Біотит +gregtech.material.powellite=Повеліт +gregtech.material.pyrite=Пірит +gregtech.material.pyrolusite=Піролюзит +gregtech.material.pyrope=Піроп +gregtech.material.rock_salt=Кам'яна сіль +gregtech.material.ruridit=Руридит +gregtech.material.wulfenite=Вульфеніт +gregtech.material.rubber=Гума +gregtech.material.ruby=Рубін +gregtech.material.salt=Сіль +gregtech.material.saltpeter=Селітра +gregtech.material.aluminium_sulfite=Сульфіт алюмінію +gregtech.material.sapphire=Сапфір +gregtech.material.tin_alloy=Олов'яний сплав +gregtech.material.topaz=Топаз +gregtech.material.tungstate=Вольфрамат +gregtech.material.ultimet=Ультімет +gregtech.material.tantalite=Танталіт +gregtech.material.coke=Кокс +gregtech.material.soldering_alloy=Паяльний сплав +gregtech.material.spessartine=Спесартин +gregtech.material.sphalerite=Сфалерит +gregtech.material.stainless_steel=Нержавіюча сталь +gregtech.material.steel=Сталь +gregtech.material.stibnite=Антимоніт +gregtech.material.tetrahedrite=Тетраедрит +gregtech.material.uraninite=Уранініт +gregtech.material.uvarovite=Уваровіт +gregtech.material.vanadium_gallium=Ванадій-галій +gregtech.material.wrought_iron=Ковке залізо +gregtech.material.yellow_limonite=Жовтий лімоніт +gregtech.material.quartzite=Кварцит +gregtech.material.graphite=Графіт +gregtech.material.graphene=Графен +gregtech.material.scheelite=Шеєліт +gregtech.material.sodalite=Содаліт +gregtech.material.yttrium_barium_cuprate=Ітрій-барій купрат +gregtech.material.nether_quartz=Незерський кварц +gregtech.material.certus_quartz=Справжний кварц +gregtech.material.tungstic_acid=Вольфрамова кислота +gregtech.material.osmiridium=Осмистий іридій +gregtech.material.calcium_chloride=Хлорид кальцію +gregtech.material.lithium_chloride=Хлорид літію +gregtech.material.bornite=Борніт +gregtech.material.chalcocite=Халькозин +gregtech.material.inert_metal_mixture=Суміш інертних металів +gregtech.material.nickel_zinc_ferrite=Ферит цинко нікелю +gregtech.material.silicon_dioxide=Діоксид кремнію +gregtech.material.ferrosilite=Феросиліт +gregtech.material.iron_magnetic=Магнітне залізо +gregtech.material.carbon_dioxide=Діоксид вуглецю +gregtech.material.titanium_tetrachloride=Тетрахлорид титану +gregtech.material.nitrogen_dioxide=Діоксид азоту +gregtech.material.hydrogen_sulfide=Сірководень +gregtech.material.sulfuric_acid=Сульфатна кислота +gregtech.material.massicot=Масикот +gregtech.material.uranium_triplatinum=Триплатинауран +gregtech.material.samarium_iron_arsenic_oxide=Самарій залізо арсен оксид +gregtech.material.indium_tin_barium_titanium_cuprate=Індій олово барій титан купорос +gregtech.material.rtm_alloy=Сплав RTM +gregtech.material.zirconia=Оксид цирконію +gregtech.material.zirconium_tetrachloride=Хлорид цирконію +gregtech.material.hafnia=Гафнія +gregtech.material.platinum_group_sludge=Мул платинової групи +gregtech.material.cobalt_oxide=Оксид кобальту +gregtech.material.lepidolite=Лепідоліт +gregtech.material.tungsten_carbide=Карбід вольфраму +gregtech.material.nitric_acid=Нітратна кислота +gregtech.material.hypochlorous_acid=Гіпохлоритна кислота +gregtech.material.calcium_phosphide=Фосфід кальцію +gregtech.material.arsenic_trioxide=Триоксид арсену +gregtech.material.enriched_uranium_hexafluoride=Гексафторид збагаченого урану +gregtech.material.mercury_barium_calcium_cuprate=Ртутно-барієво-кальцієвий купорос +gregtech.material.ruthenium_tetroxide=Чотириокис рутенію +gregtech.material.zinc_sulfide=Сульфід цинку +gregtech.material.ilmenite_slag=Ільменітовий шлак +gregtech.material.hafnium_tetrachloride=Тетрахлорид гафнію +gregtech.material.zircon=Циркон +gregtech.material.gallium_arsenide=Арсенід галію +gregtech.material.potash=Карбонат калію +gregtech.material.soda_ash=Кальцинована сода +gregtech.material.indium_gallium_phosphide=Фосфід індію та галію +gregtech.material.magnesium_chloride=Хлорид магнію +gregtech.material.sodium_sulfide=Сульфід натрію +gregtech.material.phosphorus_pentoxide=Оксид фосфору +gregtech.material.quicklime=Негашене вапно +gregtech.material.sodium_bisulfate=Бісульфат натрію +gregtech.material.ferrite_mixture=Феритова суміш +gregtech.material.magnesia=Магнезія +gregtech.material.realgar=Реальгар +gregtech.material.sodium_bicarbonate=Гідрокарбонат натрію +gregtech.material.potassium_dichromate=Дихромат калію +gregtech.material.chromium_trioxide=Триоксид хрому +gregtech.material.antimony_trioxide=Сенармонтит +gregtech.material.zincite=Цинкіт +gregtech.material.cupric_oxide=Оксид міді +gregtech.material.metal_mixture=Суміш металів +gregtech.material.sodium_hydroxide=Гідроксид натрію +gregtech.material.sodium_persulfate=Персульфат натрію +gregtech.material.bastnasite=Бастнезит +gregtech.material.pentlandite=Пентландит +gregtech.material.spodumene=Сподумен +gregtech.material.glauconite_sand=Глауконітовий пісок +gregtech.material.malachite=Малахіт +gregtech.material.mica=Слюда +gregtech.material.barite=Барит +gregtech.material.alunite=Алуніт +gregtech.material.talc=Тальк +gregtech.material.soapstone=Жировик +gregtech.material.kyanite=Кіаніт +gregtech.material.phosphoric_acid=Ортофосфатна кислота +gregtech.material.sulfur_trioxide=Триоксид сірки +gregtech.material.sulfur_dioxide=Діоксид сірки +gregtech.material.carbon_monoxide=Монооксид вуглецю +gregtech.material.ammonia=Аміак +gregtech.material.hydrofluoric_acid=Флуоридна кислота +gregtech.material.nitric_oxide=Оксид азоту +gregtech.material.iron_iii_chloride=Хлорид заліза(III) +gregtech.material.uranium_hexafluoride=Гексафторид урану +gregtech.material.depleted_uranium_hexafluoride=Гексафторид збідненого урану +gregtech.material.nitrous_oxide=Оксид нітрогену +gregtech.material.ender_pearl=Перлина Енду +gregtech.material.potassium_feldspar=Польовий шпат калію +gregtech.material.neodymium_magnetic=Магніт неодимовий +gregtech.material.hydrochloric_acid=Хлоридна кислота +gregtech.material.steam=Пар +gregtech.material.distilled_water=Дистильована вода +gregtech.material.sodium_potassium=Натрій калію +gregtech.material.samarium_magnetic=Магнітний самарій +gregtech.material.manganese_phosphide=Фосфід мангану +gregtech.material.magnesium_diboride=Диборид магнію +gregtech.material.uranium_rhodium_dinaquadide=Динаквадид урану та родію +gregtech.material.enriched_naquadah_trinium_europium_duranide=Збагачений наквада-дуранід тринію європію +gregtech.material.ruthenium_trinium_americium_neutronate=Нейтронат рутенію тринію америцію +gregtech.material.platinum_raw=Необроболена платина +gregtech.material.rhodium_sulfate=Сульфат родію +gregtech.material.osmium_tetroxide=Тетроксид осмію +gregtech.material.iridium_chloride=Хлорид іридію +gregtech.material.fluoroantimonic_acid=Фторантимонова кислота +gregtech.material.titanium_trifluoride=Трифторид титану +gregtech.material.indium_phosphide=Фосфід індію +gregtech.material.barium_sulfide=Сульфід барію +gregtech.material.trinium_sulfide=Сульфід трініуму +gregtech.material.gallium_sulfide=Сульфід галію +gregtech.material.antimony_trifluoride=Трифторид стибію +gregtech.material.enriched_naquadah_sulfate=Збагачений сульфат наквади +gregtech.material.naquadria_sulfate=Сульфат наквади +gregtech.material.pyrochlore=Пірохлор diff --git a/src/main/resources/assets/gregtech/lang/zh_cn.lang b/src/main/resources/assets/gregtech/lang/zh_cn.lang index 591a998e8d2..3236fb9fd19 100644 --- a/src/main/resources/assets/gregtech/lang/zh_cn.lang +++ b/src/main/resources/assets/gregtech/lang/zh_cn.lang @@ -119,7 +119,7 @@ option.gregtech.steam_boiler=蒸汽锅炉 option.gregtech.transformer=变压器 option.gregtech.workable=机器工作状态 -gregtech.waila.energy_stored=能量:%d EU / %d EU +gregtech.waila.energy_stored=能量:%s EU / %s EU gregtech.waila.progress_idle=闲置 gregtech.waila.progress_tick=进度:%d t / %d t gregtech.waila.progress_sec=进度:%d s / %d s @@ -1830,6 +1830,14 @@ gregtech.material.enriched_naquadah_sulfate=硫酸富集硅岩 gregtech.material.naquadria_sulfate=硫酸超能硅岩 gregtech.material.pyrochlore=烧绿石 gregtech.material.rtm_alloy=钌钨钼合金 +gregtech.material.ilmenite_slag=钛铁矿渣 +gregtech.material.zircon=锆石 +gregtech.material.zirconia=氧化锆 +gregtech.material.zirconium_tetrachloride=四氯化锆 +gregtech.material.hafnia=二氧化铪 +gregtech.material.hafnium_tetrachloride=四氯化铪 +gregtech.material.zircaloy_4=锆-4合金 +gregtech.material.inconel_718=因科镍-718 # Organic Chemistry Materials @@ -2043,6 +2051,11 @@ gregtech.material.acidic_naquadria_solution=酸性超能硅岩溶液 gregtech.material.naquadria_waste=超能硅岩废液 gregtech.material.lapotron=兰波顿 gregtech.material.uu_matter=UU物质 +gregtech.material.bauxite_slurry=铝土浆液 +gregtech.material.cracked_bauxite_slurry=裂化铝土浆液 +gregtech.material.bauxite_sludge=铝土泥渣 +gregtech.material.decalcified_bauxite_sludge=脱钙铝土泥渣 +gregtech.material.bauxite_slag=铝土矿渣 # Second Degree Materials @@ -2403,7 +2416,7 @@ tile.optical_pipe_normal.name=光缆 tile.optical_pipe_normal.tooltip1=传递§f算力§7或§f研究数据§7 tile.laser_pipe_normal.name=激光传导线缆 -tile.laser_pipe_normal.tooltip1=无线损地传递能量,只限直线摆放 +tile.laser_pipe_normal.tooltip1=§f无损§7传递能量,仅限直线摆放 metaitem.prospector.lv.name=电动勘探扫描仪(LV) metaitem.prospector.hv.name=电动勘探扫描仪(HV) @@ -4798,7 +4811,7 @@ gregtech.machine.large_miner.ev.name=基础采矿场 gregtech.machine.large_miner.iv.name=进阶采矿场 gregtech.machine.large_miner.luv.name=进阶采矿场 II gregtech.machine.miner.multi.modes=具有精准采集模式与区块对齐模式。 -gregtech.machine.miner.multi.production=产出§f研磨机§7§f3x§7倍的粉碎矿石。 +gregtech.machine.miner.multi.production=它能产出§f三倍§7于§f研磨机§7的粉碎矿石。 gregtech.machine.miner.fluid_usage=每tick消耗§f%,d L§7的§f%s§7,超频时翻倍。 gregtech.machine.miner.multi.description=一台工作范围极广的多方块采矿机,能够提供巨量矿石。 gregtech.machine.miner.multi.needsfluid=钻井液不足! @@ -4817,7 +4830,7 @@ gregtech.machine.miner.chunkradius=区块半径:%d gregtech.machine.fluid_drilling_rig.mv.name=基础流体钻机 gregtech.machine.fluid_drilling_rig.hv.name=进阶流体钻机 gregtech.machine.fluid_drilling_rig.ev.name=进阶流体钻机 II -gregtech.machine.fluid_drilling_rig.description=钻取基岩之下的涓涓流体。 +gregtech.machine.fluid_drilling_rig.description=钻取基岩之下的漫漫流体。 gregtech.machine.fluid_drilling_rig.production=§e产量倍数:§f%dx,超频时为%fx gregtech.machine.fluid_drilling_rig.depletion=§b损耗率:§f%s%% gregtech.machine.fluid_drilling_rig.shows_depletion=显示流体矿脉信息 @@ -5155,9 +5168,9 @@ gregtech.maintenance.configurable_duration=处理耗时:%fx gregtech.maintenance.configurable_duration.unchanged_description=配方以正常速度运行。更改配置以更新。 gregtech.maintenance.configurable_duration.changed_description=配方处理速度现为正常速度(不计超频)的%f倍。 -gregtech.maintenance.configurable_time=故障几率:%fx -gregtech.maintenance.configurable_time.unchanged_description=故障的发生几率为正常值。更改配置以更新。 -gregtech.maintenance.configurable_time.changed_description=故障的发生几率现为正常值的%f倍。 +gregtech.maintenance.configurable_time=故障概率:%fx +gregtech.maintenance.configurable_time.unchanged_description=故障的发生概率为正常值。更改配置以更新。 +gregtech.maintenance.configurable_time.changed_description=故障的发生概率现为正常值的%f倍。 gregtech.maintenance.configurable.tooltip_basic=以更频繁的维护需求为代价,加快机器的处理速度 gregtech.maintenance.configurable.tooltip_more_info=按住SHIFT进行特殊交互 @@ -5183,7 +5196,7 @@ gregtech.machine.muffler_hatch.uxv.name=§eUXV§r消声仓 gregtech.machine.muffler_hatch.opv.name=§9OpV§r消声仓 gregtech.machine.muffler_hatch.max.name=§c§lMAX§r消声仓 -gregtech.muffler.recovery_tooltip=§b收集几率:§f%d%% +gregtech.muffler.recovery_tooltip=§b收集概率:§f%d%% gregtech.machine.pump_hatch.name=水泵输出仓 gregtech.machine.pump_hatch.tooltip=原始水泵专用流体输出口 @@ -5295,7 +5308,7 @@ gregtech.machine.laser_hatch.target.tooltip1=远距离接收能量 gregtech.machine.laser_hatch.tooltip2=§c激光传导线缆必须直线摆放!§7 gregtech.machine.fluid_tank.max_multiblock=多方块结构最大尺寸:%,dx%,dx%,d -gregtech.machine.fluid_tank.fluid=含有%s mB%s +gregtech.machine.fluid_tank.fluid=含有%s L%s # ME Parts gregtech.machine.me_import_item_bus.name=ME输入总线 @@ -5496,14 +5509,14 @@ fluid.spawnlocation.name=流体矿脉信息 gregtech.jei.fluid.vein_weight=矿脉权重:%d gregtech.jei.fluid.min_yield=最小产量:%d gregtech.jei.fluid.max_yield=最大产量:%d -gregtech.jei.fluid.depletion_chance=消耗几率:%d%% +gregtech.jei.fluid.depletion_chance=消耗概率:%d%% gregtech.jei.fluid.depletion_amount=消耗量:%d gregtech.jei.fluid.depleted_rate=殆尽后产量:%d gregtech.jei.fluid.dimension=维度: gregtech.jei.fluid.weight_hover=流体矿脉的生成权重。鼠标悬于图标可查看该流体在特定生物群系中特殊的生成权重 gregtech.jei.fluid.min_hover=流体矿脉所能具有的的最小产量 gregtech.jei.fluid.max_hover=流体矿脉所能具有的的最大产量 -gregtech.jei.fluid.dep_chance_hover=开采流体矿脉时消耗的几率 +gregtech.jei.fluid.dep_chance_hover=开采流体矿脉时消耗的概率 gregtech.jei.fluid.dep_amount_hover=消耗后消耗的量 gregtech.jei.fluid.dep_yield_hover=流体矿脉殆尽后能开采的最大流体量 @@ -5661,7 +5674,7 @@ gregtech.multiblock.large_combustion_engine.supply_liquid_oxygen_to_boost=提供 gregtech.multiblock.large_combustion_engine.obstructed=引擎进气口受阻! gregtech.multiblock.large_combustion_engine.obstructed.desc=引擎进气口前方必须有一格空气。 -gregtech.multiblock.turbine.fuel_amount=燃料量:%s mB(%s) +gregtech.multiblock.turbine.fuel_amount=燃料量:%s L(%s) gregtech.multiblock.turbine.fuel_needed=消耗量:%s / %s ticks gregtech.multiblock.turbine.rotor_speed=转子转速:%s gregtech.multiblock.turbine.rotor_rpm_unit_name=RPM @@ -5751,14 +5764,14 @@ gregtech.multiblock.hpca.warning_multiple_bridges=- 多个桥接组件(没有 gregtech.multiblock.hpca.warning_no_computation=- 没有计算组件 gregtech.multiblock.hpca.warning_low_cooling=- 冷却不足 gregtech.multiblock.hpca.info_max_computation=最大算力:%s -gregtech.multiblock.hpca.info_max_cooling_demand=冷却液需求:%s -gregtech.multiblock.hpca.info_max_cooling_available=冷却液可用:%s -gregtech.multiblock.hpca.info_max_coolant_required=冷却液还需:%s +gregtech.multiblock.hpca.info_max_cooling_demand=冷却需求:%s +gregtech.multiblock.hpca.info_max_cooling_available=冷却可用:%s +gregtech.multiblock.hpca.info_max_coolant_required=冷却液需求:%s L/t gregtech.multiblock.hpca.info_coolant_name=多氯联苯冷却液 gregtech.multiblock.hpca.info_bridging_enabled=桥接已启动 gregtech.multiblock.hpca.info_bridging_disabled=桥接已关闭 -gregtech.command.usage=用法:/gregtech +gregtech.command.usage=用法:/gregtech gregtech.command.worldgen.usage=用法:/gregtech worldgen gregtech.command.worldgen.reload.usage=用法:/gregtech worldgen reload gregtech.command.worldgen.reload.success=已从配置文件中重载世界生成设定。 @@ -5785,6 +5798,12 @@ gregtech.command.copy.copied_and_click=已复制至剪贴板。点击以再次 gregtech.command.copy.click_to_copy=点击以复制 gregtech.command.copy.copied_start=已复制[ gregtech.command.copy.copied_end=]至剪贴板 +gregtech.command.datafix.usage=用法:/gregtech datafix +gregtech.command.datafix.bqu.usage=用法:/gregtech datafix [confirm] +gregtech.command.datafix.bqu.backup=备份你的存档和BQu配置文件,然后使用“confirm”参数重新运行 +gregtech.command.datafix.bqu.start=开始迁移BQu任务数据库… +gregtech.command.datafix.bqu.complete=BQu任务数据库迁移完成 +gregtech.command.datafix.bqu.failed=BQu任务数据库迁移失败。恢复你的备份! gregtech.chat.cape=§5恭喜你:你刚刚解锁了一件新披风!查看终端应用程序“披风选择器”来使用它。§r diff --git a/src/main/resources/assets/gregtech/models/item/tools/toolbelt.json b/src/main/resources/assets/gregtech/models/item/tools/toolbelt.json new file mode 100644 index 00000000000..25e4069ef67 --- /dev/null +++ b/src/main/resources/assets/gregtech/models/item/tools/toolbelt.json @@ -0,0 +1,7 @@ +{ + "parent": "item/handheld", + "textures": { + "layer0": "gregtech:items/tools/toolbelt_belt", + "layer1": "gregtech:items/tools/toolbelt_loops" + } +} diff --git a/src/main/resources/assets/gregtech/sounds.json b/src/main/resources/assets/gregtech/sounds.json index 10977e9cf2d..1b48b5e5953 100644 --- a/src/main/resources/assets/gregtech/sounds.json +++ b/src/main/resources/assets/gregtech/sounds.json @@ -397,5 +397,15 @@ "stream" : false } ] + }, + "click" : { + "subtitle" : "gregtech.subtitle.click", + "category" : "players", + "sounds" : [ + { + "name" : "gregtech:click", + "stream" : false + } + ] } } diff --git a/src/main/resources/assets/gregtech/sounds/click.ogg b/src/main/resources/assets/gregtech/sounds/click.ogg new file mode 100644 index 00000000000..c523d784b79 Binary files /dev/null and b/src/main/resources/assets/gregtech/sounds/click.ogg differ diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/activity_detector.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/activity_detector.json deleted file mode 100644 index 6e5523990e7..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/activity_detector.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Activity Detector", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:302" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/advanced_activity_detector.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/advanced_activity_detector.json deleted file mode 100644 index d6e5d2faf81..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/advanced_activity_detector.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Advanced Activity Detector", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:303" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/computer_monitor.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/computer_monitor.json deleted file mode 100644 index 9557d8c2c78..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/computer_monitor.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Computer Monitorc", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:307" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/conveyor.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/conveyor.json deleted file mode 100644 index 11e8a651db3..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/conveyor.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Conveyor Cover", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:157" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/crafting_table.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/crafting_table.json deleted file mode 100644 index c6fd856c2d0..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/crafting_table.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Crafting Table Cover", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:308" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/digital_interface_cover.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/digital_interface_cover.json deleted file mode 100644 index 3e9b91d7b99..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/digital_interface_cover.json +++ /dev/null @@ -1,253 +0,0 @@ -{ - "metaitem": "cover.digital", - "section": "Covers", - "title": "Digital Interface Cover", - "stream": [ - { - "type": "textbox", - "isCenter": false, - "content": [ - "§cDigital Interface Cover §ris a new cover, hereinafter referred to as the §lDIC§r.\n" - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 312, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 313, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "§lContents:" - ] - }, - { - "type": "textbox", - "link": "introduction", - "content": [ - "1. §9Introduction" - ] - }, - { - "type": "textbox", - "link": "fluid", - "content": [ - "2. §9Fluid Mode" - ] - }, - { - "type": "textbox", - "link": "item", - "content": [ - "3. §r§9Item Mode" - ] - }, - { - "type": "textbox", - "link": "energy", - "content": [ - "4. §9Energy Mode" - ] - }, - { - "type": "textbox", - "link": "machine", - "content": [ - "5. §9Machine Mode" - ] - }, - { - "type": "textbox", - "link": "proxy", - "content": [ - "6. §9Proxy Mode" - ] - }, - { - "type": "textbox", - "link": "wireless", - "content": [ - "7. §9Wireless Cover" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "introduction", - "content": [ - "§lIntroduction:" - ] - }, - { - "type": "textbox", - "content": [ - "You can place it at any side of machines, including the front side. It will automatically detect the machine and display the information of the machine.\n\nUsing the Screwdriver right click the §4DIC§r to open GUI.\n\nThere are five modes supported: §lFluid, Item, Energy, Machine, and Proxy§r.\n\nIn addition to the GUI, you can interact with DIC directly by hand.Try exploring on your own." - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "fluid", - "content": [ - "§lFluid Mode:" - ] - }, - { - "type": "textbox", - "content": [ - "monitor and interact(fill or drain) with fluids." - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107397364-8d212680-6b39-11eb-9152-b91f8f559ed6.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "item", - "content": [ - "§lItem Mode:" - ] - }, - { - "type": "textbox", - "content": [ - "monitor and interact(fill or extract) with items." - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107397608-c8235a00-6b39-11eb-95ad-77e4e5bc5d8b.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "energy", - "content": [ - "§lEnergy Mode:" - ] - }, - { - "type": "textbox", - "content": [ - "monitor the Energy usage. (monitoring energy stored, input and output per second)." - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107397946-1a647b00-6b3a-11eb-8680-52d13dd56e59.png", - "width": 190, - "height": 110 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "machine", - "content": [ - "§lMachine Mode:" - ] - }, - { - "type": "textbox", - "content": [ - "monitor and interact (stop or active) with workable machines. (low power, is working, working progress, isActive)." - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107398096-42ec7500-6b3a-11eb-8c26-b708ae183c3d.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "proxy", - "content": [ - "§lProxy Mode:" - ] - }, - { - "type": "textbox", - "content": [ - "should be used with the §1§lCentral Monitor§r." - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107856228-c1f6eb80-6e61-11eb-8098-454ea7133ca1.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "wireless", - "content": [ - "§lWireless:" - ] - }, - { - "type": "textbox", - "content": [ - "The wireless cover only has §4proxy Mode§r, allowing the §1§lCentral Monitor§r to access the cover remotely. Bind it remotely by right-clicking on a Central Monitor, and clear the binding by shift-right-clicking on Air." - ] - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/ender_fluid_link.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/ender_fluid_link.json deleted file mode 100644 index d88198015f9..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/ender_fluid_link.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Ender Fluid Link Cover", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:311" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/energy_detector.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/energy_detector.json deleted file mode 100644 index 8d5fc2e475b..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/energy_detector.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Energy Detector", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:306" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/fluid_detector.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/fluid_detector.json deleted file mode 100644 index 9562d8b3b92..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/fluid_detector.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Fluid Detector", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:304" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/fluid_filter.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/fluid_filter.json deleted file mode 100644 index 6c60268ca91..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/fluid_filter.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Fluid Filter", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:290" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/fluid_regulator.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/fluid_regulator.json deleted file mode 100644 index 163bed84c5a..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/fluid_regulator.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Fluid Regulator Cover", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:247" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/infinite_water.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/infinite_water.json deleted file mode 100644 index c7c7301571b..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/infinite_water.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Infinite Water Cover", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:310" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/item_detector.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/item_detector.json deleted file mode 100644 index 71ec3aa4ed6..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/item_detector.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Item Detector", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:305" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/item_filter.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/item_filter.json deleted file mode 100644 index 52d6678b331..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/item_filter.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Item Filter", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:291" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/machine_controller.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/machine_controller.json deleted file mode 100644 index a930161ac5c..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/machine_controller.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Machine Controller", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:301" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/ore_dictionary_filter.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/ore_dictionary_filter.json deleted file mode 100644 index d08d8d18401..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/ore_dictionary_filter.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Ore Dictionary Filter", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:292" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/pump.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/pump.json deleted file mode 100644 index c5f615d74cb..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/pump.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Pump Cover", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:142" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/robot_arm.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/robot_arm.json deleted file mode 100644 index 28294c1190e..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/robot_arm.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Robot Arm Cover", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:187" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/shutter_module.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/shutter_module.json deleted file mode 100644 index db8644be3b4..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/shutter_module.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Shutter Module", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:309" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/smart_item_filter.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/smart_item_filter.json deleted file mode 100644 index b8c617b0b67..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/covers/smart_item_filter.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Covers", - "title": "Smart Item Filter", - "stream": [], - "fixed": [], - "item": "gregtech:meta_item_1:293" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/axe.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/axe.json deleted file mode 100644 index 30e9c44f99a..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/axe.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Tools", - "title": "Axe", - "stream": [], - "fixed": [], - "item": "gregtech:meta_tool:3" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/buzzsaw.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/buzzsaw.json deleted file mode 100644 index 747a0c678e5..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/buzzsaw.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Tools", - "title": "Buzzsaw", - "stream": [], - "fixed": [], - "item": "gregtech:meta_tool:32" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/drill.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/drill.json deleted file mode 100644 index a8cdb41186e..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/drill.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Tools", - "title": "Drill", - "stream": [], - "fixed": [], - "item": "gregtech:meta_tool:20" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/file.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/file.json deleted file mode 100644 index e37a5a6437d..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/file.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Tools", - "title": "File", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6File§r is a tool that is only used for crafting recipes. No special uses unfortunately.\n\nLike most Gregtech tools, it can be repaired in an anvil." - ] - } - ], - "fixed": [], - "item": "gregtech:meta_tool:9" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/hammer.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/hammer.json deleted file mode 100644 index 466e74ee9b5..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/hammer.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Tools", - "title": "Hammer", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Hammer§r is a tool mainly used in crafting recipes.\n\nHowever, it has one special use outside of crafting recipes. When Right Clicked on a machine, it will mute the sounds of the machine running. Simply Right Click again to unmute.\n\nLike most Gregtech tools, it can be repaired in an anvil." - ] - } - ], - "fixed": [], - "item": "gregtech:meta_tool:6" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/mining_hammer.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/mining_hammer.json deleted file mode 100644 index c83b8f534a8..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/mining_hammer.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Tools", - "title": "Mining Hammer", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Mining Hammer§r is an Early Game alternative to the §6Drill§r, which does not require a source of power. It mines in a simple 3x3 area, and will mine in a 1x1 area when sneaking. Make sure to make some before going mining.\n\nLike most Gregtech tools, it can be repaired in an anvil." - ] - } - ], - "fixed": [], - "item": "gregtech:meta_tool:19" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/saw.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/saw.json deleted file mode 100644 index 0be14973fff..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/saw.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Tools", - "title": "Saw", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Saw§r is a Gregtech tool that is mainly using in crafting recipes, but has some special uses outside of crafting recipes.\n\nFirstly, it will harvest §1Ice§r and §1Packed Ice§r as if it had Silk Touch, dropping the actual items.\n\nSecondly, it will act like Shears when harvesting §1Leaves§r and §1Vines§r, meaning that the actual blocks will be dropped." - ] - } - ], - "fixed": [], - "item": "gregtech:meta_tool:5" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/screwdriver.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/screwdriver.json deleted file mode 100644 index f0b0125daca..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/screwdriver.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Tools", - "title": "Screwdriver", - "stream": [], - "fixed": [], - "item": "gregtech:meta_tool:11" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/sense.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/sense.json deleted file mode 100644 index a291d156b8c..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/sense.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Tools", - "title": "Sense", - "stream": [], - "fixed": [], - "item": "gregtech:meta_tool:17" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/wrench.json b/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/wrench.json deleted file mode 100644 index 99a163904d9..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/en_us/tools/wrench.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "section": "Tools", - "title": "Wrench", - "stream": [ - { - "type": "textbox", - "isCenter": false, - "content": [ - "The §6Wrench§r is one of the main tools in §1Gregtech§r and has several important uses.\n\nFirst, the Wrench can be the designated tool for breaking machines (Config option, default false). If a Wrench is not used to break the machine, it will break slower.\n\nSecondly, the Wrench can be used to set the output side for machines and multiblock components. Using the §4Machine Grid§r or just clicking on the desired face, Right Clicking with a Wrench will set the output face.\n\nRelated to the above, the Wrench can be used to set the Front Face of machines. Sneaking while Right Clicking (either directly on a face of the machine or using the machine grid) will change the front face of a machine, if it can be changed.\n\nIn addition to manipulating machines, wrenches are used for manipulating pipes. When Right Clicking on a pipe with a wrench, it will enable or disable the pipe connections to the corresponding face. When Sneaking while Right Clicking, pipes will have their travel routes blocked instead (Fluid Pipes only).\n\nLike most Gregtech tools, it can be repaired in an anvil." - ] - } - ], - "fixed": [], - "item": "gregtech:meta_tool:8" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/zh_cn/covers/digital_interface_cover.json b/src/main/resources/assets/gregtech/terminal/guide/items/zh_cn/covers/digital_interface_cover.json deleted file mode 100644 index 59fd56d2cad..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/zh_cn/covers/digital_interface_cover.json +++ /dev/null @@ -1,253 +0,0 @@ -{ - "metaitem": "cover.digital", - "section": "覆盖版", - "title": "数字化接口覆盖版", - "stream": [ - { - "type": "textbox", - "isCenter": false, - "content": [ - "§c数字化接口覆盖版 §r是一个新覆盖版, 一下简称 §lDIC§r.\n" - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 312, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 313, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "§l目录:" - ] - }, - { - "type": "textbox", - "link": "introduction", - "content": [ - "1. §9介绍" - ] - }, - { - "type": "textbox", - "link": "fluid", - "content": [ - "2. §9流体模式" - ] - }, - { - "type": "textbox", - "link": "item", - "content": [ - "3. §r§9物品模式" - ] - }, - { - "type": "textbox", - "link": "energy", - "content": [ - "4. §9能源模式" - ] - }, - { - "type": "textbox", - "link": "machine", - "content": [ - "5. §9机器模式" - ] - }, - { - "type": "textbox", - "link": "proxy", - "content": [ - "6. §9代理模式" - ] - }, - { - "type": "textbox", - "link": "wireless", - "content": [ - "7. §9无线覆盖板" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "introduction", - "content": [ - "§l介绍:" - ] - }, - { - "type": "textbox", - "content": [ - "你可以将DIC放在任机器何面(包括正面)。它会自动检测机器并可视化信息。\n\n用扳手右键§4DIC§r 可以打开GUI。\n\n有五种模式: §l流体, 物品, 能源, 机器, 以及代理§r.\n\n此外,你也能直接用手和覆盖版进行交互。尝试着自己探索吧!" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "fluid", - "content": [ - "§l流体模式:" - ] - }, - { - "type": "textbox", - "content": [ - "监控并交互(填充或抽取)流体." - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107397364-8d212680-6b39-11eb-9152-b91f8f559ed6.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "item", - "content": [ - "§l物品模式:" - ] - }, - { - "type": "textbox", - "content": [ - "监控并交互(提取或存放)物品。" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107397608-c8235a00-6b39-11eb-95ad-77e4e5bc5d8b.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "energy", - "content": [ - "§l能源模式:" - ] - }, - { - "type": "textbox", - "content": [ - "监控能源情况。 (监控能源储量,输入/输出的每秒流量)" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107397946-1a647b00-6b3a-11eb-8680-52d13dd56e59.png", - "width": 190, - "height": 110 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "machine", - "content": [ - "§l机器模式:" - ] - }, - { - "type": "textbox", - "content": [ - "监控并交互(暂停或启动)机器(是否低电量,是否工作,当前配方进度,是否启动)。" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107398096-42ec7500-6b3a-11eb-8c26-b708ae183c3d.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "proxy", - "content": [ - "§l代理模式:" - ] - }, - { - "type": "textbox", - "content": [ - "应该配合§1§l中央监控器§r使用。" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107856228-c1f6eb80-6e61-11eb-8098-454ea7133ca1.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "wireless", - "content": [ - "§l无线覆盖版:" - ] - }, - { - "type": "textbox", - "content": [ - "无线覆盖版只有 §4代理模式§r, 允许§1§l中央监控器§r 远程访问改覆盖版. 通过右键点击中央监控器来绑定,通过对空气shfit右键点击来取消绑定。" - ] - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/items/zh_cn/tools/wrench.json b/src/main/resources/assets/gregtech/terminal/guide/items/zh_cn/tools/wrench.json deleted file mode 100644 index 1a48f7fc6c3..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/items/zh_cn/tools/wrench.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "metaitem": "tool.wrench", - "section": "工具", - "title": "Wrench", - "stream": [ - { - "type": "textbox", - "isCenter": false, - "content": [ - "扳扳这,扳扳那" - ] - }, - { - "type": "textbox", - "isCenter": true, - "fontSize": 5, - "content": [ - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/machines/en_us/steam/steam_boiler_coal_bronze.json b/src/main/resources/assets/gregtech/terminal/guide/machines/en_us/steam/steam_boiler_coal_bronze.json deleted file mode 100644 index ea0ae9bbbdf..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/machines/en_us/steam/steam_boiler_coal_bronze.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "machine": "steam_boiler_coal_bronze", - "section": "Steam", - "title": "Small Steam Coal Boiler", - "stream": [ - { - "type": "textbox", - "isCenter": false, - "content": [ - "Wrench this, wrench that" - ] - }, - { - "type": "textbox", - "isCenter": true, - "fontSize": 5, - "content": [ - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/advanced_fluid_drilling_plant.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/advanced_fluid_drilling_plant.json deleted file mode 100644 index 20f7045ceac..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/advanced_fluid_drilling_plant.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Electric", - "title": "Advanced Fluid Drilling Plant", - "stream": [ - { - "type": "textbox", - "content": [ - "§oExtreme is very apprioriate this time around, and you will see why.§r\n\nAt the cost of 4x the drilling Power, the §3Advanced Fluid Drilling Rig§r will be gaining §616x the output§r in Fluid.\nThe depletion of veins is also halved. This means you will get a total of §632x§r as much Oil (or whatever fluid) from a bedrock fluid vein until depletion!\n\nEven when depleted, you can still use this and be very power positive.\n\nOne single §3Advanced Fluid Drilling Rig§r should be enough to supply Power for a base up to §dLuV§r Age and possibly beyond!\n\nAs a brief §9reminder§r:\n§9-§r §aLight Oil§r can be used for §dLPG§r and §dMethane§r, to run in §3Large Gas Turbines§r.\n§9-§r §aOil§r can be used for §dDiesel§r and §dCetane-Boosted Diesel§r, to run in §3Large Combustion Engines§r.\n§9-§r §aHeavy Oil§r can be used for §dNitrobenzene§r, to run in §3Large Gas Turbines§r." - ] - } - ], - "fixed": [], - "metatileentity": "fluid_drilling_rig.hv" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/advanced_processing_array.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/advanced_processing_array.json deleted file mode 100644 index 2ffe5eb1b67..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/advanced_processing_array.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Electric", - "title": "Advanced Processing Array", - "stream": [], - "fixed": [], - "metatileentity": "advanced_processing_array" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/assembly_line.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/assembly_line.json deleted file mode 100644 index 379c8bca589..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/assembly_line.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Electric", - "title": "Assembly Line", - "stream": [ - { - "type": "textbox", - "content": [ - "§oNo. The Assembly Line is not just a big Assembler, it\u0027s a lot more than that!\nYou can also call it the Assline. Do not feel guilty.§r\n\nMaking §dLuV§r Components will require more work.\nThe §3Assembly Line§r is an entry point towards late game.\n\nThis Multiblock has a §cvariable size§r. Each §3ULV Input Bus§r accepts a different stack of items.\nYou will want to build this with a size of §d10§r to get started, or of a size of §d14§r to accept all possible recipes.\n\nRecipes require §aFluids§r, so it is a good idea to keep the §3Input Hatches§r permanently filled with §dSoldering Alloy§r, §dLubricant§r and §dStyrene-Butadienne Rubber§r.\n\nMy recommendation of Assembly Line §4automation§r goes as follows:\nHave your Interface face an §3Item P2P§r. Set two output P2Ps, into the first §3Input Bus§r, and into §3Item Pipes§r. Make your Item Pipes connect to all Input Buses including the first.\nDo not forget §dBlocking Mode§r, and you have got yourself an easy automation! This will also work flawlessly once we inevitably add ordered item inputs.\n\n\n§bLots of Lore:§r GT5\u0027s Assembly Line is a massive project to work towards, even more so than here. You are required to scan items to put their construction data into a Data Stick. That Data Stick is then required to fit into a Data Hatch which has limited slots on the Assembly Line.\n\nThe recipe could only be viewed by printing a book with the Data Stick! It was then made to display in NEI once you acquire the item.\nTecTech made a nice machine which acts as a recipe viewer for the Data Stick (this mod is so great...).\n\nFurthermore, Item and Fluid inputs are required to be ordered the same way as the recipe indicates it. This makes automation of the Assembly Line a nice challenge which can be solved using other mods, redstone, GT item pipes... you pick it.\n\nWe are planning to port some of the GT5 features, as the Assembly Line §lshould be a challenge§r for the player." - ] - } - ], - "fixed": [], - "metatileentity": "assembly_line" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/basic_fluid_drilling_rig.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/basic_fluid_drilling_rig.json deleted file mode 100644 index e504de906ab..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/basic_fluid_drilling_rig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Electric", - "title": "Basic Fluid Drilling Rig", - "stream": [ - { - "type": "textbox", - "content": [ - "§oFinally, Fluid Drilling Rigs in GTCEu!§r\n\nIt is quite an investment to get to run a §3Fluid Drilling Rig§r, but it is by far the most prominent §6source of Oil§r.\nIt pumps fluids from underneath Bedrock. Note that the fluids aren\u0027t actually there, instead they are simulated.\n\nFluid veins are stored within regions of §48x8 chunks§r. Each vein has a different fluid, but they are mostly types Oil.\nYou are not able to do prospection for fluid veins §oyet§r, this will come in the §6HV§r Age.\n\nEach vein generates with a different base yield. This is typically between §d150L§r to §d300L per second§r.\n\nWhen drained, fluid veins will slowly deplete. This will cause the fluid yield to decrease over time, until it reaches its depletion yield. At that point you should move the Rig to somewhere else.\nA §3Basic Fluid Drilling Rig§r will last for 100,000 operations (with 1 second per operation) until depletion. This is enough for §6well over 10,000§r buckets of Oil. Higher tier Rigs will massively increase the yield, while also decreasing the depletion rate.\n\n\nWhat you can find in the §2Overworld§r:\n§9Oil:§r richer in §aLight Fuel§r, the most appreciated variant.\n§9Light Oil:§r richer in §aRefinery Gas§r, usable for power.\n§9Heavy Oil:§r richer in §aHeavy Fuel§r, which has uses that are more niche.\n§9Raw Oil:§r essentially a less dense version of §aOil§r, the least appreciated.\n§9Natural Gas:§r grants §aRefinery Gas§r with no distillation required.\n§9Salt Water:§r grants §aSodium§r and §aChlorine§r, useful later.\n\n§rWhat you can find in the §cNether§r:\n§9Natural Gas:§r grants §aRefinery Gas§r but with higher yield than the Overworld vein.\n§9Lava:§r you know what this is.\n\n\nFor starters you may have to tap randomly until you find something you like. Whatever you pump can be used to refuel your Fluid Rig." - ] - } - ], - "fixed": [], - "metatileentity": "fluid_drilling_rig.mv" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/basic_ore_drilling_plant.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/basic_ore_drilling_plant.json deleted file mode 100644 index 200af4c7c9f..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/basic_ore_drilling_plant.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Electric", - "title": "Basic Ore Drilling Plant", - "stream": [ - { - "type": "textbox", - "content": [ - "A completely §doptional§r Multiblock.\n\nThe §3Larger Miner§r is ridiculously good to collect ores from veins!\n\nOres are mined as if they were §amacerated§r, but they yield §6three times§r as many §dCrushed ores§r.\n\nYou will need §aDrilling Fluid§r automation to run this.\n\nYou might also want to use a §3Quantum Tunnel§r from AE2 and §3GTEU P2P Tunnels§r to transfer the items and to power it up.\n\n\n§bLore:§r There were some interesting side effects from porting this over from Gregicality, as the multiblock originated from GregTech 5... It\u0027s not perfect, as there isn\u0027t really any advantage on upgrading this miner to the advanced versions. We were thinking of rebalancing the energy costs and yield per tier, so there may be rework for this miner at some point!" - ] - } - ], - "fixed": [], - "metatileentity": "large_miner.ev" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/central_monitor.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/central_monitor.json deleted file mode 100644 index 1c130bac657..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/central_monitor.json +++ /dev/null @@ -1,183 +0,0 @@ -{ - "metatileentity": "central_monitor", - "section": "Electric", - "title": "Central Monitor", - "stream": [ - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1029, - "count": 1 - }, - { - "id": "gregtech:machine", - "damage": 1667, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "§lContents:" - ] - }, - { - "type": "textbox", - "link": "introduction", - "content": [ - "1. §9Introduction" - ] - }, - { - "type": "textbox", - "link": "fluid", - "content": [ - "2. §9How to build it" - ] - }, - { - "type": "textbox", - "link": "item", - "content": [ - "3. §r§9How to use it" - ] - }, - { - "type": "textbox", - "link": "energy", - "content": [ - "4. §9Plugins" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107856228-c1f6eb80-6e61-11eb-8098-454ea7133ca1.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "ref": "introduction", - "content": [ - "§lIntroduction" - ] - }, - { - "type": "textbox", - "content": [ - "§c§lCentral Monitor§r is a multi machine for monitor (visualization and interaction).\n\nIt can monitor the storage and status of machines, including all §9Digital Interface Cover§r§9\u0027s §rfeatures, and extends the capabilities of machines to the screen.\n\nIn addition, there are many plugins that support more advanced features." - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "fluid", - "content": [ - "§lHow to build it?" - ] - }, - { - "type": "textbox", - "content": [ - "In order to build it, you need a §c§lCentral Monitor§r, several §c§lMonitor Screen§r, several §c§lSteel Metal Casing§r, and at least one §c§lEnergy Input Hatch§r.\n\nYou can build the screen from 3×2 to 14×9 (width × height). The default build height is 3, and you can adjust the screen height in the GUI before the structure formed.\n\n§lEnergy Cost:§r 50 EU/s for each screen." - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "item", - "content": [ - "§lHow to use it?" - ] - }, - { - "type": "textbox", - "content": [ - "1. The back of §c§lCentral Monitor §rcan be connected to cables or wires, which can be connected to the energy net to monitor all the machines being proxied (A §9Digital Interface Cover§r set with proxy mode is placed at the connecting side between the machine and the wire. ). Besides, a §9Wireless Cover §rthat is boung to the central monitor can also be used, avoiding using cables.\n\n2. Right click the §c§lCentral Monitor §ror screwdriver right click the §c§lMonitor§r to open the GUI for settings." - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "energy", - "content": [ - "§lPlugins" - ] - }, - { - "type": "textbox", - "content": [ - "Put the plugin into the plugin slot for use. For specific features, please refer to their guide pages. The following are the supported plugins.\n\n§4§lNote§r§4: §rsome plugins need to work with the proxy mode in the §c§lCentral Monitor§r, and the proxy mode is only used for plugins." - ] - }, - { - "type": "card", - "fill": -3745585, - "width": 170, - "height": 60, - "isShadow": true - }, - { - "type": "textbox", - "content": [ - "\n\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - } - ], - "fixed": [ - { - "type": "slots", - "x": 48, - "y": 930, - "width": 100, - "height": 18, - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 780, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 781, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 782, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 783, - "count": 1 - } - ] - } - ] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/distillation_tower.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/distillation_tower.json deleted file mode 100644 index cea752f1798..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/distillation_tower.json +++ /dev/null @@ -1,106 +0,0 @@ -{ - "section": "Electric", - "title": "Distillation Tower", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Distillation Tower§r is the Variable Layer Multiblock form of the Single Block Distilleries. While the Distillery can only have one output from an input fluid, the Distillation Tower can get all possible outputs from the input fluid.\n\nHowever, the Distillation Tower has a few additional limitations. Most importantly, The number of fluids that the Distillation Tower can output is equal to the number of layers of the of the Multiblock. Additionally, the Distillation Tower cannot be formed with Multifluid output hatches, and the fluid input hatch must be located on the bottom layer of the structure." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1005, - "count": 1 - } - ] - } - ], - "fixed": [ - { - "type": "card", - "x": 10, - "y": 234, - "width": 177, - "height": 90, - "fill": -3745585, - "isShadow": true - }, - { - "type": "slots", - "x": 3, - "y": 269, - "width": 52, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1181, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": -1, - "y": 242, - "width": 61, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1196, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": -5, - "y": 296, - "width": 67, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1166, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 50, - "y": 241, - "width": 100, - "height": 20, - "content": [ - "Fluid Output Hatch. Exactly 1 per layer" - ] - }, - { - "type": "textbox", - "x": 49, - "y": 267, - "width": 100, - "height": 20, - "content": [ - "Fluid Input Hatch. Exactly 1" - ] - }, - { - "type": "textbox", - "x": 46, - "y": 294, - "width": 100, - "height": 20, - "content": [ - "Item Output bus. Optionally 1" - ] - } - ], - "metatileentity": "distillation_tower" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/electric_blast_furnace.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/electric_blast_furnace.json deleted file mode 100644 index 483e092d20c..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/electric_blast_furnace.json +++ /dev/null @@ -1,243 +0,0 @@ -{ - "section": "Electric", - "title": "Electric Blast Furnace", - "stream": [ - { - "type": "textbox", - "isCenter": false, - "content": [ - "The §6Electric Blast Furnace§r is one of the main Multiblock Structures in Gregtech, and the main goal of earlygame progression." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1001, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "Like all Gregtech Multiblocks, this structure is modular, and can be made up of many different combinations of Multiblock Parts." - ] - }, - { - "type": "card", - "fill": -3745585, - "width": 180, - "height": 190, - "isShadow": true - }, - { - "type": "textbox", - "content": [ - "The §6Electric Blast Furnace§r can form with any combination of blocks above. For example, if the desired recipe does not deal with fluids, neither of the fluid related hatches are required.\n\nOverclocking the Blast Furnace is as simple as ensuring the the Multiblock has 2 Energy Inputs, so 4 Amps of energy can be received, which will ensure that the mutliblock runs at the tier above the energy inputs.\n\nFor the Blast Furnace specifically, the Muffler Hatch needs to be placed at the center of the top layer, and must face upwards." - ] - }, - { - "type": "textbox", - "content": [ - "The §3Electric Blast Furnace§r, §3Pyrolyse Oven, §3Multi Smelter§r, and §3Cracking Unit§r all require heating Coils. But what are the advantages of using higher tier coils?\n\nThe latter three are quite straightforward. Higher tier coils reduce the §eprocessing time§r of the Pyrolyse Oven, reduce the §9energy usage§r of the Cracking Unit, and increase the §anumber of parallel smelts§r and reduce the §9energy usage§r of the Multi Smelter.\n\nFor the EBF, things get slightly more complicated. The EBF smelts items at a certain §dtemperature§r. This is mainly determined by the tier of heating coil used - §r§6Cupronickel§r is §d1800K§r, §bKanthal§r is §d2700K§r, etc. Additionally, starting from §6HV§r, each tier of energy adds §d100K§r to the temperature.\n\nEach EBF recipe has a certain base temperature, for example, §bAluminium§r is smelted at §d1700K§r. If the EBF temperature is not high enough, the recipe can\u0027t be done. If the EBF temperature is high enough, 2 different bonuses are applied:\n§9-§r For every §d900K§r above the recipe temperature, the amount of energy required is multiplied by §a0.95x§r, which stacks.\n§9-§r For every §d1800K§r above the recipe temperature, one additional overclock will be §6100% efficient§r; in other words, it will §5quadruple the speed§r, instead of doubling it." - ] - } - ], - "fixed": [ - { - "type": "slots", - "x": 12, - "y": 159, - "width": 35, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1001, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 11, - "y": 182, - "width": 36, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1151, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 12, - "y": 206, - "width": 34, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1166, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 13, - "y": 228, - "width": 32, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1181, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 13, - "y": 251, - "width": 32, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1196, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 10, - "y": 273, - "width": 38, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1654, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 10, - "y": 296, - "width": 38, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1657, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 9, - "y": 319, - "width": 40, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1211, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 52, - "y": 159, - "width": 100, - "height": 20, - "content": [ - "The Controller block" - ] - }, - { - "type": "textbox", - "x": 52, - "y": 182, - "width": 100, - "height": 20, - "content": [ - "Item Input. Minimum 1" - ] - }, - { - "type": "textbox", - "x": 51, - "y": 206, - "width": 108, - "height": 10, - "content": [ - "Item Output. Minimum 1" - ] - }, - { - "type": "textbox", - "x": 51, - "y": 230, - "width": 125, - "height": 10, - "content": [ - "Fluid Input. No Minimum" - ] - }, - { - "type": "textbox", - "x": 49, - "y": 251, - "width": 131, - "height": 10, - "content": [ - "Fluid Output. No Minimum" - ] - }, - { - "type": "textbox", - "x": 48, - "y": 271, - "width": 135, - "height": 20, - "content": [ - "Maintence Hatch. Required based on Config. Exactly 1" - ] - }, - { - "type": "textbox", - "x": 48, - "y": 295, - "width": 100, - "height": 20, - "content": [ - "Muffler Hatch. Exactly 1" - ] - }, - { - "type": "textbox", - "x": 47, - "y": 318, - "width": 100, - "height": 20, - "content": [ - "Energy Input. Minimum 1" - ] - } - ], - "metatileentity": "electric_blast_furnace" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/fusion_reactor_1.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/fusion_reactor_1.json deleted file mode 100644 index 049f379b986..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/fusion_reactor_1.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Electric", - "title": "Fusion Reactor MK 1", - "stream": [], - "fixed": [], - "metatileentity": "fusion_reactor.luv" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/fusion_reactor_2.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/fusion_reactor_2.json deleted file mode 100644 index fbd7234eb99..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/fusion_reactor_2.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Electric", - "title": "Fusion Reactor MK 2", - "stream": [], - "fixed": [], - "metatileentity": "fusion_reactor.zpm" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/fusion_reactor_3.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/fusion_reactor_3.json deleted file mode 100644 index 6f896cd695f..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/fusion_reactor_3.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Electric", - "title": "Fusion Reactor MK 3", - "stream": [], - "fixed": [], - "metatileentity": "fusion_reactor.uv" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/implosion_compressor.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/implosion_compressor.json deleted file mode 100644 index bb6d263b219..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/implosion_compressor.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "section": "Electric", - "title": "Implosion Compressor", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Implosion Compressor§r is a Multiblock that turns gem dusts back into gems, as well as processes a few other recipes." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1003, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "Recipes in the Implosion Compressor use varying explosives with different efficiencies, so make sure to check recipes in JEI." - ] - } - ], - "fixed": [ - { - "type": "card", - "x": 11, - "y": 138, - "width": 179, - "height": 112, - "fill": -3745585, - "isShadow": true - }, - { - "type": "slots", - "x": 6, - "y": 147, - "width": 63, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1151, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 6, - "y": 174, - "width": 63, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1166, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 7, - "y": 203, - "width": 63, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1657, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 9, - "y": 229, - "width": 58, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1654, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 56, - "y": 146, - "width": 100, - "height": 20, - "content": [ - "Item Input Bus. Minimum 1" - ] - }, - { - "type": "textbox", - "x": 52, - "y": 172, - "width": 100, - "height": 20, - "content": [ - "Item Output Bus. Minimum 1" - ] - }, - { - "type": "textbox", - "x": 53, - "y": 203, - "width": 100, - "height": 20, - "content": [ - "Muffler Hatch. Exactly 1" - ] - }, - { - "type": "textbox", - "x": 55, - "y": 227, - "width": 100, - "height": 20, - "content": [ - "Maintenance Hatch. Exactly 1" - ] - } - ], - "metatileentity": "implosion_compressor" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/large_chemical_reactor.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/large_chemical_reactor.json deleted file mode 100644 index 257f082cb09..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/large_chemical_reactor.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Electric", - "title": "Large Chemical Reactor", - "stream": [ - { - "type": "textbox", - "content": [ - "The §3Large Chemical Reactor (LCR)§r is a multiblock §3Chemical Reactor§r with more input/output slots, which can handle more recipes thanks to Teflon.\n\nThe §3LCR§r can perform some exclusive reactions which allow you to combine multiple normal §3Chemical Reactor§r steps into a §6single step§r. Examples below:\n§9-§r §aNitrogen Dioxide§r (for Nitric Acid and Dinitrogen Tetroxide)\n§9-§r §aSulfuric Acid§r\n§9-§r §aPhenol§r\n§9-§r §aEpichlorohydrin§r (you need it for Epoxy§r!)\n§9-§r §aEpoxy§r\n\n\nThere are also §3LCR§r exclusive recipes. For example §aRadon§r requires it.\n\nAll §dOverclocks§r in the §3LCR§r are §6100% efficient§r; each overclock will §5quadruple the speed§r, as opposed to doubling it.\n\n\n§9Tip:§r Given the amount of LCRs you may end up using, I would recommend using the §dwallsharing§r to its full potential.\nYou may share one 2A (standard) §3Energy Hatch§r with 2 LCRs.\nYou may share §3Input/Output Hatches§r, but be careful to not make them run the wrong recipes.\nKeep in mind Maintenance is not sharable." - ] - } - ], - "fixed": [], - "metatileentity": "large_chemical_reactor" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/multi_smelter.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/multi_smelter.json deleted file mode 100644 index f2e74134c6e..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/multi_smelter.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Electric", - "title": "Multi Smelter", - "stream": [ - { - "type": "textbox", - "content": [ - "§oThe §3§oMulti Smelter§r§o might be the §6§omost powerful Furnace§r§o in modded Minecraft.§r\n\nAt its lowest power (Cupronickel coils and LV Voltage), it smelts 32 items in just 12 seconds - equivalent to §926.7 Furnaces§r, or 3.3 Steam Ovens!\n\nNot to mention, standard §aoverclocks§r are in effect.\nAnd more importantly higher tier §3Coils§r increase the amount of items it can smelt in §dparallel§r! Higher tier §3Coils§r also provide better energy and duration discounts for recipes." - ] - } - ], - "fixed": [], - "metatileentity": "multi_furnace" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/oil_cracking_unit.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/oil_cracking_unit.json deleted file mode 100644 index 0526093adf4..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/oil_cracking_unit.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Electric", - "title": "Oil Cracking Unit", - "stream": [ - { - "type": "textbox", - "content": [ - "§oLet\u0027s get cracking, shall we?§r\n\nThe §3Oil Cracking Unit§r is a multiblock meant to make cracked fluids. It has all the recipes of §3Chemical Reactor§r Cracking, but it is §6lossless§r.\n\nThis multiblock is §doptional§r, but it saves a lot of Fuel in the long term!\n\nHigher Coil tiers provide small energy discount, not too important." - ] - } - ], - "fixed": [], - "metatileentity": "cracker" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/processing_array.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/processing_array.json deleted file mode 100644 index 2ab24c291d6..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/processing_array.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Electric", - "title": "Processing Array", - "stream": [ - { - "type": "textbox", - "content": [ - "§oThe Processing Array does nothing... except that it does a lot!§r\n\nThe §3Processing Array§r is a power §6automation tool§r.\nIt combines several single block machines into one single multiblock.\nPlace up to §d16§r Machines into the §3Machine Access Interface§r.\n\nThe §3PA§r will now §asimulate§r all the machines you put inside, as if they were running at the same time.\nThis means recipes can now be performed up to §d16§r at a time, this is called §4parallel§r.\n\nPower cost is based on the current recipe being run, times the number of §4parallel§r being performed.\nAs an §9example§r, §316 LV Distilleries§r will require an §3HV Energy Hatch§r in order to run effectively.\n\n\n§cWhere or why is the Processing Array useful?§r\n§9-§r §4Parallelization is superior§r to oveclocking. Use it for passive setups such as Ore Processing or Oil Distilling.\n§9-§r §6Distinct buses§r: a §3PA§r can accept up to 10 §3Input Buses§r. Use it for your pattern automation with §3Extruder§r, §3Engraver§r, and many other.\n\n\n§9Note:§r With §2Gregicality Multiblocks§r installed, the §3PA§r can be mostly replaced with all the specialized Multiblocks instead. That\u0027s for you if you hate 3x3 blue cubes, or if you hate crafting numerous low tier machines.\n\n\n§bLore:§r In GregTech 5, the Data Orb was used to Matter Replicator to store data of the material you wanted to replicate. There is no replication here, the Orb is just a crafting component." - ] - } - ], - "fixed": [], - "metatileentity": "processing_array" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/pyrolyse_oven.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/pyrolyse_oven.json deleted file mode 100644 index bb143f76d3c..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/pyrolyse_oven.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Electric", - "title": "Pyrolyse Oven", - "stream": [ - { - "type": "textbox", - "content": [ - "§oThe Pyrolyse Oven processes organic products by thermal decomposition in an inert environment.§r\n\nThe §3Pyrolyse Oven§r is an electric equivalent of the §3Coke Oven§r. It can produce §9Coal Coke§r and §9Charcoal§r with a §9Creosote§r byproduct just as before, but also has additional §6Organic Byproducts§r. The most beneficial of these being §aWood Tar§r.\nAnother product is §aBiomass§r, which is more pertinent for progression §oright now§r.\n\nThose byproducts can be Distilled for an array of organic resources, with different byproducts giving different ratios of different chemicals.\nYou will need to read the §9Distillation§r Quest to hopefully understand the full scale..\n\nThere are recipes that can accept §bNitrogen§r to double the speed.\n\nThe §3Cupronickel Coils§r are more than enough to get started, but you will want to upgrade eventually. This is because the §3Cupronickel Coils§r actually have a processing speed malus, making all recipes slower. This malus turns into a processing speed bonus as the coil tier used increases.\n\n\n§9§lNote:§r§l The Plant path is one path towards §9§lEthylene§r§l. The other path involves Oil.§r\nThe Pyrolyse Oven remains §doptional§r. But it is great to have either for Power, or for the various Byproducts.\n\n\n§bLore:§r In GT5u, the structure for the Pyrolyse Oven is a giant box with only 9 coils inside. Players usually spend several minutes debugging what is wrong due to the lack of JEI preview." - ] - } - ], - "fixed": [], - "metatileentity": "pyrolyse_oven" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/vacuum_freezer.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/vacuum_freezer.json deleted file mode 100644 index 01c1f2dc76f..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/electric/vacuum_freezer.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "section": "Electric", - "title": "Vacuum Freezer", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Vacuum Freezer§r is one of the more important Multiblocks, as it allows you to get actual ingots from super heated Blast Furnace outputs." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1002, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "Any ingots made in the §6Electric Blast Furnace§r that have a blast temperature of greater than §91750§r K will not generate regular ingots, but instead will generate Hot Ingots. These Ingots will damage the player when held, and are required to be cooled down in the Vacuum Freezer." - ] - } - ], - "fixed": [ - { - "type": "card", - "x": 6, - "y": 189, - "width": 178, - "height": 105, - "fill": -3745585, - "isShadow": true - }, - { - "type": "slots", - "x": 7, - "y": 198, - "width": 56, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1151, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 14, - "y": 224, - "width": 43, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1166, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 54, - "y": 199, - "width": 100, - "height": 20, - "content": [ - "Item Input bus. Maximum 1" - ] - }, - { - "type": "textbox", - "x": 53, - "y": 223, - "width": 100, - "height": 20, - "content": [ - "Item Output Bus. Maximum 1" - ] - }, - { - "type": "slots", - "x": 8, - "y": 249, - "width": 55, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1181, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 1, - "y": 274, - "width": 68, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1196, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 52, - "y": 248, - "width": 100, - "height": 20, - "content": [ - "Fluid Input Hatch. Optionally 1" - ] - }, - { - "type": "textbox", - "x": 51, - "y": 273, - "width": 100, - "height": 20, - "content": [ - "Fluid Output Hatch. Optionally 1" - ] - } - ], - "metatileentity": "vacuum_freezer" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/extreme_combustion_engine.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/extreme_combustion_engine.json deleted file mode 100644 index b61c47fa6a7..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/extreme_combustion_engine.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Generator", - "title": "Extreme Combustion Engine", - "stream": [ - { - "type": "textbox", - "content": [ - "§oThe Ultimate Combustion fuel Generator!§r\n\nTo run the §3Extreme Combustion Engine§r, you will most likely want to boost it (§oelse why would you bother...§r).\nYou will want a §34A IV Dynamo Hatch§r as the output, and one §3Vacuum Freezer§r for §aLiquid Oxygen§r.\n\nYou can now harness the equivalent of 1 §dLuV§r Amp, while burning fuel at §6200% efficiency§r!\n\nDon\u0027t forge to keep it supplied with a small amount of §aLubricant§r.\n\nThe §3ECE§r is also void-free, unlike Large Turbines. Any energy that cannot be output will momentarily pause the multiblock.\n\n\n§bLore:§r The ECE comes from GT:NH. However... the story is not so great. The stats on the tooltip looked similar to this one, so far so good.\nHowever if you made calculations, you ended up realizing you needed to run around 16 whole HV Vacuum Freezers to keep up with Liquid Oxygen...\nThe one and only fuel it would accept is High Octane Gasoline, which was stated to be burned at 300% efficiency when boosted, but it was a lie! The efficiency remained 100%!\nThe GT:NH team recently decided to rework the ECE among other power options, phew!" - ] - } - ], - "fixed": [], - "metatileentity": "extreme_combustion_engine" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_bronze_boiler.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_bronze_boiler.json deleted file mode 100644 index ee94e350d65..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_bronze_boiler.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Generator", - "title": "Large Bronze Boiler", - "stream": [ - { - "type": "textbox", - "content": [ - "This is an §6optional§r power generating multiblock, depending on which power options you chose.\n\n\nThe §3Large Boilers§r ultimately are §othe§r option for large scale Steam production. They will run off solid and liquid fuels.\n§cImportant:§r This Boiler can also §cexplode§r similarly to the regular Boilers!\n§cWater supply is crucial§r. But simply upgrading the §3Output Hatch§r on your §3Primitive Pump§r should be enough.\n\n\nOnce fully heated up, the §3LBB§r produces 800 Steam per tick, which is §d400EU/t§r after conversion, or 12.5 Basic Steam Turbines! This (relatively!) immense power comes at the cost of §la lot§r of burnable fuel.\n§5§lBut§r the GUI can let you §9throttle§r the Boiler, down to 25% power for 200 Steam per tick. That is §d100EU/t§r, or slightly above 3 Basic Steam Turbines." - ] - } - ], - "fixed": [], - "metatileentity": "large_boiler.bronze" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_combustion_engine.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_combustion_engine.json deleted file mode 100644 index 1bea232463c..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_combustion_engine.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Generator", - "title": "Large Combustion Engine", - "stream": [ - { - "type": "textbox", - "content": [ - "The §3Large Combustion Engine§r is a multiblock able to burn §dCombustion Fuels§r for even more Power Generation!\n\nIt\u0027s default production outputs 2048 EU/t, which is simply the same as 4 §3Turbo Combustion Generators§r.\n\nWhere it shines is the ability to §6boost§r it with §aOxygen§r.\nThis will double the fuel consumption, but §9triple the power generation§r for 6144 EU/t!\nThis results in §6150% Fuel efficiency§r.\n\nIt also requires a small amount of §aLubricant§r, nothing too crazy.\n\nThe §3LCE§r is also void-free, unlike Large Turbines. Any energy that cannot be output will momentarily pause the multiblock.\n\n\n§9Note:§r To harness the 6144 EU/t Power output, you will need a §34A EV Dynamo Hatch§r, or an §3IV Dynamo Hatch§r." - ] - } - ], - "fixed": [], - "metatileentity": "large_combustion_engine" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_gas_turbine.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_gas_turbine.json deleted file mode 100644 index f9cca9cd4c9..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_gas_turbine.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Generator", - "title": "Large Gas Turbine", - "stream": [ - { - "type": "textbox", - "content": [ - "The §3Large Gas Turbine§r may not be so impressive in the §5EV§r Age, but it has the ability to scale really well, to §9better production§r than the base 4096 EU/t, and §9greater efficiency§r.\n\nEach Large Turbine will require a §aTurbine Rotor§r and a §3Rotor Holder§r. More on the Turbine mechanics in the §lnext§r Quest.\n\n§9Note:§r To harness the Power output when using a Rotor having more than 100% Power stats, you will need a §34A EV Dynamo Hatch§r or an §3IV Dynamo Hatch§r.\nTurbines §cvoid§r energy that they can not output." - ] - } - ], - "fixed": [], - "metatileentity": "large_turbine.gas" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_plasma_turbine.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_plasma_turbine.json deleted file mode 100644 index 7ae7b70399d..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_plasma_turbine.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "section": "Generator", - "title": "Large Plasma Turbine", - "stream": [], - "fixed": [], - "metatileentity": "large_turbine.plasma" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_steam_turbine.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_steam_turbine.json deleted file mode 100644 index c4b7cb22ea6..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_steam_turbine.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Generator", - "title": "Large Steam Turbine", - "stream": [ - { - "type": "textbox", - "content": [ - "§oIf you\u0027re still running off Steam, here is a solution for you!§r\n\nThe §3Large Steam Turbine§r is a multiblock Steam Turbine for §6HV§r power. It is a quite expensive multiblock to generate 1024 EU/t, but it also the ability to scale to §9higher Power Production and higher Effiency§r.\n\nThe Turbine will output §dDistilled Water§r given an §3Output Hatch§r, so you can loop it back to your §3Large Boilers§r.\nNot completely recommend, as your Boilers will end up exploding if the system fails...\n\nEach Large Turbine will require a §aTurbine Rotor§r and a §3Rotor Holder§r. More on the Turbine mechanics in the §lnext§r Quest.\n\n§9Note:§r Turbines §cvoid§r energy that they can not output. If you plan on using this with HV power, use a Rotor with close to 100% Power stat." - ] - } - ], - "fixed": [], - "metatileentity": "large_turbine.steam" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_steel_boiler.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_steel_boiler.json deleted file mode 100644 index 59da1510221..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/generator/large_steel_boiler.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Generator", - "title": "Large Steel Boiler", - "stream": [ - { - "type": "textbox", - "content": [ - "If you\u0027re still running off the §3Large Bronze Boiler§r, you may want to upgrade to the §3Large Steel Boiler§r.\n\nIt is slightly more efficient than the §3LBB§r, and produces §d900 EU/t worth of Steam§r." - ] - } - ], - "fixed": [], - "metatileentity": "large_boiler.steel" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/advanced_maintenance.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/advanced_maintenance.json deleted file mode 100644 index cc2a252d8d8..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/advanced_maintenance.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Hatches", - "title": "Advanced Maintenance", - "stream": [ - { - "type": "textbox", - "content": [ - "You now have access to two §3new Maintenance Hatches§r. Both start with §6no Maintenance required§r.\n\nThe §3Automatic Maintenance Hatch§r is pretty simple, it eliminates the need for Maintenance, §6forever§r.\n\nThe §3Configurable Maintenance Hatch§r is more interesting. You can configure it to cut off §a10% duration§r on recipes, at the cost of making Maintenance happen three times as fast. That is §d16 real hours§r of activity.\n§9Reminder:§r You can put Tape in the maintenance Hatch to automatically fix problems.\n\n\n§bLore:§r The Automatic Maintenance Hatch texture and mechanic comes from TecTech, an addon mod originally made for GregTech: New Horizons. I will be honest with you: that mod is excessively cool!\nMore TecTech references coming up, if you stick with us with the late game!" - ] - } - ], - "fixed": [], - "metatileentity": "maintenance_hatch_full_auto" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/energy_hatch.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/energy_hatch.json deleted file mode 100644 index 49c10bc70bd..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/energy_hatch.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Hatches", - "title": "Energy Hatch", - "stream": [ - { - "type": "textbox", - "content": [ - "§oTo power Multiblocks with energy, you need Energy Hatches.§r\n\nMultiblocks do not look at Voltage of recipes, instead they simply check if they have the Power requirement.\nFor example, The EBF needs at least §4120EU/t§r power input to run its recipes. It is achieved with §3two LV Energy Hatches§r. Each one takes 2 Amps of LV, so that\u0027s 4 Amps of LV for 128EU/t maximum power.\n\n\n§9Note:§r Be wary of Cable §closses§r bringing the actual power input below the recipe requirement! I §lhighly§r recommend placing your §3Battery Buffer§r next to the §3Energy Hatches§r for the minimum cable length." - ] - } - ], - "fixed": [], - "metatileentity": "energy_hatch.input.lv" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/maintenance_hatch.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/maintenance_hatch.json deleted file mode 100644 index a6db7c6fb68..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/maintenance_hatch.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Hatches", - "title": "Maintenance Hatch", - "stream": [ - { - "type": "textbox", - "content": [ - "§oI know what you\u0027re thinking! Don\u0027t think! I mean... Maintenance in GregTech is not as bad as you think, and looking at multiblocks with this hatch makes me feel happy.§r\n\nMost Multiblocks require a §3Maintenance Hatch§r. You will need to do Maintenance for the Multiblock to begin operating.\nThis is done by having a §9Wrench§r, a §9Screwdriver§r, a §9Soft Mallet§r, a §9Hammer§r, a §9Wire Cutter§r, and a §9Crowbar§r in your inventory, opening the Maintenance Hatch and §4clicking the center spot once§r. §cNo need to move tools individually§r.\nAlternatively you can fix problems by placing a §9Tape§r in the Maintenance Hatch, but I would love to tell you that\u0027s unethical.\n\nMaintenance problems may occur after §d48 real hours of activity§r. Needless to say they are very rare. Each problem increases the recipe durations by 10%. Fixing the problems is done the same way as above.\n\n\nAt §6HV§r age, you will unlock other Maintenance Hatches that do not enforce fixing the problems manually.\n\n\n§bLore:§r Maintenance dates back to GregTech 3 for Minecraft 1.5.2. That\u0027s a long time ago!\nMaintenance problems increased power usage instead of duration. And that caused all sorts of \"happy\" issues. Ah, fun times!" - ] - } - ], - "fixed": [], - "metatileentity": "maintenance_hatch" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/muffler_hatch.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/muffler_hatch.json deleted file mode 100644 index e11eef2deb6..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/muffler_hatch.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Hatches", - "title": "Muffler Hatch", - "stream": [ - { - "type": "textbox", - "content": [ - "The §3Electric Blast Furnace§r requires a §3Muffler Hatch§r to run. This hatch must be §cunobstructed§r so it can output its beautiful smoke particles.\n\nWhen a recipe is performed, there is a small chance for the §3Muffler Hatch§r to give bonus items, typically tiny Dusts of Ash.\n\n§9Note:§r Do not try to automate the extraction of items from the §3Muffler Hatch§r, it is not intended. It voids excess when full, so do not worry about it stopping machines from running.\n\n\n§bLore:§r In GregTech 5, polluting multiblocks had Muffler Hatches. The higher tier the hatch, the lower the Pollution.\nPollution had interesting effects such as turning grass and dirt into sand.\nMuffler Hatches in GTCEu are more about the look (can you deny that the particles look good!?) and small rewards, rather than punishing game mechanics." - ] - } - ], - "fixed": [], - "metatileentity": "muffler_hatch.lv" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/multiblock_input_output.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/multiblock_input_output.json deleted file mode 100644 index 3a6532b2d87..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/hatches/multiblock_input_output.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "section": "Hatches", - "title": "Multiblock Input/Output", - "stream": [ - { - "type": "textbox", - "content": [ - "§3Busses§r are needed to for Multiblocks in order to insert recipe inputs and retrieve recipe outputs.\nHigher tier §3Busses§r have more slots for items\n\nFor fluids, you will need §3Hatches§r.\n\nFor fluids, there are also special §3Multi-Fluid Hatches§r, which can handle multiple fluids at the same time. These come in 4x and 9x versions." - ] - } - ], - "fixed": [], - "metatileentity": "item_bus.import.lv" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/coke_oven.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/coke_oven.json deleted file mode 100644 index 2b300585370..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/coke_oven.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "section": "Primitive", - "title": "Coke Oven", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Coke Oven§r is most likely one of the first Multiblocks that you will make. It is the source of early game §1Charcoal§r, a nice fuel for making §1Steel§r initially." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1017, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "Unlike other Multiblocks,this structure has a limited number of multiblock parts that can be added." - ] - } - ], - "fixed": [ - { - "type": "card", - "x": 6, - "y": 137, - "width": 182, - "height": 61, - "fill": -3745585, - "isShadow": true - }, - { - "type": "slots", - "x": 3, - "y": 140, - "width": 52, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1017, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": -3, - "y": 163, - "width": 65, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1018, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 46, - "y": 160, - "width": 100, - "height": 20, - "content": [ - "The Coke Oven Hatch. Maximum: 5" - ] - }, - { - "type": "textbox", - "x": 47, - "y": 139, - "width": 100, - "height": 20, - "content": [ - "The Controller Block" - ] - } - ], - "metatileentity": "coke_oven" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/multiblock_steel_tank.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/multiblock_steel_tank.json deleted file mode 100644 index b9b4d9b8bc6..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/multiblock_steel_tank.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "section": "Primitive", - "title": "Steel Multiblock Tank", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Steel Multiblock Tank§r is another early game multiblock for storing fluids. However, unlike the Wooden version, this structure can store gases and hot fluids." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1599, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "Similar to the Wooden version, this structure has specific Multiblock Parts used for automating fluid input and output into the structure." - ] - } - ], - "fixed": [ - { - "type": "slots", - "x": 2, - "y": 149, - "width": 52, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1598, - "count": 1 - } - ] - }, - { - "type": "card", - "x": 8, - "y": 146, - "width": 178, - "height": 32, - "fill": -3745585, - "isShadow": true - }, - { - "type": "textbox", - "x": 47, - "y": 149, - "width": 137, - "height": 20, - "content": [ - "Tank Valve for automating structure. Maximum: 2" - ] - } - ], - "metatileentity": "tank.steel" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/multiblock_wooden_tank.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/multiblock_wooden_tank.json deleted file mode 100644 index 4fb6f84f526..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/multiblock_wooden_tank.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "section": "Primitive", - "title": "Wooden Multiblock Tank", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Wooden Multiblock Tank§r is an early game solution for storing liquids. Unfortunately, it cannot store much, as it does not handle gases or hot liquids." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1597, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "This Multiblock has one possible Multiblock Part, which is used for automatically filling and extracting fluids from the structure." - ] - } - ], - "fixed": [ - { - "type": "slots", - "x": -12, - "y": 176, - "width": 59, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1596, - "count": 1 - } - ] - }, - { - "type": "card", - "x": 7, - "y": 170, - "width": 178, - "height": 35, - "fill": -3745585, - "isShadow": true - }, - { - "type": "textbox", - "x": 35, - "y": 176, - "width": 137, - "height": 20, - "content": [ - "Tank Valve for automating structure. Maximum: 2" - ] - } - ], - "metatileentity": "tank.wood" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/primitive_blast_furnace.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/primitive_blast_furnace.json deleted file mode 100644 index 34c471d6958..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/primitive_blast_furnace.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "section": "Primitive", - "title": "Primitive Blast Furnace", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Primitive Blast Furnace§r is the main multiblock of the Steam Age. It is used for making the first §1Steel§r, which is the main gateway to the §2LV§r age." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1000, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "Unlike other §3Gregtech§r Multiblocks, there are no multiblock parts that can be used in this structure. It is only composed of the controller and the Primitive Bricks." - ] - } - ], - "fixed": [], - "metatileentity": "primitive_blast_furnace.bronze" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/primitive_water_pump.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/primitive_water_pump.json deleted file mode 100644 index 59377b8d57f..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/primitive_water_pump.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "section": "Primitive", - "title": "Primitive Water Pump", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Primitive Water Pump§r is a Multiblock used for gathering water in the early game. The amount of water gathered depends on the biome that the Multiblock is constructed in. Detailed information on the rates in available on the §3JEI§r information page for the Multiblock." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1648, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "The §6Primitive Water Pump§r has only one possible Multiblock part, though it is limited in what tier the part can be." - ] - } - ], - "fixed": [ - { - "type": "slots", - "x": -23, - "y": 189, - "width": 100, - "height": 18, - "item_list": [] - }, - { - "type": "slots", - "x": 61, - "y": 182, - "width": 67, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1649, - "count": 1 - }, - { - "id": "gregtech:machine", - "damage": 1195, - "count": 1 - }, - { - "id": "gregtech:machine", - "damage": 1196, - "count": 1 - } - ] - }, - { - "type": "card", - "x": 9, - "y": 174, - "width": 180, - "height": 76, - "fill": -3745585, - "isShadow": true - }, - { - "type": "textbox", - "x": 13, - "y": 203, - "width": 168, - "height": 40, - "content": [ - "The §6Primitive Water Pump§r is limited to §rthe specific output hatch, §ra §2ULV§r output hatch, or a §2LV§r output hatch" - ] - } - ], - "metatileentity": "primitive_water_pump" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/steam_grinder.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/steam_grinder.json deleted file mode 100644 index 4a3ad379efd..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/steam_grinder.json +++ /dev/null @@ -1,112 +0,0 @@ -{ - "section": "Primitive", - "title": "Steam Grinder", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Steam Grinder§r is an early game multiblock for performing macerator recipes. It can perform up to §58§r recipes in parallel, and has duration of §51.5§r times the normal macerator recipe duration.\n\nHowever, only the first output from the recipe will be output. This means that no byproducts will be recieved from any ores grinded down." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1025, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "Unlike other Multiblocks, this structure has specialized hatches for handling steam that must be used." - ] - } - ], - "fixed": [ - { - "type": "card", - "x": 4, - "y": 217, - "width": 182, - "height": 81, - "fill": -3745585, - "isShadow": true - }, - { - "type": "slots", - "x": 11, - "y": 224, - "width": 50, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1651, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 5, - "y": 247, - "width": 62, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1652, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 10, - "y": 272, - "width": 52, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1653, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 53, - "y": 224, - "width": 117, - "height": 20, - "content": [ - "Specialized Output bus for Steam Multiblocks" - ] - }, - { - "type": "textbox", - "x": 53, - "y": 250, - "width": 120, - "height": 20, - "content": [ - "Specialized Input bus for Steam Multiblocks" - ] - }, - { - "type": "textbox", - "x": 53, - "y": 273, - "width": 120, - "height": 20, - "content": [ - "Specialized Input Hatch for Steam Multiblocks" - ] - } - ], - "metatileentity": "steam_grinder" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/steam_oven.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/steam_oven.json deleted file mode 100644 index b45a1bf6604..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/en_us/primitive/steam_oven.json +++ /dev/null @@ -1,112 +0,0 @@ -{ - "section": "Primitive", - "title": "Steam Oven", - "stream": [ - { - "type": "textbox", - "content": [ - "The §6Steam Oven§r is an early game multiblock for performing furnace recipes. It can perform up to §58§r recipes in parallel, and has duration of §51.5§r times the normal furnace recipe duration.\n\nThis should not really matter, but only the first output from the recipe will be obtained. Although if someone is adding a weird furnace recipe, that is their fault." - ] - }, - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1024, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "Unlike other Multiblocks, this structure has specialized hatches for handling steam that must be used." - ] - } - ], - "fixed": [ - { - "type": "card", - "x": 4, - "y": 217, - "width": 182, - "height": 81, - "fill": -3745585, - "isShadow": true - }, - { - "type": "slots", - "x": 11, - "y": 224, - "width": 50, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1651, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 5, - "y": 247, - "width": 62, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1652, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 10, - "y": 272, - "width": 52, - "height": 18, - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1653, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 53, - "y": 224, - "width": 117, - "height": 20, - "content": [ - "Specialized Output bus for Steam Multiblocks" - ] - }, - { - "type": "textbox", - "x": 53, - "y": 250, - "width": 120, - "height": 20, - "content": [ - "Specialized Input bus for Steam Multiblocks" - ] - }, - { - "type": "textbox", - "x": 53, - "y": 273, - "width": 120, - "height": 20, - "content": [ - "Specialized Input Hatch for Steam Multiblocks" - ] - } - ], - "metatileentity": "steam_oven" -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/zh_cn/electric/central_monitor.json b/src/main/resources/assets/gregtech/terminal/guide/multiblocks/zh_cn/electric/central_monitor.json deleted file mode 100644 index 4de1eb5024f..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/multiblocks/zh_cn/electric/central_monitor.json +++ /dev/null @@ -1,183 +0,0 @@ -{ - "section": "电力", - "title": "中央监控器", - "stream": [ - { - "type": "slots", - "item_list": [ - { - "id": "gregtech:machine", - "damage": 1028, - "count": 1 - }, - { - "id": "gregtech:machine", - "damage": 1667, - "count": 1 - } - ] - }, - { - "type": "textbox", - "content": [ - "§l目录:" - ] - }, - { - "type": "textbox", - "link": "introduction", - "content": [ - "1. §9介绍" - ] - }, - { - "type": "textbox", - "link": "fluid", - "content": [ - "2. §9如何构建它" - ] - }, - { - "type": "textbox", - "link": "item", - "content": [ - "3. §r§9如何使用它" - ] - }, - { - "type": "textbox", - "link": "energy", - "content": [ - "4. §9插件" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/107856228-c1f6eb80-6e61-11eb-8098-454ea7133ca1.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "ref": "introduction", - "content": [ - "§l介绍" - ] - }, - { - "type": "textbox", - "content": [ - "§c§l中央监控仪§r是一个用来监控(可视化和交互)的多方块.\n\n它可以监控并交互机器的存储及运行状态,它包含§9数字化接口覆盖版§r§9§r的所有功能,并将机器的其他接口扩展到屏幕上。\n\n此外,还有许多插件支持更多高级功能。" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "fluid", - "content": [ - "§l怎么构建它?" - ] - }, - { - "type": "textbox", - "content": [ - "为了构建它,你需要一个§c§l中央监控器§r,一些§c§l监控屏幕§r,一些§c§l不锈钢机械方块§r,个至少一个§c§l能源输入仓§r.\n\n屏幕尺寸从3×2到14×9(宽 × 高)不等。默认高度是3,但是你可以在结构成型前在GUI中设置高度。\n\n§l能源消耗:§r每个屏幕50 EU/s。" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "item", - "content": [ - "§l如何使用它?" - ] - }, - { - "type": "textbox", - "content": [ - "1. §c§l中央监控器的§r的背后可以连接线缆,线缆所处的电网中可以监控所有被代理的机器(§9数字化接口覆盖版§r设置为代理模式,并放置在线和机器的接口处。) 此外,绑定了中央控制器的§9无线覆盖版§r同样可以使用,避免使用线缆。\n\n2. 右击§c§l中央监控器§r或者扳手右击§c§l监控屏幕§r可以打开GUI进行设置。" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "energy", - "content": [ - "§l插件" - ] - }, - { - "type": "textbox", - "content": [ - "将插件放入插件槽中使用。有关具体功能,请参阅其指南页。以下是支持的插件。\n\n§4§l注意§r§4: §r在§c§l中央监控器§r中,有些插件需要使用代理模式工作,而代理模式仅用于插件。" - ] - }, - { - "type": "card", - "fill": -3745585, - "width": 170, - "height": 60, - "isShadow": true - }, - { - "type": "textbox", - "content": [ - "\n\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - } - ], - "fixed": [ - { - "type": "slots", - "x": 48, - "y": 730, - "width": 100, - "height": 18, - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 780, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 781, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 782, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 783, - "count": 1 - } - ] - } - ], - "metatileentity": "central_monitor" -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/01_definition.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/01_definition.json deleted file mode 100644 index b319e88fe15..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/01_definition.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "section": "CraftTweaker/Material", - "title": "Material Definition", - "stream": [ - { - "type": "textbox", - "fontSize": 11, - "fontColor": -65536, - "content": [ - "§lFirstly, you should know what is the Material." - ] - }, - { - "type": "textbox", - "content": [ - "Material is the basis of CEu. It defines to a substance and its properties. It usually takes the form of an §lelement§r or a §lchemical§r, but it can also take the form of something weird like the §lEnder Eye§r." - ] - }, - { - "type": "textbox", - "fontSize": 11, - "fontColor": -16776961, - "content": [ - "§lSecondly, it defines which properties?" - ] - }, - { - "type": "textbox", - "content": [ - "The §lmaterial§r specifies whether it has a §lfluid§r state, §lplasma§r state, §ldust§r state, etc. When it has a specific state, the CEu will register the corresponding item or fluid automatically." - ] - }, - { - "type": "textbox", - "fontSize": 11, - "fontColor": -16731136, - "content": [ - "§lThirdly, What else does it define?" - ] - }, - { - "type": "textbox", - "content": [ - "You can actually define its colors, flag, iconSet, cableProperties, Element, formula, components and so on. Don\u0027t worry, they are not complicated, will be introduced in other pages." - ] - } - ], - "fixed": [] -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/02_element.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/02_element.json deleted file mode 100644 index 22f3b6a04af..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/02_element.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "section": "CraftTweaker/Material", - "title": "Element", - "stream": [ - { - "type": "textbox", - "fontSize": 9, - "content": [ - "The §lElement§r use to specify a material as an elemental and affects its chemical fomular. CEu basically has the periodic table, so you probably won\u0027t need it. \n\n§lContents:" - ] - }, - { - "type": "textbox", - "link": "element", - "content": [ - "1. §9Element" - ] - }, - { - "type": "textbox", - "link": "ct", - "content": [ - "2. §9CT" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "element", - "content": [ - "§c§lElement:§r\n §l○ §nprotons§r – Amount of Protons\n §l○ §nneutrons§r – Amount of Neutrons (I could have made mistakes with the Neutron amount calculation, please tell me if I did something wrong)\n §l○ §nhalfLifeSeconds§r – Amount of Half Life this Material has in Seconds. -1 for stable Materials\n §l○ §ndecayTo§r – String representing the Elements it decays to. Separated by an \u0027\u0026\u0027 Character\n §l○ §nname§r – Name of the Element\n §l○ §nsymbol§r – Symbol of the Element" - ] - }, - { - "type": "textbox", - "content": [ - "§lExisting elements:" - ] - }, - { - "type": "textbox", - "stroke": 1623820032, - "stroke_width": 3, - "fill": 1623820032, - "content": [ - " §l○ §c§lH§r: 1, 0, -1, null, \"Hydrogen\", \"H\", false\n §l○ §c§lD§r: 1, 1, -1, \"H\", \"Deuterium\", \"D\", true\n §l○ §c§lT§r: 1, 2, -1, \"D\", \"Tritium\", \"T\", true\n §l○ §c§lHe§r: 2, 2, -1, null, \"Helium\", \"He\", false\n §l○ §c§lHe3§r: 2, 1, -1, \"H\u0026D\", \"Helium-3\", \"He-3\", true\n §l○ §c§lLi§r: 3, 4, -1, null, \"Lithium\", \"Li\", false\n §l○ §c§lBe§r: 4, 5, -1, null, \"Beryllium\", \"Be\", false\n §l○ §c§lB§r: 5, 5, -1, null, \"Boron\", \"B\", false\n §l○ §c§lC§r: 6, 6, -1, null, \"Carbon\", \"C\", false\n §l○ §c§lN§r: 7, 7, -1, null, \"Nitrogen\", \"N\", false\n §l○ §c§lO§r: 8, 8, -1, null, \"Oxygen\", \"O\", false\n §l○ §c§lF§r: 9, 9, -1, null, \"Fluorine\", \"F\", false\n §l○ §c§lNe§r: 10, 10, -1, null, \"Neon\", \"Ne\", false\n §l○ §c§lNa§r: 11, 11, -1, null, \"Sodium\", \"Na\", false\n §l○ §c§lMg§r: 12, 12, -1, null, \"Magnesium\", \"Mg\", false\n §l○ §c§lAl§r: 13, 13, -1, null, \"Aluminium\", \"Al\", false\n §l○ §c§lSi§r: 14, 14, -1, null, \"Silicon\", \"Si\", false\n §l○ §c§lP§r: 15, 15, -1, null, \"Phosphorus\", \"P\", false\n §l○ §c§lS§r: 16, 16, -1, null, \"Sulfur\", \"S\", false\n §l○ §c§lCl§r: 17, 18, -1, null, \"Chlorine\", \"Cl\", false\n §l○ §c§lAr§r: 18, 22, -1, null, \"Argon\", \"Ar\", false\n §l○ §c§lK§r: 19, 20, -1, null, \"Potassium\", \"K\", false\n §l○ §c§lCa§r: 20, 20, -1, null, \"Calcium\", \"Ca\", false\n §l○ §c§lSc§r: 21, 24, -1, null, \"Scandium\", \"Sc\", false\n §l○ §c§lTi§r: 22, 26, -1, null, \"Titanium\", \"Ti\", false\n §l○ §c§lV§r: 23, 28, -1, null, \"Vanadium\", \"V\", false\n §l○ §c§lCr§r: 24, 28, -1, null, \"Chrome\", \"Cr\", false\n §l○ §c§lMn§r: 25, 30, -1, null, \"Manganese\", \"Mn\", false\n §l○ §c§lFe§r: 26, 30, -1, null, \"Iron\", \"Fe\", false\n §l○ §c§lCo§r: 27, 32, -1, null, \"Cobalt\", \"Co\", false\n §l○ §c§lNi§r: 28, 30, -1, null, \"Nickel\", \"Ni\", false\n §l○ §c§lCu§r: 29, 34, -1, null, \"Copper\", \"Cu\", false\n §l○ §c§lZn§r: 30, 35, -1, null, \"Zinc\", \"Zn\", false\n §l○ §c§lGa§r: 31, 39, -1, null, \"Gallium\", \"Ga\", false\n §l○ §c§lGe§r: 32, 40, -1, null, \"Germanium\", \"Ge\", false\n §l○ §c§lAs§r: 33, 42, -1, null, \"Arsenic\", \"As\", false\n §l○ §c§lSe§r: 34, 45, -1, null, \"Selenium\", \"Se\", false\n §l○ §c§lBr§r: 35, 45, -1, null, \"Bromine\", \"Br\", false\n §l○ §c§lKr§r: 36, 48, -1, null, \"Krypton\", \"Kr\", false\n §l○ §c§lRb§r: 37, 48, -1, null, \"Rubidium\", \"Rb\", false\n §l○ §c§lSr§r: 38, 49, -1, null, \"Strontium\", \"Sr\", false\n §l○ §c§lY§r: 39, 50, -1, null, \"Yttrium\", \"Y\", false\n §l○ §c§lZr§r: 40, 51, -1, null, \"Zirconium\", \"Zr\", false\n §l○ §c§lNb§r: 41, 53, -1, null, \"Niobium\", \"Nb\", false\n §l○ §c§lMo§r: 42, 53, -1, null, \"Molybdenum\", \"Mo\", false\n §l○ §c§lTc§r: 43, 55, -1, null, \"Technetium\", \"Tc\", false\n §l○ §c§lRu§r: 44, 57, -1, null, \"Ruthenium\", \"Ru\", false\n §l○ §c§lRh§r: 45, 58, -1, null, \"Rhodium\", \"Rh\", false\n §l○ §c§lPd§r: 46, 60, -1, null, \"Palladium\", \"Pd\", false\n §l○ §c§lAg§r: 47, 60, -1, null, \"Silver\", \"Ag\", false\n §l○ §c§lCd§r: 48, 64, -1, null, \"Cadmium\", \"Cd\", false\n §l○ §c§lIn§r: 49, 65, -1, null, \"Indium\", \"In\", false\n §l○ §c§lSn§r: 50, 68, -1, null, \"Tin\", \"Sn\", false\n §l○ §c§lSb§r: 51, 70, -1, null, \"Antimony\", \"Sb\", false\n §l○ §c§lTe§r: 52, 75, -1, null, \"Tellurium\", \"Te\", false\n §l○ §c§lI§r: 53, 74, -1, null, \"Iodine\", \"I\", false\n §l○ §c§lXe§r: 54, 77, -1, null, \"Xenon\", \"Xe\", false\n §l○ §c§lCs§r: 55, 77, -1, null, \"Caesium\", \"Cs\", false\n §l○ §c§lBa§r: 56, 81, -1, null, \"Barium\", \"Ba\", false\n §l○ §c§lLa§r: 57, 81, -1, null, \"Lanthanum\", \"La\", false\n §l○ §c§lCe§r: 58, 82, -1, null, \"Cerium\", \"Ce\", false\n §l○ §c§lPr§r: 59, 81, -1, null, \"Praseodymium\", \"Pr\", false\n §l○ §c§lNd§r: 60, 84, -1, null, \"Neodymium\", \"Nd\", false\n §l○ §c§lPm§r: 61, 83, -1, null, \"Promethium\", \"Pm\", false\n §l○ §c§lSm§r: 62, 88, -1, null, \"Samarium\", \"Sm\", false\n §l○ §c§lEu§r: 63, 88, -1, null, \"Europium\", \"Eu\", false\n §l○ §c§lGd§r: 64, 93, -1, null, \"Gadolinium\", \"Gd\", false\n §l○ §c§lTb§r: 65, 93, -1, null, \"Terbium\", \"Tb\", false\n §l○ §c§lDy§r: 66, 96, -1, null, \"Dysprosium\", \"Dy\", false\n §l○ §c§lHo§r: 67, 97, -1, null, \"Holmium\", \"Ho\", false\n §l○ §c§lEr§r: 68, 99, -1, null, \"Erbium\", \"Er\", false\n §l○ §c§lTm§r: 69, 99, -1, null, \"Thulium\", \"Tm\", false\n §l○ §c§lYb§r: 70, 103, -1, null, \"Ytterbium\", \"Yb\", false\n §l○ §c§lLu§r: 71, 103, -1, null, \"Lutetium\", \"Lu\", false\n §l○ §c§lHf§r: 72, 106, -1, null, \"Hafnium\", \"Hf\", false\n §l○ §c§lTa§r: 73, 107, -1, null, \"Tantalum\", \"Ta\", false\n §l○ §c§lW§r: 74, 109, -1, null, \"Tungsten\", \"W\", false\n §l○ §c§lRe§r: 75, 111, -1, null, \"Rhenium\", \"Re\", false\n §l○ §c§lOs§r: 76, 114, -1, null, \"Osmium\", \"Os\", false\n §l○ §c§lIr§r: 77, 115, -1, null, \"Iridium\", \"Ir\", false\n §l○ §c§lPt§r: 78, 117, -1, null, \"Platinum\", \"Pt\", false\n §l○ §c§lAu§r: 79, 117, -1, null, \"Gold\", \"Au\", false\n §l○ §c§lHg§r: 80, 120, -1, null, \"Mercury\", \"Hg\", false\n §l○ §c§lTl§r: 81, 123, -1, null, \"Thallium\", \"Tl\", false\n §l○ §c§lPb§r: 82, 125, -1, null, \"Lead\", \"Pb\", false\n §l○ §c§lBi§r: 83, 125, -1, null, \"Bismuth\", \"Bi\", false\n §l○ §c§lPo§r: 84, 124, -1, null, \"Polonium\", \"Po\", false\n §l○ §c§lAt§r: 85, 124, -1, null, \"Astatine\", \"At\", false\n §l○ §c§lRn§r: 86, 134, -1, null, \"Radon\", \"Rn\", false\n §l○ §c§lFr§r: 87, 134, -1, null, \"Francium\", \"Fr\", false\n §l○ §c§lRa§r: 88, 136, -1, null, \"Radium\", \"Ra\", false\n §l○ §c§lAc§r: 89, 136, -1, null, \"Actinium\", \"Ac\", false\n §l○ §c§lTh§r: 90, 140, -1, null, \"Thorium\", \"Th\", false\n §l○ §c§lPa§r: 91, 138, -1, null, \"Protactinium\", \"Pa\", false\n §l○ §c§lU§r: 92, 146, -1, null, \"Uranium\", \"U\", false\n §l○ §c§lU238§r: 92, 146, -1, null, \"Uranium-238\", \"U-238\", false\n §l○ §c§lU235§r: 92, 143, -1, null, \"Uranium-235\", \"U-235\", true\n §l○ §c§lNp§r: 93, 144, -1, null, \"Neptunium\", \"Np\", false\n §l○ §c§lPu§r: 94, 152, -1, null, \"Plutonium\", \"Pu\", false\n §l○ §c§lPu239§r: 94, 145, -1, null, \"Plutonium-239\", \"Pu-239\", false\n §l○ §c§lPu241§r: 94, 149, -1, null, \"Plutonium-241\", \"Pu-241\", true\n §l○ §c§lAm§r: 95, 150, -1, null, \"Americium\", \"Am\", false\n §l○ §c§lCm§r: 96, 153, -1, null, \"Curium\", \"Cm\", false\n §l○ §c§lBk§r: 97, 152, -1, null, \"Berkelium\", \"Bk\", false\n §l○ §c§lCf§r: 98, 153, -1, null, \"Californium\", \"Cf\", false\n §l○ §c§lEs§r: 99, 153, -1, null, \"Einsteinium\", \"Es\", false\n §l○ §c§lFm§r: 100, 157, -1, null, \"Fermium\", \"Fm\", false\n §l○ §c§lMd§r: 101, 157, -1, null, \"Mendelevium\", \"Md\", false\n §l○ §c§lNo§r: 102, 157, -1, null, \"Nobelium\", \"No\", false\n §l○ §c§lLr§r: 103, 159, -1, null, \"Lawrencium\", \"Lr\", false\n §l○ §c§lRf§r: 104, 161, -1, null, \"Rutherfordium\", \"Rf\", false\n §l○ §c§lDb§r: 105, 163, -1, null, \"Dubnium\", \"Db\", false\n §l○ §c§lSg§r: 106, 165, -1, null, \"Seaborgium\", \"Sg\", false\n §l○ §c§lBh§r: 107, 163, -1, null, \"Bohrium\", \"Bh\", false\n §l○ §c§lHs§r: 108, 169, -1, null, \"Hassium\", \"Hs\", false\n §l○ §c§lMt§r: 109, 167, -1, null, \"Meitnerium\", \"Mt\", false\n §l○ §c§lDs§r: 110, 171, -1, null, \"Darmstadtium\", \"Ds\", false\n §l○ §c§lRg§r: 111, 169, -1, null, \"Roentgenium\", \"Rg\", false\n §l○ §c§lCn§r: 112, 173, -1, null, \"Copernicium\", \"Cn\", false\n §l○ §c§lNh§r: 113, 171, -1, null, \"Nihonium\", \"Nh\", false\n §l○ §c§lFl§r: 114, 175, -1, null, \"Flerovium\", \"Fl\", false\n §l○ §c§lMc§r: 115, 173, -1, null, \"Moscovium\", \"Mc\", false\n §l○ §c§lLv§r: 116, 177, -1, null, \"Livermorium\", \"Lv\", false\n §l○ §c§lTs§r: 117, 177, -1, null, \"Tennessine\", \"Ts\", false\n §l○ §c§lOg§r: 118, 176, -1, null, \"Oganesson\", \"Og\", false\n §l○ §c§lTr§r: 119, 178, -1, null, \"Tritanium\", \"Tr\", false\n §l○ §c§lDr§r: 120, 180, -1, null, \"Duranium\", \"Dr\", false\n §l○ §c§lKe§r: 125, 198, -1, null, \"Trinium\", \"Ke\", false\n §l○ §c§lNq§r: 174, 352, 140, null, \"Naquadah\", \"Nq\", true\n §l○ §c§lNq1§r: 174, 354, 140, null, \"NaquadahEnriched\", \"Nq+\", true\n §l○ §c§lNq2§r: 174, 348, 140, null, \"Naquadria\", \"*Nq*\", true\n §l○ §c§lNt§r: 0, 1000, -1, null, \"Neutronium\", \"Nt\", false\n §l○ §c§lAd§r: 750, 1000, -1, null, \"Adamantium\", \"Ad\", false\n §l○ §c§lVb§r: 850, 900, -1, null, \"Vibranium\", \"Vb\", false\n §l○ §c§lTn§r: 550, 670, -1, null, \"Taranium\", \"Tn\", false" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "ct", - "content": [ - "§lElements.add§r: §o§nElements.add(long protons, long neutrons, long halfLifeSeconds, String decayTo, String name, String symbol, boolean isIsotope)§r \nAdd a new element.\n\n§lElements.get§r: §o§nElements.get(String name)§r \nGet the element by name." - ] - }, - { - "type": "textbox", - "stroke": 687800320, - "stroke_width": 3, - "fill": 687800320, - "content": [ - "§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialBuilder§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Material§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Elements§r§5;§r§5\n§r§5\n§r§9var§r§5 §r§0Au§r§5 §r§5\u003d§r§5 §r§0Elements§r§5.§r§0get§r§5(§r§0Au§r§5)§r§5;§r§5 §r§8// get an existing element.§r§5\n§r§9var§r§5 §r§0name§r§5 §r§5\u003d§r§5 §r§0Au§r§5.§r§0name§r§5;§r§5 §r§8// \"Gold\"§r§5\n§r§9var§r§5 §r§0symbol§r§5 §r§5\u003d§r§5 §r§0Au§r§5.§r§0symbol§r§5;§r§5 §r§8// \"Au\"§r§5\n§r§9var§r§5 §r§0protons§r§5 §r§5\u003d§r§5 §r§0Au§r§5.§r§0protons§r§5 §r§8// 79§r§5\n§r§9var§r§5 §r§0neutrons§r§5 §r§5\u003d§r§5 §r§0Au§r§5.§r§0neutrons§r§8// 117§r§5\n§r§9var§r§5 §r§0mass§r§5 §r§5\u003d§r§5 §r§0Au§r§5.§r§0mass§r§5 §r§8// 196§r§5\n§r§5\n§r§9var§r§5 §r§0CEu§r§5 §r§5\u003d§r§5 §r§0Elements§r§5.§r§0add§r§5(§r§c999§r§5,§r§5 §r§c999§r§5,§r§5 §r§5-§r§c1§r§5,§r§5 §r§cnull§r§5,§r§5 §r§2\"GTCEu\"§r§5,§r§5 §r§2\"CEu\"§r§5,§r§5 §r§cfalse§r§5)§r§5;§r§5 §r§8// create a new element.§r§5\n§r§5\n§r§9var§r§5 §r§0myMaterial§r§5 §r§5\u003d§r§5 §r§0MaterialBuilder§r§5(§r§2\"my_material\"§r§5)§r§5.§r§0element§r§5(§r§2\"CEu\"§r§5)§r§5.§r§0build§r§5(§r§5)§r§5;§r§5 §r§8// register my element.§r§5\n§r" - ] - } - ], - "fixed": [] -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/03_flag.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/03_flag.json deleted file mode 100644 index e739ce18cc5..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/03_flag.json +++ /dev/null @@ -1,148 +0,0 @@ -{ - "section": "CraftTweaker/Material", - "title": "MaterialFlag", - "stream": [ - { - "type": "textbox", - "fontSize": 9, - "content": [ - "The §lMaterialFlag§r refers to some additional features it has.\n\nAvailable MaterialFlag are: " - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "element", - "content": [ - "§r§4§ogeneric:" - ] - }, - { - "type": "textbox", - "content": [ - " §l○ §n\"no_unification\"§r: Add to material to disable it\u0027s unification fully todo implement.\n §l○ §n\"decomposition_requires_hydrogen\"§r: Decomposition recipe requires hydrogen as additional input. Amount is equal to input amount.\n §l○ §n\"decomposition_by_electrolyzing\"§r: Enables electrolyzer decomposition recipe generation.\n §l○ §n\"decomposition_by_centrifuging\"§r: Enables centrifuge decomposition recipe generatio.\n §l○ §n\"disable_decomposition\"§r: Disables decomposition recipe generation for this material and all materials that has it as component.\n §l○ §n\"explosive\"§r: Add to material if it is some kind of explosive.\n §l○ §n\"flammable\"§r: Add to material if it is some kind of flammable." - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "ct", - "content": [ - "§4§oGenerate a plate for this material If it\u0027s dust material, dust compressor recipe into plate will be generated If it\u0027s metal material, bending machine recipes will be generated If block is found, cutting machine recipe will be also generated:" - ] - }, - { - "type": "textbox", - "content": [ - "§n\"generate_plate\"§r, §n\"generate_rod\"§r, §n\"generate_frame\"§r, §n\"generate_gear\"§r, §n\"generate_long_rod\"§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "content": [ - "§4§oThis will prevent material from creating Shapeless recipes for dust to block and vice versa Also preventing extruding and alloy smelting recipes via SHAPE_EXTRUDING/MOLD_BLOCK:" - ] - }, - { - "type": "textbox", - "content": [ - "§n\"exclude_block_crafting_recipes\"§r, §n\"exclude_plate_compressor_recipe\"§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "content": [ - "§4§oThis will prevent material from creating Shapeless recipes for dust to block and vice versa:" - ] - }, - { - "type": "textbox", - "content": [ - "§n\"exclude_block_crafting_by_hand_recipes\"§r, §n\"mortar_grindable\"§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "content": [ - "§4§oAdd to material if it cannot be worked by any other means, than smashing or smelting. This is used for coated Materials:" - ] - }, - { - "type": "textbox", - "content": [ - "§n\"no_working\"§r, §n\"no_smashing\"§r, §n\"no_smelting\"§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "content": [ - "§4§oAdd this to your Material if you want to have its Ore Calcite heated in a Blast Furnace for more output. Already listed are: Iron, Pyrite, PigIron, WroughtIron:" - ] - }, - { - "type": "textbox", - "content": [ - "§n\"blast_furnace_calcite_double\"§r, §n\"blast_furnace_calcite_triple\"§r, §n\"generate_foil\"§r, §n\"generate_bolt_screw\"§r, §n\"generate_ring\"§r, §n\"generate_spring\"§r, §n\"generate_spring_small\"§r, §n\"generate_small_gear\"§r, §n\"generate_fine_wire\"§r, §n\"generate_rotor\"§r, §n\"generate_dense\"§r, §n\"generate_round\"§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "content": [ - "§4§oIf this material can be crystallized:" - ] - }, - { - "type": "textbox", - "content": [ - "§n\"crystallizable\"§r, §n\"generate_lens\"§r, §n\"high_sifter_output\"§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - } - ], - "fixed": [] -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/04_icon_set.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/04_icon_set.json deleted file mode 100644 index f0749c2b2a5..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/04_icon_set.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "section": "CraftTweaker/Material", - "title": "MaterialIconSet", - "stream": [ - { - "type": "textbox", - "fontSize": 9, - "content": [ - "The §lMaterialIconSet§r will determine the appearance of the material." - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "element", - "content": [ - "§rAvailable MaterialIconSet are:" - ] - }, - { - "type": "textbox", - "content": [ - "§l\"NONE\", \"METALLIC\", \"DULL\", \"MAGNETIC\", \"QUARTZ\", \"DIAMOND\", \"EMERALD\", \"SHINY\", \"ROUGH\", \"FINE\", \"SAND\", \"FLINT\", \"RUBY\", \"LAPIS\", \"FLUID\", \"GAS\", \"LIGNITE\", \"OPAL\", \"GLASS\", \"WOOD\", \"GEM_HORIZONTAL\", \"GEM_VERTICAL\", \"PAPER\", \"NETHERSTAR\", \"BRIGHT\"§r." - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "ct", - "content": [ - "For example, the following figure shows the appearance of ores with different Materialiconsets." - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/143435701-058dcfea-ea35-4976-a7ba-7901fa791e36.png", - "width": 190, - "height": 100 - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - } - ], - "fixed": [] -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/05_create.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/05_create.json deleted file mode 100644 index feaa04ef1f8..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/05_create.json +++ /dev/null @@ -1,257 +0,0 @@ -{ - "section": "CraftTweaker/Material", - "title": "Create a Material", - "stream": [ - { - "type": "textbox", - "fontSize": 9, - "content": [ - "You can help create a Material by the §lMaterialBuilder§r.\n\n§lContents:" - ] - }, - { - "type": "textbox", - "link": "bui", - "content": [ - "1. §9MaterialBuilder" - ] - }, - { - "type": "textbox", - "link": "pro", - "content": [ - "2. §9Material Properties" - ] - }, - { - "type": "textbox", - "link": "ico", - "content": [ - "3. §9Material IconSet" - ] - }, - { - "type": "textbox", - "link": "com", - "content": [ - "4. §9Material Component" - ] - }, - { - "type": "textbox", - "link": "fla", - "content": [ - "5. §9Material Flag" - ] - }, - { - "type": "textbox", - "link": "ele", - "content": [ - "6§r. §9Material Element" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "content": [ - "§lMaterialBuilder" - ], - "ref": "bui" - }, - { - "type": "textbox", - "ref": "element", - "content": [ - "§o§nMaterialBuilder(String materialName)§r" - ] - }, - { - "type": "textbox", - "stroke": 687800320, - "stroke_width": 3, - "fill": 687800320, - "content": [ - "§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialBuilder§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Material§r§5;§r§5\n§r§5\n§r§9var§r§5 §r§0myMaterial§r§5 §r§5\u003d§r§5 §r§0MaterialBuilder§r§5(§r§2\"my_material\"§r§5)§r§5.§r§0build§r§5(§r§5)§r§5;§r§5\n" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "pro", - "content": [ - "§lMaterial Properties" - ] - }, - { - "type": "textbox", - "content": [ - "§lcolor§r: §o§ncolor(int color)§r\nSet the Color of this Material. Defaults to 0xFFFFFF unless §ncolorAverage()§r.\n\n§lcolorAverage§r: §o§ncolorAverage(int color)§r\nColor will be a weighted average of the components of the Material.\n\n§lFluid§r: §o§nfluid(@Optional String type, @Optional boolean hasBlock)§r\nAdd a FluidProperty to this Material.\n §l○§r type – The Material.FluidType of this Material, either \"fluid\" or \"gas\".\n §l○§r hasBlock – If true, create a Fluid Block for this Material.\n\n§lplasma§r: §o§nplasma()§r \nAdd a PlasmaProperty to this Material.\n §l○§r type – The Material.FluidType of this Material, either \"fluid\" or \"gas\".\n §l○§r hasBlock – If true, create a Fluid Block for this Material.\n\n§ldust§r: §o§ndust(@Optional int harvestLevel, @Optional int burnTime)§r \nAdd a DustProperty to this Material.\n §l○§r harvestLevel – The Harvest Level of this block for Mining. If this Material also has a ToolProperty, this value will also be used to determine the tool\u0027s Mining Level.\n §l○§r burnTime – The Burn Time (in ticks) of this Material as a Furnace Fuel.\n\n§lingot§r: §o§ningot(@Optional int harvestLevel, @Optional int burnTime)§r \nAdd an IngotProperty to this Material.\n §l○§r harvestLevel – The Harvest Level of this block for Mining. If this Material also has a ToolProperty, this value will also be used to determine the tool\u0027s Mining level. If this Material already had a Harvest Level defined, it will be overridden.\n §l○§r burnTime – The Burn Time (in ticks) of this Material as a Furnace Fuel. If this Material already had a Burn Time defined, it will be overridden.\n\n§lgem§r: §o§ngem(@Optional int harvestLevel, @Optional int burnTime)§r \nAdd a GemProperty to this Material.\n §l○§r harvestLevel – The Harvest Level of this block for Mining. If this Material also has a ToolProperty, this value will also be used to determine the tool\u0027s Mining level. If this Material already had a Harvest Level defined, it will be overridden.\n §l○§r burnTime – The Burn Time (in ticks) of this Material as a Furnace Fuel. If this Material already had a Burn Time defined, it will be overridden.\n\n§ltoolStats§r: §o§ntoolStats(float speed, float damage, int durability, int enchantability)§r \nSet the stat for tools which are made from this Material.\n §l○§r speed – Speed.\n §l○§r damage – Attack damage.\n §l○§r durability – Durability of tools.\n §l○§r enchantability – Enchantability of tools.\n\n§lblastTemp§r: §o§nblastTemp(int temp)§r \nBlast Furnace Temperature of this Material. If below 1000K, Primitive Blast Furnace recipes will be also added. If above 1750K, a Hot Ingot and its Vacuum Freezer recipe will be also added.\n\nIf a Material with this Property has a Fluid, its temperature will be set to this if it is the default Fluid temperature.\n §l○§r temp – Temperature.\n\n§lore§r: §o§nore(@Optional int oreMultiplier, @Optional int byproductMultiplier, @Optional boolean emissive)§r \nAdd ore blocks of this Material.\n §l○§r oreMultiplier – Crushed Ore output amount multiplier during Maceration. Default: 1 (no multiplier).\n §l○§r byproductMultiplier – Byproducts output amount multiplier during Maceration. Default: 1 (no multiplier).\n §l○§r emissive – Should ore block use the emissive texture. Default: false.\n\nEmissive ore as follow:" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/143446969-80de6354-ad12-4170-81f5-071d6c0bb7cd.png", - "width": 190, - "height": 110 - }, - { - "type": "textbox", - "content": [ - "§lwashedIn§r: §o§nwashedIn(String materialName, @Optional int washedAmount)§r \n\n§lwashedIn§r: §o§nwashedIn(Material material, @Optional int washedAmount)§r \nSet washing product of this Material (must has the ore property).\n §l○§r material – material.\n §l○§r washedAmount – amount.\n\n§lseparatedInto§r: §o§nseparatedInto(String... materialNames)§r \n\n§lseparatedInto§r: §o§nseparatedInto(Material... materials)§r \nSet separated products of this Material (must has the ore property).\n §l○§r materials – separated materials.\n\n§laddOreByproducts§r: §o§naddOreByproducts(String... materialNames)§r \n\n§laddOreByproducts§r: §o§naddOreByproducts(Material... materials)§r \nSet ore byproducts of this Material (must has the ore property).\n §l○§r materials – separated materials.\n\n§loreSmeltInto§r: §o§noreSmeltInto(String materialName)§r \n\n§loreSmeltInto§r: §o§noreSmeltInto(Material material)§r \nSet smelt product of this Material (must has the ore property).\n §l○§r material – material.\n\n§lpolarizesInto§r: §o§npolarizesInto(String materialName)§r \n\n§lpolarizesInto§r: §o§npolarizesInto(Material material)§r \nSet polarizes product of this Material (must has the ore property).\n §l○§r material – material.\n\n§larcSmeltInto§r: §o§narcSmeltInto(String materialName)§r \n\n§larcSmeltInto§r: §o§narcSmeltInto(Material material)§r \nSet arcSmelt product of this Material (must has the ore property).\n §l○§r material – material.\n\n§lmacerateInto§r: §o§nmacerateInto(String materialName)§r \n\n§lmacerateInto§r: §o§nmacerateInto(Material material)§r \nSet macerate product of this Material (must has the ore property).\n §l○§r material – material.\n\n§lingotSmeltInto§r: §o§ningotSmeltInto(String materialName)§r \n\n§lingotSmeltInto§r: §o§ningotSmeltInto(Material material)§r \nSet ingotSmelt product of this Material (must has the ore property).\n §l○§r material – material.\n\n§lfluidTemp§r: §o§nfluidTemp(int temp)§r \nSet the temperature of the fluid of this Material (must has the fluid property).\n §l○§r temp – temperature.\n\n§lcableProperties§r: §o§ncableProperties(long voltage, int amperage, int loss, @Optional boolean isSuperCon)§r \nAdd a cables and wires of this Material.\n §l○§r voltage – voltage.\n §l○§r amperage – amperage.\n §l○§r loss – loss.\n §l○§r isSuperCon – isSuperCon.\n\n§lfluidPipeProperties§r: §o§nfluidPipeProperties(int maxTemp, int throughput, boolean gasProof)§r \nAdd fluid pipes of this Material.\n §l○§r maxTemp – max acceptable temperature.\n §l○§r throughput – §l//TODO§r.\n §l○§r gasProof – §l//TODO§r.\n\n§litemPipeProperties§r: §o§nitemPipeProperties(int priority, float stacksPerSec)§r \nAdd item pipes of this Material.\n §l○§r priority – Items will try to take the path with the lowest priority.\n §l○§r stacksPerSec – rate in stacks per sec.\n\n§laddDefaultEnchant§r: §o§naddDefaultEnchant(IEnchantment enchantment)§r \nAdd Default Enchant of this Material.\n §l○§r enchantment – enchantment." - ] - }, - { - "type": "textbox", - "stroke": 687800320, - "stroke_width": 3, - "fill": 687800320, - "content": [ - "§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialBuilder§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Material§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialRegistry§r§5;§r§5\n§r§5\n§r§9var§r§5 §r§0gold§r§5 §r§5\u003d§r§5 §r§0MaterialRegistry§r§5(§r§2\"gold\"§r§5)§r§5\n§r§9var§r§5 §r§0copper§r§5 §r§5\u003d§r§5 §r§0MaterialRegistry§r§5(§r§2\"copper\"§r§5)§r§5\n§r§5\n§r§9var§r§5 §r§0myMaterial§r§5 §r§5\u003d§r§5 §r§0MaterialBuilder§r§5(§r§2\"my_material\"§r§5)§r§5 §r§8// name§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0color§r§5(§r§5-§r§c1§r§5)§r§5 §r§8// white§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0fluid§r§5(§r§2\"gas\"§r§5,§r§5 §r§cfalse§r§5)§r§5 §r§8// gas without block§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0dust§r§5(§r§5)§r§5 §r§8// has dust§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0ingot§r§5(§r§5)§r§5 §r§8// has ingot§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0toolStats§r§5(§r§c10§r§5,§r§5 §r§c3§r§5,§r§5 §r§c256§r§5,§r§5 §r§c21§r§5)§r§5 §r§8// tool stats§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0blastTemp§r§5(§r§c1000§r§5)§r§5 §r§8// EBF temperature§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0ore§r§5(§r§5)§r§5 §r§8// has ore blocks§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0addOreByproducts§r§5(§r§0gold§r§5,§r§5 §r§0copper§r§5)§r§5 §r§8// add byproducts§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0cableProperties§r§5(§r§c0§r§5,§r§5 §r§c2§r§5,§r§5 §r§c0§r§5,§r§5 §r§ctrue§r§5)§r§5 §r§8// add cables§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5.§r§0build§r§5(§r§5)§r§5;§r§5\n" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "ico", - "content": [ - "§lMaterial IconSet" - ] - }, - { - "type": "textbox", - "content": [ - "§liconSet§r: §o§niconSet(String iconSet)§r \nSet the MaterialIconSet of this Material. Defaults vary depending on if the Material has a: \n §l○§r §nGemProperty§r, it will default to §l\"GEM_VERTICAL\"§r\n §l○§r §nIngotProperty§r or §nDustProperty§r, it will default to §l\"DULL\"§r\n §l○§r §nFluidProperty§r, it will default to either §l\"FLUID\"§r or §l\"GAS\"§r, depending on the FluidType\n §l○§r §nPlasmaProperty§r, it will default to §l\"FLUID\"§r\n\nDefault will be determined by first-found Property in this order, unless specified." - ] - }, - { - "type": "textbox", - "stroke": 687800320, - "stroke_width": 3, - "fill": 687800320, - "content": [ - "§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialBuilder§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Material§r§5;§r§5\n§r§5\n§r§9var§r§5 §r§0myMaterial§r§5 §r§5\u003d§r§5 §r§0MaterialBuilder§r§5(§r§2\"my_material\"§r§5)§r§5.§r§0iconSet§r§5(§r§2\"QUARTZ\"§r§5)§r§5.§r§0build§r§5(§r§5)§r§5;§r§5\n§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "com", - "content": [ - "§lComponent" - ] - }, - { - "type": "textbox", - "content": [ - "The §lComponent§r refers to compositions of the material. \nFor example, the compositions of the §lSugar§r are §n2*Carbon§r, §n5*Water§r, and §n25*Oxygen§r. That would affect its chemical formula:" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/143438573-cd2e9078-744d-4861-a00c-1e9fc5ccd32a.png", - "width": 110, - "height": 50 - }, - { - "type": "textbox", - "content": [ - "§lcomponents§r: §o§ncomponents(MaterialStack[] components)§r \nSet the compositions of the material.\n §l○§r components - compositions." - ] - }, - { - "type": "textbox", - "stroke": 687800320, - "stroke_width": 3, - "fill": 687800320, - "content": [ - "§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialBuilder§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Material§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialStack§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialRegistry§r§5;§r§5\n§r§5\n§r§9var§r§5 §r§0carbonMaterial§r§5 §r§5\u003d§r§5 §r§0MaterialRegistry§r§5.§r§0get§r§5(§r§2\"carbon\"§r§5)§r§5;§r§5\n§r§9var§r§5 §r§0oxygenMaterial§r§5 §r§5\u003d§r§5 §r§0MaterialRegistry§r§5.§r§0get§r§5(§r§2\"oxygen\"§r§5)§r§5;§r§5\n§r§5\n§r§0val§r§5 §r§0compositions§r§5 §r§0as§r§5 §r§0MaterialStack§r§5[§r§5]§r§5 §r§5\u003d§r§5 §r§5[§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5 §r§5 §r§5 §r§5 §r§0carbonMaterial§r§5 §r§5*§r§5 §r§c2§r§5,§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5 §r§5 §r§5 §r§5 §r§0oxygenMaterial§r§5 §r§5*§r§5 §r§c3§r§5,§r§5\n§r§5 §r§5 §r§5 §r§5 §r§5]§r§5;§r§5\n§r§5\n§r§9var§r§5 §r§0myMaterial§r§5 §r§5\u003d§r§5 §r§0MaterialBuilder§r§5(§r§2\"my_material\"§r§5)§r§5.§r§0components§r§5(§r§0compositions§r§5)§r§5.§r§0build§r§5(§r§5)§r§5;§r§5\n§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "fla", - "content": [ - "§lMaterial Flag" - ] - }, - { - "type": "textbox", - "content": [ - "§lflags§r: §o§nflags(String... names)§r \nAdd MaterialFlags to this Material.\n §l○§r names - names of specific MaterialFlags." - ] - }, - { - "type": "textbox", - "stroke": 687800320, - "stroke_width": 3, - "fill": 687800320, - "content": [ - "§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialBuilder§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Material§r§5;§r§5\n§r§5\n§r§9var§r§5 §r§0myMaterial§r§5 §r§5\u003d§r§5 §r§0MaterialBuilder§r§5(§r§2\"my_material\"§r§5)§r§5.§r§0flags§r§5(§r§2\"generate_rod\"§r§5,§r§5 §r§2\"generate_foil\"§r§5)§r§5.§r§0build§r§5(§r§5)§r§5;§r§5\n§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "ele", - "content": [ - "§lElement" - ] - }, - { - "type": "textbox", - "content": [ - "§lelement§r: §o§nelement(String elementName)§r \nSet the element of this Material.\n §l○§r elementName - names of the element." - ] - }, - { - "type": "textbox", - "stroke": 687800320, - "stroke_width": 3, - "fill": 687800320, - "content": [ - "§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialBuilder§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Material§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Elements§r§5;§r§5\n§r§5\n§r§9var§r§5 §r§0CEu§r§5 §r§5\u003d§r§5 §r§0Elements§r§5.§r§0add§r§5(§r§c999§r§5,§r§5 §r§c999§r§5,§r§5 §r§5-§r§c1§r§5,§r§5 §r§cnull§r§5,§r§5 §r§2\"GTCEu\"§r§5,§r§5 §r§2\"CEu\"§r§5,§r§5 §r§cfalse§r§5)§r§5;§r§5 §r§8// create a new element.§r§5\n§r§5\n§r§9var§r§5 §r§0myMaterial§r§5 §r§5\u003d§r§5 §r§0MaterialBuilder§r§5(§r§2\"my_material\"§r§5)§r§5.§r§0element§r§5(§r§2\"CEu\"§r§5)§r§5.§r§0build§r§5(§r§5)§r§5;§r§5 §r§8// register my element.§r§5\n§r" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - } - ], - "fixed": [] -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/06_modify.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/06_modify.json deleted file mode 100644 index f9e1deeaf23..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/material/06_modify.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "section": "CraftTweaker/Material", - "title": "Modify Existing Materials", - "stream": [ - { - "type": "textbox", - "fontSize": 9, - "content": [ - "You can get Materials by the §lMaterialRegistry§r." - ] - }, - { - "type": "textbox", - "link": "element", - "content": [ - "1. §9Getters" - ] - }, - { - "type": "textbox", - "link": "ct", - "content": [ - "2. §9Setters" - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "element", - "content": [ - "§c§lGetters:" - ] - }, - { - "type": "textbox", - "content": [ - " §l○§r §o§nMaterialRegistry.get(String materialName)§r get §nMaterial§r by name.\n\n §l○§r §o§nMaterialRegistry.getAllMaterials()§r get §nMaterial§r List.\n\n §l○§r §o§ngetChemicalFormula()§r get default formula.\n\n §l○§r §o§nmaterialRGB§r get default materialRGB.\n\n §l○§r §o§nradioactive§r get default radioactive.\n\n §l○§r §o§nprotons§r get default protons.\n\n §l○§r §o§nneutrons§r get default neutrons.\n\n §l○§r §o§nmass§r get default mass.\n\n §l○§r §o§naverageProtons§r get default averageProtons.\n\n §l○§r §o§naverageNeutrons§r get default averageNeutrons.\n\n §l○§r §o§naverageMass§r get default averageMass.\n\n §l○§r §o§nblastTemperature§r get default blastTemperature.\n\n §l○§r §o§ncamelCaseName§r get default camelCaseName.\n\n §l○§r §o§nunlocalizedName§r get default unlocalizedName.\n\n §l○§r §o§nlocalizedName§r get default localizedName.\n\n §l○§r §o§nname§r get default name." - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "ref": "ct", - "content": [ - "§c§lSetters:" - ] - }, - { - "type": "textbox", - "content": [ - " §l○§r §o§nsetFormula(String formula, @Optional boolean withFormatting)§r Set the formula of this Material.\n\n §l○§r §o§naddFlags(String... names)§r Add additional flags to this Material.\n\n §l○§r §o§nsetMaterialRGB(int materialRGB)§r Set the color of this Material.\n\n §l○§r §o§nsetFormula(String formula, @Optional boolean withFormatting)§r Set the formula of this Material." - ] - }, - { - "type": "textbox", - "content": [ - "\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d\u003d" - ] - }, - { - "type": "textbox", - "stroke": 687800320, - "stroke_width": 3, - "fill": 687800320, - "content": [ - "§5\n§r§8#loader gregtech§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0MaterialRegistry§r§5;§r§5\n§r§9import§r§5 §r§0mods§r§5.§r§0gregtech§r§5.§r§0material§r§5.§r§0Material§r§5;§r§5\n§r§5\n§r§9var§r§5 §r§0gold§r§5 §r§5\u003d§r§5 §r§0MaterialRegistry§r§5.§r§0get§r§5(§r§2\"gold\"§r§5)§r§5;§r§5\n§r§9var§r§5 §r§0name§r§5 §r§5\u003d§r§5 §r§0gold§r§5.§r§0name§r§5;§r§5 §r§8// \"gold\"§r§5\n§r§9var§r§5 §r§0color§r§5 §r§5\u003d§r§5 §r§0gold§r§5.§r§0materialRGB§r§5;§r§5 §r§8// 0xFFE650§r§5\n§r§0gold§r§5.§r§0setFormula§r§5(§r§2\"AggA\"§r§5)§r§5;§r§5 §r§8// set formula§r§5\n§r§9var§r§5 §r§0formula§r§5 §r§5\u003d§r§5 §r§0gold§r§5.§r§0getChemicalFormula§r§5(§r§5)§r§5;§r§5 §r§8// \"AggA\"§r§5\n§r§0gold§r§5.§r§0addFlag§r§5(§r§2\"generate_long_rod\"§r§5,§r§5 §r§2\"generate_gear\"§r§5)§r§5;§r§5 §r§8// add gold long rod, add gold gear§r§5\n§r" - ] - } - ], - "fixed": [] -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/terminal/ct_terminal_01.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/terminal/ct_terminal_01.json deleted file mode 100644 index b1cdd3a9570..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/crafttweaker/terminal/ct_terminal_01.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "section": "CraftTweaker/Terminal", - "title": "CraftTweaker of Terminal", - "stream": [ - { - "type": "textbox", - "content": [ - "Content:" - ] - }, - { - "type": "textbox", - "content": [ - "§1§lURL:§r§n https://github.com/Gregicality/GregTech/wiki/CraftTweaker-of-Terminal" - ] - }, - { - "type": "textbox", - "ref": "api", - "isShadow": false, - "content": [ - "§4§lAPI:" - ] - }, - { - "type": "textbox", - "fontSize": 9, - "content": [ - "1. §1registerDevice(deviceItemStack, deviceName)§0:\nRegister the custon device.\n\n2. §1createAppRegistryBuilder(appName):\n§0Create the registryBuilder according to the app name (found in the store app).\n\n3. §1isDefaultApp(default):\n§0Make it as a default app.\n\n4. §1battery(euTier, cost):\n§0Set battery requirements for all tier.\n\n5. §1battery(appTier, euTier, cost):\n§0Set battery requirements for the specific tier.\n\n6. §1device(deviceName...):\n§0Set device requirements for all tier. (available by default: \"scanner\", \"wireless\", \"camera\", \"solar_lv\").\n\n7. §1device(appTier, device...):\n§0Set device requirements for the specific tier.\n\n8. §1upgrade(upgradeItemStack...):\n§0Set upgrade requirements for all tier.\n\n9. §1upgrade(appTier, upgradeItemStack...):\n§0Set upgrade requirements for the specific tier.\n\n10. §1build():\n§0finish and register." - ] - }, - { - "type": "textbox", - "ref": "demo", - "space": 1, - "content": [ - "\n§4§lZS Demo:" - ] - }, - { - "type": "textbox", - "fill": -912478525, - "fontSize": 9, - "content": [ - "import mods.gregtech.TerminalRegistry;\n\nTerminalRegistry.registerDevice(\u003core:ingotIron\u003e.firstItem, \"ingot_iron\");\n\nTerminalRegistry.createAppRegistryBuilder(\"ore_prospector\")\n .isDefaultApp(true)\n .battery(1, 500)\n .battery(3, 3, 1000)\n .device(\"camera\", \"wireless\")\n .device(4, \"ingot_iron\")\n .upgrade(\u003cminecraft:apple\u003e * 9)\n .upgrade(2, \u003cminecraft:apple\u003e * 9, \u003cminecraft:grass\u003e * 12)\n .build();" - ] - }, - { - "type": "textbox", - "fontSize": 9, - "content": [ - "§4§lResult:\n§rCustom Device" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/140280593-37922838-4a20-4e1b-9be9-73935c4c8c13.png", - "width": 190, - "height": 120 - }, - { - "type": "textbox", - "content": [ - "Register Battery, Device, and Upgrade" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/140280587-84dc8f67-6dde-472f-9ed8-6a4c5e71abc4.png", - "width": 190, - "height": 120 - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/140280590-d4700a88-5780-4e0f-95f8-130e82f4634a.png", - "width": 190, - "height": 120 - } - ], - "fixed": [ - { - "type": "textbox", - "x": 49, - "y": 40, - "width": 16, - "height": 10, - "link": "api", - "content": [ - "§9§napi" - ] - }, - { - "type": "textbox", - "x": 67, - "y": 40, - "width": 25, - "height": 10, - "link": "demo", - "content": [ - "§9§ndemo" - ] - } - ] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_0_guidepage.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_0_guidepage.json deleted file mode 100644 index 8fe3a94e403..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_0_guidepage.json +++ /dev/null @@ -1,148 +0,0 @@ -{ - "section": "Guide Widget Api", - "title": "Guide Page", - "stream": [ - { - "type": "textbox", - "content": [ - "In this page we'll learn how to write a guide page.", - "-------------------------------", - "Let's take a look at an example config file for a guide page.", - "§lJSON§r:", - "{", - " \"section\": \"section name here\",", - " \"title\": \"title here\",", - " \"stream\": [", - " {", - " \"type\": \"textbox\",", - " \"content\": [\"TextBox widget\"]", - " }", - " ],", - " \"fixed\": [", - " {", - " \"x\": 50,", - " \"y\": 100,", - " \"width\": 150,", - " \"height\": 40,", - " \"type\": 0,", - " \"content\": [\"TextBox widget\"]", - " }", - " ]", - "}", - "-------------------------------", - "§lContents§r" - ] - }, - { - "type": "textbox", - "link": "section", - "content": [ - " 1.§nsection§r" - ] - }, - { - "type": "textbox", - "link": "title", - "content": [ - " 2.§ntitle§r" - ] - }, - { - "type": "textbox", - "link": "stream", - "content": [ - " 3.§nstream§r" - ] - }, - { - "type": "textbox", - "link": "fixed", - "content": [ - " 4.§nfixed§r" - ] - }, - { - "type": "textbox", - "ref": "section", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nsection§r (§4required§r)", - "§ltype§r: String", - "§lillustrate§r: Specifies which section of the application the page belongs to.", - "The application automatically merges pages of the same section name and builds a directory tree." - ] - }, - { - "type": "textbox", - "ref": "title", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §ntitle§r (§4required§r)", - "§ltype§r: String", - "§lillustrate§r: The page title." - ] - }, - { - "type": "textbox", - "ref": "stream", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nstream§r (§4required§r)", - "§ltype§r: Array", - "§lillustrate§r: Widgets in streaming layout. You don't need to care the position and size of widgets in stream, all typography will be done automatically." - ] - }, - { - "type": "textbox", - "ref": "fixed", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nfixed§r (§4required§r)", - "§ltype§r: Array", - "§lillustrate§r: Widgets in fixed layout. You need to specify the position and size of each widget." - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: fixed and stream" - ] - }, - { - "type": "textbox", - "isCenter": true, - "hover_text": ["stream widget"], - "content": [ - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - } - ], - "fixed": [ - { - "type": "image", - "x": 30, - "y": 800, - "stroke": 4278190335, - "hover_text": ["fixed widget", "\"x\": 30","\"y\": 800","\"width\": 100","\"width\": 100"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 100, - "height": 100 - } - ] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_1_widget.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_1_widget.json deleted file mode 100644 index 7d8d23bea8c..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_1_widget.json +++ /dev/null @@ -1,304 +0,0 @@ -{ - "section": "Guide Widget Api", - "title": "Guide Widget", - "stream": [ - { - "type": "textbox", - "content": [ - "In this page we'll learn what is §4§lGuide Widget§r, and its public attributes.", - "Widgets are rendered in the Guide Page, which is the basis for your custom pages. §nTextbox§r, §nImage§r, etc", - "To use it, just add the related JSON code under the §l\"fixed\"§r or §l\"stream\"§r.", - "There are some attributes effects (styles) that are valid for all widgets", - "-------------------------------", - "§lJSON§r:", - "{", - " \"type\": \"type here\",", - " \"x\": 50,", - " \"y\": 100,", - " \"width\": 150,", - " \"height\": 40,", - " \"ref\": \"ref\",", - " \"stroke\": 0,", - " \"stroke_width\": 1,", - " \"fill\": 0,", - " \"link\": \"ref\"", - " \"hover_text\": [\"text here\"]", - "}", - "-------------------------------", - "§lContents§r" - ] - }, - { - "type": "textbox", - "link": "type", - "content": [ - " 1.§ntype§r" - ] - }, - { - "type": "textbox", - "link": "xywh", - "content": [ - " 2.§nx, y, width, height§r" - ] - }, - { - "type": "textbox", - "link": "ref", - "content": [ - " 3.§nref§r" - ] - }, - { - "type": "textbox", - "link": "fill", - "content": [ - " 4.§nfill§r" - ] - }, - { - "type": "textbox", - "link": "stroke", - "content": [ - " 5.§nstroke§r" - ] - }, - { - "type": "textbox", - "link": "stroke_width", - "content": [ - " 6.§nstroke_width§r" - ] - }, - { - "type": "textbox", - "link": "link", - "content": [ - " 7.§nlink§r" - ] - }, - { - "type": "textbox", - "link": "hover", - "content": [ - " 8.§nhover_text§r" - ] - }, - { - "type": "textbox", - "ref": "type", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §ntype§r (§4required§r)", - "§ltype§r: String", - "§lillustrate§r: This is the unique id of the widget. See the API documentation for each widget." - ] - }, - { - "type": "textbox", - "ref": "xywh", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nx, y, width, height§r (§4optional§r)", - "§ltype§r: Integer", - "§lillustrate§r: The position and size of the widget. In a stream layout, you usually don't need to set it (the image widget needs to set width and height). Under fixed layout you must set these four attributes." - ] - }, - { - "type": "textbox", - "ref": "ref", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nref§r (§4optional§r)", - "§ltype§r: String", - "§ldefault§r: null", - "§lillustrate§r: This is a tag of this widget. The ref should be unique on the same page." - ] - }, - { - "type": "textbox", - "ref": "fill", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nfill§r (§6optional§r)", - "§ltype§r: Number", - "§ldefault§r: 0", - "§lillustrate§r: The background color." - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: 4278190335 (0xFF0000FF)" - ] - }, - { - "type": "textbox", - "isCenter": true, - "fill": 4278190335, - "content": [ - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - }, - { - "type": "textbox", - "ref": "stroke", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nstroke§r (§6optional§r)", - "§ltype§r: Number", - "§ldefault§r: 0", - "§lillustrate§r: The border color." - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: 4278190335 (0xFF0000FF)" - ] - }, - { - "type": "image", - "form": "item", - "source": "minecraft:ender_pearl", - "stroke": 4278190335, - "width": 50, - "height": 50 - }, - { - "type": "textbox", - "ref": "stroke_width", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nstroke_width§r (§6optional§r)", - "§ltype§r: Number", - "§ldefault§r: 1", - "§lillustrate§r: The border width." - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: 5" - ] - }, - { - "type": "image", - "form": "item", - "source": "minecraft:ender_pearl", - "stroke": 4278190335, - "stroke_width": 5, - "width": 50, - "height": 50 - }, - { - "type": "textbox", - "ref": "link", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nlink§r (§6optional§r)", - "§ltype§r: String", - "§ldefault§r: null", - "§lillustrate§r: Click to jump to the specified location. Need to be used with ref, target is ref." - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"P2\"" - ] - }, - { - "type": "textbox", - "isCenter": true, - "fill": 4286430975, - "hover_text": ["\"ref\": \"P1\""], - "ref": "P1", - "link": "P2", - "content": ["Click Me!"] - }, - { - "type": "textbox", - "content": [ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"P1\"" - ] - }, - { - "type": "textbox", - "isCenter": true, - "fill": 4286430975, - "hover_text": ["\"ref\": \"P2\""], - "ref": "P2", - "link": "P1", - "content": ["Click Me!"] - }, - { - "type": "textbox", - "ref": "hover", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nhover_text§r (§6optional§r)", - "§ltype§r: Array", - "§ldefault§r: null", - "§lillustrate§r: Displays text when the mouse is over the widget." - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: [\"THIS IS\",\"GT ICON\"]" - ] - }, - { - "type": "image", - "hover_text": ["THIS IS","GT ICON"], - "form": "resource", - "source": "gregtech:textures/gui/icon/gregtech_logo.png", - "width": 100, - "height": 100 - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_2_textbox.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_2_textbox.json deleted file mode 100644 index f67b885350a..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_2_textbox.json +++ /dev/null @@ -1,256 +0,0 @@ -{ - "section": "Guide Widget Api", - "title": "1. TextBox Widget", - "stream": [ - { - "type": "textbox", - "content": [ - "In this page we'll learn how to use the powerful §4§lTextBox§r, which is the most commonly used. So you should read the API documentation carefully.", - "-------------------------------", - "§lWidget Type§r: §ntextbox§r", - "-------------------------------", - "§lJSON§r:", - "{", - " \"type\": \"textbox\",", - " \"space\": 1,", - " \"fontSize\": 9,", - " \"fontColor\": 4278190080,", - " \"isCenter\": false,", - " \"isShadow\": false,", - " \"content\": [\"content here!\"]", - "}", - "-------------------------------", - "§lContents§r" - ] - }, - { - "type": "textbox", - "link": "content", - "content": [ - " 1.§ncontent§r" - ] - }, - { - "type": "textbox", - "link": "space", - "content": [ - " 2.§nspace§r" - ] - }, - { - "type": "textbox", - "link": "fontSize", - "content": [ - " 3.§nfontSize§r" - ] - }, - { - "type": "textbox", - "link": "fontColor", - "content": [ - " 4.§nfontColor§r" - ] - }, - { - "type": "textbox", - "link": "isCenter", - "content": [ - " 5.§nisCenter§r" - ] - }, - { - "type": "textbox", - "link": "isShadow", - "content": [ - " 6.§nisShadow§r" - ] - }, - { - "type": "textbox", - "ref": "content", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §ncontent§r (§4required§r)", - "§ltype§r: Array", - "§lillustrate§r: Text contents, each item will be a newline.Text that is too long will auto wrap itself. (Supporting Minecraft Formatting Code)" - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "content": [ - "§lDemo§r: [...]", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - }, - { - "type": "textbox", - "ref": "space", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nspace§r (§6optional§r)", - "§ltype§r: Number", - "§ldefault§r: 1", - "§lillustrate§r: The spacing between lines of text." - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "space": 5, - "content": [ - "§lDemo§r: 5", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - },{ - "type": "textbox", - "ref": "fontSize", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nfontSize§r (§6optional§r)", - "§ltype§r: Number", - "§ldefault§r: 9", - "§lillustrate§r: The font size. (Actually it's the height of the font)" - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "fontSize": 5, - "content": [ - "§lDemo§r: 5", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - },{ - "type": "textbox", - "ref": "fontColor", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nfontColor§r (§6optional§r)", - "§ltype§r: Number", - "§ldefault§r: 4278190080", - "§lillustrate§r: The default color of the content. You can also set the colors with special symbols (provided by Minecraft).But maybe you need it sometimes." - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "fontColor": 5, - "content": [ - "§lDemo§r: 4294901760 (0xFFFF0000)", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - }, - { - "type": "textbox", - "ref": "isCenter", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nisCenter§r (§6optional§r)", - "§ltype§r: Boolean", - "§ldefault§r: false", - "§lillustrate§r: Text-align center." - ] - }, - { - "type": "textbox", - "isCenter": false, - "stroke": 4294901760, - "content": [ - "§lDemo§r: false", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - },{ - "type": "textbox", - "ref": "isShadow", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nisShadow§r (§6optional§r)", - "§ltype§r: Boolean", - "§ldefault§r: false", - "§lillustrate§r: Render shadow." - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "isShadow": true, - "content": [ - "§lDemo§r: true", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_3_image.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_3_image.json deleted file mode 100644 index 39f6d14f5ad..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/guide_widget_api/api_3_image.json +++ /dev/null @@ -1,207 +0,0 @@ -{ - "section": "Guide Widget Api", - "title": "2. Image Widget", - "stream": [ - { - "type": "textbox", - "content": [ - "In this page we'll learn how to add an §4§lImage§r. There are three different forms of image supported here: §4Url§r, §4Item§r, and §4ResourceLocation§r. Don't worry, it's easy", - "-------------------------------", - "§lWidget Type§r: §nimage§r", - "-------------------------------", - "§lJSON§r:", - "{", - " \"type\": \"image\",", - " \"form\": \"Item\",", - " \"source\": \"minecraft:ender_pearl\",", - " \"width\": 100,", - " \"height\": 100", - "}", - "-------------------------------", - "§lContents§r" - ] - }, - { - "type": "textbox", - "link": "form", - "content": [ - " 1.§nform§r" - ] - }, - { - "type": "textbox", - "link": "source", - "content": [ - " 2.§nsource§r" - ] - }, - { - "type": "textbox", - "link": "wh", - "content": [ - " 3.§nwidth, height§r" - ] - }, - { - "type": "textbox", - "ref": "form", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nform§r (§4required§r)", - "§ltype§r: String", - "§lillustrate§r: It can only be set one of §4Url§r, §4Item§r, or §4ResourceLocation§r.", - " \"url\" -- image url.", - " \"item\" -- The registered name of the Item in game.", - " \"resource\" -- The resource location." - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"url\"" - ] - }, - { - "type": "image", - "hover_text": ["https://z3.ax1x.com/2021/07/29/Wb4Djs.gif"], - "form": "url", - "source": "https://z3.ax1x.com/2021/07/29/Wb4Djs.gif", - "stroke": 4278190080, - "stroke_width": 2, - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"item\"" - ] - }, - { - "type": "image", - "hover_text": ["minecraft:ender_pearl"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"resource\"" - ] - }, - { - "type": "image", - "hover_text": ["gregtech:textures/gui/icon/multiblock_category.png"], - "form": "resource", - "source": "gregtech:textures/gui/icon/multiblock_category.png", - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "ref": "source", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nsource§r (§4required§r)", - "§ltype§r: String", - "§lillustrate§r: The source of the picture. The three images above correspond to the following sources:" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"https://z3.ax1x.com/2021/07/29/Wb4Djs.gif\"" - ] - }, - { - "type": "image", - "hover_text": ["https://z3.ax1x.com/2021/07/29/Wb4Djs.gif"], - "form": "url", - "source": "https://z3.ax1x.com/2021/07/29/Wb4Djs.gif", - "stroke": 4278190080, - "stroke_width": 2, - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"minecraft:ender_pearl\"" - ] - }, - { - "type": "image", - "hover_text": ["minecraft:ender_pearl"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"gregtech:textures/gui/icon/multiblock_category.png\"" - ] - }, - { - "type": "image", - "hover_text": ["gregtech:textures/gui/icon/multiblock_category.png"], - "form": "resource", - "source": "gregtech:textures/gui/icon/multiblock_category.png", - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "ref": "wh", - "content": [ - "-------------------------------", - "", - "§lAttr§r: §nwidth, height§r (§4required§r)", - "§ltype§r: Integer", - "§lillustrate§r: The Size of the picture." - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"50, 50\"" - ] - }, - { - "type": "image", - "hover_text": ["minecraft:ender_pearl"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 50, - "height": 50 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§lDemo§r: \"100, 50\"" - ] - }, - { - "type": "image", - "hover_text": ["minecraft:ender_pearl"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 100, - "height": 50 - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/important_concepts/machine_grid.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/important_concepts/machine_grid.json deleted file mode 100644 index 31aafa46b30..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/important_concepts/machine_grid.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "section": "Important Concepts", - "title": "Machine Grid", - "stream": [], - "fixed": [] -} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/multiblocks/forming_multiblocks.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/multiblocks/forming_multiblocks.json deleted file mode 100644 index e98245d48a4..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/multiblocks/forming_multiblocks.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "section": "Multiblocks", - "title": "Forming Multiblocks", - "stream": [ - { - "type": "textbox", - "content": [ - "§oThis is a Guide to help you form Multiblocks and troubleshoot issues.§r\n\nThere are two really important factors to know when building Multiblocks.\n\n§lCheck the JEI preview:§r This one was probably obvious, but there\u0027s more than just a picture of how the Multiblock looks like! Use your mouse to §drotate§r the preview, §9hover over the parts§r to gain additional informations. The JEI page also contains the amount of blocks to build it. You can also §dright-click§r a block in the preview to get a display of all available blocks in that placement.\n\n\n§lThe JEI preview is a suggestion:§r There is no unique way to form the Multiblock. Most of the time, you have complete freedom for the §9tier of Buses/Hatches§r. And you also have the §dfreedom of placement§r.\n\nTaking the EBF as example, any tier of Energy/Bus/Hatch can be used, and they can be placed anywhere replacing a casing. Fluid Hatches are also optional, though you probably want them to handle recipes with fluid.\n\nAdditionally, you can §dsneak right-click§r the multiblock controller for an §6in-world preview§r, or use the §4Terminal§r\u0027s Multiblock Helper." - ] - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/multiblocks/large_turbine_mechanics.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/multiblocks/large_turbine_mechanics.json deleted file mode 100644 index a96702086bc..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/multiblocks/large_turbine_mechanics.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "section": "Multiblocks", - "title": "Large Turbine Mechanics", - "stream": [ - { - "type": "textbox", - "content": [ - "§oThe Large Turbines are the most complex Multiblock Generators there exists in GTCEu in the present day.§r\n\nLet\u0027s start with the §4drawbacks§r of §3Large Turbines§r:\n§9-§r They work off §cInertia§r, which requires continuous running to achieve maximum Power.\n§9-§r Any excess unconsumed Energy produced will be §cvoided§r. So ideally you want to use large Energy buffers, and possibly control your Turbines with a redstone RS latch type of deal.\n§9-§r They require a §aRotor§r which loses durability over time and eventually §cbreak§r.\n§9-§r A little bit of Math is required to get the expected results.\n\n\nNow, with the §6upsides§r:\n§9-§r They can scale §9Power§r production substancially higher than the base output thanks to tiered §3Rotor Holders§r.\n§9-§r The §aRotor§r can give a huge boost to §dFuel efficiency§r, and §9Power§r production.\n§9-§r Self satisfaction for setting them up properly (yay!).\n\n\n§3Rotor Holders§r above the tier of the §3Large Turbine§r will §6double§r the production for every tier, multiplicatively.\n§3Rotor Holders§r above the tier of the §3Large Turbine§r will increase the efficiency by 10% for every tier, additively.\n\n§aRotors§r have a §9Power§r, §dEfficiency§r and §4Durability§r that are based on tool stats.\n§9Power§r multiplies the production of the §3Turbine§r. This stacks multiplicatively with the §3Rotor Holder§r.\n§dEfficiency§r reduces the fuel consumption. This stacks multiplicatively with the §3Rotor Holder§r.\n§4Durability§r is the lifetime of the §aRotor§r in seconds, when the §3Turbine§r is active.\n\n\n§2§lIn summary:§r\n\nThe §9Power§r output affects both the fuel consumption and the EU/t generation. It is calculated with the following formula:\n§cproduction \u003d baseEUt §l*§r rotorPower §l*§r 2^(rotorHolderTier - turbineTier)§r\n\nThe §dEfficiency§r reduces the fuel consumption, but does not alter the EU/t generation. It is calculated with the following formula:\n§cefficiency \u003d rotorEfficiency §l*§r (1 + 0.1 §l*§r (rotorHolderTier - turbineTier))§r\n\n\n§2§lSome examples:§r\n\nLarge Steam Turbine, with Ultimet Rotor and EV Rotor Holder:\nProduction \u003d 1024 §l*§r 1.60 §l*§r 2 \u003d 3276 EU/t\nEfficiency \u003d 1.30 §l*§r 1.10 \u003d 143%\n(Steam consumption \u003d 4582 L/t, this is above a Titanium Boiler, or a TungstenSteel Boiler with §m70% throttle)\n\nLarge Gas Turbine, with Chrome Rotor and EV Rotor Holder:\nProduction \u003d 4096 §l*§r 1.70 §l*§r 1 \u003d 5325 EU/t\nEfficiency \u003d 1.55 §l*§r 1.00 \u003d 155%\n(The same fuel consumption would produce 3435 EU/t using 6.7 Turbo Gas Turbines)\n\nLarge Plasma Turbine, with HSS-S Rotor and ZPM Rotor Holder:\nProduction \u003d 16834 §l*§r 2.50 §l*§r 4 \u003d 168340 EU/t\nEfficiency \u003d 1.80 §l*§r 1.20 \u003d 216%\n(This is more than a ZPM Amp!)" - ] - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/multiblocks/multibock_troubleshooting.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/multiblocks/multibock_troubleshooting.json deleted file mode 100644 index 096c157438a..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/multiblocks/multibock_troubleshooting.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "section": "Multiblocks", - "title": "Multiblock Troubleshooting", - "stream": [ - { - "type": "textbox", - "content": [ - "If a multiblock is formed, but you are having troubles figuring out why it does not run:\n§9-§r Check if the Multiblock is properly plugged in (we all make these mistakes!).\n\n§9-§r Do the initial Maintenance fix.\n\n§9-§r Verify the recipe usage, the max EU/t has to be greater than that of the recipe.\n\n§9- §rCheck the special requirements the recipe may have (JEI always has some kind of indication for it).\n\n§9-§r Make sure the recipe is properly input, this is less obvious than in a regular machine because you have to juggle between Input Bus and Input Hatch.\n\n§9-§r Make sure there is space for output. Maybe the multiblock formed but you forgot a Hatch. The other biggest offender is the Output Hatches being too low tier and having too little capacity!" - ] - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/resource_pack/emissive_texture.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/resource_pack/emissive_texture.json deleted file mode 100644 index 752ae4248f0..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/resource_pack/emissive_texture.json +++ /dev/null @@ -1,135 +0,0 @@ -{ - "section": "Resource Pack", - "title": "Custom Emissive Texture", - "stream": [ - { - "type": "textbox", - "content": [ - "Developers and resource pack authors can easily have emissive textures and set the bloom effect.\n\n§lContents:" - ] - }, - { - "type": "textbox", - "link": "emissive", - "content": [ - "1. §1Emissive Texture" - ] - }, - { - "type": "textbox", - "link": "bloom", - "content": [ - "2.§1 Bloom" - ] - }, - { - "type": "textbox", - "link": "demo", - "content": [ - "3. §1Demo" - ] - }, - { - "type": "textbox", - "ref": "emissive", - "content": [ - "§lEmissive Texture" - ] - }, - { - "type": "textbox", - "content": [ - "* For model-based blocks: Similar to §4CTM§r, you only need to set mcmeta file for the texture that you want to have the emissive effect." - ] - }, - { - "type": "card", - "fill": -3745585, - "width": 190, - "height": 100, - "isShadow": true - }, - { - "type": "textbox", - "content": [ - "§2light §rhere represents the default level of light it emit (from 0~15). Besides, you can also set sky and block separately as what CTM does." - ] - }, - { - "type": "textbox", - "content": [ - "* For CEu machines: They mostly are overlay textures under the assets/textures/blocks/machines and assets/textures/overlay/machines. You no need to set the mcmeta file for them. Just add a new texture file for the emissive part named \"XXX_emissive.png\"." - ] - }, - { - "type": "textbox", - "content": [ - "§lBloom" - ], - "ref": "bloom" - }, - { - "type": "textbox", - "content": [ - "* For CEu machines: You don\u0027t need to modify anything; all emissive textures have the bloom effect by default.\n\n* For model-based blocks: You just need to add an extra line to the mcmeta file. (§2\"layer\"§r: \"BLOOM\")" - ] - }, - { - "type": "card", - "fill": -3745585, - "width": 190, - "height": 110, - "isShadow": true - }, - { - "type": "textbox", - "ref": "demo", - "content": [ - "§lDemo" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/138578815-d2d4e357-8080-4d57-b8ac-61235eac8c2a.png", - "width": 190, - "height": 130 - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/138578838-b9e6a16d-e348-4fea-8ab4-8a940e1ecd0f.png", - "width": 190, - "height": 100 - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/138578853-9a2497f4-e1f5-45e9-ab64-26b5eb859139.png", - "width": 190, - "height": 110 - } - ], - "fixed": [ - { - "type": "textbox", - "x": 8, - "y": 206, - "width": 181, - "height": 90, - "content": [ - "{\n §2\"ctm\"§r: {\n §2\"ctm_version\"§r: 1,\n §2\"gregtech:§r true,\n §2\"extra\"§r: {\n §2\"light\"§r: 15\n }\n }\n}" - ] - }, - { - "type": "textbox", - "x": 8, - "y": 550, - "width": 181, - "height": 100, - "content": [ - "{\n §2\"ctm\"§r: {\n §2\"ctm_version\"§r: 1,\n §2\"layer\"§r: \"BLOOM\",\n §2\"gregtech\"§r true,\n §2\"extra\"§r: {\n §2\"light\"§r: 15\n }\n }\n}" - ] - } - ] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/terminal/terminal_hardware.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/terminal/terminal_hardware.json deleted file mode 100644 index 3a9c51f4a73..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/en_us/terminal/terminal_hardware.json +++ /dev/null @@ -1,223 +0,0 @@ -{ - "section": "Terminal", - "title": "Hardware", - "stream": [ - { - "type": "textbox", - "content": [ - "Current supported §4§lhardware§r:" - ] - }, - { - "type": "textbox", - "link": "battery", - "content": [ - " 1.§nBattery" - ] - }, - { - "type": "textbox", - "link": "device", - "content": [ - " 2.§nDevice" - ] - }, - { - "type": "textbox", - "isCenter": true, - "isShadow": false, - "content": [ - "§lBattery" - ], - "ref": "battery" - }, - { - "type": "card", - "fill": -2172721, - "width": 170, - "height": 90, - "isShadow": true - }, - { - "type": "textbox", - "ref": "device", - "isCenter": true, - "content": [ - "\n\n§lDevice" - ] - }, - { - "type": "card", - "fill": -2172721, - "width": 170, - "height": 133, - "isShadow": true - } - ], - "fixed": [ - { - "type": "textbox", - "x": 18, - "y": 92, - "width": 160, - "height": 30, - "content": [ - "All §4§lresuable§r batteries can be used as the §lBattery Hardware" - ] - }, - { - "type": "textbox", - "x": 53, - "y": 229, - "width": 102, - "height": 10, - "content": [ - "Wireless transmitter" - ] - }, - { - "type": "slots", - "x": 47, - "y": 136, - "width": 100, - "height": 18, - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 732, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 733, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 742, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 748, - "count": 1 - }, - { - "id": "gregtech:meta_item_1", - "damage": 753, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": -16, - "y": 224, - "width": 100, - "height": 18, - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 503, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": -16, - "y": 250, - "width": 100, - "height": 18, - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 466, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 52, - "y": 253, - "width": 100, - "height": 10, - "content": [ - "Prospector" - ] - }, - { - "type": "textbox", - "x": 52, - "y": 279, - "width": 100, - "height": 10, - "content": [ - "Solar" - ] - }, - { - "type": "slots", - "x": 10, - "y": 325, - "width": 48, - "height": 18, - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 467, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 12, - "y": 275, - "width": 45, - "height": 18, - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 333, - "count": 1 - } - ] - }, - { - "type": "slots", - "x": 22, - "y": 302, - "width": 25, - "height": 18, - "item_list": [ - { - "id": "gregtech:meta_item_1", - "damage": 504, - "count": 1 - } - ] - }, - { - "type": "textbox", - "x": 52, - "y": 306, - "width": 100, - "height": 10, - "content": [ - "Camera" - ] - }, - { - "type": "textbox", - "x": 51, - "y": 325, - "width": 100, - "height": 20, - "content": [ - "Advanced Prospector" - ] - } - ] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/crafttweaker/terminal/ct_terminal_01.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/crafttweaker/terminal/ct_terminal_01.json deleted file mode 100644 index d787b384e06..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/crafttweaker/terminal/ct_terminal_01.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "section": "CraftTweaker/终端", - "title": "终端的CT教程", - "stream": [ - { - "type": "textbox", - "content": [ - "目录:" - ] - }, - { - "type": "textbox", - "content": [ - "§1§lURL:§r§n https://github.com/Gregicality/GregTech/wiki/CraftTweaker-of-Terminal" - ] - }, - { - "type": "textbox", - "ref": "api", - "isShadow": false, - "content": [ - "§4§lAPI:" - ] - }, - { - "type": "textbox", - "fontSize": 9, - "content": [ - "1. §1registerDevice(deviceItemStack, deviceName)§0:\n注册自定义设备。\n\n2. §1createAppRegistryBuilder(appName):\n§0根据应用名称(可从商店获取)获得构造器。\n\n3. §1isDefaultApp(default):\n§0设置为默认应用。\n\n4. §1battery(euTier, cost):\n§0为所有层级设置相同的电池要求。\n\n5. §1battery(appTier, euTier, cost):\n§0为特定等级设置电池要求。\n\n6. §1device(deviceName...):\n§0为所有等级设置设备要求。 (默认可用设备: \"scanner\", \"wireless\", \"camera\", \"solar_lv\").\n\n7. §1device(appTier, device...):\n§0为特定等级设置设备要求。\n\n8. §1upgrade(upgradeItemStack...):\n§0设置所有等级的升级要求。\n\n9. §1upgrade(appTier, upgradeItemStack...):\n§0设置特定等级的升级和要求。\n\n10. §1build():\n§0完成并注册。" - ] - }, - { - "type": "textbox", - "ref": "demo", - "space": 1, - "content": [ - "\n§4§lZS Demo:" - ] - }, - { - "type": "textbox", - "fill": -912478525, - "fontSize": 9, - "content": [ - "import mods.gregtech.TerminalRegistry;\n\nTerminalRegistry.registerDevice(\u003core:ingotIron\u003e.firstItem, \"ingot_iron\");\n\nTerminalRegistry.createAppRegistryBuilder(\"ore_prospector\")\n .isDefaultApp(true)\n .battery(1, 500)\n .battery(3, 3, 1000)\n .device(\"camera\", \"wireless\")\n .device(4, \"ingot_iron\")\n .upgrade(\u003cminecraft:apple\u003e * 9)\n .upgrade(2, \u003cminecraft:apple\u003e * 9, \u003cminecraft:grass\u003e * 12)\n .build();" - ] - }, - { - "type": "textbox", - "fontSize": 9, - "content": [ - "§4§l结果:\n§r自定义设备" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/140280593-37922838-4a20-4e1b-9be9-73935c4c8c13.png", - "width": 190, - "height": 120 - }, - { - "type": "textbox", - "content": [ - "注册电池、设备、升级" - ] - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/140280587-84dc8f67-6dde-472f-9ed8-6a4c5e71abc4.png", - "width": 190, - "height": 120 - }, - { - "type": "image", - "form": "url", - "source": "https://user-images.githubusercontent.com/18493855/140280590-d4700a88-5780-4e0f-95f8-130e82f4634a.png", - "width": 190, - "height": 120 - } - ], - "fixed": [ - { - "type": "textbox", - "x": 27, - "y": 24, - "width": 16, - "height": 10, - "link": "api", - "content": [ - "§9§napi" - ] - }, - { - "type": "textbox", - "x": 41, - "y": 24, - "width": 25, - "height": 10, - "link": "demo", - "content": [ - "§9§ndemo" - ] - } - ] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_0_guidepage.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_0_guidepage.json deleted file mode 100644 index c501c92ca8c..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_0_guidepage.json +++ /dev/null @@ -1,148 +0,0 @@ -{ - "section": "指南页控件API", - "title": "指南页", - "stream": [ - { - "type": "textbox", - "content": [ - "这一页我们将学习如何编写指南页。", - "-------------------------------", - "先看一看一个简单里指南页示例。", - "§lJSON§r:", - "{", - " \"section\": \"section name here\",", - " \"title\": \"title here\",", - " \"stream\": [", - " {", - " \"type\": \"textbox\",", - " \"content\": [\"TextBox widget\"]", - " }", - " ],", - " \"fixed\": [", - " {", - " \"x\": 50,", - " \"y\": 100,", - " \"width\": 150,", - " \"height\": 40,", - " \"type\": 0,", - " \"content\": [\"TextBox widget\"]", - " }", - " ]", - "}", - "-------------------------------", - "§l目录§r" - ] - }, - { - "type": "textbox", - "link": "section", - "content": [ - " 1.§nsection§r" - ] - }, - { - "type": "textbox", - "link": "title", - "content": [ - " 2.§ntitle§r" - ] - }, - { - "type": "textbox", - "link": "stream", - "content": [ - " 3.§nstream§r" - ] - }, - { - "type": "textbox", - "link": "fixed", - "content": [ - " 4.§nfixed§r" - ] - }, - { - "type": "textbox", - "ref": "section", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nsection§r (§4必须§r)", - "§l类型§r: String", - "§l说明§r: 指定页面属于哪个章节。", - "指南App会自动合并具有相同节名的页面并构建目录树。" - ] - }, - { - "type": "textbox", - "ref": "title", - "content": [ - "-------------------------------", - "", - "§l属性§r: §ntitle§r (§4必须§r)", - "§l类型§r: String", - "§l说明§r: 页标题。" - ] - }, - { - "type": "textbox", - "ref": "stream", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nstream§r (§4必须§r)", - "§l类型§r: Array", - "§l说明§r: 属于流布局的控件。 你不需要关心控件在流中的位置和大小,所有的排版都会自动完成。" - ] - }, - { - "type": "textbox", - "ref": "fixed", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nfixed§r (§4必须§r)", - "§l类型§r: Array", - "§l说明§r: 属于固定布局的控件。 您需要指定每个控件的位置和大小。" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: 固定布局和流布局" - ] - }, - { - "type": "textbox", - "isCenter": true, - "hover_text": ["流布局"], - "content": [ - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - } - ], - "fixed": [ - { - "type": "image", - "x": 30, - "y": 800, - "stroke": 4278190335, - "hover_text": ["固定布局", "\"x\": 30","\"y\": 800","\"width\": 100","\"width\": 100"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 100, - "height": 100 - } - ] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_1_widget.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_1_widget.json deleted file mode 100644 index a1575f6685e..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_1_widget.json +++ /dev/null @@ -1,304 +0,0 @@ -{ - "section": "指南页控件API", - "title": "控件", - "stream": [ - { - "type": "textbox", - "content": [ - "这里我们将学习什么是 §4§l控件§r, 以及它的公共属性。", - "控件被渲染在指南页中,是一切的基础。 §n文本控件§r, §n图片控件§r, 等等", - "要使用控件,只需要将对应的控件配置写在 §l\"fixed\"§r 或者 §l\"stream\"§r下即可。", - "有一些公共属性、效果(样式)对所有控件都有效。", - "-------------------------------", - "§lJSON§r:", - "{", - " \"type\": \"type here\",", - " \"x\": 50,", - " \"y\": 100,", - " \"width\": 150,", - " \"height\": 40,", - " \"ref\": \"ref\",", - " \"stroke\": 0,", - " \"stroke_width\": 1,", - " \"fill\": 0,", - " \"link\": \"ref\"", - " \"hover_text\": [\"text here\"]", - "}", - "-------------------------------", - "§l目录§r" - ] - }, - { - "type": "textbox", - "link": "type", - "content": [ - " 1.§ntype§r" - ] - }, - { - "type": "textbox", - "link": "xywh", - "content": [ - " 2.§nx, y, width, height§r" - ] - }, - { - "type": "textbox", - "link": "ref", - "content": [ - " 3.§nref§r" - ] - }, - { - "type": "textbox", - "link": "fill", - "content": [ - " 4.§nfill§r" - ] - }, - { - "type": "textbox", - "link": "stroke", - "content": [ - " 5.§nstroke§r" - ] - }, - { - "type": "textbox", - "link": "stroke_width", - "content": [ - " 6.§nstroke_width§r" - ] - }, - { - "type": "textbox", - "link": "link", - "content": [ - " 7.§nlink§r" - ] - }, - { - "type": "textbox", - "link": "hover", - "content": [ - " 8.§nhover_text§r" - ] - }, - { - "type": "textbox", - "ref": "type", - "content": [ - "-------------------------------", - "", - "§l属性§r: §ntype§r (§4必须§r)", - "§l类型§r: String", - "§l说明§r: 控件类型的唯一标识。通过api文档可以查看控件对应的控件类型标识。" - ] - }, - { - "type": "textbox", - "ref": "xywh", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nx, y, width, height§r (§4可选§r)", - "§l类型§r: Integer", - "§l说明§r: 控件的位置和大小。 在流布局中,通常不需要设置它(图片控件需要设置宽度和高度)。 在固定布局下,你必须设置这四个属性。" - ] - }, - { - "type": "textbox", - "ref": "ref", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nref§r (§4可选§r)", - "§l类型§r: String", - "§l缺省值§r: null", - "§l说明§r: 这是这个控件的一个引用标记。 同一页中的引用标记应该是唯一的。" - ] - }, - { - "type": "textbox", - "ref": "fill", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nfill§r (§6可选§r)", - "§l类型§r: Number", - "§l缺省值§r: 0", - "§l说明§r: 背景颜色。" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: 4278190335 (0xFF0000FF)" - ] - }, - { - "type": "textbox", - "isCenter": true, - "fill": 4278190335, - "content": [ - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - }, - { - "type": "textbox", - "ref": "stroke", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nstroke§r (§6可选§r)", - "§l类型§r: Number", - "§l缺省值§r: 0", - "§l说明§r: 边框颜色" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: 4278190335 (0xFF0000FF)" - ] - }, - { - "type": "image", - "form": "item", - "source": "minecraft:ender_pearl", - "stroke": 4278190335, - "width": 50, - "height": 50 - }, - { - "type": "textbox", - "ref": "stroke_width", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nstroke_width§r (§6可选§r)", - "§l类型§r: Number", - "§l缺省值§r: 1", - "§l说明§r: 边框宽度。" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: 5" - ] - }, - { - "type": "image", - "form": "item", - "source": "minecraft:ender_pearl", - "stroke": 4278190335, - "stroke_width": 5, - "width": 50, - "height": 50 - }, - { - "type": "textbox", - "ref": "link", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nlink§r (§6可选§r)", - "§l类型§r: String", - "§l缺省值§r: null", - "§l说明§r: 单击可跳转到指定引用的位置。需要与引用标记一起使用,目标是ref。" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"P2\"" - ] - }, - { - "type": "textbox", - "isCenter": true, - "fill": 4286430975, - "hover_text": ["\"ref\": \"P1\""], - "ref": "P1", - "link": "P2", - "content": ["点我!"] - }, - { - "type": "textbox", - "content": [ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"P1\"" - ] - }, - { - "type": "textbox", - "isCenter": true, - "fill": 4286430975, - "hover_text": ["\"ref\": \"P2\""], - "ref": "P2", - "link": "P1", - "content": ["点我!"] - }, - { - "type": "textbox", - "ref": "hover", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nhover_text§r (§6可选§r)", - "§l类型§r: Array", - "§l缺省值§r: null", - "§l说明§r: 鼠标悬停时的展示文本。" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: [\"这是\",\"GT图标\"]" - ] - }, - { - "type": "image", - "hover_text": ["这是","GT图标"], - "form": "resource", - "source": "gregtech:textures/gui/icon/gregtech_logo.png", - "width": 100, - "height": 100 - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_2_textbox.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_2_textbox.json deleted file mode 100644 index 83c645bd0c2..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_2_textbox.json +++ /dev/null @@ -1,256 +0,0 @@ -{ - "section": "指南页控件API", - "title": "1. 文本控件", - "stream": [ - { - "type": "textbox", - "content": [ - "我们将学习指南中最常用的控件 §4§l文本控件§r。 因此,您应该仔细阅读API文档。", - "-------------------------------", - "§l控件类型标识§r: §ntextbox§r", - "-------------------------------", - "§lJSON§r:", - "{", - " \"type\": \"textbox\",", - " \"space\": 1,", - " \"fontSize\": 9,", - " \"fontColor\": 4278190080,", - " \"isCenter\": false,", - " \"isShadow\": false,", - " \"content\": [\"content here!\"]", - "}", - "-------------------------------", - "§l目录§r" - ] - }, - { - "type": "textbox", - "link": "content", - "content": [ - " 1.§ncontent§r" - ] - }, - { - "type": "textbox", - "link": "space", - "content": [ - " 2.§nspace§r" - ] - }, - { - "type": "textbox", - "link": "fontSize", - "content": [ - " 3.§nfontSize§r" - ] - }, - { - "type": "textbox", - "link": "fontColor", - "content": [ - " 4.§nfontColor§r" - ] - }, - { - "type": "textbox", - "link": "isCenter", - "content": [ - " 5.§nisCenter§r" - ] - }, - { - "type": "textbox", - "link": "isShadow", - "content": [ - " 6.§nisShadow§r" - ] - }, - { - "type": "textbox", - "ref": "content", - "content": [ - "-------------------------------", - "", - "§l属性§r: §ncontent§r (§4必须§r)", - "§l类型§r: Array", - "§l说明§r: 文本内容数组,每一项都会换行。 文本太长会自动换行。 (支持Minecraft格式代码) " - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "content": [ - "§l示例§r: [...]", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - }, - { - "type": "textbox", - "ref": "space", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nspace§r (§6可选§r)", - "§l类型§r: Number", - "§l缺省值§r: 1", - "§l说明§r: 文本行之间的间隔。" - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "space": 5, - "content": [ - "§l示例§r: 5", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - },{ - "type": "textbox", - "ref": "fontSize", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nfontSize§r (§6可选§r)", - "§l类型§r: Number", - "§l缺省值§r: 9", - "§l说明§r: 字体大小。(实际上是字体的高度)" - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "fontSize": 5, - "content": [ - "§l示例§r: 5", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - },{ - "type": "textbox", - "ref": "fontColor", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nfontColor§r (§6可选§r)", - "§l类型§r: Number", - "§l缺省值§r: 4278190080", - "§l说明§r: 文本的默认颜色。你也可以用特殊的符号设置颜色(Minecraft提供的)。但也许有时候你需要它。" - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "fontColor": 5, - "content": [ - "§l示例§r: 4294901760 (0xFFFF0000)", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - }, - { - "type": "textbox", - "ref": "isCenter", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nisCenter§r (§6可选§r)", - "§l类型§r: Boolean", - "§l缺省值§r: false", - "§l说明§r: 文本水平居中。" - ] - }, - { - "type": "textbox", - "isCenter": false, - "stroke": 4294901760, - "content": [ - "§l示例§r: false", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - },{ - "type": "textbox", - "ref": "isShadow", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nisShadow§r (§6可选§r)", - "§l类型§r: Boolean", - "§l缺省值§r: false", - "§l说明§r: 渲染文本阴影。" - ] - }, - { - "type": "textbox", - "isCenter": true, - "stroke": 4294901760, - "isShadow": true, - "content": [ - "§l示例§r: true", - "§nMinecraft Formatting", - "§r§00 §11 §22 §33", - "§44 §55 §66 §77", - "§88 §99 §aa §bb", - "§cc §dd §ee §ff", - "§r§0k §kMinecraft", - "§rl §lMinecraft", - "§rm §mMinecraft", - "§rn §nMinecraft", - "§ro §oMinecraft", - "§rr §rMinecraft" - ] - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_3_image.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_3_image.json deleted file mode 100644 index 9098438adb2..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/guide_widget_api/api_3_image.json +++ /dev/null @@ -1,207 +0,0 @@ -{ - "section": "指南页控件API", - "title": "2. 图片控件", - "stream": [ - { - "type": "textbox", - "content": [ - "我们将学习实用的§4§l图片控件§r。这里支持三种不同形式的图像:§4Url§r, §4Item§r, and §4ResourceLocation§r。别担心,一切都很容易。", - "-------------------------------", - "§l控件类型标识§r: §nimage§r", - "-------------------------------", - "§lJSON§r:", - "{", - " \"type\": \"image\",", - " \"form\": \"Item\",", - " \"source\": \"minecraft:ender_pearl\",", - " \"width\": 100,", - " \"height\": 100", - "}", - "-------------------------------", - "§l目录§r" - ] - }, - { - "type": "textbox", - "link": "form", - "content": [ - " 1.§nform§r" - ] - }, - { - "type": "textbox", - "link": "source", - "content": [ - " 2.§nsource§r" - ] - }, - { - "type": "textbox", - "link": "wh", - "content": [ - " 3.§nwidth, height§r" - ] - }, - { - "type": "textbox", - "ref": "form", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nform§r (§4必须§r)", - "§l类型§r: String", - "§l说明§r: 它只能是 §4Url§r, §4Item§r, 或 §4ResourceLocation§r中的一个。", - " \"url\" -- image url.", - " \"item\" -- The registered name of the Item in game.", - " \"resource\" -- The resource location." - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"url\"" - ] - }, - { - "type": "image", - "hover_text": ["https://z3.ax1x.com/2021/07/29/Wb4Djs.gif"], - "form": "url", - "source": "https://z3.ax1x.com/2021/07/29/Wb4Djs.gif", - "stroke": 4278190080, - "stroke_width": 2, - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"item\"" - ] - }, - { - "type": "image", - "hover_text": ["minecraft:ender_pearl"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"resource\"" - ] - }, - { - "type": "image", - "hover_text": ["gregtech:textures/gui/icon/coke_oven.png"], - "form": "resource", - "source": "gregtech:textures/gui/icon/coke_oven.png", - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "ref": "source", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nsource§r (§4必须§r)", - "§l类型§r: String", - "§l说明§r: The source of the picture. The three images above correspond to the following sources:" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"https://z3.ax1x.com/2021/07/29/Wb4Djs.gif\"" - ] - }, - { - "type": "image", - "hover_text": ["https://z3.ax1x.com/2021/07/29/Wb4Djs.gif"], - "form": "url", - "source": "https://z3.ax1x.com/2021/07/29/Wb4Djs.gif", - "stroke": 4278190080, - "stroke_width": 2, - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"minecraft:ender_pearl\"" - ] - }, - { - "type": "image", - "hover_text": ["minecraft:ender_pearl"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"gregtech:textures/gui/icon/coke_oven.png\"" - ] - }, - { - "type": "image", - "hover_text": ["gregtech:textures/gui/icon/coke_oven.png"], - "form": "resource", - "source": "gregtech:textures/gui/icon/coke_oven.png", - "width": 100, - "height": 100 - }, - { - "type": "textbox", - "ref": "wh", - "content": [ - "-------------------------------", - "", - "§l属性§r: §nwidth, height§r (§4必须§r)", - "§l类型§r: Integer", - "§l说明§r: 图片尺寸。" - ] - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"50, 50\"" - ] - }, - { - "type": "image", - "hover_text": ["minecraft:ender_pearl"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 50, - "height": 50 - }, - { - "type": "textbox", - "isCenter": true, - "content": [ - "§l示例§r: \"100, 50\"" - ] - }, - { - "type": "image", - "hover_text": ["minecraft:ender_pearl"], - "form": "item", - "source": "minecraft:ender_pearl", - "width": 100, - "height": 50 - } - ], - "fixed": [] -} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/resource_pack/emissive_texture.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/resource_pack/emissive_texture.json deleted file mode 100644 index dfef1a0bd48..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/resource_pack/emissive_texture.json +++ /dev/null @@ -1 +0,0 @@ -{"section":"资源包","title":"自定义发光材质","stream":[{"type":"textbox","content":["开发人员和资源包作者可以很容易地有发光材质和设置泛光效果。\n\n§l目录:"]},{"type":"textbox","link":"emissive","content":["1. §1发光材质"]},{"type":"textbox","link":"bloom","content":["2.§1 泛光"]},{"type":"textbox","link":"demo","content":["3. §1示例"]},{"type":"textbox","ref":"emissive","content":["§l发光材质"]},{"type":"textbox","content":["* 对于常规模型: 与§4CTM§r相似,你只需要为你想要有发射效果的材质配置mcmeta文件即可。"]},{"type":"card","fill":-3745585,"width":190,"height":100,"isShadow":true},{"type":"textbox","content":["这里的§2light §r表示它发出的默认光级别(从0~15)。另外,你也可以像CTM一样把sky和block分开设置。"]},{"type":"textbox","content":["* 对于CEu机器: 他们材质大多数在 assets/textures/blocks/machines 和 assets/textures/overlay/machines下。 你不需要为他们设置mcmeta文件。只需为发光部分添加一个名为 \"XXX_emissive.png\"的材质即可。"]},{"type":"textbox","content":["§l泛光"],"ref":"bloom"},{"type":"textbox","content":["* 对于CEu机器: 你不需要修改任何东西,所有发光的材质都自带泛光。\n\n* 对于基本模型: 你只需要在mcmeta文件中添加额外的一行。 (§2\"layer\"§r: \"BLOOM\")"]},{"type":"card","fill":-3745585,"width":190,"height":110,"isShadow":true},{"type":"textbox","ref":"demo","content":["§l示例"]},{"type":"image","form":"url","source":"https://user-images.githubusercontent.com/18493855/138578815-d2d4e357-8080-4d57-b8ac-61235eac8c2a.png","width":190,"height":130},{"type":"image","form":"url","source":"https://user-images.githubusercontent.com/18493855/138578838-b9e6a16d-e348-4fea-8ab4-8a940e1ecd0f.png","width":190,"height":100},{"type":"image","form":"url","source":"https://user-images.githubusercontent.com/18493855/138578853-9a2497f4-e1f5-45e9-ab64-26b5eb859139.png","width":190,"height":110}],"fixed":[{"type":"textbox","x":8,"y":171,"width":181,"height":90,"content":["{\n §2\"ctm\"§r: {\n §2\"ctm_version\"§r: 1,\n §2\"gregtech:§r true,\n §2\"extra\"§r: {\n §2\"light\"§r: 15\n }\n }\n}"]},{"type":"textbox","x":7,"y":466,"width":181,"height":100,"content":["{\n §2\"ctm\"§r: {\n §2\"ctm_version\"§r: 1,\n §2\"layer\"§r: \"BLOOM\",\n §2\"gregtech\"§r true,\n §2\"extra\"§r: {\n §2\"light\"§r: 15\n }\n }\n}"]}]} diff --git a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/terminal/terminal_hardware.json b/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/terminal/terminal_hardware.json deleted file mode 100644 index ebfa5647886..00000000000 --- a/src/main/resources/assets/gregtech/terminal/guide/tutorials/zh_cn/terminal/terminal_hardware.json +++ /dev/null @@ -1 +0,0 @@ -{"section":"终端","title":"Hardware","stream":[{"type":"textbox","content":["Current supported §4§lhardware§r:"]},{"type":"textbox","link":"battery","content":[" 1.§nBattery"]},{"type":"textbox","link":"device","content":[" 2.§nDevice"]},{"type":"textbox","isCenter":true,"isShadow":false,"content":["§lBattery"],"ref":"battery"},{"type":"card","fill":-2172721,"width":170,"height":90,"isShadow":true},{"type":"textbox","ref":"device","isCenter":true,"content":["\n\n§lDevice"]},{"type":"card","fill":-2172721,"width":170,"height":113,"isShadow":true}],"fixed":[{"type":"textbox","x":18,"y":92,"width":160,"height":30,"content":["All §4§lresuable§r batteries could be used as the §lBattery Hardware"]},{"type":"textbox","x":53,"y":229,"width":102,"height":10,"content":["Wireless transmitter"]},{"type":"slots","x":47,"y":136,"width":100,"height":18,"item_list":[{"id":"gregtech:meta_item_1","damage":732,"count":1},{"id":"gregtech:meta_item_1","damage":733,"count":1},{"id":"gregtech:meta_item_1","damage":742,"count":1},{"id":"gregtech:meta_item_1","damage":748,"count":1},{"id":"gregtech:meta_item_1","damage":753,"count":1}]},{"type":"slots","x":-16,"y":224,"width":100,"height":18,"item_list":[{"id":"gregtech:meta_item_1","damage":468,"count":1}]},{"type":"slots","x":-16,"y":250,"width":100,"height":18,"item_list":[{"id":"gregtech:meta_item_1","damage":465,"count":1}]},{"type":"textbox","x":52,"y":253,"width":100,"height":10,"content":["Scanner"]},{"type":"textbox","x":52,"y":279,"width":100,"height":10,"content":["Solar"]},{"type":"slots","x":12,"y":275,"width":45,"height":18,"item_list":[{"id":"gregtech:meta_item_1","damage":333,"count":1}]},{"type":"slots","x":22,"y":302,"width":25,"height":18,"item_list":[{"id":"gregtech:meta_item_1","damage":469,"count":1}]},{"type":"textbox","x":52,"y":306,"width":100,"height":10,"content":["Camera"]}]} diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active.png new file mode 100644 index 00000000000..bcaa1934780 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active.png.mcmeta b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active.png.mcmeta new file mode 100644 index 00000000000..60af678259b --- /dev/null +++ b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active.png.mcmeta @@ -0,0 +1,5 @@ +{ + "animation":{ + "frametime":4 + } +} \ No newline at end of file diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active_emissive.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active_emissive.png new file mode 100644 index 00000000000..f3d2b53db29 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active_emissive.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active_emissive.png.mcmeta b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active_emissive.png.mcmeta new file mode 100644 index 00000000000..f70648e7b1b --- /dev/null +++ b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_active_emissive.png.mcmeta @@ -0,0 +1,14 @@ +{ + "ctm": { + "ctm_version": 1, + "type": "CTM", + "layer": "BLOOM", + "gregtech": true, + "textures": [ + "gregtech:blocks/casings/quantum/controller_active_emissive" + ] + }, + "animation":{ + "frametime":4 + } +} diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_active.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_active.png new file mode 100644 index 00000000000..6c93d14ea6b Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_active.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_active_emissive.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_active_emissive.png new file mode 100644 index 00000000000..10af88febdf Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_active_emissive.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_active_emissive.png.mcmeta b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_active_emissive.png.mcmeta new file mode 100644 index 00000000000..4e8c6493e99 --- /dev/null +++ b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_active_emissive.png.mcmeta @@ -0,0 +1,5 @@ +{ + "animation": { + "frametime": 8 + } +} diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_inactive.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_inactive.png new file mode 100644 index 00000000000..6c93d14ea6b Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_front_inactive.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_inactive.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_inactive.png new file mode 100644 index 00000000000..2c3e0d025d4 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/controller_inactive.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender.png new file mode 100644 index 00000000000..b79e381d3ef Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender_active.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender_active.png new file mode 100644 index 00000000000..e77eec21401 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender_active.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender_active_emissive.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender_active_emissive.png new file mode 100644 index 00000000000..3e2be0d612a Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender_active_emissive.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender_active_emissive.png.mcmeta b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender_active_emissive.png.mcmeta new file mode 100644 index 00000000000..66b15be410d --- /dev/null +++ b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/extender_active_emissive.png.mcmeta @@ -0,0 +1,5 @@ +{ + "animation":{ + "frametime":4 + } +} diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_active.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_active.png new file mode 100644 index 00000000000..3e37ee5702a Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_active.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_active_emissive.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_active_emissive.png new file mode 100644 index 00000000000..bd4e03ab408 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_active_emissive.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_active_emissive.png.mcmeta b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_active_emissive.png.mcmeta new file mode 100644 index 00000000000..ea715020dc5 --- /dev/null +++ b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_active_emissive.png.mcmeta @@ -0,0 +1,5 @@ +{ + "animation":{ + "frametime":4 + } +} diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_inactive.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_inactive.png new file mode 100644 index 00000000000..3e37ee5702a Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/proxy_inactive.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_casing.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_casing.png new file mode 100644 index 00000000000..e3e9eda45ec Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_casing.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_connected.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_connected.png new file mode 100644 index 00000000000..979458b11ad Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_connected.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_connected_emissive.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_connected_emissive.png new file mode 100644 index 00000000000..e6ce137eee4 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_connected_emissive.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_disconnected.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_disconnected.png new file mode 100644 index 00000000000..d703813cf92 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_disconnected.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_powered.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_powered.png new file mode 100644 index 00000000000..767c0e84670 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_powered.png differ diff --git a/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_powered_emissive.png b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_powered_emissive.png new file mode 100644 index 00000000000..2083500cae4 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/blocks/casings/quantum/quantum_indicator_powered_emissive.png differ diff --git a/src/main/resources/assets/gregtech/textures/gui/overlay/menu_overlay.png b/src/main/resources/assets/gregtech/textures/gui/overlay/menu_overlay.png new file mode 100644 index 00000000000..dc166fac7e4 Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/gui/overlay/menu_overlay.png differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/console/icon.png b/src/main/resources/assets/gregtech/textures/gui/terminal/console/icon.png deleted file mode 100644 index 1aa90b06a4b..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/console/icon.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/fluid_prospector/icon.png b/src/main/resources/assets/gregtech/textures/gui/terminal/fluid_prospector/icon.png deleted file mode 100644 index c9ef5ce0d7a..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/fluid_prospector/icon.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/frame_side_down.png b/src/main/resources/assets/gregtech/textures/gui/terminal/frame_side_down.png deleted file mode 100644 index 67e56db7dc7..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/frame_side_down.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/frame_side_up.png b/src/main/resources/assets/gregtech/textures/gui/terminal/frame_side_up.png deleted file mode 100644 index 9e7a2e0ff8d..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/frame_side_up.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/guide_editor/icon.png b/src/main/resources/assets/gregtech/textures/gui/terminal/guide_editor/icon.png deleted file mode 100644 index d9f2047fd1a..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/guide_editor/icon.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/hardware_manager/circuit.png b/src/main/resources/assets/gregtech/textures/gui/terminal/hardware_manager/circuit.png deleted file mode 100644 index 1d9e6095cab..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/hardware_manager/circuit.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/multiblock_ar/icon.png b/src/main/resources/assets/gregtech/textures/gui/terminal/multiblock_ar/icon.png deleted file mode 100644 index 82a592d8ac6..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/multiblock_ar/icon.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/multiblock_ar/profile.png b/src/main/resources/assets/gregtech/textures/gui/terminal/multiblock_ar/profile.png deleted file mode 100644 index d7ad55895cb..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/multiblock_ar/profile.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/ore_prospector/icon.png b/src/main/resources/assets/gregtech/textures/gui/terminal/ore_prospector/icon.png deleted file mode 100644 index 9aa927b81f8..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/ore_prospector/icon.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/terminal_dialog.png b/src/main/resources/assets/gregtech/textures/gui/terminal/terminal_dialog.png deleted file mode 100644 index d18efc6cbc1..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/terminal_dialog.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/terminal_frame.png b/src/main/resources/assets/gregtech/textures/gui/terminal/terminal_frame.png deleted file mode 100644 index b557aef1cc1..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/terminal_frame.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/terminal_home.png b/src/main/resources/assets/gregtech/textures/gui/terminal/terminal_home.png deleted file mode 100644 index 4d7bac24410..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/terminal_home.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/vtank_viewer/icon.png b/src/main/resources/assets/gregtech/textures/gui/terminal/vtank_viewer/icon.png deleted file mode 100644 index d287058807f..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/vtank_viewer/icon.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/world_prospector/icon.png b/src/main/resources/assets/gregtech/textures/gui/terminal/world_prospector/icon.png deleted file mode 100644 index 32acbcd65c2..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/world_prospector/icon.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/gui/terminal/world_prospector/profile.png b/src/main/resources/assets/gregtech/textures/gui/terminal/world_prospector/profile.png deleted file mode 100644 index 1575c67f60b..00000000000 Binary files a/src/main/resources/assets/gregtech/textures/gui/terminal/world_prospector/profile.png and /dev/null differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/1.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/1.png index 84cedc4f95c..457151ffb04 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/1.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/1.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/2.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/2.png index ac659fcc3d2..01c22b9cb21 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/2.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/2.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/3.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/3.png index 16367774a66..e30fb8a12bd 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/3.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/3.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/4.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/4.png index b1a09beb290..238b5cfe2db 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/4.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/4.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/5.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/5.png index 331db0c53db..90b27417a47 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/5.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/5.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/6.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/6.png index 3e7b32cc48a..fc9be24e090 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/6.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/6.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/7.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/7.png index 47f697cfbf2..6339fa1a0d8 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/7.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/7.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/8.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/8.png index c68a9b70d48..1988a040f61 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/8.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.ev.vanadium/8.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.hull.ev.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.hull.ev.png index fb8e5a6d9c4..9bf5827f415 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.hull.ev.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.hull.ev.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.hull.luv.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.hull.luv.png index df159727211..8e187b4d761 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.hull.luv.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.hull.luv.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/1.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/1.png index b9e35673290..c2d478be819 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/1.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/1.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/2.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/2.png index caae7e00d5d..c07354fd053 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/2.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/2.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/3.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/3.png index 90180530ae2..6e022fb922e 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/3.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/3.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/4.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/4.png index 114823c5bad..dfde328e7b2 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/4.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/4.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/5.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/5.png index 7189dd0b2a6..b577c01b183 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/5.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/5.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/6.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/6.png index 54d31601ddf..d6496bb6426 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/6.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/6.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/7.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/7.png index 4e771428cb0..352d4563fd7 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/7.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/7.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/8.png b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/8.png index 33778625078..208f924fc3d 100644 Binary files a/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/8.png and b/src/main/resources/assets/gregtech/textures/items/metaitems/battery.luv.vanadium/8.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png new file mode 100644 index 00000000000..0918698052f Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png differ diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png new file mode 100644 index 00000000000..6944f44d2ae Binary files /dev/null and b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png differ diff --git a/src/main/resources/gregtech_at.cfg b/src/main/resources/gregtech_at.cfg index 76892c9fc05..b1286b391a8 100644 --- a/src/main/resources/gregtech_at.cfg +++ b/src/main/resources/gregtech_at.cfg @@ -84,3 +84,10 @@ public net.minecraft.entity.item.EntityItem field_145804_b # pickupDelay # Explosion public net.minecraft.world.Explosion field_77283_e # exploder + +# GuiIngame +public net.minecraft.client.gui.GuiIngame field_110330_c # WIDGETS_TEX_PATH +public net.minecraft.client.gui.GuiIngame func_184044_a(IIFLnet/minecraft/entity/player/EntityPlayer;Lnet/minecraft/item/ItemStack;)V # renderHotbarItem + +# Gui +public net.minecraft.client.gui.Gui field_73735_i # zLevel diff --git a/src/main/resources/mixins.gregtech.forge.json b/src/main/resources/mixins.gregtech.forge.json index 81605c0c9dc..61138099624 100644 --- a/src/main/resources/mixins.gregtech.forge.json +++ b/src/main/resources/mixins.gregtech.forge.json @@ -4,8 +4,10 @@ "target": "@env(DEFAULT)", "minVersion": "0.8", "compatibilityLevel": "JAVA_8", - "mixins" : [ + "mixins": [ + "GuiIngameForgeMixin", "ModelLoaderRegistryMixin", + "OreIngredientMixin", "SpecialArmorPropertiesMixin" ], "client": [], diff --git a/src/main/resources/mixins.gregtech.jei.json b/src/main/resources/mixins.gregtech.jei.json index 2520843c7d6..107771e5f35 100644 --- a/src/main/resources/mixins.gregtech.jei.json +++ b/src/main/resources/mixins.gregtech.jei.json @@ -1,12 +1,15 @@ { - "package" : "gregtech.mixins.jei", - "refmap" : "mixins.gregtech.refmap.json", - "target" : "@env(DEFAULT)", - "minVersion" : "0.8", - "compatibilityLevel" : "JAVA_8", - "mixins" : [ - "JEITooltipMixin" + "package": "gregtech.mixins.jei", + "refmap": "mixins.gregtech.refmap.json", + "target": "@env(DEFAULT)", + "minVersion": "0.8", + "compatibilityLevel": "JAVA_8", + "mixins": [ + "BasicRecipeTransferHandlerServerMixin", + "IngredientGridMixin", + "JEITooltipMixin", + "StackHelperMixin" ], - "client" : [], - "server" : [] + "client": [], + "server": [] } diff --git a/src/main/resources/mixins.gregtech.minecraft.json b/src/main/resources/mixins.gregtech.minecraft.json index 3c9abf97778..85676f99055 100644 --- a/src/main/resources/mixins.gregtech.minecraft.json +++ b/src/main/resources/mixins.gregtech.minecraft.json @@ -9,6 +9,8 @@ }, "mixins": [ "BlockConcretePowderMixin", + "ContainerMixin", + "BlockRenderLayerMixin", "DamageSourceMixin", "EnchantmentCanApplyMixin", "MinecraftMixin" diff --git a/src/main/resources/mixins.gregtech.mui2.json b/src/main/resources/mixins.gregtech.mui2.json new file mode 100644 index 00000000000..cb97f2be00c --- /dev/null +++ b/src/main/resources/mixins.gregtech.mui2.json @@ -0,0 +1,24 @@ +{ + "package": "gregtech.mixins.mui2", + "refmap": "mixins.gregtech.refmap.json", + "target": "@env(DEFAULT)", + "minVersion": "0.8", + "compatibilityLevel": "JAVA_8", + "injectors": { + "maxShiftBy": 10 + }, + "mixins": [ + "ItemSlotSHMixin", + "PanelSyncHandlerMixin", + "PanelSyncManagerMixin", + "StyledTextMixin", + "TextWidgetMixin", + "ToggleButtonMixin", + "TooltipMixin", + "TooltipMixin$RichTextWidgetMixin" + ], + "client": [ + "ClientEventHandlerMixin" + ], + "server": [] +} diff --git a/src/main/resources/mixins.gregtech.nothirium.json b/src/main/resources/mixins.gregtech.nothirium.json new file mode 100644 index 00000000000..c3ffca3074e --- /dev/null +++ b/src/main/resources/mixins.gregtech.nothirium.json @@ -0,0 +1,12 @@ +{ + "package": "gregtech.mixins.nothirium", + "refmap": "mixins.gregtech.refmap.json", + "target": "@env(DEFAULT)", + "minVersion": "0.8", + "compatibilityLevel": "JAVA_8", + "mixins": [ + "ChunkRenderPassMixin" + ], + "client": [], + "server": [] +} diff --git a/src/test/java/gregtech/api/recipes/logic/IParallelableRecipeLogicTest.java b/src/test/java/gregtech/api/recipes/logic/IParallelableRecipeLogicTest.java index 8ab302939fa..882d9287e6a 100644 --- a/src/test/java/gregtech/api/recipes/logic/IParallelableRecipeLogicTest.java +++ b/src/test/java/gregtech/api/recipes/logic/IParallelableRecipeLogicTest.java @@ -12,6 +12,7 @@ import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeBuilder; import gregtech.api.recipes.RecipeMap; +import gregtech.api.recipes.RecipeMapBuilder; import gregtech.api.recipes.builders.BlastRecipeBuilder; import gregtech.api.unification.material.Materials; import gregtech.api.util.GTUtility; @@ -24,6 +25,7 @@ import gregtech.common.metatileentities.multi.multiblockpart.MetaTileEntityMultiblockPart; import net.minecraft.init.Blocks; +import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; @@ -38,8 +40,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.CoreMatchers.*; public class IParallelableRecipeLogicTest { @@ -713,6 +714,44 @@ public MetaTileEntity getMetaTileEntity() { MatcherAssert.assertThat(outputRecipe, nullValue()); } + @Test + public void findParallelRecipe_SmallMaxStackSize() { + MetaTileEntityElectricBlastFurnace EBF = initEBF(521); + + int parallelLimit = 4; + + // Create a recipe Map to be used for testing + RecipeMap map = new RecipeMapBuilder<>("electric_blast_furnace", new BlastRecipeBuilder()) + .itemInputs(3).itemOutputs(2).fluidInputs(1).fluidOutputs(1).build(); + + // Create a simple recipe to be used for testing + // Use an output item with small max stack size + Recipe recipe = map.recipeBuilder() + .inputs(new ItemStack(Blocks.COBBLESTONE)) + .outputs(new ItemStack(Items.ELYTRA)) + .blastFurnaceTemp(1000) + .EUt(30).duration(100) + .build().getResult(); + + IParallelableRecipeLogic logic = new ParallelableTestLogic(EBF, map, ParallelLogicType.MULTIPLY); + + // Populate the Input Bus + importItemBus.getImportItems().insertItem(0, new ItemStack(Blocks.COBBLESTONE, 16), false); + + // Saturate the export bus, except for one slot + exportItemBus.getExportItems().insertItem(0, new ItemStack(Blocks.BONE_BLOCK, 16), false); + exportItemBus.getExportItems().insertItem(1, new ItemStack(Blocks.BONE_BLOCK, 16), false); + exportItemBus.getExportItems().insertItem(2, new ItemStack(Blocks.BONE_BLOCK, 16), false); + + RecipeBuilder parallelRecipe = logic.findMultipliedParallelRecipe(map, recipe, + importItemBus.getImportItems(), importFluidBus.getImportFluids(), + exportItemBus.getExportItems(), exportFluidBus.getExportFluids(), parallelLimit, Integer.MAX_VALUE, + EBF); + + MatcherAssert.assertThat(parallelRecipe, notNullValue()); + MatcherAssert.assertThat(parallelRecipe.getParallel(), is(1)); + } + @Test public void applyParallelBonus_Test() { MetaTileEntityElectricBlastFurnace EBF = initEBF(518); diff --git a/src/test/java/gregtech/api/recipes/recipeproperties/RecipePropertyStorageTest.java b/src/test/java/gregtech/api/recipes/recipeproperties/RecipePropertyStorageTest.java deleted file mode 100644 index e3daea5e015..00000000000 --- a/src/test/java/gregtech/api/recipes/recipeproperties/RecipePropertyStorageTest.java +++ /dev/null @@ -1,138 +0,0 @@ -package gregtech.api.recipes.recipeproperties; - -import org.hamcrest.MatcherAssert; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import static org.hamcrest.CoreMatchers.is; - -public class RecipePropertyStorageTest { - - private static final String propInt1Key = "propInt1"; - - private static final DefaultProperty propInt1 = new DefaultProperty<>(propInt1Key, Integer.class); - private static final DefaultProperty propInt2 = new DefaultProperty<>("propInt2", Integer.class); - private static final DefaultProperty propInt1_2 = new DefaultProperty<>("propInt1", Integer.class); - private static final DefaultProperty wrongCast = new DefaultProperty<>("wrongCast", Integer.class); - - private RecipePropertyStorage storage; - - @BeforeEach - public void initTestStub() { - this.storage = new RecipePropertyStorage(); - } - - @Test - public void storing_unique_recipe_properties_succeeds() { - MatcherAssert.assertThat(storage.store(propInt1, 1), is(true)); - MatcherAssert.assertThat(storage.store(propInt2, 1), is(true)); - } - - @Test - public void storing_same_property_twice_fails() { - MatcherAssert.assertThat(storage.store(propInt1, 1), is(true)); - MatcherAssert.assertThat(storage.store(propInt1, 1), is(false)); - } - - @Test - public void storing_unique_properties_with_same_key_fails() { - MatcherAssert.assertThat(storage.store(propInt1, 1), is(true)); - MatcherAssert.assertThat(storage.store(propInt1_2, 1), is(false)); - } - - @Test - public void storing_property_with_wrong_cast_fails() { - MatcherAssert.assertThat(storage.store(wrongCast, "This is not int"), is(false)); - } - - @Test - public void storing_property_without_value_fails() { - MatcherAssert.assertThat(storage.store(propInt1, null), is(false)); - } - - @Test - public void get_size_returns_correct_value() { - storage.store(propInt1, 1); // succeeds - - MatcherAssert.assertThat(storage.getSize(), is(1)); - - storage.store(propInt2, 2); // succeeds - - MatcherAssert.assertThat(storage.getSize(), is(2)); - - storage.store(propInt1, 1); // fails - - MatcherAssert.assertThat(storage.getSize(), is(2)); - } - - @Test - public void get_recipe_properties_returns_correct_value() { - storage.store(propInt1, 1); // succeeds - storage.store(propInt2, 2); // succeeds - - Map, Object> map = new HashMap<>(); - map.put(propInt1, 1); - map.put(propInt2, 2); - Set, Object>> expectedProperties = map.entrySet(); - - Set, Object>> actualProperties = storage.getRecipeProperties(); - - MatcherAssert.assertThat(actualProperties.size(), is(2)); - MatcherAssert.assertThat( - actualProperties.containsAll(expectedProperties) && expectedProperties.containsAll(actualProperties), - is(true)); - } - - @Test - public void get_recipe_property_value_returns_correct_value_if_exists() { - final int expectedValue = 1; - storage.store(propInt1, expectedValue); // succeeds - - int actual = storage.getRecipePropertyValue(propInt1, 0); - - MatcherAssert.assertThat(actual, is(expectedValue)); - } - - @Test - public void get_recipe_property_value_returns_default_value_if_does_not_exists() { - final int expectedValue = 0; - storage.store(propInt1, 1); // succeeds - - int actual = storage.getRecipePropertyValue(propInt2, expectedValue); - - MatcherAssert.assertThat(actual, is(expectedValue)); - } - - @Test - // CT way - public void get_recipe_property_keys() { - storage.store(propInt1, 1); // succeeds - storage.store(propInt2, 2); // succeeds - - Set expectedKeys = new HashSet<>(); - expectedKeys.add(propInt1.getKey()); - expectedKeys.add(propInt2.getKey()); - - Set actualKeys = storage.getRecipePropertyKeys(); - - MatcherAssert.assertThat(expectedKeys.containsAll(actualKeys) && actualKeys.containsAll(expectedKeys), - is(true)); - } - - @Test - // CT way - public void get_raw_recipe_property_value_via_string_key() { - final int expectedValue = 1; - - storage.store(propInt1, expectedValue); // succeeds - - Object actualValue = storage.getRawRecipePropertyValue(propInt1.getKey()); - - MatcherAssert.assertThat(actualValue, is(expectedValue)); - } -} diff --git a/src/test/java/gregtech/api/util/TierByVoltageTest.java b/src/test/java/gregtech/api/util/TierByVoltageTest.java index b0f75d0ac86..fafe266f771 100644 --- a/src/test/java/gregtech/api/util/TierByVoltageTest.java +++ b/src/test/java/gregtech/api/util/TierByVoltageTest.java @@ -127,7 +127,7 @@ public void testVSpecialCases() { expectTier(0L, ULV, ULV); expectTier(2L, ULV, ULV); expectTier(Integer.MAX_VALUE + 1L, MAX, MAX); - expectTier(Long.MAX_VALUE, MAX, MAX); + expectTier(Long.MAX_VALUE, MAX, MAX_TRUE); expectTier(-1L, ULV, ULV); }