diff --git a/build.gradle b/build.gradle index b783f61..d5e12bf 100644 --- a/build.gradle +++ b/build.gradle @@ -121,9 +121,8 @@ dependencies { //compile "codechicken:CodeChickenLib:${minecraft_version}-${CCLIB_version}:dev" //compile "codechicken:CodeChickenCore:${minecraft_version}-${ccc_version}:dev" //compile "codechicken:NotEnoughItems:${minecraft_version}-${NEI_version}:dev" - //deobfCompile "mezz.jei:jei_${minecraft_version}:${jei_version}" - //compileOnly fg.deobf("mezz.jei:jei-${minecraft_version}:${jei_version}") + compileOnly fg.deobf("mezz.jei:jei-${minecraft_version_previos}:${jei_version}") // Configuration shadow "ninja.leaping.configurate:configurate-hocon:${configurate_version}" diff --git a/gradle.properties b/gradle.properties index c800146..36935d2 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,15 +6,16 @@ org.gradle.daemon=false mod_version=1.4 # Minecraft Version Information -minecraft_version=1.14.2 +minecraft_version=1.14.3 minecraft_version_toml=14 +minecraft_version_previos=1.14.2 # Forge Version Information -forge_version=26.0.43 -forge_version_toml=26 +forge_version=27.0.2 +forge_version_toml=27 # Mappings Information -mappings_version=20190621-1.14.2 +mappings_version=20190625-1.14.3 -jei_version=5.0.+ +jei_version=6.0.+ configurate_version=3.3 diff --git a/src/main/java/slimeknights/mantle/Mantle.java b/src/main/java/slimeknights/mantle/Mantle.java index 067ab46..f56d41e 100644 --- a/src/main/java/slimeknights/mantle/Mantle.java +++ b/src/main/java/slimeknights/mantle/Mantle.java @@ -2,16 +2,14 @@ package slimeknights.mantle; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.common.Mod; - import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent; import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; - import slimeknights.mantle.client.ClientProxy; -import slimeknights.mantle.common.CommonProxy; +import slimeknights.mantle.common.ServerProxy; /** * Mantle @@ -30,15 +28,13 @@ public class Mantle { public static Mantle instance; /* Proxies for sides, used for graphics processing */ - public static CommonProxy proxy = DistExecutor.runForDist(() -> ClientProxy::new, () -> CommonProxy::new); + public static ServerProxy proxy = DistExecutor.runForDist(() -> ClientProxy::new, () -> ServerProxy::new); - public Mantle() - { + public Mantle() { instance = this; FMLJavaModLoadingContext.get().getModEventBus().addListener(this::preInit); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::init); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::postInit); - } private void preInit(final FMLCommonSetupEvent event) { diff --git a/src/main/java/slimeknights/mantle/block/BlockConnectedTexture.java b/src/main/java/slimeknights/mantle/block/BlockConnectedTexture.java deleted file mode 100644 index 27c5dd5..0000000 --- a/src/main/java/slimeknights/mantle/block/BlockConnectedTexture.java +++ /dev/null @@ -1,85 +0,0 @@ -package slimeknights.mantle.block; - -import javax.annotation.Nonnull; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.state.BooleanProperty; -import net.minecraft.state.StateContainer; -import net.minecraft.util.Direction; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IWorld; - -/** - * Creates a block with textures that connect to other blocks - *

- * Based off a tutorial by Darkhax, used under the Creative Commons Zero 1.0 Universal license - */ -public class BlockConnectedTexture extends Block { - - // These are the properties used for determining whether or not a side is connected. They - // do NOT take up block IDs, they are unlisted properties - public static final BooleanProperty CONNECTED_DOWN = BooleanProperty.create("connected_down"); - public static final BooleanProperty CONNECTED_UP = BooleanProperty.create("connected_up"); - public static final BooleanProperty CONNECTED_NORTH = BooleanProperty.create("connected_north"); - public static final BooleanProperty CONNECTED_SOUTH = BooleanProperty.create("connected_south"); - public static final BooleanProperty CONNECTED_WEST = BooleanProperty.create("connected_west"); - public static final BooleanProperty CONNECTED_EAST = BooleanProperty.create("connected_east"); - - public BlockConnectedTexture(Block.Properties builder) { - - super(builder); - // By default none of the sides are connected - this.setDefaultState(this.stateContainer.getBaseState() - .with(CONNECTED_DOWN, Boolean.FALSE) - .with(CONNECTED_EAST, Boolean.FALSE) - .with(CONNECTED_NORTH, Boolean.FALSE) - .with(CONNECTED_SOUTH, Boolean.FALSE) - .with(CONNECTED_UP, Boolean.FALSE) - .with(CONNECTED_WEST, Boolean.FALSE)); - } - - @Override - public BlockState updatePostPlacement(BlockState stateIn, Direction facing, BlockState facingState, IWorld worldIn, BlockPos currentPos, BlockPos facingPos) { - - // Creates the state to use for the block. This is where we check if every side is - // connectable or not. - - return stateIn.with(CONNECTED_DOWN, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.DOWN)) - .with(CONNECTED_EAST, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.EAST)) - .with(CONNECTED_NORTH, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.NORTH)) - .with(CONNECTED_SOUTH, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.SOUTH)) - .with(CONNECTED_UP, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.UP)) - .with(CONNECTED_WEST, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.WEST)); - } - - @Override - protected void fillStateContainer(StateContainer.Builder builder) { - builder.add(CONNECTED_DOWN, CONNECTED_UP, CONNECTED_NORTH, CONNECTED_SOUTH, CONNECTED_WEST, CONNECTED_EAST); - } - - /** - * Checks if a specific side of a block can connect to this block. For this example, a side - * is connectable if the block is the same block as this one. - * - * @param state Base state to check - * @param world The world to run the check in. - * @param pos The position of the block to check for. - * @param side The side of the block to check. - * @return Whether or not the side is connectable. - */ - private boolean isSideConnectable(BlockState state, IWorld world, BlockPos pos, Direction side) { - final BlockState connected = world.getBlockState(pos.offset(side)); - return connected != null && this.canConnect(state, connected); - } - - /** - * Checks if this block should connect to another block - * @param original BlockState to check - * @param connected BlockState to check - * @return True if the block is valid to connect - */ - protected boolean canConnect(@Nonnull BlockState original, @Nonnull BlockState connected) { - return original.getBlock() == connected.getBlock(); - } -} \ No newline at end of file diff --git a/src/main/java/slimeknights/mantle/block/ConnectedTextureBlock.java b/src/main/java/slimeknights/mantle/block/ConnectedTextureBlock.java new file mode 100644 index 0000000..997d4f7 --- /dev/null +++ b/src/main/java/slimeknights/mantle/block/ConnectedTextureBlock.java @@ -0,0 +1,85 @@ +package slimeknights.mantle.block; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockState; +import net.minecraft.state.BooleanProperty; +import net.minecraft.state.StateContainer; +import net.minecraft.util.Direction; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IWorld; + +import javax.annotation.Nonnull; + +/** + * Creates a block with textures that connect to other blocks + *

+ * Based off a tutorial by Darkhax, used under the Creative Commons Zero 1.0 Universal license + */ +public class ConnectedTextureBlock extends Block { + + // These are the properties used for determining whether or not a side is connected. They + // do NOT take up block IDs, they are unlisted properties + public static final BooleanProperty CONNECTED_DOWN = BooleanProperty.create("connected_down"); + public static final BooleanProperty CONNECTED_UP = BooleanProperty.create("connected_up"); + public static final BooleanProperty CONNECTED_NORTH = BooleanProperty.create("connected_north"); + public static final BooleanProperty CONNECTED_SOUTH = BooleanProperty.create("connected_south"); + public static final BooleanProperty CONNECTED_WEST = BooleanProperty.create("connected_west"); + public static final BooleanProperty CONNECTED_EAST = BooleanProperty.create("connected_east"); + + public ConnectedTextureBlock(Block.Properties builder) { + + super(builder); + // By default none of the sides are connected + this.setDefaultState(this.stateContainer.getBaseState() + .with(CONNECTED_DOWN, Boolean.FALSE) + .with(CONNECTED_EAST, Boolean.FALSE) + .with(CONNECTED_NORTH, Boolean.FALSE) + .with(CONNECTED_SOUTH, Boolean.FALSE) + .with(CONNECTED_UP, Boolean.FALSE) + .with(CONNECTED_WEST, Boolean.FALSE)); + } + + @Override + public BlockState updatePostPlacement(BlockState stateIn, Direction facing, BlockState facingState, IWorld worldIn, BlockPos currentPos, BlockPos facingPos) { + + // Creates the state to use for the block. This is where we check if every side is + // connectable or not. + + return stateIn.with(CONNECTED_DOWN, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.DOWN)) + .with(CONNECTED_EAST, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.EAST)) + .with(CONNECTED_NORTH, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.NORTH)) + .with(CONNECTED_SOUTH, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.SOUTH)) + .with(CONNECTED_UP, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.UP)) + .with(CONNECTED_WEST, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.WEST)); + } + + @Override + protected void fillStateContainer(StateContainer.Builder builder) { + builder.add(CONNECTED_DOWN, CONNECTED_UP, CONNECTED_NORTH, CONNECTED_SOUTH, CONNECTED_WEST, CONNECTED_EAST); + } + + /** + * Checks if a specific side of a block can connect to this block. For this example, a side + * is connectable if the block is the same block as this one. + * + * @param state Base state to check + * @param world The world to run the check in. + * @param pos The position of the block to check for. + * @param side The side of the block to check. + * @return Whether or not the side is connectable. + */ + private boolean isSideConnectable(BlockState state, IWorld world, BlockPos pos, Direction side) { + final BlockState connected = world.getBlockState(pos.offset(side)); + return connected != null && this.canConnect(state, connected); + } + + /** + * Checks if this block should connect to another block + * @param original BlockState to check + * @param connected BlockState to check + * @return True if the block is valid to connect + */ + protected boolean canConnect(@Nonnull BlockState original, @Nonnull BlockState connected) { + return original.getBlock() == connected.getBlock(); + } +} diff --git a/src/main/java/slimeknights/mantle/block/BlockInventory.java b/src/main/java/slimeknights/mantle/block/InventoryBlock.java similarity index 80% rename from src/main/java/slimeknights/mantle/block/BlockInventory.java rename to src/main/java/slimeknights/mantle/block/InventoryBlock.java index 7e3c778..a549ad9 100644 --- a/src/main/java/slimeknights/mantle/block/BlockInventory.java +++ b/src/main/java/slimeknights/mantle/block/InventoryBlock.java @@ -10,21 +10,18 @@ import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryHelper; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.world.IBlockReader; import net.minecraft.world.World; +import slimeknights.mantle.tileentity.InventoryTileEntity; import javax.annotation.Nonnull; -import slimeknights.mantle.tileentity.TileInventory; +public abstract class InventoryBlock extends ContainerBlock { -// Updated Version of InventoryBlock in Mantle -public abstract class BlockInventory extends ContainerBlock -{ - protected BlockInventory(Block.Properties builder) { + protected InventoryBlock(Block.Properties builder) { super(builder); } @@ -45,11 +42,11 @@ public abstract class BlockInventory extends ContainerBlock @Override public boolean onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) { - if(player.isSneaking()) { + if (player.isSneaking()) { return false; } - if(!world.isRemote) { + if (!world.isRemote) { return this.openGui(player, world, pos); } @@ -58,15 +55,15 @@ public abstract class BlockInventory extends ContainerBlock @Override public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, LivingEntity placer, - ItemStack stack) { + ItemStack stack) { super.onBlockPlacedBy(worldIn, pos, state, placer, stack); // set custom name from named stack - if(stack.hasDisplayName()) { + if (stack.hasDisplayName()) { TileEntity tileentity = worldIn.getTileEntity(pos); - if(tileentity instanceof TileInventory) { - ((TileInventory) tileentity).setCustomName(stack.getDisplayName()); + if (tileentity instanceof InventoryTileEntity) { + ((InventoryTileEntity) tileentity).setCustomName(stack.getDisplayName()); } } } @@ -78,7 +75,7 @@ public abstract class BlockInventory extends ContainerBlock TileEntity tileentity = worldIn.getTileEntity(pos); - if(tileentity instanceof TileInventory) { + if (tileentity instanceof InventoryTileEntity) { InventoryHelper.dropInventoryItems(worldIn, pos, (IInventory) tileentity); worldIn.updateComparatorOutputLevel(pos, this); } @@ -92,4 +89,4 @@ public abstract class BlockInventory extends ContainerBlock public BlockRenderType getRenderType(BlockState state) { return BlockRenderType.MODEL; } -} +} \ No newline at end of file diff --git a/src/main/java/slimeknights/mantle/block/BlockStairsBase.java b/src/main/java/slimeknights/mantle/block/StairsBaseBlock.java similarity index 55% rename from src/main/java/slimeknights/mantle/block/BlockStairsBase.java rename to src/main/java/slimeknights/mantle/block/StairsBaseBlock.java index f98de81..6c1f578 100644 --- a/src/main/java/slimeknights/mantle/block/BlockStairsBase.java +++ b/src/main/java/slimeknights/mantle/block/StairsBaseBlock.java @@ -1,13 +1,12 @@ package slimeknights.mantle.block; import net.minecraft.block.Block; -import net.minecraft.block.BlockState; import net.minecraft.block.StairsBlock; -// Mojang made the constructor for stairs protected, so this class is basically a wrapper to change that and fix a lighting error -public class BlockStairsBase extends StairsBlock -{ - public BlockStairsBase(Block model) { +// Mojang made the constructor for stairs protected, so this class is basically a wrapper to change that +public class StairsBaseBlock extends StairsBlock { + + public StairsBaseBlock(Block model) { super(model.getDefaultState(), Block.Properties.from(model)); } } diff --git a/src/main/java/slimeknights/mantle/client/ClientProxy.java b/src/main/java/slimeknights/mantle/client/ClientProxy.java index 0b42c2a..87e6d3a 100644 --- a/src/main/java/slimeknights/mantle/client/ClientProxy.java +++ b/src/main/java/slimeknights/mantle/client/ClientProxy.java @@ -3,27 +3,27 @@ package slimeknights.mantle.client; import net.minecraft.client.Minecraft; import net.minecraft.resources.IReloadableResourceManager; import net.minecraftforge.common.MinecraftForge; - import slimeknights.mantle.client.book.BookLoader; -import slimeknights.mantle.common.CommonProxy; +import slimeknights.mantle.common.ServerProxy; -public class ClientProxy extends CommonProxy { +public class ClientProxy extends ServerProxy { - private BookLoader bookLoader; + private BookLoader bookLoader; - @Override - public void preInit() { - bookLoader = new BookLoader(); - } + @Override + public void preInit() { + this.bookLoader = new BookLoader(); + } - @Override - public void init() { - bookLoader.onResourceManagerReload(Minecraft.getInstance().getResourceManager()); - } + @Override + public void init() { + this.bookLoader.onResourceManagerReload(Minecraft.getInstance().getResourceManager()); + } + + @Override + public void postInit() { + ((IReloadableResourceManager) Minecraft.getInstance().getResourceManager()).addReloadListener(this.bookLoader); + MinecraftForge.EVENT_BUS.register(new ExtraHeartRenderHandler()); + } - @Override - public void postInit() { - ((IReloadableResourceManager) Minecraft.getInstance().getResourceManager()).addReloadListener(bookLoader); - MinecraftForge.EVENT_BUS.register(new ExtraHeartRenderHandler()); - } } diff --git a/src/main/java/slimeknights/mantle/client/CreativeTab.java b/src/main/java/slimeknights/mantle/client/CreativeTab.java index 73b0566..a794a9f 100644 --- a/src/main/java/slimeknights/mantle/client/CreativeTab.java +++ b/src/main/java/slimeknights/mantle/client/CreativeTab.java @@ -19,7 +19,7 @@ public class CreativeTab extends ItemGroup { } public void setDisplayIcon(ItemStack displayIcon) { - if(!displayIcon.isEmpty()) { + if (!displayIcon.isEmpty()) { this.icon = displayIcon; } } @@ -28,13 +28,13 @@ public class CreativeTab extends ItemGroup { @OnlyIn(Dist.CLIENT) @Override public ItemStack getIcon() { - return icon; + return this.icon; } @Nonnull @OnlyIn(Dist.CLIENT) @Override public ItemStack createIcon() { - return icon; + return this.icon; } } diff --git a/src/main/java/slimeknights/mantle/client/ExtraHeartRenderHandler.java b/src/main/java/slimeknights/mantle/client/ExtraHeartRenderHandler.java index 343a562..289e0d5 100644 --- a/src/main/java/slimeknights/mantle/client/ExtraHeartRenderHandler.java +++ b/src/main/java/slimeknights/mantle/client/ExtraHeartRenderHandler.java @@ -16,22 +16,21 @@ import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.ForgeIngameGui; import net.minecraftforge.client.event.RenderGameOverlayEvent; - -import java.util.Random; - import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; import slimeknights.mantle.Mantle; +import java.util.Random; + @OnlyIn(Dist.CLIENT) public class ExtraHeartRenderHandler { + private static final ResourceLocation ICON_HEARTS = new ResourceLocation(Mantle.modId, "textures/gui/hearts.png"); private static final ResourceLocation ICON_ABSORB = new ResourceLocation(Mantle.modId, "textures/gui/absorb.png"); private static final ResourceLocation ICON_VANILLA = AbstractGui.GUI_ICONS_LOCATION; private final Minecraft mc = Minecraft.getInstance(); - private int updateCounter = 0; private int playerHealth = 0; private int lastPlayerHealth = 0; private long healthUpdateCounter = 0; @@ -44,7 +43,7 @@ public class ExtraHeartRenderHandler { private static int left_height = 39; - public void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height) { + public void blit(int x, int y, int textureX, int textureY, int width, int height) { Minecraft.getInstance().ingameGUI.blit(x, y, textureX, textureY, width, height); } @@ -52,41 +51,38 @@ public class ExtraHeartRenderHandler { @SubscribeEvent(priority = EventPriority.LOW) public void renderHealthbar(RenderGameOverlayEvent.Pre event) { Entity renderViewEnity = this.mc.getRenderViewEntity(); - if(event.getType() != RenderGameOverlayEvent.ElementType.HEALTH - || event.isCanceled() - || !(renderViewEnity instanceof PlayerEntity)) { + if (event.getType() != RenderGameOverlayEvent.ElementType.HEALTH + || event.isCanceled() + || !(renderViewEnity instanceof PlayerEntity)) { return; } - PlayerEntity player = (PlayerEntity)this.mc.getRenderViewEntity(); + PlayerEntity player = (PlayerEntity) this.mc.getRenderViewEntity(); // extra setup stuff from us left_height = ForgeIngameGui.left_height; - width = mc.mainWindow.getScaledWidth(); - height = mc.mainWindow.getScaledHeight(); + this.width = this.mc.mainWindow.getScaledWidth(); + this.height = this.mc.mainWindow.getScaledHeight(); event.setCanceled(true); - updateCounter = mc.ingameGUI.getTicks(); + int updateCounter = this.mc.ingameGUI.getTicks(); // start default forge/mc rendering // changes are indicated by comment - mc.getProfiler().startSection("health"); + this.mc.getProfiler().startSection("health"); GlStateManager.enableBlend(); int health = MathHelper.ceil(player.getHealth()); - boolean highlight = healthUpdateCounter > (long)updateCounter && (healthUpdateCounter - (long)updateCounter) / 3L %2L == 1L; + boolean highlight = this.healthUpdateCounter > (long) updateCounter && (this.healthUpdateCounter - (long) updateCounter) / 3L % 2L == 1L; - if (health < this.playerHealth && player.hurtResistantTime > 0) - { + if (health < this.playerHealth && player.hurtResistantTime > 0) { this.lastSystemTime = Util.milliTime(); - this.healthUpdateCounter = (long)(this.updateCounter + 20); + this.healthUpdateCounter = (long) (updateCounter + 20); } - else if (health > this.playerHealth && player.hurtResistantTime > 0) - { + else if (health > this.playerHealth && player.hurtResistantTime > 0) { this.lastSystemTime = Util.milliTime(); - this.healthUpdateCounter = (long)(this.updateCounter + 10); + this.healthUpdateCounter = (long) (updateCounter + 10); } - if (Util.milliTime() - this.lastSystemTime > 1000L) - { + if (Util.milliTime() - this.lastSystemTime > 1000L) { this.playerHealth = health; this.lastPlayerHealth = health; this.lastSystemTime = Util.milliTime(); @@ -96,7 +92,7 @@ public class ExtraHeartRenderHandler { int healthLast = this.lastPlayerHealth; IAttributeInstance attrMaxHealth = player.getAttribute(SharedMonsterAttributes.MAX_HEALTH); - float healthMax = (float)attrMaxHealth.getValue(); + float healthMax = (float) attrMaxHealth.getValue(); float absorb = MathHelper.ceil(player.getAbsorptionAmount()); // CHANGE: simulate 10 hearts max if there's more, so vanilla only renders one row max @@ -107,147 +103,152 @@ public class ExtraHeartRenderHandler { int healthRows = MathHelper.ceil((healthMax + absorb) / 2.0F / 10.0F); int rowHeight = Math.max(10 - (healthRows - 2), 3); - this.rand.setSeed((long)(updateCounter * 312871)); + this.rand.setSeed((long) (updateCounter * 312871)); - int left = width / 2 - 91; - int top = height - left_height; + int left = this.width / 2 - 91; + int top = this.height - left_height; left_height += (healthRows * rowHeight); - if (rowHeight != 10) left_height += 10 - rowHeight; - - regen = -1; - if (player.isPotionActive(Effects.REGENERATION)) - { - regen = updateCounter % 25; + if (rowHeight != 10) { + left_height += 10 - rowHeight; } - final int TOP = 9 * (mc.world.getWorldInfo().isHardcore() ? 5 : 0); + this.regen = -1; + if (player.isPotionActive(Effects.REGENERATION)) { + this.regen = updateCounter % 25; + } + + final int TOP = 9 * (this.mc.world.getWorldInfo().isHardcore() ? 5 : 0); final int BACKGROUND = (highlight ? 25 : 16); int MARGIN = 16; - if (player.isPotionActive(Effects.POISON)) MARGIN += 36; - else if (player.isPotionActive(Effects.WITHER)) MARGIN += 72; + if (player.isPotionActive(Effects.POISON)) { + MARGIN += 36; + } + else if (player.isPotionActive(Effects.WITHER)) { + MARGIN += 72; + } float absorbRemaining = absorb; - for (int i = MathHelper.ceil((healthMax + absorb) / 2.0F) - 1; i >= 0; --i) - { + for (int i = MathHelper.ceil((healthMax + absorb) / 2.0F) - 1; i >= 0; --i) { //int b0 = (highlight ? 1 : 0); - int row = MathHelper.ceil((float)(i + 1) / 10.0F) - 1; + int row = MathHelper.ceil((float) (i + 1) / 10.0F) - 1; int x = left + i % 10 * 8; int y = top - row * rowHeight; - if (health <= 4) y += rand.nextInt(2); - if (i == regen) y -= 2; - - drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9); - - if (highlight) - { - if (i * 2 + 1 < healthLast) - drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); //6 - else if (i * 2 + 1 == healthLast) - drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); //7 + if (health <= 4) { + y += this.rand.nextInt(2); + } + if (i == this.regen) { + y -= 2; } - if (absorbRemaining > 0.0F) - { - if (absorbRemaining == absorb && absorb % 2.0F == 1.0F) - { - drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); //17 + this.blit(x, y, BACKGROUND, TOP, 9, 9); + + if (highlight) { + if (i * 2 + 1 < healthLast) { + this.blit(x, y, MARGIN + 54, TOP, 9, 9); //6 + } + else if (i * 2 + 1 == healthLast) { + this.blit(x, y, MARGIN + 63, TOP, 9, 9); //7 + } + } + + if (absorbRemaining > 0.0F) { + if (absorbRemaining == absorb && absorb % 2.0F == 1.0F) { + this.blit(x, y, MARGIN + 153, TOP, 9, 9); //17 absorbRemaining -= 1.0F; } - else - { - drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); //16 + else { + this.blit(x, y, MARGIN + 144, TOP, 9, 9); //16 absorbRemaining -= 2.0F; } } - else - { - if (i * 2 + 1 < health) - drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); //4 - else if (i * 2 + 1 == health) - drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); //5 + else { + if (i * 2 + 1 < health) { + this.blit(x, y, MARGIN + 36, TOP, 9, 9); //4 + } + else if (i * 2 + 1 == health) { + this.blit(x, y, MARGIN + 45, TOP, 9, 9); //5 + } } } - - renderExtraHearts(left, top, player); - renderExtraAbsorption(left, top - rowHeight, player); - + this.renderExtraHearts(left, top, player); + this.renderExtraAbsorption(left, top - rowHeight, player); this.mc.getTextureManager().bindTexture(ICON_VANILLA); ForgeIngameGui.left_height += 10; - if(absorb > 0) { + if (absorb > 0) { ForgeIngameGui.left_height += 10; } event.setCanceled(true); GlStateManager.disableBlend(); - mc.getProfiler().endSection(); + this.mc.getProfiler().endSection(); } private void renderExtraHearts(int xBasePos, int yBasePos, PlayerEntity player) { - int potionOffset = getPotionOffset(player); + int potionOffset = this.getPotionOffset(player); // Extra hearts this.mc.getTextureManager().bindTexture(ICON_HEARTS); int hp = MathHelper.ceil(player.getHealth()); - renderCustomHearts(xBasePos, yBasePos, potionOffset, hp, false); + this.renderCustomHearts(xBasePos, yBasePos, potionOffset, hp, false); } private void renderCustomHearts(int xBasePos, int yBasePos, int potionOffset, int count, boolean absorb) { int regenOffset = absorb ? 10 : 0; - for(int iter = 0; iter < count / 20; iter++) { + for (int iter = 0; iter < count / 20; iter++) { int renderHearts = (count - 20 * (iter + 1)) / 2; int heartIndex = iter % 11; - if(renderHearts > 10) { + if (renderHearts > 10) { renderHearts = 10; } - for(int i = 0; i < renderHearts; i++) { - int y = getYRegenOffset(i, regenOffset); - if(absorb) { - this.drawTexturedModalRect(xBasePos + 8 * i, yBasePos + y, 0, 54, 9, 9); + for (int i = 0; i < renderHearts; i++) { + int y = this.getYRegenOffset(i, regenOffset); + if (absorb) { + this.blit(xBasePos + 8 * i, yBasePos + y, 0, 54, 9, 9); } - this.drawTexturedModalRect(xBasePos + 8 * i, yBasePos + y, 0 + 18 * heartIndex, potionOffset, 9, 9); + this.blit(xBasePos + 8 * i, yBasePos + y, 18 * heartIndex, potionOffset, 9, 9); } - if(count % 2 == 1 && renderHearts < 10) { - int y = getYRegenOffset(renderHearts, regenOffset); - if(absorb) { - this.drawTexturedModalRect(xBasePos + 8 * renderHearts, yBasePos + y, 0, 54, 9, 9); + if (count % 2 == 1 && renderHearts < 10) { + int y = this.getYRegenOffset(renderHearts, regenOffset); + if (absorb) { + this.blit(xBasePos + 8 * renderHearts, yBasePos + y, 0, 54, 9, 9); } - this.drawTexturedModalRect(xBasePos + 8 * renderHearts, yBasePos + y, 9 + 18 * heartIndex, potionOffset, 9, 9); + this.blit(xBasePos + 8 * renderHearts, yBasePos + y, 9 + 18 * heartIndex, potionOffset, 9, 9); } } } private int getYRegenOffset(int i, int offset) { - return i + offset == regen ? -2 : 0; + return i + offset == this.regen ? -2 : 0; } private int getPotionOffset(PlayerEntity player) { int potionOffset = 0; EffectInstance potion = player.getActivePotionEffect(Effects.WITHER); - if(potion != null) { + if (potion != null) { potionOffset = 18; } potion = player.getActivePotionEffect(Effects.POISON); - if(potion != null) { + if (potion != null) { potionOffset = 9; } - if(mc.world.getWorldInfo().isHardcore()) { + if (this.mc.world.getWorldInfo().isHardcore()) { potionOffset += 27; } return potionOffset; } private void renderExtraAbsorption(int xBasePos, int yBasePos, PlayerEntity player) { - int potionOffset = getPotionOffset(player); + int potionOffset = this.getPotionOffset(player); // Extra hearts this.mc.getTextureManager().bindTexture(ICON_ABSORB); int absorb = MathHelper.ceil(player.getAbsorptionAmount()); - renderCustomHearts(xBasePos, yBasePos, potionOffset, absorb, true); + this.renderCustomHearts(xBasePos, yBasePos, potionOffset, absorb, true); } } diff --git a/src/main/java/slimeknights/mantle/client/ModelHelper.java b/src/main/java/slimeknights/mantle/client/ModelHelper.java index dd767f4..74a3b2d 100644 --- a/src/main/java/slimeknights/mantle/client/ModelHelper.java +++ b/src/main/java/slimeknights/mantle/client/ModelHelper.java @@ -1,7 +1,6 @@ package slimeknights.mantle.client; import com.google.common.collect.ImmutableMap; - import net.minecraft.block.BlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.model.BakedQuad; @@ -37,10 +36,10 @@ public class ModelHelper { private static TRSRTransformation get(float tx, float ty, float tz, float ax, float ay, float az, float s) { return TRSRTransformation.blockCenterToCorner(new TRSRTransformation( - new Vector3f(tx / 16, ty / 16, tz / 16), - TRSRTransformation.quatFromXYZDegrees(new Vector3f(ax, ay, az)), - new Vector3f(s, s, s), - null)); + new Vector3f(tx / 16, ty / 16, tz / 16), + TRSRTransformation.quatFromXYZDegrees(new Vector3f(ax, ay, az)), + new Vector3f(s, s, s), + null)); } static { @@ -73,44 +72,43 @@ public class ModelHelper { } } - private static class ColorTransformer extends VertexTransformer { - private final float r,g,b,a; + private final float r, g, b, a; public ColorTransformer(int color, VertexFormat format) { super(new UnpackedBakedQuad.Builder(format)); int a = (color >> 24); - if(a == 0) { + if (a == 0) { a = 255; } int r = (color >> 16) & 0xFF; int g = (color >> 8) & 0xFF; int b = (color >> 0) & 0xFF; - this.r = (float)r/255f; - this.g = (float)g/255f; - this.b = (float)b/255f; - this.a = (float)a/255f; + this.r = (float) r / 255f; + this.g = (float) g / 255f; + this.b = (float) b / 255f; + this.a = (float) a / 255f; } @Override public void put(int element, float... data) { - VertexFormatElement.Usage usage = parent.getVertexFormat().getElement(element).getUsage(); + VertexFormatElement.Usage usage = this.parent.getVertexFormat().getElement(element).getUsage(); // transform normals and position - if(usage == VertexFormatElement.Usage.COLOR && data.length >= 4) { - data[0] = r; - data[1] = g; - data[2] = b; - data[3] = a; + if (usage == VertexFormatElement.Usage.COLOR && data.length >= 4) { + data[0] = this.r; + data[1] = this.g; + data[2] = this.b; + data[3] = this.a; } super.put(element, data); } public UnpackedBakedQuad build() { - return ((UnpackedBakedQuad.Builder) parent).build(); + return ((UnpackedBakedQuad.Builder) this.parent).build(); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/BookHelper.java b/src/main/java/slimeknights/mantle/client/book/BookHelper.java index 686c52e..74bc462 100644 --- a/src/main/java/slimeknights/mantle/client/book/BookHelper.java +++ b/src/main/java/slimeknights/mantle/client/book/BookHelper.java @@ -9,10 +9,10 @@ import java.util.Arrays; public class BookHelper { public static String getSavedPage(ItemStack item) { - if(!item.isEmpty() && item.hasTag()) { + if (!item.isEmpty() && item.hasTag()) { CompoundNBT mantleBook = item.getTag().getCompound("mantle").getCompound("book"); - if(mantleBook.contains("page", Arrays.asList(INBT.NBT_TYPES).indexOf("STRING"))) { + if (mantleBook.contains("page", Arrays.asList(INBT.NBT_TYPES).indexOf("STRING"))) { return mantleBook.getString("page"); } } @@ -23,7 +23,7 @@ public class BookHelper { public static void writeSavedPage(ItemStack item, String page) { CompoundNBT compound = item.getTag(); - if(compound == null) { + if (compound == null) { compound = new CompoundNBT(); } diff --git a/src/main/java/slimeknights/mantle/client/book/BookLoader.java b/src/main/java/slimeknights/mantle/client/book/BookLoader.java index 97bcef1..83494d7 100644 --- a/src/main/java/slimeknights/mantle/client/book/BookLoader.java +++ b/src/main/java/slimeknights/mantle/client/book/BookLoader.java @@ -2,7 +2,6 @@ package slimeknights.mantle.client.book; import com.google.gson.Gson; import com.google.gson.GsonBuilder; - import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.resources.IResourceManager; @@ -11,38 +10,24 @@ import net.minecraft.util.Hand; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.ModLoadingContext; - -import java.util.HashMap; - -import javax.annotation.Nonnull; - import slimeknights.mantle.client.book.action.StringActionProcessor; import slimeknights.mantle.client.book.action.protocol.ProtocolGoToPage; import slimeknights.mantle.client.book.data.BookData; -import slimeknights.mantle.client.book.data.content.ContentBlank; -import slimeknights.mantle.client.book.data.content.ContentBlockInteraction; -import slimeknights.mantle.client.book.data.content.ContentCrafting; -import slimeknights.mantle.client.book.data.content.ContentImage; -import slimeknights.mantle.client.book.data.content.ContentImageText; -import slimeknights.mantle.client.book.data.content.ContentSmelting; -import slimeknights.mantle.client.book.data.content.ContentSmithing; -import slimeknights.mantle.client.book.data.content.ContentStructure; -import slimeknights.mantle.client.book.data.content.ContentText; -import slimeknights.mantle.client.book.data.content.ContentTextImage; -import slimeknights.mantle.client.book.data.content.ContentTextLeftImage; -import slimeknights.mantle.client.book.data.content.ContentTextRightImage; -import slimeknights.mantle.client.book.data.content.PageContent; +import slimeknights.mantle.client.book.data.content.*; import slimeknights.mantle.client.book.data.deserializer.HexStringDeserializer; import slimeknights.mantle.client.book.repository.BookRepository; import slimeknights.mantle.network.NetworkWrapper; import slimeknights.mantle.network.book.PacketUpdateSavedPage; +import javax.annotation.Nonnull; +import java.util.HashMap; + @OnlyIn(Dist.CLIENT) public class BookLoader implements IResourceManagerReloadListener { /** GSON object to be used for book loading purposes */ public static final Gson GSON = new GsonBuilder().registerTypeAdapter(int.class, new HexStringDeserializer()) - .create(); + .create(); /** Maps page content presets to names */ private static final HashMap> typeToContentMap = new HashMap<>(); @@ -53,7 +38,7 @@ public class BookLoader implements IResourceManagerReloadListener { private static final NetworkWrapper wrapper = new NetworkWrapper("mantle:books"); public BookLoader() { - wrapper.registerPacket(PacketUpdateSavedPage.class, PacketUpdateSavedPage::encode, PacketUpdateSavedPage::decode, PacketUpdateSavedPage.Handler::handle); + wrapper.registerPacket(PacketUpdateSavedPage.class, PacketUpdateSavedPage::encode, PacketUpdateSavedPage::new, PacketUpdateSavedPage::handle); // Register page types registerPageType("blank", ContentBlank.class); @@ -82,7 +67,7 @@ public class BookLoader implements IResourceManagerReloadListener { * @RecommendedInvoke init */ public static void registerPageType(String name, Class clazz) { - if(typeToContentMap.containsKey(name)) { + if (typeToContentMap.containsKey(name)) { throw new IllegalArgumentException("Page type " + name + " already in use."); } @@ -126,10 +111,10 @@ public class BookLoader implements IResourceManagerReloadListener { books.put(name.contains(":") ? name : ModLoadingContext.get().getActiveContainer().getNamespace() + ":" + name, info); - if(appendIndex) { - info.addTransformer(BookTransformer.IndexTranformer()); + if (appendIndex) { + info.addTransformer(BookTransformer.indexTranformer()); } - if(appendContentTable) { + if (appendContentTable) { info.addTransformer(BookTransformer.contentTableTransformer()); } @@ -137,10 +122,10 @@ public class BookLoader implements IResourceManagerReloadListener { } public static void updateSavedPage(PlayerEntity player, ItemStack item, String page) { - if(player == null) { + if (player == null) { return; } - if(player.getHeldItem(Hand.MAIN_HAND).isEmpty()) { + if (player.getHeldItem(Hand.MAIN_HAND).isEmpty()) { return; } diff --git a/src/main/java/slimeknights/mantle/client/book/BookTransformer.java b/src/main/java/slimeknights/mantle/client/book/BookTransformer.java index 05c3ab1..9a53516 100644 --- a/src/main/java/slimeknights/mantle/client/book/BookTransformer.java +++ b/src/main/java/slimeknights/mantle/client/book/BookTransformer.java @@ -6,7 +6,7 @@ import slimeknights.mantle.client.book.data.SectionData; import slimeknights.mantle.client.book.data.content.ContentSectionList; import slimeknights.mantle.client.book.data.content.ContentTableOfContents; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; +import slimeknights.mantle.client.screen.book.BookScreen; import java.util.ArrayList; import java.util.Arrays; @@ -14,9 +14,17 @@ import java.util.List; public abstract class BookTransformer { - public static BookTransformer IndexTranformer() { return IndexTranformer.INSTANCE; } - public static BookTransformer contentTableTransformer() { return ContentTableTransformer.INSTANCE; } - public static BookTransformer contentTableTransformerForSection(String sectionName) { return new ContentTableTransformer(sectionName); } + public static BookTransformer indexTranformer() { + return IndexTranformer.INSTANCE; + } + + public static BookTransformer contentTableTransformer() { + return ContentTableTransformer.INSTANCE; + } + + public static BookTransformer contentTableTransformerForSection(String sectionName) { + return new ContentTableTransformer(sectionName); + } /** * Called when all the sections within the book are loaded. @@ -33,12 +41,12 @@ public abstract class BookTransformer { public void transform(BookData book) { SectionData index = new SectionData(true) { @Override - public void update(GuiBook.AdvancementCache advancementCache) { + public void update(BookScreen.AdvancementCache advancementCache) { this.pages.clear(); List visibleSections = this.parent.getVisibleSections(advancementCache); - if(visibleSections.isEmpty()) { + if (visibleSections.isEmpty()) { return; } @@ -46,7 +54,7 @@ public abstract class BookTransformer { PageData[] pages = new PageData[(int) Math.ceil(visibleSections.size() / 9F)]; - for(int i = 0; i < pages.length; i++) { + for (int i = 0; i < pages.length; i++) { pages[i] = new PageData(true); pages[i].name = "page" + (i + 1); @@ -54,7 +62,7 @@ public abstract class BookTransformer { ContentSectionList content = new ContentSectionList(); pages[i].content = content; - for(int j = i * 9; j - i * 9 < 9 && j < visibleSections.size(); j++) { + for (int j = i * 9; j - i * 9 < 9 && j < visibleSections.size(); j++) { content.addSection(visibleSections.get(j)); } } @@ -86,37 +94,37 @@ public abstract class BookTransformer { public void transform(BookData book) { final int ENTRIES_PER_PAGE = 24; - for(SectionData section : book.sections) { - if(section.name.equals("index")) { + for (SectionData section : book.sections) { + if (section.name.equals("index")) { continue; } - if(this.sectionToTransform != null && !section.name.equals(this.sectionToTransform)) { + if (this.sectionToTransform != null && !section.name.equals(this.sectionToTransform)) { continue; } int genPages = (int) Math.ceil(section.getPageCount() * 1.F / ENTRIES_PER_PAGE); - if(genPages == 0) { + if (genPages == 0) { continue; } PageData[] pages = new PageData[genPages]; - for(int i = 0; i < pages.length; i++) { + for (int i = 0; i < pages.length; i++) { pages[i] = new PageData(true); pages[i].name = "tableofcontents" + i; TextData[] text = new TextData[i > pages.length - 1 ? ENTRIES_PER_PAGE : section - .getPageCount() - (genPages - 1) * ENTRIES_PER_PAGE]; - for(int j = 0; j < text.length; j++) { + .getPageCount() - (genPages - 1) * ENTRIES_PER_PAGE]; + for (int j = 0; j < text.length; j++) { text[j] = new TextData((i * ENTRIES_PER_PAGE + j + 1) + ". " + section.pages.get(i * ENTRIES_PER_PAGE + j) - .getTitle()); + .getTitle()); text[j].action = "go-to-page-rtn:" + section.name + "." + section.pages.get(i * ENTRIES_PER_PAGE + j).name; } pages[i].content = new ContentTableOfContents(i == 0 ? section.getTitle() : "", text); } - for(int i = pages.length - 1; i >= 0; i--) { + for (int i = pages.length - 1; i >= 0; i--) { section.pages.add(0, pages[i]); } } diff --git a/src/main/java/slimeknights/mantle/client/book/StructureBlockAccess.java b/src/main/java/slimeknights/mantle/client/book/StructureBlockAccess.java index f1040e2..fb0844a 100644 --- a/src/main/java/slimeknights/mantle/client/book/StructureBlockAccess.java +++ b/src/main/java/slimeknights/mantle/client/book/StructureBlockAccess.java @@ -23,8 +23,8 @@ import java.util.function.Predicate; import javax.annotation.Nullable; -public class StructureBlockAccess implements IWorldReader -{ +public class StructureBlockAccess implements IWorldReader { + private final StructureInfo data; private final BlockState[][][] structure; @@ -56,11 +56,11 @@ public class StructureBlockAccess implements IWorldReader int y = pos.getY(); int z = pos.getZ(); - if(y >= 0 && y < this.structure.length) { - if(x >= 0 && x < this.structure[y].length) { - if(z >= 0 && z < this.structure[y][x].length) { + if (y >= 0 && y < this.structure.length) { + if (x >= 0 && x < this.structure[y].length) { + if (z >= 0 && z < this.structure[y][x].length) { int index = y * (this.data.structureLength * this.data.structureWidth) + x * this.data.structureWidth + z; - if(index <= this.data.getLimiter()) { + if (index <= this.data.getLimiter()) { return this.structure[y][x][z] != null ? this.structure[y][x][z] : Blocks.AIR.getDefaultState(); } } diff --git a/src/main/java/slimeknights/mantle/client/book/StructureInfo.java b/src/main/java/slimeknights/mantle/client/book/StructureInfo.java index 8b23bc7..08e733e 100644 --- a/src/main/java/slimeknights/mantle/client/book/StructureInfo.java +++ b/src/main/java/slimeknights/mantle/client/book/StructureInfo.java @@ -13,6 +13,7 @@ import net.minecraftforge.registries.ForgeRegistries; import slimeknights.mantle.client.book.data.element.BlockData; public class StructureInfo { + public BlockState[][][] data; public int blockCount = 0; public int[] countPerLevel; @@ -30,11 +31,11 @@ public class StructureInfo { this.structureLength = length; BlockState[][][] states = new BlockState[height][length][width]; - for(int y = 0; y < height; y++) { - for(int x = 0; x < length; x++) { - for(int z = 0; z < width; z++) { - for(BlockData data : blockData) { - if(this.inside(x, y, z, data.pos, data.endPos)) { + for (int y = 0; y < height; y++) { + for (int x = 0; x < length; x++) { + for (int z = 0; z < width; z++) { + for (BlockData data : blockData) { + if (this.inside(x, y, z, data.pos, data.endPos)) { states[y][x][z] = this.convert(data); break; } @@ -49,12 +50,12 @@ public class StructureInfo { private BlockState convert(BlockData data) { Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(data.block)); - if(block == null) { + if (block == null) { return Blocks.AIR.getDefaultState(); } BlockState state = block.getDefaultState(); - if (data.state != null || !data.state.isEmpty()) { + if (data.state != null && !data.state.isEmpty()) { for (Map.Entry entry : data.state.entrySet()) { Optional> property = state.getProperties().stream().filter(iProperty -> entry.getKey().equals(iProperty.getName())).findFirst(); @@ -69,16 +70,15 @@ public class StructureInfo { private > BlockState setProperty(BlockState state, IProperty prop, String valueString) { java.util.Optional value = prop.parseValue(valueString); - if(value.isPresent()) { + if (value.isPresent()) { state = state.with(prop, value.get()); } return state; } - private boolean inside(int x, int y, int z, int[] rangeStart, int[] rangeEnd) { - if(x >= rangeStart[0] && x <= rangeEnd[0]) { - if(y >= rangeStart[1] && y <= rangeEnd[1]) { + if (x >= rangeStart[0] && x <= rangeEnd[0]) { + if (y >= rangeStart[1] && y <= rangeEnd[1]) { return z >= rangeStart[2] && z <= rangeEnd[2]; } } @@ -98,20 +98,22 @@ public class StructureInfo { public boolean canStep() { int index = this.blockIndex; do { - if(++index >= this.maxBlockIndex) { + if (++index >= this.maxBlockIndex) { return false; } - } while(this.isEmpty(index)); + } + while (this.isEmpty(index)); return true; } public void step() { int start = this.blockIndex; do { - if(++this.blockIndex >= this.maxBlockIndex) { + if (++this.blockIndex >= this.maxBlockIndex) { this.blockIndex = 0; } - } while(this.isEmpty(this.blockIndex) && this.blockIndex != start); + } + while (this.isEmpty(this.blockIndex) && this.blockIndex != start); } private boolean isEmpty(int index) { diff --git a/src/main/java/slimeknights/mantle/client/book/action/StringActionProcessor.java b/src/main/java/slimeknights/mantle/client/book/action/StringActionProcessor.java index eb151e5..e3fe521 100644 --- a/src/main/java/slimeknights/mantle/client/book/action/StringActionProcessor.java +++ b/src/main/java/slimeknights/mantle/client/book/action/StringActionProcessor.java @@ -3,7 +3,7 @@ package slimeknights.mantle.client.book.action; import java.util.HashMap; import slimeknights.mantle.client.book.action.protocol.ActionProtocol; -import slimeknights.mantle.client.gui.book.GuiBook; +import slimeknights.mantle.client.screen.book.BookScreen; public class StringActionProcessor { @@ -12,10 +12,10 @@ public class StringActionProcessor { private static final HashMap protocols = new HashMap<>(); public static void registerProtocol(ActionProtocol protocol) { - if(protocol == null || protocol.protocol == null || protocol.protocol.isEmpty()) { + if (protocol == null || protocol.protocol == null || protocol.protocol.isEmpty()) { throw new IllegalArgumentException("Protocol must be defined and must not have an empty protocol identifier."); } - if(protocols.containsKey(protocol.protocol)) { + if (protocols.containsKey(protocol.protocol)) { throw new IllegalArgumentException("Protocol " + protocol.protocol + " already registered."); } @@ -23,15 +23,15 @@ public class StringActionProcessor { } //Format: action://param - public static void process(String action, GuiBook book) { - if(!action.contains(PROTOCOL_SEPARATOR)) { + public static void process(String action, BookScreen book) { + if (!action.contains(PROTOCOL_SEPARATOR)) { return; } String protoId = action.substring(0, action.indexOf(PROTOCOL_SEPARATOR)); String protoParam = action.substring(action.indexOf(PROTOCOL_SEPARATOR) + PROTOCOL_SEPARATOR.length()); - if(protocols.containsKey(protoId)) { + if (protocols.containsKey(protoId)) { protocols.get(protoId).processCommand(book, protoParam); } } diff --git a/src/main/java/slimeknights/mantle/client/book/action/protocol/ActionProtocol.java b/src/main/java/slimeknights/mantle/client/book/action/protocol/ActionProtocol.java index c583aca..67544a1 100644 --- a/src/main/java/slimeknights/mantle/client/book/action/protocol/ActionProtocol.java +++ b/src/main/java/slimeknights/mantle/client/book/action/protocol/ActionProtocol.java @@ -1,6 +1,6 @@ package slimeknights.mantle.client.book.action.protocol; -import slimeknights.mantle.client.gui.book.GuiBook; +import slimeknights.mantle.client.screen.book.BookScreen; public abstract class ActionProtocol { @@ -10,5 +10,5 @@ public abstract class ActionProtocol { this.protocol = protocol; } - public abstract void processCommand(GuiBook book, String param); + public abstract void processCommand(BookScreen book, String param); } diff --git a/src/main/java/slimeknights/mantle/client/book/action/protocol/ProtocolGoToPage.java b/src/main/java/slimeknights/mantle/client/book/action/protocol/ProtocolGoToPage.java index 78fa068..895fb7a 100644 --- a/src/main/java/slimeknights/mantle/client/book/action/protocol/ProtocolGoToPage.java +++ b/src/main/java/slimeknights/mantle/client/book/action/protocol/ProtocolGoToPage.java @@ -1,6 +1,6 @@ package slimeknights.mantle.client.book.action.protocol; -import slimeknights.mantle.client.gui.book.GuiBook; +import slimeknights.mantle.client.screen.book.BookScreen; public class ProtocolGoToPage extends ActionProtocol { @@ -20,10 +20,10 @@ public class ProtocolGoToPage extends ActionProtocol { } @Override - public void processCommand(GuiBook book, String param) { + public void processCommand(BookScreen book, String param) { int pageNum = book.book.findPageNumber(param); - if(pageNum >= 0) { + if (pageNum >= 0) { book.openPage(pageNum, this.returner); } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/BookData.java b/src/main/java/slimeknights/mantle/client/book/data/BookData.java index e13135e..f809784 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/BookData.java +++ b/src/main/java/slimeknights/mantle/client/book/data/BookData.java @@ -4,6 +4,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; +import net.minecraft.util.text.ITextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import slimeknights.mantle.Mantle; @@ -12,8 +13,9 @@ import slimeknights.mantle.client.book.BookTransformer; import slimeknights.mantle.client.book.data.content.ContentError; import slimeknights.mantle.client.book.data.element.ItemStackData; import slimeknights.mantle.client.book.repository.BookRepository; -import slimeknights.mantle.client.gui.book.GuiBook; +import slimeknights.mantle.client.screen.book.BookScreen; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -49,7 +51,7 @@ public class BookData implements IDataItem { @Override public void load() { - if(this.initialized) { + if (this.initialized) { return; } Mantle.logger.info("Started loading book..."); @@ -59,15 +61,16 @@ public class BookData implements IDataItem { this.appearance = new AppearanceData(); this.itemLinks.clear(); - for(BookRepository repo : this.repositories) { + for (BookRepository repo : this.repositories) { try { List repoContents = repo.getSections(); this.sections.addAll(repoContents); - for(SectionData section : repoContents) { + for (SectionData section : repoContents) { section.source = repo; } - } catch(Exception e) { + } + catch (Exception e) { SectionData error = new SectionData(); error.name = "errorenous"; PageData page = new PageData(true); @@ -81,11 +84,12 @@ public class BookData implements IDataItem { ResourceLocation appearanceLocation = repo.getResourceLocation("appearance.json"); - if(repo.resourceExists(appearanceLocation)) { + if (repo.resourceExists(appearanceLocation)) { try { this.appearance = BookLoader.GSON - .fromJson(repo.resourceToString(repo.getResource(appearanceLocation)), AppearanceData.class); - } catch(Exception e) { + .fromJson(repo.resourceToString(repo.getResource(appearanceLocation)), AppearanceData.class); + } + catch (Exception e) { e.printStackTrace(); } } @@ -94,26 +98,27 @@ public class BookData implements IDataItem { ResourceLocation itemLinkLocation = repo.getResourceLocation("items.json"); - if(repo.resourceExists(itemLinkLocation)) { + if (repo.resourceExists(itemLinkLocation)) { try { this.itemLinks = new ArrayList<>(Arrays.asList(BookLoader.GSON - .fromJson(repo.resourceToString(repo.getResource(itemLinkLocation)), ItemStackData.ItemLink[].class))); - } catch(Exception e) { + .fromJson(repo.resourceToString(repo.getResource(itemLinkLocation)), ItemStackData.ItemLink[].class))); + } + catch (Exception e) { e.printStackTrace(); } } ResourceLocation languageLocation = repo.getResourceLocation("language.lang"); - if(repo.resourceExists(languageLocation)) { + if (repo.resourceExists(languageLocation)) { try { BufferedReader br = new BufferedReader(new InputStreamReader(repo.getResource(languageLocation) - .getInputStream(), StandardCharsets.UTF_8)); + .getInputStream(), StandardCharsets.UTF_8)); String next = br.readLine(); - while(next != null) { - if(!next.startsWith("//") && next.contains("=")) { + while (next != null) { + if (!next.startsWith("//") && next.contains("=")) { String key = next.substring(0, next.indexOf('=')); String value = next.substring(next.indexOf('=') + 1); @@ -122,36 +127,38 @@ public class BookData implements IDataItem { next = br.readLine(); } - } catch(Exception ignored) { + } + catch (Exception ignored) { } } } - for(int i = 0; i < this.sections.size(); i++){ + for (int i = 0; i < this.sections.size(); i++) { SectionData section = this.sections.get(i); - if(section.name == null) + if (section.name == null) { continue; + } List matchingSections = this.sections.stream().filter(sect -> section.name.equalsIgnoreCase(sect.name)).collect(Collectors.toList()); - if(matchingSections.size() < 2){ + if (matchingSections.size() < 2) { continue; } LinkedSectionData linkedSection = new LinkedSectionData(); - for(SectionData match : matchingSections){ - linkedSection.addSection(match); + for (SectionData match : matchingSections) { + linkedSection.addSection(match); - if(match != section){ - this.sections.remove(match); - } + if (match != section) { + this.sections.remove(match); } + } this.sections.set(i, linkedSection); } - for(SectionData section : this.sections) { - if(section.source == null) { + for (SectionData section : this.sections) { + if (section.source == null) { section.source = BookRepository.DUMMY; } @@ -159,22 +166,23 @@ public class BookData implements IDataItem { section.load(); } - for(BookTransformer transformer : this.transformers) { + for (BookTransformer transformer : this.transformers) { transformer.transform(this); } // Loads orphaned sections, unless something went wrong, that would only be sections added by a transformer - for(SectionData section : this.sections) { - if(section.source == null) { + for (SectionData section : this.sections) { + if (section.source == null) { section.source = BookRepository.DUMMY; } - if(section.parent == null) { + if (section.parent == null) { section.parent = this; section.load(); } } - } catch(Exception e) { + } + catch (Exception e) { this.sections.clear(); SectionData section = new SectionData(true); section.name = "errorenous"; @@ -194,11 +202,11 @@ public class BookData implements IDataItem { return this.findSection(name, null); } - public SectionData findSection(String name, GuiBook.AdvancementCache advancementCache) { - for(SectionData section : this.sections) { + public SectionData findSection(String name, BookScreen.AdvancementCache advancementCache) { + for (SectionData section : this.sections) { section.update(advancementCache); - if(section.name.equals(name.toLowerCase())) { + if (section.name.equals(name.toLowerCase())) { return section.isUnlocked(advancementCache) ? section : null; } } @@ -210,16 +218,16 @@ public class BookData implements IDataItem { return this.getFirstPageNumber(section, null); } - public int getFirstPageNumber(SectionData section, @Nullable GuiBook.AdvancementCache advancementCache) { + public int getFirstPageNumber(SectionData section, @Nullable BookScreen.AdvancementCache advancementCache) { int pages = 0; - for(SectionData sect : this.sections) { + for (SectionData sect : this.sections) { sect.update(advancementCache); - if(section == sect) { + if (section == sect) { return section.isUnlocked(advancementCache) ? pages + 1 : -1; } - if(!sect.isUnlocked(advancementCache)) { + if (!sect.isUnlocked(advancementCache)) { continue; } @@ -233,20 +241,20 @@ public class BookData implements IDataItem { return this.findPage(number, null); } - public PageData findPage(int number, @Nullable GuiBook.AdvancementCache advancementCache) { - if(number < 0) { + public PageData findPage(int number, @Nullable BookScreen.AdvancementCache advancementCache) { + if (number < 0) { return null; } int pages = 0; - for(SectionData section : this.sections) { + for (SectionData section : this.sections) { section.update(advancementCache); - if(!section.isUnlocked(advancementCache)) { + if (!section.isUnlocked(advancementCache)) { continue; } - if(pages + section.getPageCount() > number) { + if (pages + section.getPageCount() > number) { return section.pages.get(number - pages); } else { @@ -261,7 +269,7 @@ public class BookData implements IDataItem { return this.findPage(location, null); } - public PageData findPage(String location, @Nullable GuiBook.AdvancementCache advancementCache) { + public PageData findPage(String location, @Nullable BookScreen.AdvancementCache advancementCache) { return this.findPage(this.findPageNumber(location, advancementCache)); } @@ -269,32 +277,32 @@ public class BookData implements IDataItem { return this.findPageNumber(location, null); } - public int findPageNumber(String location, @Nullable GuiBook.AdvancementCache advancementCache) { + public int findPageNumber(String location, @Nullable BookScreen.AdvancementCache advancementCache) { location = location.toLowerCase(); int pages = 0; - if(!location.contains(".")) { + if (!location.contains(".")) { return -1; } String sectionName = location.substring(0, location.indexOf('.')); String pageName = location.substring(location.indexOf('.') + 1); - for(SectionData section : this.sections) { + for (SectionData section : this.sections) { section.update(advancementCache); - if(!section.isUnlocked(advancementCache)) { + if (!section.isUnlocked(advancementCache)) { continue; } - if(!sectionName.equals(section.name)) { + if (!sectionName.equals(section.name)) { pages += section.getPageCount(); continue; } - for(PageData page : section.pages) { - if(!pageName.equals(page.name)) { + for (PageData page : section.pages) { + if (!pageName.equals(page.name)) { pages++; continue; } @@ -310,9 +318,9 @@ public class BookData implements IDataItem { return this.getPageCount(null); } - public int getPageCount(@Nullable GuiBook.AdvancementCache advancementCache) { + public int getPageCount(@Nullable BookScreen.AdvancementCache advancementCache) { int pages = 0; - for(SectionData section : this.sections) { + for (SectionData section : this.sections) { section.update(advancementCache); pages += section.isUnlocked(advancementCache) ? section.getPageCount() : 0; @@ -324,13 +332,13 @@ public class BookData implements IDataItem { return this.getFullPageCount(null); } - public int getFullPageCount(@Nullable GuiBook.AdvancementCache advancementCache) { + public int getFullPageCount(@Nullable BookScreen.AdvancementCache advancementCache) { return (int) Math.ceil((this.getPageCount(advancementCache) - 1) / 2F) + 1; } public String getItemAction(ItemStackData item) { - for(ItemStackData.ItemLink link : this.itemLinks) { - if(item.id.equals(link.item.id) && (!link.damageSensitive)) { + for (ItemStackData.ItemLink link : this.itemLinks) { + if (item.id.equals(link.item.id) && (!link.damageSensitive)) { return link.action; } } @@ -338,11 +346,11 @@ public class BookData implements IDataItem { return ""; } - public List getVisibleSections(GuiBook.AdvancementCache advancementCache) { + public List getVisibleSections(BookScreen.AdvancementCache advancementCache) { List visible = new ArrayList<>(); - for(SectionData section : this.sections) { - if(section.isUnlocked(advancementCache) || !section.hideWhenLocked) { + for (SectionData section : this.sections) { + if (section.isUnlocked(advancementCache) || !section.hideWhenLocked) { visible.add(section); } } @@ -350,29 +358,28 @@ public class BookData implements IDataItem { return visible; } - public String translate(String string) { String out = this.strings.get(string); return out != null ? out : string; } - public void openGui(@Nullable ItemStack item) { - if(!this.initialized) { + public void openGui(@Nonnull ITextComponent title, @Nullable ItemStack item) { + if (!this.initialized) { this.load(); } - if(Minecraft.getInstance().player != null) { - Minecraft.getInstance().displayGuiScreen(new GuiBook(this, item)); + if (Minecraft.getInstance().player != null) { + Minecraft.getInstance().displayGuiScreen(new BookScreen(title, this, item)); } } public void addRepository(BookRepository repository) { - if(repository != null && !this.repositories.contains(repository)) { + if (repository != null && !this.repositories.contains(repository)) { this.repositories.add(repository); } } public void addTransformer(BookTransformer transformer) { - if(transformer != null && !this.transformers.contains(transformer)) { + if (transformer != null && !this.transformers.contains(transformer)) { this.transformers.add(transformer); } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/LinkedSectionData.java b/src/main/java/slimeknights/mantle/client/book/data/LinkedSectionData.java index 70d586a..466c264 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/LinkedSectionData.java +++ b/src/main/java/slimeknights/mantle/client/book/data/LinkedSectionData.java @@ -3,43 +3,44 @@ package slimeknights.mantle.client.book.data; import java.util.ArrayList; public class LinkedSectionData extends SectionData { - private transient ArrayList sections = new ArrayList<>(); - public LinkedSectionData(){ - super(true); + private transient ArrayList sections = new ArrayList<>(); + + public LinkedSectionData() { + super(true); + } + + @Override + public void load() { + this.pages.clear(); + + this.name = this.name.toLowerCase(); + + for (SectionData section : this.sections) { + section.parent = this.parent; + section.unnamedPageCounter = this.unnamedPageCounter; + section.load(); + this.unnamedPageCounter = section.unnamedPageCounter; + + this.pages.addAll(section.pages); } - @Override - public void load() { - this.pages.clear(); + this.icon.location = this.source.getResourceLocation(this.icon.file, true); + } - this.name = this.name.toLowerCase(); - - for(SectionData section : this.sections){ - section.parent = this.parent; - section.unnamedPageCounter = this.unnamedPageCounter; - section.load(); - this.unnamedPageCounter = section.unnamedPageCounter; - - this.pages.addAll(section.pages); - } - - this.icon.location = this.source.getResourceLocation(this.icon.file, true); + public void addSection(SectionData data) { + if (!data.name.equalsIgnoreCase(this.name) && !this.sections.isEmpty()) { + throw new IllegalArgumentException("Linked sections must contain all sections of the same name."); } - public void addSection(SectionData data){ - if(!data.name.equalsIgnoreCase(this.name) && !this.sections.isEmpty()){ - throw new IllegalArgumentException("Linked sections must contain all sections of the same name."); - } + if (this.sections.isEmpty()) { + this.name = data.name; + this.icon = data.icon; + this.hideWhenLocked = data.hideWhenLocked; - if(this.sections.isEmpty()){ - this.name = data.name; - this.icon = data.icon; - this.hideWhenLocked = data.hideWhenLocked; - - } - - this.requirements.addAll(data.requirements); - this.sections.add(data); } + + this.requirements.addAll(data.requirements); + this.sections.add(data); + } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/PageData.java b/src/main/java/slimeknights/mantle/client/book/data/PageData.java index c37ce13..fbb507c 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/PageData.java +++ b/src/main/java/slimeknights/mantle/client/book/data/PageData.java @@ -1,11 +1,6 @@ package slimeknights.mantle.client.book.data; import net.minecraft.client.renderer.texture.AtlasTexture; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; - import net.minecraft.resources.IResource; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -17,6 +12,10 @@ import slimeknights.mantle.client.book.data.element.DataLocation; import slimeknights.mantle.client.book.data.element.ItemStackData; import slimeknights.mantle.client.book.repository.BookRepository; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; + @OnlyIn(Dist.CLIENT) public class PageData implements IDataItem { @@ -36,7 +35,7 @@ public class PageData implements IDataItem { } public PageData(boolean custom) { - if(custom) { + if (custom) { this.data = "no-load"; } } @@ -48,32 +47,34 @@ public class PageData implements IDataItem { @Override @SuppressWarnings("unchecked") public void load() { - if(this.name == null) { + if (this.name == null) { this.name = "page" + this.parent.unnamedPageCounter++; } this.name = this.name.toLowerCase(); - if(!this.data.equals("no-load")) { + if (!this.data.equals("no-load")) { IResource pageInfo = this.source.getResource(this.source.getResourceLocation(this.data)); - if(pageInfo != null) { + if (pageInfo != null) { String data = this.source.resourceToString(pageInfo); - if(!data.isEmpty()) { + if (!data.isEmpty()) { Class ctype = BookLoader.getPageType(this.type); try { this.content = BookLoader.GSON.fromJson(data, ctype); - } catch(Exception e) { + } + catch (Exception e) { this.content = new ContentError(ctype == null ? "Failed to create a page of type \"" + this.type + "\", perhaps the type is not registered?" : "Failed to create a page of type \"" + this.type + "\", perhaps the page file \"" + this.data + "\" is missing or invalid?", e); } } } } - if(this.content == null) { + if (this.content == null) { try { this.content = BookLoader.getPageType(this.type).newInstance(); - } catch(InstantiationException | IllegalAccessException | NullPointerException e) { + } + catch (InstantiationException | IllegalAccessException | NullPointerException e) { this.content = new ContentError("Failed to create a page of type \"" + this.type + "\", perhaps the type is not registered?"); } } @@ -81,48 +82,53 @@ public class PageData implements IDataItem { try { this.content.parent = this; this.content.load(); - } catch(Exception e) { + } + catch (Exception e) { this.content = new ContentError("Failed to load page " + this.parent.name + "." + this.name + ".", e); e.printStackTrace(); } this.content.source = this.source; - for(Field f : this.content.getClass().getFields()) { - if(Modifier.isTransient(f.getModifiers()) || Modifier.isStatic(f.getModifiers()) || Modifier - .isFinal(f.getModifiers())) { + for (Field f : this.content.getClass().getFields()) { + if (Modifier.isTransient(f.getModifiers()) || Modifier.isStatic(f.getModifiers()) || Modifier + .isFinal(f.getModifiers())) { continue; } try { - if(f.get(this.content) == null) { + if (f.get(this.content) == null) { continue; } - } catch(IllegalAccessException e) { + } + catch (IllegalAccessException e) { e.printStackTrace(); } - for(ValueHotswap swap : hotswaps) { + for (ValueHotswap swap : hotswaps) { Class c = f.getType(); - if(c.isArray() && c.getComponentType().isAssignableFrom(swap.t)) { + if (c.isArray() && c.getComponentType().isAssignableFrom(swap.t)) { try { f.setAccessible(true); Object[] o = (Object[]) f.get(this.content); - for(Object ob : o) { + for (Object ob : o) { swap.swap(this.source, ob); } - } catch(IllegalAccessException e) { + } + catch (IllegalAccessException e) { e.printStackTrace(); } - } else if(swap.t.isAssignableFrom(c)) { + } + else if (swap.t.isAssignableFrom(c)) { try { f.setAccessible(true); Object o = f.get(this.content); swap.swap(this.source, o); - } catch(IllegalAccessException e) { + } + catch (IllegalAccessException e) { e.printStackTrace(); } } @@ -136,7 +142,8 @@ public class PageData implements IDataItem { hotswap.t = t; hotswaps.add(hotswap); - } catch(InstantiationException | IllegalAccessException e) { + } + catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } @@ -151,7 +158,7 @@ public class PageData implements IDataItem { @Override public void swap(BookRepository source, DataLocation object) { object.location = object.file == "$BLOCK_ATLAS" ? AtlasTexture.LOCATION_BLOCKS_TEXTURE : source - .getResourceLocation(object.file, true); + .getResourceLocation(object.file, true); } }.getClass()); addSwap(ItemStackData.class, new ValueHotswap() { @@ -160,7 +167,7 @@ public class PageData implements IDataItem { object.source = source; object.itemListLocation = source.getResourceLocation(object.itemList); - if(object.itemListLocation != null) { + if (object.itemListLocation != null) { object.id = "->itemList"; } } @@ -168,7 +175,7 @@ public class PageData implements IDataItem { addSwap(BlockData.class, new ValueHotswap() { @Override public void swap(BookRepository source, BlockData object) { - if(object.endPos == null) { + if (object.endPos == null) { object.endPos = object.pos; } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/PageDataModule.java b/src/main/java/slimeknights/mantle/client/book/data/PageDataModule.java index e93fe04..05218dd 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/PageDataModule.java +++ b/src/main/java/slimeknights/mantle/client/book/data/PageDataModule.java @@ -1,6 +1,7 @@ package slimeknights.mantle.client.book.data; public class PageDataModule extends PageData { - /** Module required to load this section, see {@link slimeknights.mantle.pulsar.control.PulseManager#isPulseLoaded(String)} for more details */ - public String module = ""; + + /** Module required to load this section, see {@link slimeknights.mantle.pulsar.control.PulseManager#isPulseLoaded(String)} for more details */ + public String module = ""; } diff --git a/src/main/java/slimeknights/mantle/client/book/data/SectionData.java b/src/main/java/slimeknights/mantle/client/book/data/SectionData.java index 6056aac..3fdb4d0 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/SectionData.java +++ b/src/main/java/slimeknights/mantle/client/book/data/SectionData.java @@ -9,7 +9,7 @@ import slimeknights.mantle.client.book.BookLoader; import slimeknights.mantle.client.book.data.content.ContentError; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.repository.BookRepository; -import slimeknights.mantle.client.gui.book.GuiBook; +import slimeknights.mantle.client.screen.book.BookScreen; import javax.annotation.Nullable; import java.util.ArrayList; @@ -35,7 +35,7 @@ public class SectionData implements IDataItem { } public SectionData(boolean custom) { - if(custom) { + if (custom) { this.data = "no-load"; } } @@ -46,20 +46,21 @@ public class SectionData implements IDataItem { @Override public void load() { - if(this.name == null) { + if (this.name == null) { this.name = "section" + this.parent.unnamedSectionCounter++; } this.name = this.name.toLowerCase(); - if(!this.data.equals("no-load")) { + if (!this.data.equals("no-load")) { IResource pagesInfo = this.source.getResource(this.source.getResourceLocation(this.data)); - if(pagesInfo != null) { + if (pagesInfo != null) { String data = this.source.resourceToString(pagesInfo); - if(!data.isEmpty()) { + if (!data.isEmpty()) { try { this.pages = this.getPages(data); - } catch(Exception e) { + } + catch (Exception e) { this.pages = new ArrayList<>(); PageData pdError = new PageData(true); pdError.name = "errorrenous"; @@ -72,7 +73,7 @@ public class SectionData implements IDataItem { } } - for(PageData page : this.pages) { + for (PageData page : this.pages) { page.parent = this; page.source = this.source; page.load(); @@ -84,13 +85,13 @@ public class SectionData implements IDataItem { /** * Gets a list of pages from the given data * @param data JSON data - * @return ArrayList of pages for the book + * @return ArrayList of pages for the book */ protected ArrayList getPages(String data) { return new ArrayList<>(Arrays.asList(BookLoader.GSON.fromJson(data, PageData[].class))); } - public void update(@Nullable GuiBook.AdvancementCache advancementCache) { + public void update(@Nullable BookScreen.AdvancementCache advancementCache) { } public String getTitle() { @@ -102,13 +103,13 @@ public class SectionData implements IDataItem { return this.pages.size(); } - public boolean isUnlocked(GuiBook.AdvancementCache advancementCache) { - if(advancementCache == null || this.requirements == null || this.requirements.size() == 0) { + public boolean isUnlocked(BookScreen.AdvancementCache advancementCache) { + if (advancementCache == null || this.requirements == null || this.requirements.size() == 0) { return true; } - for(String achievement : this.requirements) { - if(!requirementSatisfied(achievement, advancementCache)) { + for (String achievement : this.requirements) { + if (!requirementSatisfied(achievement, advancementCache)) { return false; } } @@ -116,8 +117,8 @@ public class SectionData implements IDataItem { return true; } - public static boolean requirementSatisfied(String requirement, GuiBook.AdvancementCache advancementCache) { - if(advancementCache == null) { + public static boolean requirementSatisfied(String requirement, BookScreen.AdvancementCache advancementCache) { + if (advancementCache == null) { return true; } diff --git a/src/main/java/slimeknights/mantle/client/book/data/SectionDataModule.java b/src/main/java/slimeknights/mantle/client/book/data/SectionDataModule.java index 722ae40..46611f9 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/SectionDataModule.java +++ b/src/main/java/slimeknights/mantle/client/book/data/SectionDataModule.java @@ -9,19 +9,20 @@ import java.util.function.Predicate; import java.util.stream.Collectors; public class SectionDataModule extends SectionData { + /** Module required to load this section, see {@link slimeknights.mantle.pulsar.control.PulseManager#isPulseLoaded(String)} for more details */ public String module = ""; @Override protected ArrayList getPages(String data) { - // this should always be the case, but just for safety - if(this.source instanceof ModuleFileRepository) { - // just filters out pages where the module is not loaded - Predicate manager = ((ModuleFileRepository) this.source).getManager(); - return new ArrayList<>(Arrays.stream(BookLoader.GSON.fromJson(data, PageDataModule[].class)) - .filter((page)->page.module.isEmpty() || manager.test(page.module)) - .collect(Collectors.toList())); - } - return super.getPages(data); + // this should always be the case, but just for safety + if (this.source instanceof ModuleFileRepository) { + // just filters out pages where the module is not loaded + Predicate manager = ((ModuleFileRepository) this.source).getManager(); + return new ArrayList<>(Arrays.stream(BookLoader.GSON.fromJson(data, PageDataModule[].class)) + .filter((page) -> page.module.isEmpty() || manager.test(page.module)) + .collect(Collectors.toList())); } + return super.getPages(data); + } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentBlank.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentBlank.java index ddc55c1..0ef00a2 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentBlank.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentBlank.java @@ -1,12 +1,11 @@ package slimeknights.mantle.client.book.data.content; - -import java.util.ArrayList; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import slimeknights.mantle.client.book.data.BookData; -import slimeknights.mantle.client.gui.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.BookElement; + +import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public class ContentBlank extends PageContent { diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentBlockInteraction.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentBlockInteraction.java index bc8cd4b..9e1d51c 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentBlockInteraction.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentBlockInteraction.java @@ -1,18 +1,18 @@ package slimeknights.mantle.client.book.data.content; -import java.util.ArrayList; - import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.data.element.ItemStackData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementImage; -import slimeknights.mantle.client.gui.book.element.ElementItem; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementImage; +import slimeknights.mantle.client.screen.book.element.ElementItem; +import slimeknights.mantle.client.screen.book.element.ElementText; -import static slimeknights.mantle.client.gui.book.Textures.TEX_MISC; +import java.util.ArrayList; + +import static slimeknights.mantle.client.screen.book.Textures.TEX_MISC; public class ContentBlockInteraction extends PageContent { @@ -34,27 +34,28 @@ public class ContentBlockInteraction extends PageContent { @Override public void build(BookData book, ArrayList list, boolean rightSide) { - int x = GuiBook.PAGE_WIDTH / 2 - IMG_SMITHING.width / 2 - 10; + int x = BookScreen.PAGE_WIDTH / 2 - IMG_SMITHING.width / 2 - 10; int y = TITLE_HEIGHT; - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } list.add(new ElementImage(x, y, IMG_SMITHING.width, IMG_SMITHING.height, IMG_SMITHING, book.appearance.slotColor)); - if(this.input != null && !this.input.id.equals("")) { + if (this.input != null && !this.input.id.equals("")) { list.add(new ElementItem(x + INPUT_X, y + INPUT_Y, ITEM_SCALE, this.input.getItems(), this.input.action)); } - if(this.block != null && !this.block.id.equals("")) { + if (this.block != null && !this.block.id.equals("")) { list.add(new ElementItem(x + BLOCK_X, y + BLOCK_Y, BLOCK_SCALE, this.block.getItems(), this.block.action)); } - if(this.description != null && this.description.length > 0) { - list.add(new ElementText(0, IMG_SMITHING.height + y + 50, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - IMG_SMITHING.height - y - 50, this.description)); + if (this.description != null && this.description.length > 0) { + list.add(new ElementText(0, IMG_SMITHING.height + y + 50, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - IMG_SMITHING.height - y - 50, this.description)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentCrafting.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentCrafting.java index 243edd3..539d232 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentCrafting.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentCrafting.java @@ -1,18 +1,18 @@ package slimeknights.mantle.client.book.data.content; -import java.util.ArrayList; - import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.data.element.ItemStackData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementImage; -import slimeknights.mantle.client.gui.book.element.ElementItem; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementImage; +import slimeknights.mantle.client.screen.book.element.ElementItem; +import slimeknights.mantle.client.screen.book.element.ElementText; -import static slimeknights.mantle.client.gui.book.Textures.TEX_CRAFTING; +import java.util.ArrayList; + +import static slimeknights.mantle.client.screen.book.Textures.TEX_CRAFTING; public class ContentCrafting extends PageContent { @@ -45,42 +45,40 @@ public class ContentCrafting extends PageContent { TextData tdTitle = new TextData(this.title); tdTitle.underlined = true; - list.add(new ElementText(0, 0, GuiBook.PAGE_WIDTH, 9, tdTitle)); + list.add(new ElementText(0, 0, BookScreen.PAGE_WIDTH, 9, tdTitle)); - if(this.grid_size.equalsIgnoreCase("small")) { - x = GuiBook.PAGE_WIDTH / 2 - IMG_CRAFTING_SMALL.width / 2; + if (this.grid_size.equalsIgnoreCase("small")) { + x = BookScreen.PAGE_WIDTH / 2 - IMG_CRAFTING_SMALL.width / 2; height = y + IMG_CRAFTING_SMALL.height; list.add(new ElementImage(x, y, IMG_CRAFTING_SMALL.width, IMG_CRAFTING_SMALL.height, IMG_CRAFTING_SMALL, book.appearance.slotColor)); resultX = x + X_RESULT_SMALL; resultY = y + Y_RESULT_SMALL; - } else if(this.grid_size.equalsIgnoreCase("large")) { - x = GuiBook.PAGE_WIDTH / 2 - IMG_CRAFTING_LARGE.width / 2; + } + else if (this.grid_size.equalsIgnoreCase("large")) { + x = BookScreen.PAGE_WIDTH / 2 - IMG_CRAFTING_LARGE.width / 2; height = y + IMG_CRAFTING_LARGE.height; list.add(new ElementImage(x, y, IMG_CRAFTING_LARGE.width, IMG_CRAFTING_LARGE.height, IMG_CRAFTING_LARGE, book.appearance.slotColor)); resultX = x + X_RESULT_LARGE; resultY = y + Y_RESULT_LARGE; } - if(this.grid != null) { - for(int i = 0; i < this.grid.length; i++) { - for(int j = 0; j < this.grid[i].length; j++) { - if(this.grid[i][j].id.equals("")) { + if (this.grid != null) { + for (int i = 0; i < this.grid.length; i++) { + for (int j = 0; j < this.grid[i].length; j++) { + if (this.grid[i][j].id.equals("")) { continue; } - list.add(new ElementItem(x + SLOT_MARGIN + (SLOT_PADDING + Math - .round(ElementItem.ITEM_SIZE_HARDCODED * ITEM_SCALE)) * j, y + SLOT_MARGIN + (SLOT_PADDING + Math - .round(ElementItem.ITEM_SIZE_HARDCODED * ITEM_SCALE)) * i, ITEM_SCALE, this.grid[i][j] - .getItems(), this.grid[i][j].action)); + list.add(new ElementItem(x + SLOT_MARGIN + (SLOT_PADDING + Math.round(ElementItem.ITEM_SIZE_HARDCODED * ITEM_SCALE)) * j, y + SLOT_MARGIN + (SLOT_PADDING + Math.round(ElementItem.ITEM_SIZE_HARDCODED * ITEM_SCALE)) * i, ITEM_SCALE, this.grid[i][j].getItems(), this.grid[i][j].action)); } } } - if(this.result != null) { + if (this.result != null) { list.add(new ElementItem(resultX, resultY, ITEM_SCALE, this.result.getItems(), this.result.action)); } - if(this.description != null && this.description.length > 0) { - list.add(new ElementText(0, height + 5, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - height - 5, this.description)); + if (this.description != null && this.description.length > 0) { + list.add(new ElementText(0, height + 5, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - height - 5, this.description)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentDummy.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentDummy.java index ab75458..b6debc0 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentDummy.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentDummy.java @@ -1,11 +1,11 @@ package slimeknights.mantle.client.book.data.content; -import java.util.ArrayList; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import slimeknights.mantle.client.book.data.BookData; -import slimeknights.mantle.client.gui.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.BookElement; + +import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public class ContentDummy extends PageContent { diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentError.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentError.java index c67bbdd..5061bdd 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentError.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentError.java @@ -1,14 +1,14 @@ package slimeknights.mantle.client.book.data.content; -import java.util.ArrayList; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementText; + +import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public class ContentError extends PageContent { @@ -30,7 +30,7 @@ public class ContentError extends PageContent { this.addTitle(list, "Error"); StackTraceElement[] stackTrace = null; - if(this.exception != null){ + if (this.exception != null) { stackTrace = this.exception.getStackTrace(); } @@ -40,21 +40,20 @@ public class ContentError extends PageContent { text[0].underlined = true; text[0].paragraph = true; - if(this.exception != null) { + if (this.exception != null) { text[1] = new TextData("The following error has occured:"); text[1].color = "dark_red"; text[1].paragraph = true; - text[2] = new TextData(this.exception.getMessage() != null ? this.exception.getMessage() : this.exception.getClass() - .getSimpleName()); + text[2] = new TextData(this.exception.getMessage() != null ? this.exception.getMessage() : this.exception.getClass().getSimpleName()); text[2].color = "dark_red"; text[2].paragraph = true; } text[3] = TextData.LINEBREAK; - if(stackTrace != null){ - for(int i = 0; i < stackTrace.length && 5 + i * 2 < text.length; i++){ + if (stackTrace != null) { + for (int i = 0; i < stackTrace.length && 5 + i * 2 < text.length; i++) { text[4 + i * 2] = new TextData(stackTrace[i].toString()); text[4 + i * 2].text += "\n"; text[4 + i * 2].color = "dark_red"; @@ -62,6 +61,6 @@ public class ContentError extends PageContent { } } - list.add(new ElementText(0, TITLE_HEIGHT, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - TITLE_HEIGHT, text)); + list.add(new ElementText(0, TITLE_HEIGHT, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - TITLE_HEIGHT, text)); } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentImage.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentImage.java index e872292..6a1bae5 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentImage.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentImage.java @@ -1,14 +1,14 @@ package slimeknights.mantle.client.book.data.content; -import java.util.ArrayList; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementImage; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementImage; + +import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public class ContentImage extends PageContent { @@ -20,15 +20,17 @@ public class ContentImage extends PageContent { public void build(BookData book, ArrayList list, boolean rightSide) { int y = TITLE_HEIGHT; - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } - if(this.image != null && this.image.location != null) { - list.add(new ElementImage(0, y, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - y, this.image)); - } else { + if (this.image != null && this.image.location != null) { + list.add(new ElementImage(0, y, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - y, this.image)); + } + else { list.add(new ElementImage(ImageData.MISSING)); } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentImageText.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentImageText.java index 36d68d8..7b17509 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentImageText.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentImageText.java @@ -1,16 +1,16 @@ package slimeknights.mantle.client.book.data.content; -import java.util.ArrayList; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementImage; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementImage; +import slimeknights.mantle.client.screen.book.element.ElementText; + +import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public class ContentImageText extends PageContent { @@ -23,20 +23,22 @@ public class ContentImageText extends PageContent { public void build(BookData book, ArrayList list, boolean rightSide) { int y = TITLE_HEIGHT; - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } - if(this.image != null && this.image.location != null) { - list.add(new ElementImage(0, y, GuiBook.PAGE_WIDTH, 100, this.image)); - } else { + if (this.image != null && this.image.location != null) { + list.add(new ElementImage(0, y, BookScreen.PAGE_WIDTH, 100, this.image)); + } + else { list.add(new ElementImage(0, y, 32, 32, ImageData.MISSING)); } - if(this.text != null && this.text.length > 0) { - list.add(new ElementText(0, y + 105, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - 105 - y, this.text)); + if (this.text != null && this.text.length > 0) { + list.add(new ElementText(0, y + 105, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - 105 - y, this.text)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentSectionList.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentSectionList.java index a52bd71..79b0cb8 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentSectionList.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentSectionList.java @@ -1,12 +1,12 @@ package slimeknights.mantle.client.book.data.content; -import java.util.ArrayList; - import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.SectionData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementSection; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementSection; + +import java.util.ArrayList; public class ContentSectionList extends PageContent { @@ -21,10 +21,10 @@ public class ContentSectionList extends PageContent { int width = (ElementSection.WIDTH + 5) * 3 - 5; int height = (ElementSection.HEIGHT + 5) * 3 - 5; - int ox = (GuiBook.PAGE_WIDTH - width) / 2; - int oy = (GuiBook.PAGE_HEIGHT - height) / 2; + int ox = (BookScreen.PAGE_WIDTH - width) / 2; + int oy = (BookScreen.PAGE_HEIGHT - height) / 2; - for(int i = 0; i < this.sections.size(); i++) { + for (int i = 0; i < this.sections.size(); i++) { int ix = i % 3; int iy = (int) Math.floor(i / 3F); diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentSmelting.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentSmelting.java index 2ec3b79..d854f35 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentSmelting.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentSmelting.java @@ -1,23 +1,22 @@ package slimeknights.mantle.client.book.data.content; import net.minecraft.block.Blocks; -import net.minecraft.item.Items; import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; import net.minecraft.util.NonNullList; - -import java.util.ArrayList; - import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.data.element.ItemStackData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementImage; -import slimeknights.mantle.client.gui.book.element.ElementItem; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementImage; +import slimeknights.mantle.client.screen.book.element.ElementItem; +import slimeknights.mantle.client.screen.book.element.ElementText; -import static slimeknights.mantle.client.gui.book.Textures.TEX_SMELTING; +import java.util.ArrayList; + +import static slimeknights.mantle.client.screen.book.Textures.TEX_SMELTING; public class ContentSmelting extends PageContent { @@ -40,26 +39,26 @@ public class ContentSmelting extends PageContent { @Override public void build(BookData book, ArrayList list, boolean rightSide) { - int x = GuiBook.PAGE_WIDTH / 2 - IMG_SMELTING.width / 2; + int x = BookScreen.PAGE_WIDTH / 2 - IMG_SMELTING.width / 2; int y = TITLE_HEIGHT; TextData tdTitle = new TextData(this.title); tdTitle.underlined = true; - list.add(new ElementText(0, 0, GuiBook.PAGE_WIDTH, 9, tdTitle)); + list.add(new ElementText(0, 0, BookScreen.PAGE_WIDTH, 9, tdTitle)); list.add(new ElementImage(x, y, IMG_SMELTING.width, IMG_SMELTING.height, IMG_SMELTING, book.appearance.slotColor)); - if(this.input != null && !this.input.id.equals("")) { + if (this.input != null && !this.input.id.equals("")) { list.add(new ElementItem(x + INPUT_X, y + INPUT_Y, ITEM_SCALE, this.input.getItems(), this.input.action)); } - if(this.result != null && !this.result.id.equals("")) { + if (this.result != null && !this.result.id.equals("")) { list.add(new ElementItem(x + RESULT_X, y + RESULT_Y, ITEM_SCALE, this.result.getItems(), this.result.action)); } list.add(new ElementItem(x + FUEL_X, y + FUEL_Y, ITEM_SCALE, this.getFuelsList())); - if(this.description != null && this.description.length > 0) { - list.add(new ElementText(0, IMG_SMELTING.height + y + 5, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - y - 5, this.description)); + if (this.description != null && this.description.length > 0) { + list.add(new ElementText(0, IMG_SMELTING.height + y + 5, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - y - 5, this.description)); } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentSmithing.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentSmithing.java index f4ce607..f5817f2 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentSmithing.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentSmithing.java @@ -1,18 +1,18 @@ package slimeknights.mantle.client.book.data.content; -import java.util.ArrayList; - import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.data.element.ItemStackData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementImage; -import slimeknights.mantle.client.gui.book.element.ElementItem; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementImage; +import slimeknights.mantle.client.screen.book.element.ElementItem; +import slimeknights.mantle.client.screen.book.element.ElementText; -import static slimeknights.mantle.client.gui.book.Textures.TEX_MISC; +import java.util.ArrayList; + +import static slimeknights.mantle.client.screen.book.Textures.TEX_MISC; public class ContentSmithing extends PageContent { @@ -36,31 +36,32 @@ public class ContentSmithing extends PageContent { @Override public void build(BookData book, ArrayList list, boolean rightSide) { - int x = GuiBook.PAGE_WIDTH / 2 - IMG_SMITHING.width / 2; + int x = BookScreen.PAGE_WIDTH / 2 - IMG_SMITHING.width / 2; int y = TITLE_HEIGHT; - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } list.add(new ElementImage(x, y, IMG_SMITHING.width, IMG_SMITHING.height, IMG_SMITHING, book.appearance.slotColor)); - if(this.input != null && !this.input.id.equals("")) { + if (this.input != null && !this.input.id.equals("")) { list.add(new ElementItem(x + INPUT_X, y + INPUT_Y, ITEM_SCALE, this.input.getItems(), this.input.action)); } - if(this.modifier != null && !this.modifier.id.equals("")) { + if (this.modifier != null && !this.modifier.id.equals("")) { list.add(new ElementItem(x + MODIFIER_X, y + MODIFIER_Y, ITEM_SCALE, this.modifier.getItems(), this.modifier.action)); } - if(this.result != null && !this.result.id.equals("")) { + if (this.result != null && !this.result.id.equals("")) { list.add(new ElementItem(x + RESULT_X, y + RESULT_Y, ITEM_SCALE, this.result.getItems(), this.result.action)); } - if(this.description != null && this.description.length > 0) { - list.add(new ElementText(0, IMG_SMITHING.height + y + 5, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - IMG_SMITHING.height - y - 5, this.description)); + if (this.description != null && this.description.length > 0) { + list.add(new ElementText(0, IMG_SMITHING.height + y + 5, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - IMG_SMITHING.height - y - 5, this.description)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentStructure.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentStructure.java index f95bbc7..fea890c 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentStructure.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentStructure.java @@ -2,20 +2,18 @@ package slimeknights.mantle.client.book.data.content; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StringUtils; - -import java.util.ArrayList; - import slimeknights.mantle.client.book.BookLoader; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.BlockData; import slimeknights.mantle.client.book.repository.BookRepository; -import slimeknights.mantle.client.gui.book.GuiArrow; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementAnimationToggle; -import slimeknights.mantle.client.gui.book.element.ElementArrow; -import slimeknights.mantle.client.gui.book.element.ElementStructure; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.ArrowButton; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementAnimationToggle; +import slimeknights.mantle.client.screen.book.element.ElementStructure; +import slimeknights.mantle.client.screen.book.element.ElementText; + +import java.util.ArrayList; public class ContentStructure extends PageContent { @@ -30,15 +28,14 @@ public class ContentStructure extends PageContent { public void load() { BookRepository repo = this.parent.source; - if(this.data == null || this.data.isEmpty()) { + if (this.data == null || this.data.isEmpty()) { return; } ResourceLocation location = repo.getResourceLocation(this.data); - if(location != null && repo.resourceExists(location)) { - ContentStructure structure = BookLoader.GSON - .fromJson(repo.resourceToString(repo.getResource(location)), ContentStructure.class); + if (location != null && repo.resourceExists(location)) { + ContentStructure structure = BookLoader.GSON.fromJson(repo.resourceToString(repo.getResource(location)), ContentStructure.class); structure.parent = this.parent; structure.load(); this.size = structure.size; @@ -50,46 +47,47 @@ public class ContentStructure extends PageContent { @Override public void build(BookData book, ArrayList list, boolean rightSide) { int y = TITLE_HEIGHT; - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } int offset = 0; - int structureSizeX = GuiBook.PAGE_WIDTH; - int structureSizeY = GuiBook.PAGE_HEIGHT - y - 10; + int structureSizeX = BookScreen.PAGE_WIDTH; + int structureSizeY = BookScreen.PAGE_HEIGHT - y - 10; - if(!StringUtils.isNullOrEmpty(this.text)) { + if (!StringUtils.isNullOrEmpty(this.text)) { offset = 15; - structureSizeX -= 2*offset; - structureSizeY -= 2*offset; + structureSizeX -= 2 * offset; + structureSizeY -= 2 * offset; - list.add(new ElementText(0, GuiBook.PAGE_HEIGHT - 10 - 2*offset, GuiBook.PAGE_WIDTH, 2*offset, this.text)); + list.add(new ElementText(0, BookScreen.PAGE_HEIGHT - 10 - 2 * offset, BookScreen.PAGE_WIDTH, 2 * offset, this.text)); } - if(this.size != null && this.size.length == 3 && this.structure != null && this.structure.length > 0) { + if (this.size != null && this.size.length == 3 && this.structure != null && this.structure.length > 0) { boolean showButtons = this.size[1] > 1; - if(showButtons) { - //structureSizeX -= GuiArrow.ArrowType.REFRESH.w; + if (showButtons) { + //structureSizeX -= ArrowButton.ArrowType.REFRESH.w; } ElementStructure elementStructure = new ElementStructure(offset, y, structureSizeX, structureSizeY, this.size, this.structure); list.add(elementStructure); - if(showButtons) { + if (showButtons) { int col = book.appearance.structureButtonColor; int colHover = book.appearance.structureButtonColorHovered; int colToggled = book.appearance.structureButtonColorToggled; - int midY = y + structureSizeY / 2 - (GuiArrow.ArrowType.UP.h + GuiArrow.ArrowType.DOWN.h) / 2; + int midY = y + structureSizeY / 2 - (ArrowButton.ArrowType.UP.h + ArrowButton.ArrowType.DOWN.h) / 2; - int dx = (GuiArrow.ArrowType.REFRESH.w - GuiArrow.ArrowType.UP.w) / 2; + int dx = (ArrowButton.ArrowType.REFRESH.w - ArrowButton.ArrowType.UP.w) / 2; - //list.add(new ElementArrow(ElementStructure.BUTTON_ID_LAYER_UP, elementStructure, structureSizeX + offset + dx, midY, GuiArrow.ArrowType.UP, col, colHover)); - //midY += GuiArrow.ArrowType.UP.h + 2; - //list.add(new ElementArrow(ElementStructure.BUTTON_ID_LAYER_DOWN, elementStructure, structureSizeX + offset + dx, midY, GuiArrow.ArrowType.DOWN, col, colHover)); + //list.add(new ElementArrow(ElementStructure.BUTTON_ID_LAYER_UP, elementStructure, structureSizeX + offset + dx, midY, ArrowButton.ArrowType.UP, col, colHover)); + //midY += ArrowButton.ArrowType.UP.h + 2; + //list.add(new ElementArrow(ElementStructure.BUTTON_ID_LAYER_DOWN, elementStructure, structureSizeX + offset + dx, midY, ArrowButton.ArrowType.DOWN, col, colHover)); - list.add(new ElementAnimationToggle(ElementStructure.BUTTON_ID_ANIMATE, elementStructure, GuiBook.PAGE_WIDTH - GuiArrow.ArrowType.REFRESH.w, 0, GuiArrow.ArrowType.REFRESH, col, colHover, colToggled)); + list.add(new ElementAnimationToggle(BookScreen.PAGE_WIDTH - ArrowButton.ArrowType.REFRESH.w, 0, ArrowButton.ArrowType.REFRESH, col, colHover, colToggled, elementStructure)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentTableOfContents.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentTableOfContents.java index 62069c2..4a1704e 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentTableOfContents.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentTableOfContents.java @@ -1,14 +1,13 @@ package slimeknights.mantle.client.book.data.content; import net.minecraft.client.Minecraft; - -import java.util.ArrayList; - import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementText; + +import java.util.ArrayList; public class ContentTableOfContents extends PageContent { @@ -24,16 +23,14 @@ public class ContentTableOfContents extends PageContent { public void build(BookData book, ArrayList list, boolean rightSide) { int y = 0; - if(this.title != null && !this.title.trim().isEmpty()) { + if (this.title != null && !this.title.trim().isEmpty()) { this.addTitle(list, this.title); y += TITLE_HEIGHT; } - for(int i = 0; i < this.data.length; i++) { + for (int i = 0; i < this.data.length; i++) { TextData text = this.data[i]; - list.add(new ElementText(0, y + i * (int) (Minecraft - .getInstance().fontRenderer.FONT_HEIGHT * text.scale), GuiBook.PAGE_WIDTH, Minecraft - .getInstance().fontRenderer.FONT_HEIGHT, text)); + list.add(new ElementText(0, y + i * (int) (Minecraft.getInstance().fontRenderer.FONT_HEIGHT * text.scale), BookScreen.PAGE_WIDTH, Minecraft.getInstance().fontRenderer.FONT_HEIGHT, text)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentText.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentText.java index eb3b513..8b27fc2 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentText.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentText.java @@ -7,9 +7,9 @@ import java.util.ArrayList; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementText; @OnlyIn(Dist.CLIENT) public class ContentText extends PageContent { @@ -21,14 +21,15 @@ public class ContentText extends PageContent { public void build(BookData book, ArrayList list, boolean rightSide) { int y = TITLE_HEIGHT; - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } - if(this.text != null && this.text.length > 0) { - list.add(new ElementText(0, y, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - y, this.text)); + if (this.text != null && this.text.length > 0) { + list.add(new ElementText(0, y, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - y, this.text)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextImage.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextImage.java index ec2752f..9790646 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextImage.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextImage.java @@ -2,16 +2,15 @@ package slimeknights.mantle.client.book.data.content; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; - -import java.util.ArrayList; - import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementImage; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementImage; +import slimeknights.mantle.client.screen.book.element.ElementText; + +import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public class ContentTextImage extends PageContent { @@ -24,26 +23,29 @@ public class ContentTextImage extends PageContent { public void build(BookData book, ArrayList list, boolean rightSide) { int y = TITLE_HEIGHT; - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } - if(this.text != null && this.text.length > 0) { - list.add(new ElementText(0, y, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - 105, this.text)); + if (this.text != null && this.text.length > 0) { + list.add(new ElementText(0, y, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - 105, this.text)); } - if(this.image != null && this.image.location != null) { - list.add(new ElementImage(0, y + GuiBook.PAGE_HEIGHT - 100, GuiBook.PAGE_WIDTH, 100 - y, this.image)); - } else { - list.add(new ElementImage(0, y + GuiBook.PAGE_HEIGHT - 100, GuiBook.PAGE_WIDTH, 100 - y, ImageData.MISSING)); + if (this.image != null && this.image.location != null) { + list.add(new ElementImage(0, y + BookScreen.PAGE_HEIGHT - 100, BookScreen.PAGE_WIDTH, 100 - y, this.image)); + } + else { + list.add(new ElementImage(0, y + BookScreen.PAGE_HEIGHT - 100, BookScreen.PAGE_WIDTH, 100 - y, ImageData.MISSING)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextLeftImage.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextLeftImage.java index 2604499..3eb4a39 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextLeftImage.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextLeftImage.java @@ -2,16 +2,15 @@ package slimeknights.mantle.client.book.data.content; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; - -import java.util.ArrayList; - import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementImage; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementImage; +import slimeknights.mantle.client.screen.book.element.ElementText; + +import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public class ContentTextLeftImage extends PageContent { @@ -25,24 +24,26 @@ public class ContentTextLeftImage extends PageContent { public void build(BookData book, ArrayList list, boolean rightSide) { int y = TITLE_HEIGHT; - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } - if(this.image != null && this.image.location != null) { + if (this.image != null && this.image.location != null) { list.add(new ElementImage(0, y, 50, 50, this.image)); - } else { + } + else { list.add(new ElementImage(0, y, 50, 50, ImageData.MISSING)); } - if(this.text1 != null && this.text1.length > 0) { - list.add(new ElementText(55, y, GuiBook.PAGE_WIDTH - 55, 50, this.text1)); + if (this.text1 != null && this.text1.length > 0) { + list.add(new ElementText(55, y, BookScreen.PAGE_WIDTH - 55, 50, this.text1)); } - if(this.text2 != null && this.text2.length > 0) { - list.add(new ElementText(0, y + 55, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - 55 - y, this.text2)); + if (this.text2 != null && this.text2.length > 0) { + list.add(new ElementText(0, y + 55, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - 55 - y, this.text2)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextRightImage.java b/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextRightImage.java index ee7a8d6..2b99f56 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextRightImage.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/ContentTextRightImage.java @@ -2,16 +2,15 @@ package slimeknights.mantle.client.book.data.content; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; - -import java.util.ArrayList; - import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementImage; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementImage; +import slimeknights.mantle.client.screen.book.element.ElementText; + +import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public class ContentTextRightImage extends PageContent { @@ -25,24 +24,26 @@ public class ContentTextRightImage extends PageContent { public void build(BookData book, ArrayList list, boolean rightSide) { int y = TITLE_HEIGHT; - if(this.title == null || this.title.isEmpty()) { + if (this.title == null || this.title.isEmpty()) { y = 0; - } else { + } + else { this.addTitle(list, this.title); } - if(this.text1 != null && this.text1.length > 0) { - list.add(new ElementText(0, y, GuiBook.PAGE_WIDTH - 55, 50, this.text1)); + if (this.text1 != null && this.text1.length > 0) { + list.add(new ElementText(0, y, BookScreen.PAGE_WIDTH - 55, 50, this.text1)); } - if(this.image != null && this.image.location != null) { - list.add(new ElementImage(GuiBook.PAGE_WIDTH - 50, y, 50, 50, this.image)); - } else { - list.add(new ElementImage(GuiBook.PAGE_WIDTH - 50, y, 50, 50, ImageData.MISSING)); + if (this.image != null && this.image.location != null) { + list.add(new ElementImage(BookScreen.PAGE_WIDTH - 50, y, 50, 50, this.image)); + } + else { + list.add(new ElementImage(BookScreen.PAGE_WIDTH - 50, y, 50, 50, ImageData.MISSING)); } - if(this.text2 != null && this.text2.length > 0) { - list.add(new ElementText(0, y + 55, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT - 55 - y, this.text2)); + if (this.text2 != null && this.text2.length > 0) { + list.add(new ElementText(0, y + 55, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT - 55 - y, this.text2)); } } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/content/PageContent.java b/src/main/java/slimeknights/mantle/client/book/data/content/PageContent.java index 9f3c47c..32fe632 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/content/PageContent.java +++ b/src/main/java/slimeknights/mantle/client/book/data/content/PageContent.java @@ -1,16 +1,16 @@ package slimeknights.mantle.client.book.data.content; -import java.util.ArrayList; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.PageData; import slimeknights.mantle.client.book.data.element.TextData; import slimeknights.mantle.client.book.repository.BookRepository; -import slimeknights.mantle.client.gui.book.GuiBook; -import slimeknights.mantle.client.gui.book.element.BookElement; -import slimeknights.mantle.client.gui.book.element.ElementText; +import slimeknights.mantle.client.screen.book.BookScreen; +import slimeknights.mantle.client.screen.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.ElementText; + +import java.util.ArrayList; @OnlyIn(Dist.CLIENT) public abstract class PageContent { @@ -28,10 +28,10 @@ public abstract class PageContent { public void addTitle(ArrayList list, String title) { TextData tdTitle = new TextData(title); tdTitle.underlined = true; - this.addTitle(list, new TextData[]{tdTitle}); + this.addTitle(list, new TextData[] { tdTitle }); } public void addTitle(ArrayList list, TextData[] title) { - list.add(new ElementText(0, 0, GuiBook.PAGE_WIDTH, 9, title)); + list.add(new ElementText(0, 0, BookScreen.PAGE_WIDTH, 9, title)); } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/deserializer/HexStringDeserializer.java b/src/main/java/slimeknights/mantle/client/book/data/deserializer/HexStringDeserializer.java index d4a6c22..cc86343 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/deserializer/HexStringDeserializer.java +++ b/src/main/java/slimeknights/mantle/client/book/data/deserializer/HexStringDeserializer.java @@ -11,19 +11,22 @@ public class HexStringDeserializer implements JsonDeserializer { @Override public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - if(json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) { + throws JsonParseException { + if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) { return json.getAsInt(); - } else if(json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) { + } + else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) { try { String s = json.getAsString(); - if(s.toLowerCase().startsWith("0b")) { + if (s.toLowerCase().startsWith("0b")) { return Integer.parseInt(s.substring(2), 2); - } else if(s.toLowerCase().startsWith("0x")) { + } + else if (s.toLowerCase().startsWith("0x")) { return Integer.parseInt(s.substring(2), 16); } - } catch(NumberFormatException ignored) { + } + catch (NumberFormatException ignored) { } } diff --git a/src/main/java/slimeknights/mantle/client/book/data/element/ItemStackData.java b/src/main/java/slimeknights/mantle/client/book/data/element/ItemStackData.java index 222ad59..4f089d8 100644 --- a/src/main/java/slimeknights/mantle/client/book/data/element/ItemStackData.java +++ b/src/main/java/slimeknights/mantle/client/book/data/element/ItemStackData.java @@ -1,20 +1,17 @@ package slimeknights.mantle.client.book.data.element; import com.google.gson.JsonObject; - import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.command.arguments.ItemArgument; import net.minecraft.block.Blocks; -import net.minecraft.item.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.ListNBT; import net.minecraft.nbt.StringNBT; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; - import net.minecraftforge.registries.ForgeRegistries; import slimeknights.mantle.client.book.BookLoader; import slimeknights.mantle.client.book.repository.BookRepository; @@ -31,51 +28,54 @@ public class ItemStackData { public JsonObject nbt; public NonNullList getItems() { - if(itemListLocation != null && source.resourceExists(itemListLocation)) { + if (itemListLocation != null && source.resourceExists(itemListLocation)) { try { ItemsList itemsList = BookLoader.GSON - .fromJson(source.resourceToString(source.getResource(itemListLocation)), ItemsList.class); - NonNullList items = NonNullList. withSize(itemsList.items.length, ItemStack.EMPTY); + .fromJson(source.resourceToString(source.getResource(itemListLocation)), ItemsList.class); + NonNullList items = NonNullList.withSize(itemsList.items.length, ItemStack.EMPTY); - for(int i = 0; i < itemsList.items.length; i++) { + for (int i = 0; i < itemsList.items.length; i++) { items.set(i, itemsList.items[i].getItem()); } this.action = itemsList.action; return items; - } catch(Exception ignored) { + } + catch (Exception ignored) { } } - return NonNullList. withSize(1, getItem()); + return NonNullList.withSize(1, getItem()); } private ItemStack getItem() { Item item; boolean isMissingItem = false; try { - item = ItemArgument.getItem(null, id).getItem(); - } catch(Exception e) { + item = ForgeRegistries.ITEMS.getValue(new ResourceLocation(id));//ItemArgument.getItem(null, id).getItem(); + } + catch (Exception e) { item = Item.getItemFromBlock(Blocks.BARRIER); isMissingItem = true; } - if(item == Items.AIR) { + if (item == Items.AIR) { item = Item.getItemFromBlock(Blocks.BARRIER); isMissingItem = true; } ItemStack itemStack = new ItemStack(item, amount); - if(nbt != null) { + if (nbt != null) { try { itemStack.setTag(JsonToNBT.getTagFromJson(filterJsonQuotes(nbt.toString()))); - } catch(CommandSyntaxException ignored) { + } + catch (CommandSyntaxException ignored) { } } - if(isMissingItem) { + if (isMissingItem) { CompoundNBT display = itemStack.getOrCreateChildTag("display"); display.putString("Name", "\u00A7rUnknown Item"); ListNBT lore = new ListNBT(); @@ -95,7 +95,7 @@ public class ItemStackData { ItemStackData data = new ItemStackData(); data.id = ForgeRegistries.ITEMS.getKey(stack.getItem()).toString(); data.amount = (byte) stack.getCount(); - if(!ignoreNbt && stack.getTag() != null) { + if (!ignoreNbt && stack.getTag() != null) { data.nbt = BookLoader.GSON.toJsonTree(stack.getTag(), CompoundNBT.class).getAsJsonObject(); } diff --git a/src/main/java/slimeknights/mantle/client/book/repository/FileRepository.java b/src/main/java/slimeknights/mantle/client/book/repository/FileRepository.java index d8881c1..061bfb7 100644 --- a/src/main/java/slimeknights/mantle/client/book/repository/FileRepository.java +++ b/src/main/java/slimeknights/mantle/client/book/repository/FileRepository.java @@ -3,9 +3,10 @@ package slimeknights.mantle.client.book.repository; import net.minecraft.client.Minecraft; import net.minecraft.resources.IResource; import net.minecraft.util.ResourceLocation; - import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; +import slimeknights.mantle.client.book.BookLoader; +import slimeknights.mantle.client.book.data.SectionData; import java.io.IOException; import java.util.ArrayList; @@ -13,9 +14,6 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -import slimeknights.mantle.client.book.BookLoader; -import slimeknights.mantle.client.book.data.SectionData; - public class FileRepository extends BookRepository { public final String location; @@ -26,45 +24,44 @@ public class FileRepository extends BookRepository { @Override public List getSections() { - return new ArrayList<>(Arrays.asList(BookLoader.GSON - .fromJson(this.resourceToString(this.getResource(this.getResourceLocation("index.json"))), SectionData[].class))); + return new ArrayList<>(Arrays.asList(BookLoader.GSON.fromJson(this.resourceToString(this.getResource(this.getResourceLocation("index.json"))), SectionData[].class))); } @Override public ResourceLocation getResourceLocation(String path, boolean safe) { - if(path == null) { + if (path == null) { return safe ? new ResourceLocation("") : null; } - if(!path.contains(":")) { + if (!path.contains(":")) { String langPath = null; - if(Minecraft.getInstance().getLanguageManager() != null && Minecraft.getInstance().getLanguageManager().getCurrentLanguage() != null) - { + if (Minecraft.getInstance().getLanguageManager() != null && Minecraft.getInstance().getLanguageManager().getCurrentLanguage() != null) { langPath = Minecraft.getInstance().getLanguageManager().getCurrentLanguage().getCode(); } - String defaultLangPath = "en_US"; + String defaultLangPath = "en_us"; ResourceLocation res; - if(langPath != null) { + if (langPath != null) { res = new ResourceLocation(this.location + "/" + langPath + "/" + path); if (this.resourceExists(res)) { return res; } } res = new ResourceLocation(this.location + "/" + defaultLangPath + "/" + path); - if(this.resourceExists(res)) { + if (this.resourceExists(res)) { return res; } res = new ResourceLocation(this.location + "/" + path); - if(this.resourceExists(res)) { + if (this.resourceExists(res)) { return res; } return safe ? new ResourceLocation("") : null; - } else { + } + else { ResourceLocation res = new ResourceLocation(path); - if(this.resourceExists(res)) { + if (this.resourceExists(res)) { return res; } return safe ? new ResourceLocation("") : null; @@ -73,32 +70,34 @@ public class FileRepository extends BookRepository { @Override public IResource getResource(ResourceLocation loc) { - if(loc == null) { + if (loc == null) { return null; } try { return Minecraft.getInstance().getResourceManager().getResource(loc); - } catch(IOException e) { + } + catch (IOException e) { return null; } } @Override public boolean resourceExists(ResourceLocation location) { - if(location == null) { + if (location == null) { return false; } try { Minecraft.getInstance().getResourceManager().getResource(location); return true; - } catch(IOException e) { + } + catch (IOException e) { return false; } } @Override public String resourceToString(IResource resource, boolean skipCommments) { - if(resource == null) { + if (resource == null) { return ""; } try { @@ -107,23 +106,24 @@ public class FileRepository extends BookRepository { boolean isLongComment = false; - while(iterator.hasNext()) { + while (iterator.hasNext()) { String s = ((String) iterator.next()).trim() + "\n"; // Comment skipper - if(skipCommments) { - if(isLongComment) { - if(s.endsWith("*/")) { + if (skipCommments) { + if (isLongComment) { + if (s.endsWith("*/")) { isLongComment = false; } continue; - } else { - if(s.startsWith("/*")) { + } + else { + if (s.startsWith("/*")) { isLongComment = true; continue; } } - if(s.startsWith("//")) { + if (s.startsWith("//")) { continue; } } @@ -132,7 +132,8 @@ public class FileRepository extends BookRepository { } return builder.toString().trim(); - } catch(IOException e) { + } + catch (IOException e) { e.printStackTrace(); } diff --git a/src/main/java/slimeknights/mantle/client/book/repository/ModuleFileRepository.java b/src/main/java/slimeknights/mantle/client/book/repository/ModuleFileRepository.java index 60a2790..5554926 100644 --- a/src/main/java/slimeknights/mantle/client/book/repository/ModuleFileRepository.java +++ b/src/main/java/slimeknights/mantle/client/book/repository/ModuleFileRepository.java @@ -1,42 +1,42 @@ package slimeknights.mantle.client.book.repository; +import slimeknights.mantle.client.book.BookLoader; +import slimeknights.mantle.client.book.data.SectionData; +import slimeknights.mantle.client.book.data.SectionDataModule; +import slimeknights.mantle.pulsar.control.PulseManager; + import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; -import slimeknights.mantle.client.book.BookLoader; -import slimeknights.mantle.client.book.data.SectionData; -import slimeknights.mantle.client.book.data.SectionDataModule; -import slimeknights.mantle.client.book.repository.FileRepository; -import slimeknights.mantle.pulsar.control.PulseManager; - public class ModuleFileRepository extends FileRepository { - private Predicate manager; - public ModuleFileRepository(PulseManager manager, String location) { - super(location); - this.manager = manager::isPulseLoaded; - } + private Predicate manager; - public ModuleFileRepository(String location) { - super(location); - this.manager = PulseManager::isPulseLoadedGlobal; - } + public ModuleFileRepository(PulseManager manager, String location) { + super(location); + this.manager = manager::isPulseLoaded; + } - @Override - public List getSections() { - // same as super, except we remove any where the related module is not loaded - return Arrays.stream(BookLoader.GSON.fromJson(this.resourceToString(this.getResource(this.getResourceLocation("index.json"))), SectionDataModule[].class)) - .filter((section)->section.module.isEmpty() || this.manager.test(section.module)) - .collect(Collectors.toList()); - } + public ModuleFileRepository(String location) { + super(location); + this.manager = PulseManager::isPulseLoadedGlobal; + } - /** - * Gets the manager used to determine if a module is available - * @return Predicate to test a module availability - */ - public Predicate getManager() { - return this.manager; - } + @Override + public List getSections() { + // same as super, except we remove any where the related module is not loaded + return Arrays.stream(BookLoader.GSON.fromJson(this.resourceToString(this.getResource(this.getResourceLocation("index.json"))), SectionDataModule[].class)) + .filter((section) -> section.module.isEmpty() || this.manager.test(section.module)) + .collect(Collectors.toList()); + } + + /** + * Gets the manager used to determine if a module is available + * @return Predicate to test a module availability + */ + public Predicate getManager() { + return this.manager; + } } diff --git a/src/main/java/slimeknights/mantle/client/gui/book/GuiArrow.java b/src/main/java/slimeknights/mantle/client/gui/book/GuiArrow.java deleted file mode 100644 index 4378fe5..0000000 --- a/src/main/java/slimeknights/mantle/client/gui/book/GuiArrow.java +++ /dev/null @@ -1,76 +0,0 @@ -package slimeknights.mantle.client.gui.book; - -import com.mojang.blaze3d.platform.GlStateManager; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.AbstractGui; -import net.minecraft.client.gui.widget.button.Button; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import static slimeknights.mantle.client.gui.book.Textures.TEX_BOOK; - -@OnlyIn(Dist.CLIENT) -public class GuiArrow extends Button -{ - private static final int X = 412; - - public static final int WIDTH = 18; - public static final int HEIGHT = 10; - - // Appearance - public ArrowType arrowType; - public int color; - public int hoverColor; - - public GuiArrow(int buttonId, int x, int y, ArrowType arrowType, int color, int hoverColor) { - super(buttonId, x, y, arrowType.w, arrowType.h, ""); - - this.arrowType = arrowType; - this.color = color; - this.hoverColor = hoverColor; - } - - @Override - public void render(int mouseX, int mouseY, float partialTicks) { - if(this.visible) { - Minecraft minecraft = Minecraft.getInstance(); - minecraft.getTextureManager().bindTexture(TEX_BOOK); - - this.isHovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; - - int color = this.isHovered ? this.hoverColor : this.color; - - float r = ((color >> 16) & 0xff) / 255.F; - float g = ((color >> 8) & 0xff) / 255.F; - float b = (color & 0xff) / 255.F; - - GlStateManager.color3f(r, g, b); - AbstractGui.blit(this.x, this.y, this.arrowType.x, this.arrowType.y, this.width, this.height, this.width, this.height, 512, 512); - this.renderBg(minecraft, mouseX, mouseY); - } - } - - public enum ArrowType { - NEXT(412, 0), - PREV(412, 10), - RIGHT(412, 20), - LEFT(412, 30), - BACK_UP(412, 40, 18, 18), - UP(412, 58, 10, 18), - DOWN(412+10, 58, 10, 18), - REFRESH(412, 76, 18, 18); - - public final int x, y, w, h; - - ArrowType(int x, int y) { - this(x, y, WIDTH, HEIGHT); - } - - ArrowType(int x, int y, int w, int h) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } - } -} diff --git a/src/main/java/slimeknights/mantle/client/gui/book/GuiBookmark.java b/src/main/java/slimeknights/mantle/client/gui/book/GuiBookmark.java deleted file mode 100644 index d1dd532..0000000 --- a/src/main/java/slimeknights/mantle/client/gui/book/GuiBookmark.java +++ /dev/null @@ -1,60 +0,0 @@ -package slimeknights.mantle.client.gui.book; - -import com.mojang.blaze3d.platform.GlStateManager; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.AbstractGui; -import net.minecraft.client.gui.widget.button.Button; -import net.minecraft.util.ResourceLocation; - -import slimeknights.mantle.client.book.data.BookmarkData; - -public class GuiBookmark extends Button -{ - - private static final ResourceLocation TEX_BOOK = new ResourceLocation("mantle:textures/gui/book.png"); - - public static final int WIDTH = 31; - public static final int HEIGHT = 9; - public static final int TEX_X = 0, TEX_Y = 400; - public static final int ADD_W = 5, ADD_H = 5, ADD_X = 32, ADD_Y = 402; - - public static final float TEXT_SCALE = 0.5F; - - public int type = 0; - - public final BookmarkData data; - - public GuiBookmark(BookmarkData data) { - super(-1337, -500, -500, WIDTH, HEIGHT, ""); - - this.data = data; - } - - @Override - public void render(int mouseX, int mouseY, float partialTicks) { - if(this.visible) { - Minecraft minecraft = Minecraft.getInstance(); - int tex_y = TEX_Y + HEIGHT * this.type; - - minecraft.textureManager.bindTexture(TEX_BOOK); - - float r = ((this.data.color >> 16) & 0xff) / 255.F; - float g = ((this.data.color >> 8) & 0xff) / 255.F; - float b = (this.data.color & 0xff) / 255.F; - - GlStateManager.color3f(r, g, b); - AbstractGui.blit(this.x, this.y, TEX_X, tex_y, WIDTH, HEIGHT, this.width, this.height, 512, 512); - - if(this.data.text != null && !this.data.text.isEmpty()) { - TextDataRenderer - .drawScaledString(minecraft.fontRenderer, this.data.text, this.x + 1, this.y + this.height / 2 - minecraft.fontRenderer.FONT_HEIGHT * TEXT_SCALE / 2 + 1, 0xFFFFFFFF, true, TEXT_SCALE); - } - - GlStateManager.color3f(1F, 1F, 1F); - - if(this.data.page.equals("ADD")) { - AbstractGui.blit(this.x + this.width / 2 - ADD_W / 2, this.y + this.height / 2 - ADD_H / 2, ADD_X, ADD_Y, ADD_W, ADD_H, 512, 512); - } - } - } -} diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementAnimationToggle.java b/src/main/java/slimeknights/mantle/client/gui/book/element/ElementAnimationToggle.java deleted file mode 100644 index 93701d1..0000000 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementAnimationToggle.java +++ /dev/null @@ -1,31 +0,0 @@ -package slimeknights.mantle.client.gui.book.element; - -import slimeknights.mantle.client.gui.book.GuiArrow; - -public class ElementAnimationToggle extends ElementArrow { - - private final int arrowColorActive; - private final int arrowColorInactive; - private boolean toggled = false; - - public ElementAnimationToggle(int id, IButtonClickHandler handler, int x, int y, GuiArrow.ArrowType arrowType, int arrowColor, int arrowColorHover, int arrowColorActive) { - super(id, handler, x, y, arrowType, arrowColor, arrowColorHover); - - this.arrowColorInactive = arrowColor; - this.arrowColorActive = arrowColorActive; - } - - @Override - public void mouseClicked(double mouseX, double mouseY, int mouseButton) { - if(this.callback != null && this.isHovered(mouseX, mouseY)) { - if(this.callback.onButtonClick(this.buttonId, this)) { - this.toggled = !this.toggled; - this.updateColor(); - } - } - } - - protected void updateColor() { - this.button.color = this.toggled ? this.arrowColorActive : this.arrowColorInactive; - } -} diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementArrow.java b/src/main/java/slimeknights/mantle/client/gui/book/element/ElementArrow.java deleted file mode 100644 index e594aa2..0000000 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementArrow.java +++ /dev/null @@ -1,22 +0,0 @@ -package slimeknights.mantle.client.gui.book.element; - -import net.minecraft.client.gui.FontRenderer; - -import slimeknights.mantle.client.gui.book.GuiArrow; - -public class ElementArrow extends ElementButton { - - protected final GuiArrow button; - - public ElementArrow(int id, IButtonClickHandler handler, int x, int y, GuiArrow.ArrowType arrowType, int arrowColor, int arrowColorHover) { - super(id, x, y, arrowType.w, arrowType.h, handler); - - this.button = new GuiArrow(id, x, y, arrowType, arrowColor, arrowColorHover); - } - - @Override - public void draw(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { - this.button.render(mouseX, mouseY, partialTicks); - } - -} diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementButton.java b/src/main/java/slimeknights/mantle/client/gui/book/element/ElementButton.java deleted file mode 100644 index 6a07815..0000000 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementButton.java +++ /dev/null @@ -1,21 +0,0 @@ -package slimeknights.mantle.client.gui.book.element; - -public abstract class ElementButton extends SizedBookElement { - - protected final IButtonClickHandler callback; - - public final int buttonId; - - public ElementButton(int buttonId, int x, int y, int width, int height, IButtonClickHandler callback) { - super(x, y, width, height); - this.callback = callback; - this.buttonId = buttonId; - } - - @Override - public void mouseClicked(double mouseX, double mouseY, int mouseButton) { - if(this.callback != null && this.isHovered(mouseX, mouseY)) { - this.callback.onButtonClick(this.buttonId, this); - } - } -} diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/IButtonClickHandler.java b/src/main/java/slimeknights/mantle/client/gui/book/element/IButtonClickHandler.java deleted file mode 100644 index a4fcb75..0000000 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/IButtonClickHandler.java +++ /dev/null @@ -1,6 +0,0 @@ -package slimeknights.mantle.client.gui.book.element; - -public interface IButtonClickHandler { - /** returns true if the button click was successful */ - boolean onButtonClick(int buttonId, ElementButton button); -} diff --git a/src/main/java/slimeknights/mantle/client/model/BakedCompositeModel.java b/src/main/java/slimeknights/mantle/client/model/BakedCompositeModel.java index ccda346..9cbe6f1 100644 --- a/src/main/java/slimeknights/mantle/client/model/BakedCompositeModel.java +++ b/src/main/java/slimeknights/mantle/client/model/BakedCompositeModel.java @@ -36,26 +36,27 @@ public class BakedCompositeModel extends BakedWrapper { } public static class Builder { + ImmutableList.Builder[] builders; IBakedModel parent; public Builder() { this.builders = new ImmutableList.Builder[7]; - for(int i = 0; i < 7; i++) { + for (int i = 0; i < 7; i++) { this.builders[i] = ImmutableList.builder(); } } public void add(IBakedModel model, BlockState state, Random rand) { this.add(model, state, null, rand); - for(Direction side : Direction.values()) { + for (Direction side : Direction.values()) { this.add(model, state, side, rand); } } public void add(IBakedModel model, BlockState state, Direction side, Random rand) { int index; - if(side == null) { + if (side == null) { index = 6; } else { @@ -69,7 +70,7 @@ public class BakedCompositeModel extends BakedWrapper { ImmutableMap.Builder, ImmutableList> map = ImmutableMap.builder(); map.put(Optional.absent(), this.builders[6].build()); - for(Direction side : Direction.values()) { + for (Direction side : Direction.values()) { map.put(Optional.of(side), this.builders[side.getIndex()].build()); } diff --git a/src/main/java/slimeknights/mantle/client/model/BakedSimple.java b/src/main/java/slimeknights/mantle/client/model/BakedSimple.java index 0151ee4..168b689 100644 --- a/src/main/java/slimeknights/mantle/client/model/BakedSimple.java +++ b/src/main/java/slimeknights/mantle/client/model/BakedSimple.java @@ -33,23 +33,23 @@ public class BakedSimple implements IBakedModel { public BakedSimple(ImmutableList quads, ImmutableMap transforms, IBakedModel base) { this( - (List)quads, - transforms, - base.getParticleTexture(), - base.isAmbientOcclusion(), - base.isGui3d(), - base.getOverrides() + (List) quads, + transforms, + base.getParticleTexture(), + base.isAmbientOcclusion(), + base.isGui3d(), + base.getOverrides() ); } public BakedSimple(List quads, ImmutableMap transforms, IBakedModel base) { this( - quads, - transforms, - base.getParticleTexture(), - base.isAmbientOcclusion(), - base.isGui3d(), - base.getOverrides() + quads, + transforms, + base.getParticleTexture(), + base.isAmbientOcclusion(), + base.isGui3d(), + base.getOverrides() ); } diff --git a/src/main/java/slimeknights/mantle/client/model/BakedWrapper.java b/src/main/java/slimeknights/mantle/client/model/BakedWrapper.java index d80520f..441c8f1 100644 --- a/src/main/java/slimeknights/mantle/client/model/BakedWrapper.java +++ b/src/main/java/slimeknights/mantle/client/model/BakedWrapper.java @@ -69,6 +69,7 @@ public class BakedWrapper implements IBakedModel { } public static class Perspective extends BakedWrapper implements IBakedModel { + protected final ImmutableMap transforms; public Perspective(IBakedModel parent, ImmutableMap transforms) { diff --git a/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java b/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java index dc24910..23e0495 100644 --- a/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java +++ b/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java @@ -34,10 +34,10 @@ public class BlockItemModelWrapper implements IBakedModel { public Pair handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) { Matrix4f matrix = null; // fix transformation in hand - if(cameraTransformType == ItemCameraTransforms.TransformType.THIRD_PERSON_RIGHT_HAND) { + if (cameraTransformType == ItemCameraTransforms.TransformType.THIRD_PERSON_RIGHT_HAND) { matrix = ModelHelper.BLOCK_THIRD_PERSON_RIGHT.getMatrixVec(); } - else if(cameraTransformType == ItemCameraTransforms.TransformType.THIRD_PERSON_LEFT_HAND) { + else if (cameraTransformType == ItemCameraTransforms.TransformType.THIRD_PERSON_LEFT_HAND) { matrix = ModelHelper.BLOCK_THIRD_PERSON_LEFT.getMatrixVec(); } diff --git a/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java b/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java index a695985..d170d26 100644 --- a/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java +++ b/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java @@ -45,9 +45,9 @@ public class TRSRBakedModel implements IBakedModel { public TRSRBakedModel(IBakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scaleX, float scaleY, float scaleZ) { this(original, new TRSRTransformation(new Vector3f(x, y, z), - null, - new Vector3f(scaleX, scaleY, scaleZ), - TRSRTransformation.quatFromXYZ(rotX, rotY, rotZ))); + null, + new Vector3f(scaleX, scaleY, scaleZ), + TRSRTransformation.quatFromXYZ(rotX, rotY, rotZ))); } public TRSRBakedModel(IBakedModel original, TRSRTransformation transform) { @@ -64,8 +64,8 @@ public class TRSRBakedModel implements IBakedModel { this.faceOffset = 4 + Direction.NORTH.getHorizontalIndex() - facing.getHorizontalIndex(); - double r = Math.PI * (360 - facing.getOpposite().getHorizontalIndex() * 90)/180d; - TRSRTransformation t = new TRSRTransformation(null, null, null, TRSRTransformation.quatFromXYZ(0, (float)r, 0)); + double r = Math.PI * (360 - facing.getOpposite().getHorizontalIndex() * 90) / 180d; + TRSRTransformation t = new TRSRTransformation(null, null, null, TRSRTransformation.quatFromXYZ(0, (float) r, 0)); this.transformation = TRSRTransformation.blockCenterToCorner(t); } @@ -76,18 +76,19 @@ public class TRSRBakedModel implements IBakedModel { ImmutableList.Builder builder = ImmutableList.builder(); - if(!original.isBuiltInRenderer()) { + if (!original.isBuiltInRenderer()) { try { // adjust side to facing-rotation - if(side != null && side.getHorizontalIndex() > -1) { + if (side != null && side.getHorizontalIndex() > -1) { side = Direction.byHorizontalIndex((side.getHorizontalIndex() + faceOffset) % 4); } - for(BakedQuad quad : original.getQuads(state, side, rand)) { + for (BakedQuad quad : original.getQuads(state, side, rand)) { Transformer transformer = new Transformer(transformation, quad.getFormat()); quad.pipe(transformer); builder.add(transformer.build()); } - } catch(Exception e) { + } + catch (Exception e) { // do nothing. Seriously, why are you using immutable lists?! } } @@ -133,7 +134,7 @@ public class TRSRBakedModel implements IBakedModel { private final TRSRBakedModel model; public TRSROverride(TRSRBakedModel model) { - super(null, null, null,ImmutableList.of()); + super(null, null, null, ImmutableList.of()); this.model = model; } @@ -168,13 +169,13 @@ public class TRSRBakedModel implements IBakedModel { VertexFormatElement.Usage usage = parent.getVertexFormat().getElement(element).getUsage(); // transform normals and position - if(usage == VertexFormatElement.Usage.POSITION && data.length >= 3) { + if (usage == VertexFormatElement.Usage.POSITION && data.length >= 3) { Vector4f vec = new Vector4f(data[0], data[1], data[2], 1f); transformation.transform(vec); data = new float[4]; vec.get(data); } - else if(usage == VertexFormatElement.Usage.NORMAL && data.length >= 3) { + else if (usage == VertexFormatElement.Usage.NORMAL && data.length >= 3) { Vector3f vec = new Vector3f(data); normalTransformation.transform(vec); vec.normalize(); diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiElement.java b/src/main/java/slimeknights/mantle/client/screen/ElementScreen.java similarity index 75% rename from src/main/java/slimeknights/mantle/client/gui/GuiElement.java rename to src/main/java/slimeknights/mantle/client/screen/ElementScreen.java index 38d87e6..ff038c1 100644 --- a/src/main/java/slimeknights/mantle/client/gui/GuiElement.java +++ b/src/main/java/slimeknights/mantle/client/screen/ElementScreen.java @@ -1,4 +1,4 @@ -package slimeknights.mantle.client.gui; +package slimeknights.mantle.client.screen; import net.minecraft.client.gui.screen.Screen; import net.minecraftforge.api.distmarker.Dist; @@ -9,7 +9,7 @@ import net.minecraftforge.api.distmarker.OnlyIn; * The coordinates all refer to the coordinates inside the graphics! */ @OnlyIn(Dist.CLIENT) -public class GuiElement { +public class ElementScreen { // this is totally completely ugly but it's a simple solution that doesn't clutter everything too much >_> public static int defaultTexW = 256; @@ -23,7 +23,7 @@ public class GuiElement { public int texW; public int texH; - public GuiElement(int x, int y, int w, int h, int texW, int texH) { + public ElementScreen(int x, int y, int w, int h, int texW, int texH) { this(x, y, w, h); this.setTextureSize(texW, texH); @@ -31,7 +31,7 @@ public class GuiElement { defaultTexH = texH; } - public GuiElement(int x, int y, int w, int h) { + public ElementScreen(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; @@ -44,8 +44,8 @@ public class GuiElement { this.texH = h; } - public GuiElement shift(int xd, int yd) { - return new GuiElement(this.x + xd, this.y + yd, this.w, this.h, this.texW, this.texH); + public ElementScreen shift(int xd, int yd) { + return new ElementScreen(this.x + xd, this.y + yd, this.w, this.h, this.texW, this.texH); } /** @@ -69,8 +69,8 @@ public class GuiElement { this.h = h; } - public GuiElement get(int x, int y, int w, int h) { - return new GuiElement(x, y, w, h, this.w, this.h); + public ElementScreen get(int x, int y, int w, int h) { + return new ElementScreen(x, y, w, h, this.w, this.h); } } } diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiModule.java b/src/main/java/slimeknights/mantle/client/screen/ModuleScreen.java similarity index 82% rename from src/main/java/slimeknights/mantle/client/gui/GuiModule.java rename to src/main/java/slimeknights/mantle/client/screen/ModuleScreen.java index f8ef435..1579aaf 100644 --- a/src/main/java/slimeknights/mantle/client/gui/GuiModule.java +++ b/src/main/java/slimeknights/mantle/client/screen/ModuleScreen.java @@ -1,4 +1,4 @@ -package slimeknights.mantle.client.gui; +package slimeknights.mantle.client.screen; import net.minecraft.client.gui.screen.inventory.ContainerScreen; import net.minecraft.client.renderer.Rectangle2d; @@ -9,12 +9,11 @@ import net.minecraft.util.text.ITextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -// a sub-gui. Mostly the same as a separate GuiContainer, but doesn't do the calls that affect the game as if this were the only gui +// a sub-gui. Mostly the same as a separate ContainerScreen, but doesn't do the calls that affect the game as if this were the only gui @OnlyIn(Dist.CLIENT) -public abstract class GuiModule extends ContainerScreen -{ +public abstract class ModuleScreen extends ContainerScreen { - protected final GuiMultiModule parent; + protected final MultiModuleScreen parent; // left or right of the parent protected final boolean right; @@ -24,7 +23,7 @@ public abstract class GuiModule extends ContainerScreen public int yOffset = 0; public int xOffset = 0; - public GuiModule(GuiMultiModule parent, Container container, PlayerInventory playerInventory, ITextComponent title, boolean right, boolean bottom) { + public ModuleScreen(MultiModuleScreen parent, Container container, PlayerInventory playerInventory, ITextComponent title, boolean right, boolean bottom) { super(container, playerInventory, title); this.parent = parent; @@ -51,14 +50,14 @@ public abstract class GuiModule extends ContainerScreen } public void updatePosition(int parentX, int parentY, int parentSizeX, int parentSizeY) { - if(this.right) { + if (this.right) { this.guiLeft = parentX + parentSizeX; } else { this.guiLeft = parentX - this.xSize; } - if(this.bottom) { + if (this.bottom) { this.guiTop = parentY + parentSizeY - this.ySize; } else { @@ -75,12 +74,12 @@ public abstract class GuiModule extends ContainerScreen public boolean isMouseInModule(int mouseX, int mouseY) { return mouseX >= this.guiLeft && mouseX < this.guiRight() && - mouseY >= this.guiTop && mouseY < this.guiBottom(); + mouseY >= this.guiTop && mouseY < this.guiBottom(); } public boolean isMouseOverFullSlot(double mouseX, double mouseY) { - for(Slot slot : this.container.inventorySlots) { - if(this.parent.isSlotSelected(slot, mouseX, mouseY) && slot.getHasStack()) { + for (Slot slot : this.container.inventorySlots) { + if (this.parent.isSlotSelected(slot, mouseX, mouseY) && slot.getHasStack()) { return true; } } @@ -107,7 +106,6 @@ public abstract class GuiModule extends ContainerScreen this.drawGuiContainerForegroundLayer(mouseX, mouseY); } - /** * Custom mouse click handling. * diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiMultiModule.java b/src/main/java/slimeknights/mantle/client/screen/MultiModuleScreen.java similarity index 63% rename from src/main/java/slimeknights/mantle/client/gui/GuiMultiModule.java rename to src/main/java/slimeknights/mantle/client/screen/MultiModuleScreen.java index 5adf1be..c3839c7 100644 --- a/src/main/java/slimeknights/mantle/client/gui/GuiMultiModule.java +++ b/src/main/java/slimeknights/mantle/client/screen/MultiModuleScreen.java @@ -1,7 +1,6 @@ -package slimeknights.mantle.client.gui; +package slimeknights.mantle.client.screen; import com.google.common.collect.Lists; - import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.inventory.ContainerScreen; @@ -11,55 +10,36 @@ import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.Slot; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import slimeknights.mantle.inventory.MultiModuleContainer; +import slimeknights.mantle.inventory.WrapperSlot; -import java.lang.reflect.Field; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; -import javax.annotation.Nonnull; +public class MultiModuleScreen extends ContainerScreen { -import slimeknights.mantle.Mantle; -import slimeknights.mantle.inventory.ContainerMultiModule; -import slimeknights.mantle.inventory.SlotWrapper; - -@OnlyIn(Dist.CLIENT) -public class GuiMultiModule extends ContainerScreen -{ - - // NEI-stuff >:( - private static Field NEI_Manager; - - static { - try { - NEI_Manager = ContainerScreen.class.getDeclaredField("manager"); - } catch(NoSuchFieldException e) { - NEI_Manager = null; - } - } - - protected List modules = Lists.newArrayList(); + protected List modules = Lists.newArrayList(); public int cornerX; public int cornerY; public int realWidth; public int realHeight; - public GuiMultiModule(ContainerMultiModule container, PlayerInventory playerInventory, ITextComponent title) { + public MultiModuleScreen(MultiModuleContainer container, PlayerInventory playerInventory, ITextComponent title) { super(container, playerInventory, title); this.realWidth = -1; this.realHeight = -1; } - protected void addModule(GuiModule module) { + protected void addModule(ModuleScreen module) { this.modules.add(module); } public List getModuleAreas() { List areas = new ArrayList(this.modules.size()); - for(GuiModule module : this.modules) { + for (ModuleScreen module : this.modules) { areas.add(module.getArea()); } return areas; @@ -67,7 +47,7 @@ public class GuiMultiModule extends ContainerScreen @Override public void init() { - if(this.realWidth > -1) { + if (this.realWidth > -1) { // has to be reset before calling initGui so the position is getting retained this.xSize = this.realWidth; this.ySize = this.realHeight; @@ -79,7 +59,7 @@ public class GuiMultiModule extends ContainerScreen this.realWidth = this.xSize; this.realHeight = this.ySize; - for(GuiModule module : this.modules) { + for (ModuleScreen module : this.modules) { this.updateSubmodule(module); } @@ -90,7 +70,7 @@ public class GuiMultiModule extends ContainerScreen @Override protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { - for(GuiModule module : this.modules) { + for (ModuleScreen module : this.modules) { module.handleDrawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY); } } @@ -100,7 +80,7 @@ public class GuiMultiModule extends ContainerScreen this.drawContainerName(); this.drawPlayerInventoryName(); - for(GuiModule module : this.modules) { + for (ModuleScreen module : this.modules) { // set correct state for the module GlStateManager.pushMatrix(); GlStateManager.translatef(-this.guiLeft, -this.guiTop, 0.0F); @@ -118,9 +98,9 @@ public class GuiMultiModule extends ContainerScreen } protected void drawContainerName() { - ContainerMultiModule multiContainer = (ContainerMultiModule) this.container; + MultiModuleContainer multiContainer = (MultiModuleContainer) this.container; String localizedName = this.getTitle().getFormattedText();//multiContainer.getInventoryDisplayName(); - if(localizedName != null) { + if (localizedName != null) { this.font.drawString(localizedName, 8, 6, 0x404040); } } @@ -134,17 +114,9 @@ public class GuiMultiModule extends ContainerScreen public void init(Minecraft mc, int width, int height) { super.init(mc, width, height); - // workaround for NEIs ASM hax. sigh. - try { - for(GuiModule module : this.modules) { - module.init(mc, width, height); - if(NEI_Manager != null) { - NEI_Manager.set(module, NEI_Manager.get(this)); - } - this.updateSubmodule(module); - } - } catch(IllegalAccessException e) { - Mantle.logger.error(e); + for (ModuleScreen module : this.modules) { + module.init(mc, width, height); + this.updateSubmodule(module); } } @@ -152,7 +124,7 @@ public class GuiMultiModule extends ContainerScreen public void resize(@Nonnull Minecraft mc, int width, int height) { super.resize(mc, width, height); - for(GuiModule module : this.modules) { + for (ModuleScreen module : this.modules) { module.resize(mc, width, height); this.updateSubmodule(module); } @@ -178,7 +150,6 @@ public class GuiMultiModule extends ContainerScreen this.ySize = oldH; } - // needed to get the correct slot on clicking @Override protected boolean isPointInRegion(int left, int top, int right, int bottom, double pointX, double pointY) { @@ -187,44 +158,44 @@ public class GuiMultiModule extends ContainerScreen return pointX >= left - 1 && pointX < left + right + 1 && pointY >= top - 1 && pointY < top + bottom + 1; } - protected void updateSubmodule(GuiModule module) { + protected void updateSubmodule(ModuleScreen module) { module.updatePosition(this.cornerX, this.cornerY, this.realWidth, this.realHeight); - if(module.guiLeft < this.guiLeft) { + if (module.guiLeft < this.guiLeft) { this.xSize += this.guiLeft - module.guiLeft; this.guiLeft = module.guiLeft; } - if(module.guiTop < this.guiTop) { + if (module.guiTop < this.guiTop) { this.ySize += this.guiTop - module.guiTop; this.guiTop = module.guiTop; } - if(module.guiRight() > this.guiLeft + this.xSize) { + if (module.guiRight() > this.guiLeft + this.xSize) { this.xSize = module.guiRight() - this.guiLeft; } - if(module.guiBottom() > this.guiTop + this.ySize) { + if (module.guiBottom() > this.guiTop + this.ySize) { this.ySize = module.guiBottom() - this.guiTop; } } @Override public void drawSlot(Slot slotIn) { - GuiModule module = this.getModuleForSlot(slotIn.slotNumber); + ModuleScreen module = this.getModuleForSlot(slotIn.slotNumber); - if(module != null) { + if (module != null) { Slot slot = slotIn; // unwrap for the call to the module - if(slotIn instanceof SlotWrapper) { - slot = ((SlotWrapper) slotIn).parent; + if (slotIn instanceof WrapperSlot) { + slot = ((WrapperSlot) slotIn).parent; } - if(!module.shouldDrawSlot(slot)) { + if (!module.shouldDrawSlot(slot)) { return; } } // update slot positions - if(slotIn instanceof SlotWrapper) { - slotIn.xPos = ((SlotWrapper) slotIn).parent.xPos; - slotIn.yPos = ((SlotWrapper) slotIn).parent.yPos; + if (slotIn instanceof WrapperSlot) { + slotIn.xPos = ((WrapperSlot) slotIn).parent.xPos; + slotIn.yPos = ((WrapperSlot) slotIn).parent.yPos; } super.drawSlot(slotIn); @@ -232,16 +203,16 @@ public class GuiMultiModule extends ContainerScreen @Override public boolean isSlotSelected(Slot slotIn, double mouseX, double mouseY) { - GuiModule module = this.getModuleForSlot(slotIn.slotNumber); + ModuleScreen module = this.getModuleForSlot(slotIn.slotNumber); // mouse inside the module of the slot? - if(module != null) { + if (module != null) { Slot slot = slotIn; // unwrap for the call to the module - if(slotIn instanceof SlotWrapper) { - slot = ((SlotWrapper) slotIn).parent; + if (slotIn instanceof WrapperSlot) { + slot = ((WrapperSlot) slotIn).parent; } - if(!module.shouldDrawSlot(slot)) { + if (!module.shouldDrawSlot(slot)) { return false; } } @@ -249,12 +220,11 @@ public class GuiMultiModule extends ContainerScreen return super.isSlotSelected(slotIn, mouseX, mouseY); } - @Override public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { - GuiModule module = this.getModuleForPoint(mouseX, mouseY); - if(module != null) { - if(module.handleMouseClicked(mouseX, mouseY, mouseButton)) { + ModuleScreen module = this.getModuleForPoint(mouseX, mouseY); + if (module != null) { + if (module.handleMouseClicked(mouseX, mouseY, mouseButton)) { return false; } } @@ -263,9 +233,9 @@ public class GuiMultiModule extends ContainerScreen @Override public boolean mouseDragged(double mouseX, double mouseY, int clickedMouseButton, double timeSinceLastClick, double unkowwn) { - GuiModule module = this.getModuleForPoint(mouseX, mouseY); - if(module != null) { - if(module.handleMouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick)) { + ModuleScreen module = this.getModuleForPoint(mouseX, mouseY); + if (module != null) { + if (module.handleMouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick)) { return false; } } @@ -275,9 +245,9 @@ public class GuiMultiModule extends ContainerScreen @Override public boolean mouseReleased(double mouseX, double mouseY, int state) { - GuiModule module = this.getModuleForPoint(mouseX, mouseY); - if(module != null) { - if(module.handleMouseReleased(mouseX, mouseY, state)) { + ModuleScreen module = this.getModuleForPoint(mouseX, mouseY); + if (module != null) { + if (module.handleMouseReleased(mouseX, mouseY, state)) { return false; } } @@ -285,10 +255,10 @@ public class GuiMultiModule extends ContainerScreen return super.mouseReleased(mouseX, mouseY, state); } - protected GuiModule getModuleForPoint(double x, double y) { - for(GuiModule module : this.modules) { - if(this.isPointInRegion(module.guiLeft, module.guiTop, module.guiRight(), module.guiBottom(), - x + this.cornerX, y + this.cornerY)) { + protected ModuleScreen getModuleForPoint(double x, double y) { + for (ModuleScreen module : this.modules) { + if (this.isPointInRegion(module.guiLeft, module.guiTop, module.guiRight(), module.guiBottom(), + x + this.cornerX, y + this.cornerY)) { return module; } } @@ -296,13 +266,13 @@ public class GuiMultiModule extends ContainerScreen return null; } - protected GuiModule getModuleForSlot(int slotNumber) { + protected ModuleScreen getModuleForSlot(int slotNumber) { return this.getModuleForContainer(this.getContainer().getSlotContainer(slotNumber)); } - protected GuiModule getModuleForContainer(Container container) { - for(GuiModule module : this.modules) { - if(module.getContainer() == container) { + protected ModuleScreen getModuleForContainer(Container container) { + for (ModuleScreen module : this.modules) { + if (module.getContainer() == container) { return module; } } @@ -311,7 +281,8 @@ public class GuiMultiModule extends ContainerScreen } @Override - public ContainerMultiModule getContainer() { - return (ContainerMultiModule) this.container; + public MultiModuleContainer getContainer() { + return (MultiModuleContainer) this.container; } + } diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiElementScalable.java b/src/main/java/slimeknights/mantle/client/screen/ScalableElementScreen.java similarity index 71% rename from src/main/java/slimeknights/mantle/client/gui/GuiElementScalable.java rename to src/main/java/slimeknights/mantle/client/screen/ScalableElementScreen.java index c5f9cd9..eddc072 100644 --- a/src/main/java/slimeknights/mantle/client/gui/GuiElementScalable.java +++ b/src/main/java/slimeknights/mantle/client/screen/ScalableElementScreen.java @@ -1,27 +1,27 @@ -package slimeknights.mantle.client.gui; +package slimeknights.mantle.client.screen; import net.minecraft.client.gui.screen.Screen; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) -public class GuiElementScalable extends GuiElement { +public class ScalableElementScreen extends ElementScreen { - public GuiElementScalable(int x, int y, int w, int h, int texW, int texH) { + public ScalableElementScreen(int x, int y, int w, int h, int texW, int texH) { super(x, y, w, h, texW, texH); } - public GuiElementScalable(int x, int y, int w, int h) { + public ScalableElementScreen(int x, int y, int w, int h) { super(x, y, w, h); } public int drawScaledX(int xPos, int yPos, int width) { - for(int i = 0; i < width / this.w; i++) { + for (int i = 0; i < width / this.w; i++) { this.draw(xPos + i * this.w, yPos); } // remainder that doesn't fit total width int remainder = width % this.w; - if(remainder > 0) { + if (remainder > 0) { Screen.blit(xPos + width - remainder, yPos, this.x, this.y, remainder, this.h, this.texW, this.texH); } @@ -29,12 +29,12 @@ public class GuiElementScalable extends GuiElement { } public int drawScaledY(int xPos, int yPos, int height) { - for(int i = 0; i < height / this.h; i++) { + for (int i = 0; i < height / this.h; i++) { this.draw(xPos, yPos + i * this.h); } // remainder that doesn't fit total width int remainder = height % this.h; - if(remainder > 0) { + if (remainder > 0) { Screen.blit(xPos, yPos + height - remainder, this.x, this.y, this.w, remainder, this.texW, this.texH); } @@ -44,7 +44,7 @@ public class GuiElementScalable extends GuiElement { public int drawScaled(int xPos, int yPos, int width, int height) { // we draw full height row-wise int full = height / this.h; - for(int i = 0; i < full; i++) { + for (int i = 0; i < full; i++) { this.drawScaledX(xPos, yPos + i * this.h, width); } @@ -53,12 +53,12 @@ public class GuiElementScalable extends GuiElement { // and the remainder is drawn manually int yRest = height % this.h; // the same as drawScaledX but with the remaining height - for(int i = 0; i < width / this.w; i++) { + for (int i = 0; i < width / this.w; i++) { this.drawScaledY(xPos + i * this.w, yPos, yRest); } // remainder that doesn't fit total width int remainder = width % this.w; - if(remainder > 0) { + if (remainder > 0) { Screen.blit(xPos + width - remainder, yPos, this.x, this.y, remainder, yRest, this.texW, this.texH); } @@ -66,8 +66,8 @@ public class GuiElementScalable extends GuiElement { } @Override - public GuiElementScalable shift(int xd, int yd) { - GuiElementScalable element = new GuiElementScalable(this.x + xd, this.y + yd, this.w, this.h); + public ScalableElementScreen shift(int xd, int yd) { + ScalableElementScreen element = new ScalableElementScreen(this.x + xd, this.y + yd, this.w, this.h); element.setTextureSize(this.texW, this.texH); return element; } diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiWidget.java b/src/main/java/slimeknights/mantle/client/screen/Widget.java similarity index 86% rename from src/main/java/slimeknights/mantle/client/gui/GuiWidget.java rename to src/main/java/slimeknights/mantle/client/screen/Widget.java index b26ec9f..61ece17 100644 --- a/src/main/java/slimeknights/mantle/client/gui/GuiWidget.java +++ b/src/main/java/slimeknights/mantle/client/screen/Widget.java @@ -1,10 +1,10 @@ -package slimeknights.mantle.client.gui; +package slimeknights.mantle.client.screen; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) -public abstract class GuiWidget { +public abstract class Widget { public int xPos; public int yPos; @@ -24,3 +24,4 @@ public abstract class GuiWidget { this.height = height; } } + diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiWidgetSlider.java b/src/main/java/slimeknights/mantle/client/screen/WidgetSlider.java similarity index 75% rename from src/main/java/slimeknights/mantle/client/gui/GuiWidgetSlider.java rename to src/main/java/slimeknights/mantle/client/screen/WidgetSlider.java index aa68872..ad8fed9 100644 --- a/src/main/java/slimeknights/mantle/client/gui/GuiWidgetSlider.java +++ b/src/main/java/slimeknights/mantle/client/screen/WidgetSlider.java @@ -1,24 +1,21 @@ -package slimeknights.mantle.client.gui; +package slimeknights.mantle.client.screen; import net.minecraft.client.Minecraft; import net.minecraft.util.math.MathHelper; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.GuiScreenEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; // a vertical slider! @OnlyIn(Dist.CLIENT) -public class GuiWidgetSlider extends GuiWidget { +public class WidgetSlider extends Widget { // gui info - public final GuiElement slider; - public final GuiElement sliderHighlighted; - public final GuiElement sliderDisabled; - public final GuiElement slideBarTop; - public final GuiElement slideBarBottom; - public final GuiElementScalable slideBar; + public final ElementScreen slider; + public final ElementScreen sliderHighlighted; + public final ElementScreen sliderDisabled; + public final ElementScreen slideBarTop; + public final ElementScreen slideBarBottom; + public final ScalableElementScreen slideBar; // slider info protected int minValue; @@ -38,9 +35,8 @@ public class GuiWidgetSlider extends GuiWidget { private int clickX; private int clickY; private boolean clickedBar; // if the bar has already been clicked and not released - private boolean useMouseWheel; - public GuiWidgetSlider(GuiElement slider, GuiElement sliderHighlighted, GuiElement sliderDisabled, GuiElement slideBarTop, GuiElement slideBarBottom, GuiElementScalable slideBar) { + public WidgetSlider(ElementScreen slider, ElementScreen sliderHighlighted, ElementScreen sliderDisabled, ElementScreen slideBarTop, ElementScreen slideBarBottom, ScalableElementScreen slideBar) { this.slider = slider; this.sliderHighlighted = sliderHighlighted; this.sliderDisabled = sliderDisabled; @@ -61,7 +57,6 @@ public class GuiWidgetSlider extends GuiWidget { this.enabled = true; this.hidden = false; - this.useMouseWheel = false; } /** Sets the height of the whole slider and slidebar */ @@ -80,7 +75,7 @@ public class GuiWidgetSlider extends GuiWidget { } public int getValue() { - if(this.isHidden()) { + if (this.isHidden()) { return 0; } return Math.min(this.maxValue, Math.max(this.minValue, this.currentValue)); @@ -120,7 +115,7 @@ public class GuiWidgetSlider extends GuiWidget { @Override public void draw() { - if(this.hidden) { + if (this.hidden) { return; } @@ -133,11 +128,11 @@ public class GuiWidgetSlider extends GuiWidget { int y = this.yPos + this.getSliderTop(); // the slider depending on state - if(this.enabled) { - if(this.isScrolling) { + if (this.enabled) { + if (this.isScrolling) { this.sliderDisabled.draw(x, y); } - else if(this.isHighlighted) { + else if (this.isHighlighted) { this.sliderHighlighted.draw(x, y); } else { @@ -149,38 +144,37 @@ public class GuiWidgetSlider extends GuiWidget { } } - public void update(int mouseX, int mouseY, boolean useMouseWheel) { - if(!this.enabled || this.hidden) { + public void update(int mouseX, int mouseY) { + if (!this.enabled || this.hidden) { return; } boolean mouseDown = Minecraft.getInstance().mouseHelper.isLeftDown(); // left mouse button - this.useMouseWheel = useMouseWheel; // relative position inside the widget int x = mouseX - this.xPos; int y = mouseY - this.yPos; // reset click data - if(!mouseDown && this.clickedBar) { + if (!mouseDown && this.clickedBar) { this.clickedBar = false; } // button not pressed and scrolling -> stop scrolling - if(!mouseDown && this.isScrolling) { + if (!mouseDown && this.isScrolling) { this.isScrolling = false; } // button pressed and scrolling -> update position of slider - else if(this.isScrolling) { + else if (this.isScrolling) { float d = this.maxValue - this.minValue; float val = (float) (y - this.clickY) / (float) (this.getUsableSlidebarHeight() - this.slider.h); val *= d; - if(val < (float) this.increment / 2f) { + if (val < (float) this.increment / 2f) { // < 1/2 increment this.setSliderValue(this.minValue); } - else if(val > this.maxValue - ((float) this.increment / 2f)) { + else if (val > this.maxValue - ((float) this.increment / 2f)) { // > max-1/2 increment this.setSliderValue(this.maxValue); } @@ -190,20 +184,20 @@ public class GuiWidgetSlider extends GuiWidget { } } // not scrolling yet but possibly inside the slider - else if(x >= 0 && y >= this.getSliderTop() && + else if (x >= 0 && y >= this.getSliderTop() && x - this.sliderOffset <= this.slider.w && y <= this.getSliderTop() + this.slider.h) { this.isHighlighted = true; - if(mouseDown) { + if (mouseDown) { this.isScrolling = true; this.clickX = x - this.sliderOffset; this.clickY = y - this.getSliderTop(); } } // not on the slider but clicked on the bar - else if(mouseDown && !this.clickedBar && + else if (mouseDown && !this.clickedBar && x >= 0 && y >= 0 && x <= this.slideBar.w && y <= this.height) { - if(y < this.getSliderTop()) { + if (y < this.getSliderTop()) { this.decrement(); } else { @@ -217,24 +211,19 @@ public class GuiWidgetSlider extends GuiWidget { } } - @SubscribeEvent - public void onGuiMouseEvent(GuiScreenEvent.MouseScrollEvent.Pre event) { - double dWheel = event.getScrollDelta(); - double mouseX = event.getMouseX(); - double mouseY = event.getMouseY(); - - if(this.useMouseWheel) { - if(dWheel > 0.0) { + // Call this via Screen.mouseScrolled on your screen if you wish to use scroll data. + public boolean mouseScrolled(double mouseX, double mouseY, double scrollData, boolean useMouseWheel) { + if (useMouseWheel) { + if (scrollData > 0.0) { this.decrement(); - event.setCanceled(true); - return; + return true; } - else if(dWheel < 0.0) { + else if (scrollData < 0.0) { this.increment(); - event.setCanceled(true); - return; + return true; } } + return true; } public int increment() { @@ -248,10 +237,10 @@ public class GuiWidgetSlider extends GuiWidget { } public int setSliderValue(int val) { - if(val > this.maxValue) { + if (val > this.maxValue) { val = this.maxValue; } - else if(val < this.minValue) { + else if (val < this.minValue) { val = this.minValue; } diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiWidgetTabs.java b/src/main/java/slimeknights/mantle/client/screen/WidgetTabs.java similarity index 76% rename from src/main/java/slimeknights/mantle/client/gui/GuiWidgetTabs.java rename to src/main/java/slimeknights/mantle/client/screen/WidgetTabs.java index 020753f..6955c46 100644 --- a/src/main/java/slimeknights/mantle/client/gui/GuiWidgetTabs.java +++ b/src/main/java/slimeknights/mantle/client/screen/WidgetTabs.java @@ -1,7 +1,6 @@ -package slimeknights.mantle.client.gui; +package slimeknights.mantle.client.screen; import com.google.common.collect.Lists; - import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemRenderer; @@ -14,13 +13,13 @@ import net.minecraftforge.api.distmarker.OnlyIn; import java.util.List; @OnlyIn(Dist.CLIENT) -public class GuiWidgetTabs extends GuiWidget { +public class WidgetTabs extends Widget { private static final ResourceLocation - creativeInventoryTabs = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png"); + creativeInventoryTabs = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png"); - private final GuiElement[] tabActive = new GuiElement[3]; - private final GuiElement[] tab = new GuiElement[3]; + private final ElementScreen[] tabActive = new ElementScreen[3]; + private final ElementScreen[] tab = new ElementScreen[3]; // change this if you need different tabs public ResourceLocation tabsResource = creativeInventoryTabs; @@ -33,10 +32,10 @@ public class GuiWidgetTabs extends GuiWidget { public int highlighted; protected List icons = Lists.newArrayList(); - private final GuiMultiModule parent; + private final MultiModuleScreen parent; private boolean clicked = false; - public GuiWidgetTabs(GuiMultiModule parent, GuiElement tabLeft, GuiElement tabCenter, GuiElement tabRight, GuiElement activeLeft, GuiElement activeCenter, GuiElement activeRight) { + public WidgetTabs(MultiModuleScreen parent, ElementScreen tabLeft, ElementScreen tabCenter, ElementScreen tabRight, ElementScreen activeLeft, ElementScreen activeCenter, ElementScreen activeRight) { this.parent = parent; this.tab[0] = tabLeft; @@ -67,12 +66,12 @@ public class GuiWidgetTabs extends GuiWidget { // update highlighted this.highlighted = -1; - if(mouseY >= 0 && mouseY <= this.tab[1].h) { + if (mouseY >= 0 && mouseY <= this.tab[1].h) { // which one did we click? int x = 0; - for(int i = 0; i < this.icons.size(); i++) { + for (int i = 0; i < this.icons.size(); i++) { // clicking on spacing has no effect - if(mouseX >= x && mouseX < x + this.tab[1].w) { + if (mouseX >= x && mouseX < x + this.tab[1].w) { this.highlighted = i; break; } @@ -82,9 +81,9 @@ public class GuiWidgetTabs extends GuiWidget { } // already clicked - if(this.clicked) { + if (this.clicked) { // still clicking - if(mouseDown) { + if (mouseDown) { return; } // release click @@ -94,7 +93,7 @@ public class GuiWidgetTabs extends GuiWidget { } } // new click - else if(mouseDown) { + else if (mouseDown) { this.clicked = true; } // no click - do nothing @@ -103,7 +102,7 @@ public class GuiWidgetTabs extends GuiWidget { } // was new click, select highlighted - if(this.highlighted > -1) { + if (this.highlighted > -1) { this.selected = this.highlighted; } } @@ -111,26 +110,26 @@ public class GuiWidgetTabs extends GuiWidget { @Override public void draw() { int y = this.yPos + this.yOffset; - for(int i = 0; i < this.icons.size(); i++) { + for (int i = 0; i < this.icons.size(); i++) { int x = this.xPos + i * this.tab[0].w; - if(i > 0) { + if (i > 0) { x += i * this.spacing; } - GuiElement[] toDraw; - if(i == this.selected) { + ElementScreen[] toDraw; + if (i == this.selected) { toDraw = this.tabActive; } else { toDraw = this.tab; } - GuiElement actualTab; - if(i == 0 && x == this.parent.cornerX) { + ElementScreen actualTab; + if (i == 0 && x == this.parent.cornerX) { actualTab = toDraw[0]; } - else if(x == this.parent.cornerX + this.parent.width) { + else if (x == this.parent.cornerX + this.parent.width) { actualTab = toDraw[2]; } else { @@ -143,9 +142,8 @@ public class GuiWidgetTabs extends GuiWidget { Minecraft.getInstance().getTextureManager().bindTexture(this.tabsResource); actualTab.draw(x, y); - ItemStack icon = this.icons.get(i); - if(icon != null) { + if (icon != null) { RenderHelper.enableGUIStandardItemLighting(); this.drawItemStack(icon, x + (actualTab.w - 16) / 2, y + (actualTab.h - 16) / 2); RenderHelper.disableStandardItemLighting(); diff --git a/src/main/java/slimeknights/mantle/client/screen/book/ArrowButton.java b/src/main/java/slimeknights/mantle/client/screen/book/ArrowButton.java new file mode 100644 index 0000000..16a0897 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/screen/book/ArrowButton.java @@ -0,0 +1,71 @@ +package slimeknights.mantle.client.screen.book; + +import com.mojang.blaze3d.platform.GlStateManager; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.widget.button.Button; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import static slimeknights.mantle.client.screen.book.Textures.TEX_BOOK; + +@OnlyIn(Dist.CLIENT) +public class ArrowButton extends Button { + + public static final int WIDTH = 18; + public static final int HEIGHT = 10; + + // Appearance + public ArrowType arrowType; + public int color; + public int hoverColor; + + public ArrowButton(int x, int y, ArrowType arrowType, int color, int hoverColor, IPressable iPressable) { + super(x, y, arrowType.w, arrowType.h, "", iPressable); + + this.arrowType = arrowType; + this.color = color; + this.hoverColor = hoverColor; + } + + @Override + public void renderButton(int mouseX, int mouseY, float partialTicks) { + Minecraft minecraft = Minecraft.getInstance(); + minecraft.getTextureManager().bindTexture(TEX_BOOK); + + this.isHovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; + + int color = this.isHovered ? this.hoverColor : this.color; + + float r = ((color >> 16) & 0xff) / 255.F; + float g = ((color >> 8) & 0xff) / 255.F; + float b = (color & 0xff) / 255.F; + + GlStateManager.color3f(r, g, b); + blit(this.x, this.y, this.width, this.height, this.arrowType.x, this.arrowType.y, this.width, this.height, 512, 512); + this.renderBg(minecraft, mouseX, mouseY); + } + + public enum ArrowType { + NEXT(412, 0), + PREV(412, 10), + RIGHT(412, 20), + LEFT(412, 30), + BACK_UP(412, 40, 18, 18), + UP(412, 58, 10, 18), + DOWN(412 + 10, 58, 10, 18), + REFRESH(412, 76, 18, 18); + + public final int x, y, w, h; + + ArrowType(int x, int y) { + this(x, y, WIDTH, HEIGHT); + } + + ArrowType(int x, int y, int w, int h) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + } + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/book/GuiBook.java b/src/main/java/slimeknights/mantle/client/screen/book/BookScreen.java similarity index 74% rename from src/main/java/slimeknights/mantle/client/gui/book/GuiBook.java rename to src/main/java/slimeknights/mantle/client/screen/book/BookScreen.java index 0c41407..915f2bf 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/GuiBook.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/BookScreen.java @@ -1,7 +1,6 @@ -package slimeknights.mantle.client.gui.book; +package slimeknights.mantle.client.screen.book; import com.google.common.collect.ImmutableList; - import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.advancements.Advancement; import net.minecraft.advancements.AdvancementProgress; @@ -13,17 +12,9 @@ import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; - import net.minecraft.util.text.ITextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.annotation.Nullable; - import org.lwjgl.glfw.GLFW; import slimeknights.mantle.client.book.BookHelper; import slimeknights.mantle.client.book.BookLoader; @@ -31,14 +22,18 @@ import slimeknights.mantle.client.book.action.StringActionProcessor; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.PageData; import slimeknights.mantle.client.book.data.element.ItemStackData; -import slimeknights.mantle.client.gui.book.element.BookElement; +import slimeknights.mantle.client.screen.book.element.BookElement; -import static slimeknights.mantle.client.gui.book.Textures.TEX_BOOK; -import static slimeknights.mantle.client.gui.book.Textures.TEX_BOOKFRONT; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import static slimeknights.mantle.client.screen.book.Textures.TEX_BOOK; +import static slimeknights.mantle.client.screen.book.Textures.TEX_BOOKFRONT; @OnlyIn(Dist.CLIENT) -public class GuiBook extends Screen -{ +public class BookScreen extends Screen { public static boolean debug = false; @@ -59,11 +54,11 @@ public class GuiBook extends Screen public static int PAGE_WIDTH; public static int PAGE_HEIGHT; - static{ + static { initWidthsAndHeights(); // initializes page width and height } - private GuiArrow previousArrow, nextArrow, backArrow, indexArrow; + private ArrowButton previousArrow, nextArrow, backArrow, indexArrow; public final BookData book; private ItemStack item; @@ -81,14 +76,15 @@ public class GuiBook extends Screen PAGE_HEIGHT = (int) ((PAGE_HEIGHT_UNSCALED - (PAGE_PADDING_TOP + PAGE_PADDING_BOT + PAGE_MARGIN + PAGE_MARGIN)) / PAGE_SCALE); } - public GuiBook(ITextComponent title, BookData book, @Nullable ItemStack item) { + public BookScreen(ITextComponent title, BookData book, @Nullable ItemStack item) { super(title); this.book = book; this.item = item; this.minecraft = Minecraft.getInstance(); this.font = this.minecraft.fontRenderer; - this.init(); + + initWidthsAndHeights(); this.advancementCache = new AdvancementCache(); this.minecraft.player.connection.getAdvancementManager().setListener(this.advancementCache); @@ -96,47 +92,16 @@ public class GuiBook extends Screen this.openPage(book.findPageNumber(BookHelper.getSavedPage(item), this.advancementCache)); } - public void drawerTransform(boolean rightSide) { - if(rightSide) { - GlStateManager.translatef(this.width / 2 + PAGE_PADDING_RIGHT + PAGE_MARGIN, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2 + PAGE_PADDING_TOP + PAGE_MARGIN, 0); - } else { - GlStateManager.translatef(this.width / 2 - PAGE_WIDTH_UNSCALED + PAGE_PADDING_LEFT + PAGE_MARGIN, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2 + PAGE_PADDING_TOP + PAGE_MARGIN, 0); - } - } - - // offset to the left edge of the left/right side - protected float leftOffset(boolean rightSide) { - if(rightSide) { - // from center: go padding + margin to the right - return this.width / 2 + PAGE_PADDING_RIGHT + PAGE_MARGIN; - } else { - // from center: go page width left, then right with padding and margin - return this.width / 2 - PAGE_WIDTH_UNSCALED + PAGE_PADDING_LEFT + PAGE_MARGIN; - } - } - - protected float topOffset() { - return this.height / 2 - PAGE_HEIGHT_UNSCALED / 2 + PAGE_PADDING_TOP + PAGE_MARGIN; - } - - protected int getMouseX(boolean rightSide) { - return (int) ((Minecraft.getInstance().mouseHelper.getMouseX() * this.width / this.minecraft.mainWindow.getFramebufferWidth() - this.leftOffset(rightSide)) / PAGE_SCALE); - } - - protected int getMouseY() { - return (int) ((this.height - Minecraft.getInstance().mouseHelper.getMouseY() * this.height / this.minecraft.mainWindow.getFramebufferWidth() - 1 - this.topOffset()) / PAGE_SCALE); - } - @Override @SuppressWarnings("ForLoopReplaceableByForEach") public void render(int mouseX, int mouseY, float partialTicks) { - this.init(); + initWidthsAndHeights(); FontRenderer fontRenderer = this.book.fontRenderer; - if(fontRenderer == null) { + if (fontRenderer == null) { fontRenderer = this.minecraft.fontRenderer; } - if(debug) { + if (debug) { fill(0, 0, fontRenderer.getStringWidth("DEBUG") + 4, fontRenderer.FONT_HEIGHT + 4, 0x55000000); fontRenderer.drawString("DEBUG", 2, 2, 0xFFFFFFFF); } @@ -180,7 +145,7 @@ public class GuiBook extends Screen TextureManager render = this.minecraft.textureManager; - if(this.page == -1) { + if (this.page == -1) { render.bindTexture(TEX_BOOKFRONT); RenderHelper.disableStandardItemLighting(); @@ -188,7 +153,7 @@ public class GuiBook extends Screen blit(this.width / 2 - PAGE_WIDTH_UNSCALED / 2, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2, 0, 0, PAGE_WIDTH_UNSCALED, PAGE_HEIGHT_UNSCALED, TEX_SIZE, TEX_SIZE); GlStateManager.color3f(1F, 1F, 1F); - if(!this.book.appearance.title.isEmpty()) { + if (!this.book.appearance.title.isEmpty()) { blit(this.width / 2 - PAGE_WIDTH_UNSCALED / 2, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2, 0, PAGE_HEIGHT_UNSCALED, PAGE_WIDTH_UNSCALED, PAGE_HEIGHT_UNSCALED, TEX_SIZE, TEX_SIZE); GlStateManager.pushMatrix(); @@ -196,19 +161,18 @@ public class GuiBook extends Screen float scale = fontRenderer.getStringWidth(this.book.appearance.title) <= 67 ? 2.5F : 2F; GlStateManager.scalef(scale, scale, 1F); - fontRenderer.drawStringWithShadow(this.book.appearance.title, (this.width / 2) / scale + 3 - fontRenderer - .getStringWidth(this.book.appearance.title) / 2, (this.height / 2 - fontRenderer.FONT_HEIGHT / 2) / scale - 4, 0xAE8000); + fontRenderer.drawStringWithShadow(this.book.appearance.title, (this.width / 2) / scale + 3 - fontRenderer.getStringWidth(this.book.appearance.title) / 2, (this.height / 2 - fontRenderer.FONT_HEIGHT / 2) / scale - 4, 0xAE8000); GlStateManager.popMatrix(); } - if(!this.book.appearance.subtitle.isEmpty()) { + if (!this.book.appearance.subtitle.isEmpty()) { GlStateManager.pushMatrix(); GlStateManager.scalef(1.5F, 1.5F, 1F); - fontRenderer.drawStringWithShadow(this.book.appearance.subtitle, (this.width / 2) / 1.5F + 7 - fontRenderer - .getStringWidth(this.book.appearance.subtitle) / 2, (this.height / 2 + 100 - fontRenderer.FONT_HEIGHT * 2) / 1.5F, 0xAE8000); + fontRenderer.drawStringWithShadow(this.book.appearance.subtitle, (this.width / 2) / 1.5F + 7 - fontRenderer.getStringWidth(this.book.appearance.subtitle) / 2, (this.height / 2 + 100 - fontRenderer.FONT_HEIGHT * 2) / 1.5F, 0xAE8000); GlStateManager.popMatrix(); } - } else { + } + else { render.bindTexture(TEX_BOOK); RenderHelper.disableStandardItemLighting(); @@ -217,7 +181,7 @@ public class GuiBook extends Screen GlStateManager.color3f(1F, 1F, 1F); - if(this.page != 0) { + if (this.page != 0) { blit(this.width / 2 - PAGE_WIDTH_UNSCALED, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2, 0, PAGE_HEIGHT_UNSCALED, PAGE_WIDTH_UNSCALED, PAGE_HEIGHT_UNSCALED, TEX_SIZE, TEX_SIZE); GlStateManager.pushMatrix(); @@ -225,7 +189,7 @@ public class GuiBook extends Screen GlStateManager.scalef(PAGE_SCALE, PAGE_SCALE, 1F); - if(this.book.appearance.drawPageNumbers) { + if (this.book.appearance.drawPageNumbers) { String pNum = (this.page - 1) * 2 + 2 + ""; fontRenderer.drawString(pNum, PAGE_WIDTH / 2 - fontRenderer.getStringWidth(pNum) / 2, PAGE_HEIGHT - 10, 0xFFAAAAAA); } @@ -234,7 +198,7 @@ public class GuiBook extends Screen int mY = this.getMouseY(); // Not foreach to prevent conmodification crashes - for(int i = 0; i < this.leftElements.size(); i++) { + for (int i = 0; i < this.leftElements.size(); i++) { BookElement element = this.leftElements.get(i); GlStateManager.color4f(1F, 1F, 1F, 1F); @@ -242,7 +206,7 @@ public class GuiBook extends Screen } // Not foreach to prevent conmodification crashes - for(int i = 0; i < this.leftElements.size(); i++) { + for (int i = 0; i < this.leftElements.size(); i++) { BookElement element = this.leftElements.get(i); GlStateManager.color4f(1F, 1F, 1F, 1F); @@ -259,7 +223,7 @@ public class GuiBook extends Screen RenderHelper.disableStandardItemLighting(); int fullPageCount = this.book.getFullPageCount(this.advancementCache); - if(this.page < fullPageCount - 1 || this.book.getPageCount(this.advancementCache) % 2 != 0) { + if (this.page < fullPageCount - 1 || this.book.getPageCount(this.advancementCache) % 2 != 0) { blit(this.width / 2, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2, PAGE_WIDTH_UNSCALED, PAGE_HEIGHT_UNSCALED, PAGE_WIDTH_UNSCALED, PAGE_HEIGHT_UNSCALED, TEX_SIZE, TEX_SIZE); GlStateManager.pushMatrix(); @@ -267,7 +231,7 @@ public class GuiBook extends Screen GlStateManager.scalef(PAGE_SCALE, PAGE_SCALE, 1F); - if(this.book.appearance.drawPageNumbers) { + if (this.book.appearance.drawPageNumbers) { String pNum = (this.page - 1) * 2 + 3 + ""; fontRenderer.drawString(pNum, PAGE_WIDTH / 2 - fontRenderer.getStringWidth(pNum) / 2, PAGE_HEIGHT - 10, 0xFFAAAAAA); } @@ -276,7 +240,7 @@ public class GuiBook extends Screen int mY = this.getMouseY(); // Not foreach to prevent conmodification crashes - for(int i = 0; i < this.rightElements.size(); i++) { + for (int i = 0; i < this.rightElements.size(); i++) { BookElement element = this.rightElements.get(i); GlStateManager.color4f(1F, 1F, 1F, 1F); @@ -284,7 +248,7 @@ public class GuiBook extends Screen } // Not foreach to prevent conmodification crashes - for(int i = 0; i < this.rightElements.size(); i++) { + for (int i = 0; i < this.rightElements.size(); i++) { BookElement element = this.rightElements.get(i); GlStateManager.color4f(1F, 1F, 1F, 1F); @@ -300,26 +264,303 @@ public class GuiBook extends Screen GlStateManager.popMatrix(); } + @Override + protected void init() { + super.init(); + + // The books are unreadable at Gui Scale set to small, so we'll double the scale, and of course half the size so that all our code still works as it should + /* + if(mc.gameSettings.guiScale == 1) { + width /= 2F; + height /= 2F; + }*/ + + this.buttons.clear(); + this.children.clear(); + + this.previousArrow = this.addButton(new ArrowButton(-50, -50, ArrowButton.ArrowType.PREV, this.book.appearance.arrowColor, this.book.appearance.arrowColorHover, (p_212998_1_) -> { + this.page--; + + if (this.page < -1) { + this.page = -1; + } + + this.oldPage = -2; + this.buildPages(); + })); + + this.nextArrow = this.addButton(new ArrowButton(-50, -50, ArrowButton.ArrowType.NEXT, this.book.appearance.arrowColor, this.book.appearance.arrowColorHover, (p_212998_1_) -> { + this.page++; + + int fullPageCount = this.book.getFullPageCount(this.advancementCache); + + if (this.page >= fullPageCount) { + this.page = fullPageCount - 1; + } + + this.oldPage = -2; + this.buildPages(); + })); + + this.backArrow = this.addButton(new ArrowButton(this.width / 2 - ArrowButton.WIDTH / 2, this.height / 2 + ArrowButton.HEIGHT / 2 + PAGE_HEIGHT / 2, ArrowButton.ArrowType.LEFT, this.book.appearance.arrowColor, this.book.appearance.arrowColorHover, (p_212998_1_) -> { + if (this.oldPage >= -1) { + this.page = this.oldPage; + } + + this.oldPage = -2; + this.buildPages(); + })); + + this.indexArrow = this.addButton(new ArrowButton(this.width / 2 - PAGE_WIDTH_UNSCALED - ArrowButton.WIDTH / 2, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2, ArrowButton.ArrowType.BACK_UP, this.book.appearance.arrowColor, this.book.appearance.arrowColorHover, (p_212998_1_) -> { + this.openPage(this.book.findPageNumber("index.page1")); + + this.oldPage = -2; + this.buildPages(); + })); + + this.buildPages(); + } + + @Override + public void tick() { + super.tick(); + + this.previousArrow.visible = this.page != -1; + this.nextArrow.visible = this.page + 1 < this.book.getFullPageCount(this.advancementCache); + this.backArrow.visible = this.oldPage >= -1; + + if (this.page == -1) { + this.nextArrow.x = this.width / 2 + 80; + this.indexArrow.visible = false; + } + else { + this.previousArrow.x = this.width / 2 - 184; + this.nextArrow.x = this.width / 2 + 165; + + this.indexArrow.visible = this.book.findSection("index") != null && (this.page - 1) * 2 + 2 > this.book.findSection("index").getPageCount(); + } + + this.previousArrow.y = this.height / 2 + 75; + this.nextArrow.y = this.height / 2 + 75; + } + + /*@Override + TODO: REMOVE + public void actionPerformed(GuiButton button) { + if(button instanceof GuiBookmark) { + openPage(book.findPageNumber(((GuiBookmark) button).data.page, advancementCache)); + + return; + } + }*/ + + @Override + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { + super.keyPressed(keyCode, scanCode, modifiers); + + switch (keyCode) { + case GLFW.GLFW_KEY_LEFT: + case GLFW.GLFW_KEY_A: + this.page--; + if (this.page < -1) { + this.page = -1; + } + + this.oldPage = -2; + this.buildPages(); + return true; + case GLFW.GLFW_KEY_RIGHT: + case GLFW.GLFW_KEY_D: + this.page++; + int fullPageCount = this.book.getFullPageCount(this.advancementCache); + if (this.page >= fullPageCount) { + this.page = fullPageCount - 1; + } + this.oldPage = -2; + this.buildPages(); + return true; + case GLFW.GLFW_KEY_F3: + debug = !debug; + return true; + } + + return super.keyPressed(keyCode, scanCode, modifiers); + } + + @Override + public boolean mouseScrolled(double unKnown1, double unKnown2, double scrollDelta) { + + if (scrollDelta < 0.0D) { + this.page++; + int fullPageCount = this.book.getFullPageCount(this.advancementCache); + if (this.page >= fullPageCount) { + this.page = fullPageCount - 1; + } + this.oldPage = -2; + this.buildPages(); + + return true; + } + else if (scrollDelta > 0.0D) { + this.page--; + if (this.page < -1) { + this.page = -1; + } + + this.oldPage = -2; + this.buildPages(); + + return true; + } + + return super.mouseScrolled(scrollDelta, unKnown1, unKnown2); + } + + @Override + public boolean mouseClicked(double originalMouseX, double originalMouseY, int mouseButton) { + boolean right = false; + + double mouseX = this.getMouseX(false); + double mouseY = this.getMouseY(); + + if (mouseX > PAGE_WIDTH + (PAGE_MARGIN + PAGE_PADDING_LEFT) / PAGE_SCALE) { + mouseX = this.getMouseX(true); + right = true; + } + + // Not foreach to prevent conmodification crashes + int oldPage = this.page; + List elementList = ImmutableList.copyOf(right ? this.rightElements : this.leftElements); + for (BookElement element : elementList) { + element.mouseClicked(mouseX, mouseY, mouseButton); + // if we changed page stop so we don't act on the new page + if (this.page != oldPage) { + return true; + } + } + + return super.mouseClicked(originalMouseX, originalMouseY, mouseButton); + } + + @Override + public boolean mouseReleased(double originalMouseX, double originalMouseY, int mouseButton) { + boolean right = false; + double mouseX = this.getMouseX(false); + double mouseY = this.getMouseY(); + + if (mouseX > PAGE_WIDTH + (PAGE_MARGIN + PAGE_PADDING_LEFT) / PAGE_SCALE) { + mouseX = this.getMouseX(true); + right = true; + } + + // Not foreach to prevent conmodification crashes + for (int i = 0; right ? i < this.rightElements.size() : i < this.leftElements.size(); i++) { + BookElement element = right ? this.rightElements.get(i) : this.leftElements.get(i); + element.mouseReleased(mouseX, mouseY, mouseButton); + } + return super.mouseReleased(originalMouseX, originalMouseY, mouseButton); + } + + @Override + public boolean mouseDragged(double mouseX, double mouseY, int clickedMouseButton, double timeSinceLaslick, double unknown) { + boolean right = false; + mouseX = this.getMouseX(false); + mouseY = this.getMouseY(); + + if (mouseX > PAGE_WIDTH + (PAGE_MARGIN + PAGE_PADDING_LEFT) / PAGE_SCALE) { + mouseX = this.getMouseX(true); + right = true; + } + + // Not foreach to prevent conmodification crashes + for (int i = 0; right ? i < this.rightElements.size() : i < this.leftElements.size(); i++) { + BookElement element = right ? this.rightElements.get(i) : this.leftElements.get(i); + element.mouseClickMove(mouseX, mouseY, clickedMouseButton); + } + + return true; + } + + @Override + public void removed() { + if (this.minecraft.player == null) { + return; + } + + PageData page = this.page == 0 ? this.book.findPage(0, this.advancementCache) : this.book.findPage((this.page - 1) * 2 + 1, this.advancementCache); + + if (page == null) { + page = this.book.findPage((this.page - 1) * 2 + 2, this.advancementCache); + } + + if (this.page == -1) { + BookLoader.updateSavedPage(this.minecraft.player, this.item, ""); + } + else if (page != null && page.parent != null) { + BookLoader.updateSavedPage(this.minecraft.player, this.item, page.parent.name + "." + page.name); + } + } + + @Override + public boolean isPauseScreen() { + return false; + } + + public void drawerTransform(boolean rightSide) { + if (rightSide) { + GlStateManager.translatef(this.width / 2 + PAGE_PADDING_RIGHT + PAGE_MARGIN, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2 + PAGE_PADDING_TOP + PAGE_MARGIN, 0); + } + else { + GlStateManager.translatef(this.width / 2 - PAGE_WIDTH_UNSCALED + PAGE_PADDING_LEFT + PAGE_MARGIN, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2 + PAGE_PADDING_TOP + PAGE_MARGIN, 0); + } + } + + // offset to the left edge of the left/right side + protected float leftOffset(boolean rightSide) { + if (rightSide) { + // from center: go padding + margin to the right + return this.width / 2 + PAGE_PADDING_RIGHT + PAGE_MARGIN; + } + else { + // from center: go page width left, then right with padding and margin + return this.width / 2 - PAGE_WIDTH_UNSCALED + PAGE_PADDING_LEFT + PAGE_MARGIN; + } + } + + protected float topOffset() { + return this.height / 2 - PAGE_HEIGHT_UNSCALED / 2 + PAGE_PADDING_TOP + PAGE_MARGIN; + } + + protected int getMouseX(boolean rightSide) { + return (int) ((Minecraft.getInstance().mouseHelper.getMouseX() * this.width / this.minecraft.mainWindow.getFramebufferWidth() - this.leftOffset(rightSide)) / PAGE_SCALE); + } + + protected int getMouseY() { + return (int) ((Minecraft.getInstance().mouseHelper.getMouseY() * this.height / this.minecraft.mainWindow.getFramebufferHeight() - 1 - this.topOffset()) / PAGE_SCALE); + } + public int openPage(int page) { return this.openPage(page, false); } public int openPage(int page, boolean returner) { - if(page < 0) { + if (page < 0) { return -1; } int bookPage; - if(page == 1) { + if (page == 1) { bookPage = 0; - } else if(page % 2 == 0) { + } + else if (page % 2 == 0) { bookPage = (page - 1) / 2 + 1; - } else { + } + else { bookPage = (page - 2) / 2 + 1; } - if(bookPage >= -1 && bookPage < this.book.getFullPageCount(this.advancementCache)) { - if(returner) { + if (bookPage >= -1 && bookPage < this.book.getFullPageCount(this.advancementCache)) { + if (returner) { this.oldPage = this.page; } @@ -335,15 +576,19 @@ public class GuiBook extends Screen } public int getPage(int side) { - if(this.page == 0 && side == 0) { + if (this.page == 0 && side == 0) { return -1; - } else if(this.page == 0 && side == 1) { + } + else if (this.page == 0 && side == 1) { return 0; - } else if(side == 0) { + } + else if (side == 0) { return (this.page - 1) * 2 + 1; - } else if(side == 1) { + } + else if (side == 1) { return (this.page - 2) * 2 + 2; - } else { + } + else { return -1; } } @@ -372,301 +617,51 @@ public class GuiBook extends Screen this.leftElements.clear(); this.rightElements.clear(); - if(this.page == -1) { + if (this.page == -1) { return; } - if(this.page == 0) { + if (this.page == 0) { PageData page = this.book.findPage(0, this.advancementCache); - if(page != null) { + if (page != null) { page.content.build(this.book, this.rightElements, false); } - } else { + } + else { PageData leftPage = this.book.findPage((this.page - 1) * 2 + 1, this.advancementCache); PageData rightPage = this.book.findPage((this.page - 1) * 2 + 2, this.advancementCache); - if(leftPage != null) { + if (leftPage != null) { leftPage.content.build(this.book, this.leftElements, false); } - if(rightPage != null) { + if (rightPage != null) { rightPage.content.build(this.book, this.rightElements, true); } } - for(BookElement element : this.leftElements) { + for (BookElement element : this.leftElements) { element.parent = this; } - for(BookElement element : this.rightElements) { + for (BookElement element : this.rightElements) { element.parent = this; } } - @Override - public void init() { - super.init(); - - // The books are unreadable at Gui Scale set to small, so we'll double the scale, and of course half the size so that all our code still works as it should - /* - if(mc.gameSettings.guiScale == 1) { - width /= 2F; - height /= 2F; - }*/ - - this.previousArrow = new GuiArrow(0, -50, -50, GuiArrow.ArrowType.PREV, this.book.appearance.arrowColor, this.book.appearance.arrowColorHover) { - @Override - public void onClick(double mouseX, double mouseY) { - GuiBook.this.page--; - if(GuiBook.this.page < -1) { - GuiBook.this.page = -1; - } - - GuiBook.this.oldPage = -2; - GuiBook.this.buildPages(); - } - }; - - this.nextArrow = new GuiArrow(1, -50, -50, GuiArrow.ArrowType.NEXT, this.book.appearance.arrowColor, this.book.appearance.arrowColorHover) { - @Override - public void onClick(double mouseX, double mouseY) { - GuiBook.this.page++; - int fullPageCount = GuiBook.this.book.getFullPageCount(GuiBook.this.advancementCache); - if(GuiBook.this.page >= fullPageCount) { - GuiBook.this.page = fullPageCount - 1; - } - GuiBook.this.oldPage = -2; - GuiBook.this.buildPages(); - } - }; - - this.backArrow = new GuiArrow(2, this.width / 2 - GuiArrow.WIDTH / 2, this.height / 2 + GuiArrow.HEIGHT / 2 + PAGE_HEIGHT/2, GuiArrow.ArrowType.LEFT, this.book.appearance.arrowColor, this.book.appearance.arrowColorHover) { - @Override - public void onClick(double mouseX, double mouseY) { - if(GuiBook.this.oldPage >= -1) { - GuiBook.this.page = GuiBook.this.oldPage; - } - - GuiBook.this.oldPage = -2; - GuiBook.this.buildPages(); - } - }; - - this.indexArrow = new GuiArrow(3, this.width / 2 - PAGE_WIDTH_UNSCALED - GuiArrow.WIDTH / 2, this.height / 2 - PAGE_HEIGHT_UNSCALED / 2, GuiArrow.ArrowType.BACK_UP, this.book.appearance.arrowColor, this.book.appearance.arrowColorHover) { - @Override - public void onClick(double mouseX, double mouseY) { - GuiBook.this.openPage(GuiBook.this.book.findPageNumber("index.page1")); - - GuiBook.this.oldPage = -2; - GuiBook.this.buildPages(); - } - }; - - this.buttons.clear(); - this.buttons.add(this.previousArrow); - this.buttons.add(this.nextArrow); - this.buttons.add(this.backArrow); - this.buttons.add(this.indexArrow); - - this.buildPages(); - } - - @Override - public void tick() { - super.tick(); - - this.previousArrow.visible = this.page != -1; - this.nextArrow.visible = this.page + 1 < this.book.getFullPageCount(this.advancementCache); - this.backArrow.visible = this.oldPage >= -1; - - if(this.page == -1) { - this.nextArrow.x = this.width / 2 + 80; - this.indexArrow.visible = false; - } else { - this.previousArrow.x = this.width / 2 - 184; - this.nextArrow.x = this.width / 2 + 165; - - this.indexArrow.visible = this.book.findSection("index") != null && (this.page - 1) * 2 + 2 > this.book.findSection("index") - .getPageCount(); - } - - this.previousArrow.y = this.height / 2 + 75; - this.nextArrow.y = this.height / 2 + 75; - } - - /*@Override - TODO: REMOVE - public void actionPerformed(GuiButton button) { - if(button instanceof GuiBookmark) { - openPage(book.findPageNumber(((GuiBookmark) button).data.page, advancementCache)); - - return; - } - }*/ - - @Override - public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - super.keyPressed(keyCode, scanCode, modifiers); - - switch(keyCode) { - case GLFW.GLFW_KEY_LEFT: - case GLFW.GLFW_KEY_A: - this.page--; - if(this.page < -1) { - this.page = -1; - } - - this.oldPage = -2; - this.buildPages(); - return true; - case GLFW.GLFW_KEY_RIGHT: - case GLFW.GLFW_KEY_D: - this.page++; - int fullPageCount = this.book.getFullPageCount(this.advancementCache); - if(this.page >= fullPageCount) { - this.page = fullPageCount - 1; - } - this.oldPage = -2; - this.buildPages(); - return true; - case GLFW.GLFW_KEY_F3: - debug = !debug; - return true; - } - - return super.keyPressed(keyCode, scanCode, modifiers); - } - - @Override - public boolean mouseScrolled(double scrollDelta, double unKnown1, double unKnown2) { - - if (scrollDelta < 0.0D) { - this.page++; - int fullPageCount = this.book.getFullPageCount(this.advancementCache); - if(this.page >= fullPageCount) { - this.page = fullPageCount - 1; - } - this.oldPage = -2; - this.buildPages(); - - return true; - } - else if (scrollDelta > 0.0D) { - this.page--; - if(this.page < -1) { - this.page = -1; - } - - this.oldPage = -2; - this.buildPages(); - - return true; - } - - return super.mouseScrolled(scrollDelta, unKnown1, unKnown2); - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { - boolean right = false; - - mouseX = this.getMouseX(false); - mouseY = this.getMouseY(); - - if(mouseX > PAGE_WIDTH + (PAGE_MARGIN + PAGE_PADDING_LEFT) / PAGE_SCALE) { - mouseX = this.getMouseX(true); - right = true; - } - - // Not foreach to prevent conmodification crashes - int oldPage = this.page; - List elementList = ImmutableList.copyOf(right ? this.rightElements : this.leftElements); - for(BookElement element : elementList) { - element.mouseClicked(mouseX, mouseY, mouseButton); - // if we changed page stop so we don't act on the new page - if(this.page != oldPage) { - return true; - } - } - - return super.mouseClicked(mouseX, mouseY, mouseButton); - } - - @Override - public boolean mouseReleased(double mouseX, double mouseY, int mouseButton) { - boolean right = false; - mouseX = this.getMouseX(false); - mouseY = this.getMouseY(); - - if(mouseX > PAGE_WIDTH + (PAGE_MARGIN + PAGE_PADDING_LEFT) / PAGE_SCALE) { - mouseX = this.getMouseX(true); - right = true; - } - - // Not foreach to prevent conmodification crashes - for(int i = 0; right ? i < this.rightElements.size() : i < this.leftElements.size(); i++) { - BookElement element = right ? this.rightElements.get(i) : this.leftElements.get(i); - element.mouseReleased(mouseX, mouseY, mouseButton); - } - return super.mouseReleased(mouseX, mouseY, mouseButton); - } - - @Override - public boolean mouseDragged(double mouseX, double mouseY, int clickedMouseButton, double timeSinceLaslick, double unknown) { - boolean right = false; - mouseX = this.getMouseX(false); - mouseY = this.getMouseY(); - - if(mouseX > PAGE_WIDTH + (PAGE_MARGIN + PAGE_PADDING_LEFT) / PAGE_SCALE) { - mouseX = this.getMouseX(true); - right = true; - } - - // Not foreach to prevent conmodification crashes - for(int i = 0; right ? i < this.rightElements.size() : i < this.leftElements.size(); i++) { - BookElement element = right ? this.rightElements.get(i) : this.leftElements.get(i); - element.mouseClickMove(mouseX, mouseY, clickedMouseButton); - } - - return true; - } - - @Override - public void removed() { - if(this.minecraft.player == null) { - return; - } - - PageData page = this.page == 0 ? this.book.findPage(0, this.advancementCache) : this.book.findPage((this.page - 1) * 2 + 1, this.advancementCache); - - if(page == null) { - page = this.book.findPage((this.page - 1) * 2 + 2, this.advancementCache); - } - - if(this.page == -1) { - BookLoader.updateSavedPage(this.minecraft.player, this.item, ""); - } else if(page != null && page.parent != null) { - BookLoader.updateSavedPage(this.minecraft.player, this.item, page.parent.name + "." + page.name); - } - } - - @Override - public boolean isPauseScreen() { - return false; - } - public class AdvancementCache implements ClientAdvancementManager.IListener { + private HashMap progress = new HashMap<>(); private HashMap nameCache = new HashMap<>(); - public AdvancementProgress getProgress(String id){ + public AdvancementProgress getProgress(String id) { return this.getProgress(this.getAdvancement(id)); } - public AdvancementProgress getProgress(Advancement advancement){ + public AdvancementProgress getProgress(Advancement advancement) { return this.progress.get(advancement); } - public Advancement getAdvancement(String id){ + public Advancement getAdvancement(String id) { return this.nameCache.get(new ResourceLocation(id)); } diff --git a/src/main/java/slimeknights/mantle/client/screen/book/BookmarkButton.java b/src/main/java/slimeknights/mantle/client/screen/book/BookmarkButton.java new file mode 100644 index 0000000..566cd32 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/screen/book/BookmarkButton.java @@ -0,0 +1,58 @@ +package slimeknights.mantle.client.screen.book; + +import com.mojang.blaze3d.platform.GlStateManager; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.AbstractGui; +import net.minecraft.client.gui.widget.button.Button; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import slimeknights.mantle.client.book.data.BookmarkData; + +@OnlyIn(Dist.CLIENT) +public class BookmarkButton extends Button { + + private static final ResourceLocation TEX_BOOK = new ResourceLocation("mantle:textures/gui/book.png"); + + public static final int WIDTH = 31; + public static final int HEIGHT = 9; + public static final int TEX_X = 0, TEX_Y = 400; + public static final int ADD_W = 5, ADD_H = 5, ADD_X = 32, ADD_Y = 402; + + public static final float TEXT_SCALE = 0.5F; + + public int type = 0; + + public final BookmarkData data; + + public BookmarkButton(BookmarkData data, IPressable iPressable) { + super(-500, -500, WIDTH, HEIGHT, "", iPressable); + + this.data = data; + } + + @Override + public void renderButton(int mouseX, int mouseY, float partialTicks) { + Minecraft minecraft = Minecraft.getInstance(); + int tex_y = TEX_Y + HEIGHT * this.type; + + minecraft.textureManager.bindTexture(TEX_BOOK); + + float r = ((this.data.color >> 16) & 0xff) / 255.F; + float g = ((this.data.color >> 8) & 0xff) / 255.F; + float b = (this.data.color & 0xff) / 255.F; + + GlStateManager.color3f(r, g, b); + blit(this.x, this.y, this.width, this.height, TEX_X, tex_y, WIDTH, HEIGHT, 512, 512); + + if (this.data.text != null && !this.data.text.isEmpty()) { + TextDataRenderer.drawScaledString(minecraft.fontRenderer, this.data.text, this.x + 1, this.y + this.height / 2 - minecraft.fontRenderer.FONT_HEIGHT * TEXT_SCALE / 2 + 1, 0xFFFFFFFF, true, TEXT_SCALE); + } + + GlStateManager.color3f(1F, 1F, 1F); + + if (this.data.page.equals("ADD")) { + blit(this.x + this.width / 2 - ADD_W / 2, this.y + this.height / 2 - ADD_H / 2, ADD_X, ADD_Y, ADD_W, ADD_H, 512, 512); + } + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/book/TextDataRenderer.java b/src/main/java/slimeknights/mantle/client/screen/book/TextDataRenderer.java similarity index 74% rename from src/main/java/slimeknights/mantle/client/gui/book/TextDataRenderer.java rename to src/main/java/slimeknights/mantle/client/screen/book/TextDataRenderer.java index 9980a37..c35ed3e 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/TextDataRenderer.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/TextDataRenderer.java @@ -1,17 +1,16 @@ -package slimeknights.mantle.client.gui.book; +package slimeknights.mantle.client.screen.book; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.resources.I18n; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.client.config.GuiUtils; - import slimeknights.mantle.Mantle; import slimeknights.mantle.client.book.data.element.TextData; @@ -22,6 +21,7 @@ import java.util.List; @OnlyIn(Dist.CLIENT) public class TextDataRenderer { + /** * @deprecated Call drawText with tooltip param and then call drawTooltip separately on the tooltip layer to prevent overlap */ @@ -29,7 +29,7 @@ public class TextDataRenderer { List tooltip = new ArrayList(); String action = drawText(x, y, boxWidth, boxHeight, data, mouseX, mouseY, fr, tooltip); - if(tooltip.size() > 0) { + if (tooltip.size() > 0) { drawTooltip(tooltip, mouseX, mouseY, fr); } @@ -44,21 +44,21 @@ public class TextDataRenderer { float prevScale = 1.F; - for(TextData item : data) { + for (TextData item : data) { int box1X, box1Y, box1W = 9999, box1H = y + fr.FONT_HEIGHT; int box2X, box2Y = 9999, box2W, box2H; int box3X = 9999, box3Y = 9999, box3W, box3H; - if(item == null || item.text == null || item.text.isEmpty()) { + if (item == null || item.text == null || item.text.isEmpty()) { continue; } - if(item.text.equals("\n")) { + if (item.text.equals("\n")) { atX = x; atY += fr.FONT_HEIGHT; continue; } - if(item.paragraph) { + if (item.paragraph) { atX = x; atY += fr.FONT_HEIGHT * 2 * prevScale; } @@ -69,19 +69,19 @@ public class TextDataRenderer { modifiers += TextFormatting.getValueByName(item.color); - if(item.bold) { + if (item.bold) { modifiers += TextFormatting.BOLD; } - if(item.italic) { + if (item.italic) { modifiers += TextFormatting.ITALIC; } - if(item.underlined) { + if (item.underlined) { modifiers += TextFormatting.UNDERLINE; } - if(item.strikethrough) { + if (item.strikethrough) { modifiers += TextFormatting.STRIKETHROUGH; } - if(item.obfuscated) { + if (item.obfuscated) { modifiers += TextFormatting.OBFUSCATED; } @@ -94,8 +94,8 @@ public class TextDataRenderer { box2X = x; box2W = x + boxWidth; - for(int i = 0; i < split.length; i++) { - if(i == split.length - 1) { + for (int i = 0; i < split.length; i++) { + if (i == split.length - 1) { box3X = atX; box3Y = atY; } @@ -103,17 +103,18 @@ public class TextDataRenderer { String s = split[i]; drawScaledString(fr, modifiers + s, atX, atY, 0, item.dropshadow, item.scale); - if(i < split.length - 1) { + if (i < split.length - 1) { atY += fr.FONT_HEIGHT; atX = x; } - if(i == 0) { + if (i == 0) { box2Y = atY; - if(atX == x) { + if (atX == x) { box1W = x + boxWidth; - } else { + } + else { box1W = atX; } } @@ -122,7 +123,7 @@ public class TextDataRenderer { box2H = atY; atX += fr.getStringWidth(split[split.length - 1]) * item.scale; - if(atX - x >= boxWidth) { + if (atX - x >= boxWidth) { atX = x; atY += fr.FONT_HEIGHT * item.scale; } @@ -130,31 +131,29 @@ public class TextDataRenderer { box3W = atX; box3H = (int) (atY + fr.FONT_HEIGHT * item.scale); - if(item.tooltip != null && item.tooltip.length > 0) { + if (item.tooltip != null && item.tooltip.length > 0) { // Uncomment to render bounding boxes for event handling /*drawGradientRect(box1X, box1Y, box1W, box1H, 0xFF00FF00, 0xFF00FF00); drawGradientRect(box2X, box2Y, box2W, box2H, 0xFFFF0000, 0xFFFF0000); drawGradientRect(box3X, box3Y, box3W, box3H, 0xFF0000FF, 0xFF0000FF); drawGradientRect(mouseX, mouseY, mouseX + 5, mouseY + 5, 0xFFFF00FF, 0xFFFFFF00);*/ - if((mouseX >= box1X && mouseX <= box1W && mouseY >= box1Y && mouseY <= box1H && box1X != box1W && box1Y != box1H) || (mouseX >= box2X && mouseX <= box2W && mouseY >= box2Y && mouseY <= box2H && box2X != box2W && box2Y != box2H) || (mouseX >= box3X && mouseX <= box3W && mouseY >= box3Y && mouseY <= box3H && box3X != box3W && box1Y != box3H)) { + if ((mouseX >= box1X && mouseX <= box1W && mouseY >= box1Y && mouseY <= box1H && box1X != box1W && box1Y != box1H) || (mouseX >= box2X && mouseX <= box2W && mouseY >= box2Y && mouseY <= box2H && box2X != box2W && box2Y != box2H) || (mouseX >= box3X && mouseX <= box3W && mouseY >= box3Y && mouseY <= box3H && box3X != box3W && box1Y != box3H)) { tooltip.addAll(Arrays.asList(item.tooltip)); } } - if(item.action != null && !item.action.isEmpty()) { - if((mouseX >= box1X && mouseX <= box1W && mouseY >= box1Y && mouseY <= box1H && box1X != box1W && box1Y != box1H) || (mouseX >= box2X && mouseX <= box2W && mouseY >= box2Y && mouseY <= box2H && box2X != box2W && box2Y != box2H) || (mouseX >= box3X && mouseX <= box3W && mouseY >= box3Y && mouseY <= box3H && box3X != box3W && box1Y != box3H)) { + if (item.action != null && !item.action.isEmpty()) { + if ((mouseX >= box1X && mouseX <= box1W && mouseY >= box1Y && mouseY <= box1H && box1X != box1W && box1Y != box1H) || (mouseX >= box2X && mouseX <= box2W && mouseY >= box2Y && mouseY <= box2H && box2X != box2W && box2Y != box2H) || (mouseX >= box3X && mouseX <= box3W && mouseY >= box3Y && mouseY <= box3H && box3X != box3W && box1Y != box3H)) { action = item.action; } } - if(atY >= y + boxHeight) { - if(item.dropshadow) - { + if (atY >= y + boxHeight) { + if (item.dropshadow) { fr.drawStringWithShadow("...", atX, atY, 0); } - else - { + else { fr.drawString("...", atX, atY, 0); } break; @@ -162,7 +161,7 @@ public class TextDataRenderer { y = atY; } - if(GuiBook.debug && action != null && !action.isEmpty()) { + if (BookScreen.debug && action != null && !action.isEmpty()) { tooltip.add(""); tooltip.add(TextFormatting.GRAY + "Action: " + action); } @@ -173,14 +172,13 @@ public class TextDataRenderer { public static String translateString(String s) { s = s.replace("$$(", "$\0(").replace(")$$", ")\0$"); - while(s.contains("$(") && s.contains(")$") && s.indexOf("$(") < s.indexOf(")$")) { + while (s.contains("$(") && s.contains(")$") && s.indexOf("$(") < s.indexOf(")$")) { String loc = s.substring(s.indexOf("$(") + 2, s.indexOf(")$")); s = s.replace("$(" + loc + ")$", I18n.format(loc)); } - if(s.indexOf("$(") > s.indexOf(")$") || s.contains(")$")) { - Mantle.logger - .error("[Books] [TextDataRenderer] Detected unbalanced localization symbols \"$(\" and \")$\" in string: \"" + s + "\"."); + if (s.indexOf("$(") > s.indexOf(")$") || s.contains(")$")) { + Mantle.logger.error("[Books] [TextDataRenderer] Detected unbalanced localization symbols \"$(\" and \")$\" in string: \"" + s + "\"."); } return s.replace("$\0(", "$(").replace(")\0$", ")$"); @@ -194,15 +192,15 @@ public class TextDataRenderer { int curWidth = 0; int curHeight = (int) (fr.FONT_HEIGHT * scale); - for(int i = 0; i < s.length(); i++) { - curWidth += fr.getStringWidth(modifiers + Character.toString(s.charAt(i))) * scale; + for (int i = 0; i < s.length(); i++) { + curWidth += fr.getStringWidth(modifiers + s.charAt(i)) * scale; - if(s.charAt(i) == '\n' || (curHeight == (int) (fr.FONT_HEIGHT * scale) && curWidth > firstWidth) || (curHeight != (int) (fr.FONT_HEIGHT * scale) && curWidth > width)) { + if (s.charAt(i) == '\n' || (curHeight == (int) (fr.FONT_HEIGHT * scale) && curWidth > firstWidth) || (curHeight != (int) (fr.FONT_HEIGHT * scale) && curWidth > width)) { int oldI = i; - while(i >= 0 && s.charAt(i) != ' ') { + while (i >= 0 && s.charAt(i) != ' ') { i--; } - if(i <= 0) { + if (i <= 0) { i = oldI; } @@ -212,7 +210,7 @@ public class TextDataRenderer { curWidth = 0; curHeight += fr.FONT_HEIGHT * scale; - if(curHeight >= height) { + if (curHeight >= height) { return s.substring(0, i).trim().split("\r"); } } @@ -223,7 +221,7 @@ public class TextDataRenderer { //BEGIN METHODS FROM GUI public static void drawTooltip(List textLines, int mouseX, int mouseY, FontRenderer font) { - GuiUtils.drawHoveringText(textLines, mouseX, mouseY, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT, GuiBook.PAGE_WIDTH, font); + GuiUtils.drawHoveringText(textLines, mouseX, mouseY, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT, BookScreen.PAGE_WIDTH, font); RenderHelper.disableStandardItemLighting(); } @@ -231,12 +229,10 @@ public class TextDataRenderer { GlStateManager.pushMatrix(); GlStateManager.translatef(x, y, 0); GlStateManager.scalef(scale, scale, 1F); - if(dropShadow) - { + if (dropShadow) { font.drawStringWithShadow(text, 0, 0, color); } - else - { + else { font.drawString(text, 0, 0, color); } GlStateManager.popMatrix(); @@ -268,4 +264,4 @@ public class TextDataRenderer { GlStateManager.enableTexture(); } //END METHODS FROM GUI -} +} \ No newline at end of file diff --git a/src/main/java/slimeknights/mantle/client/gui/book/Textures.java b/src/main/java/slimeknights/mantle/client/screen/book/Textures.java similarity index 93% rename from src/main/java/slimeknights/mantle/client/gui/book/Textures.java rename to src/main/java/slimeknights/mantle/client/screen/book/Textures.java index bd6145f..5f2388e 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/Textures.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/Textures.java @@ -1,4 +1,4 @@ -package slimeknights.mantle.client.gui.book; +package slimeknights.mantle.client.screen.book; import net.minecraft.util.ResourceLocation; diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/BookElement.java b/src/main/java/slimeknights/mantle/client/screen/book/element/BookElement.java similarity index 75% rename from src/main/java/slimeknights/mantle/client/gui/book/element/BookElement.java rename to src/main/java/slimeknights/mantle/client/screen/book/element/BookElement.java index 27150b9..3c63363 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/BookElement.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/BookElement.java @@ -1,10 +1,10 @@ -package slimeknights.mantle.client.gui.book.element; +package slimeknights.mantle.client.screen.book.element; import com.google.common.collect.Lists; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.AbstractGui; +import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.util.ITooltipFlag; @@ -14,19 +14,17 @@ import net.minecraft.util.text.TextFormatting; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.client.config.GuiUtils; +import slimeknights.mantle.client.screen.book.BookScreen; import java.util.List; -import slimeknights.mantle.client.gui.book.GuiBook; - @OnlyIn(Dist.CLIENT) -public abstract class BookElement extends AbstractGui -{ +public abstract class BookElement extends AbstractGui { - public GuiBook parent; + public BookScreen parent; protected Minecraft mc = Minecraft.getInstance(); - protected TextureManager renderEngine = mc.textureManager; + protected TextureManager renderEngine = this.mc.textureManager; public int x, y; @@ -57,37 +55,38 @@ public abstract class BookElement extends AbstractGui } public void renderToolTip(FontRenderer fontRenderer, ItemStack stack, int x, int y) { - if(stack != null) { - List list = stack.getTooltip(mc.player, mc.gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL); - List list1 = Lists.newArrayList(); + if (stack != null) { + List list = stack.getTooltip(this.mc.player, this.mc.gameSettings.advancedItemTooltips ? ITooltipFlag.TooltipFlags.ADVANCED : ITooltipFlag.TooltipFlags.NORMAL); + List list1 = Lists.newArrayList(); - for(int i = 0; i < list.size(); ++i) { - if(i == 0) { + for (int i = 0; i < list.size(); ++i) { + if (i == 0) { list1.set(i, stack.getRarity().color + list.get(i).deepCopy().getFormattedText()); - } else { + } + else { list1.set(i, TextFormatting.GRAY + list.get(i).deepCopy().getFormattedText()); } } - + FontRenderer font = stack.getItem().getFontRenderer(stack); - if(font == null) { + if (font == null) { font = fontRenderer; } - GuiUtils.drawHoveringText(list1, x, y, GuiBook.PAGE_WIDTH, GuiBook.PAGE_HEIGHT, -1, font); + GuiUtils.drawHoveringText(list1, x, y, BookScreen.PAGE_WIDTH, BookScreen.PAGE_HEIGHT, -1, font); RenderHelper.disableStandardItemLighting(); } } @Deprecated public void drawHoveringText(List textLines, int x, int y, FontRenderer font) { - if(!textLines.isEmpty()) { + if (!textLines.isEmpty()) { GlStateManager.disableDepthTest(); int i = 0; - for(String s : textLines) { + for (String s : textLines) { int j = font.getStringWidth(s); - if(j > i) { + if (j > i) { i = j; } } @@ -96,16 +95,16 @@ public abstract class BookElement extends AbstractGui int i2 = y - 12; int k = 8; - if(textLines.size() > 1) { + if (textLines.size() > 1) { k += 2 + (textLines.size() - 1) * 10; } - if(l1 + i > GuiBook.PAGE_WIDTH) { + if (l1 + i > BookScreen.PAGE_WIDTH) { l1 -= 28 + i; } - if(i2 + k + 6 > GuiBook.PAGE_HEIGHT) { - i2 = GuiBook.PAGE_HEIGHT - k - 6; + if (i2 + k + 6 > BookScreen.PAGE_HEIGHT) { + i2 = BookScreen.PAGE_HEIGHT - k - 6; } int l = -267386864; @@ -121,11 +120,11 @@ public abstract class BookElement extends AbstractGui this.fillGradient(l1 - 3, i2 - 3, l1 + i + 3, i2 - 3 + 1, i1, i1); this.fillGradient(l1 - 3, i2 + k + 2, l1 + i + 3, i2 + k + 3, j1, j1); - for(int k1 = 0; k1 < textLines.size(); ++k1) { + for (int k1 = 0; k1 < textLines.size(); ++k1) { String s1 = textLines.get(k1); font.drawStringWithShadow(s1, (float) l1, (float) i2, -1); - if(k1 == 0) { + if (k1 == 0) { i2 += 2; } diff --git a/src/main/java/slimeknights/mantle/client/screen/book/element/ElementAnimationToggle.java b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementAnimationToggle.java new file mode 100644 index 0000000..9acdb73 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementAnimationToggle.java @@ -0,0 +1,32 @@ +package slimeknights.mantle.client.screen.book.element; + +import slimeknights.mantle.client.screen.book.ArrowButton; + +public class ElementAnimationToggle extends ElementArrow { + + private final int arrowColorActive; + private final int arrowColorInactive; + private boolean toggled = false; + + public ElementAnimationToggle(int x, int y, ArrowButton.ArrowType arrowType, int arrowColor, int arrowColorHover, int arrowColorActive, ElementStructure elementStructure) { + super(x, y, arrowType, arrowColor, arrowColorHover, (p_212998_1_) -> { + elementStructure.canTick = !elementStructure.canTick; + }); + + this.arrowColorInactive = arrowColor; + this.arrowColorActive = arrowColorActive; + } + + @Override + public void mouseClicked(double mouseX, double mouseY, int mouseButton) { + if (this.button != null && this.isHovered(mouseX, mouseY)) { + this.button.onPress(); + this.toggled = !this.toggled; + this.updateColor(); + } + } + + protected void updateColor() { + this.button.color = this.toggled ? this.arrowColorActive : this.arrowColorInactive; + } +} diff --git a/src/main/java/slimeknights/mantle/client/screen/book/element/ElementArrow.java b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementArrow.java new file mode 100644 index 0000000..170a19f --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementArrow.java @@ -0,0 +1,29 @@ +package slimeknights.mantle.client.screen.book.element; + +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.widget.button.Button.IPressable; +import slimeknights.mantle.client.screen.book.ArrowButton; + +public class ElementArrow extends ElementButton { + + protected final ArrowButton button; + + public ElementArrow(int x, int y, ArrowButton.ArrowType arrowType, int arrowColor, int arrowColorHover, IPressable iPressable) { + super(x, y, arrowType.w, arrowType.h); + + this.button = new ArrowButton(x, y, arrowType, arrowColor, arrowColorHover, iPressable); + } + + @Override + public void draw(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { + this.button.render(mouseX, mouseY, partialTicks); + } + + @Override + public void mouseClicked(double mouseX, double mouseY, int mouseButton) { + if (this.button != null && this.isHovered(mouseX, mouseY)) { + this.button.onPress(); + } + } + +} diff --git a/src/main/java/slimeknights/mantle/client/screen/book/element/ElementButton.java b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementButton.java new file mode 100644 index 0000000..71b6ac0 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementButton.java @@ -0,0 +1,8 @@ +package slimeknights.mantle.client.screen.book.element; + +public abstract class ElementButton extends SizedBookElement { + + public ElementButton(int x, int y, int width, int height) { + super(x, y, width, height); + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementImage.java b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementImage.java similarity index 89% rename from src/main/java/slimeknights/mantle/client/gui/book/element/ElementImage.java rename to src/main/java/slimeknights/mantle/client/screen/book/element/ElementImage.java index 0645c6a..808e534 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementImage.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementImage.java @@ -1,11 +1,10 @@ -package slimeknights.mantle.client.gui.book.element; +package slimeknights.mantle.client.screen.book.element; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.RenderHelper; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; - import slimeknights.mantle.client.book.data.element.ImageData; @OnlyIn(Dist.CLIENT) @@ -31,19 +30,19 @@ public class ElementImage extends SizedBookElement { this.image = image; - if(image.x != -1) { + if (image.x != -1) { x = image.x; } - if(image.y != -1) { + if (image.y != -1) { y = image.y; } - if(image.width != -1) { + if (image.width != -1) { width = image.width; } - if(image.height != -1) { + if (image.height != -1) { height = image.height; } - if(image.colorMultiplier != 0xFFFFFF) { + if (image.colorMultiplier != 0xFFFFFF) { colorMultiplier = image.colorMultiplier; } @@ -62,11 +61,12 @@ public class ElementImage extends SizedBookElement { GlStateManager.color3f(r, g, b); - if(this.image.item == null) { + if (this.image.item == null) { this.renderEngine.bindTexture(this.image.location); blit(this.x, this.y, this.image.u, this.image.v, this.image.uw, this.image.vh, this.width, this.height, this.image.texWidth, this.image.texHeight); - } else { + } + else { GlStateManager.pushMatrix(); GlStateManager.scalef(this.width, this.height, 1F); RenderHelper.enableGUIStandardItemLighting(); diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementItem.java b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementItem.java similarity index 82% rename from src/main/java/slimeknights/mantle/client/gui/book/element/ElementItem.java rename to src/main/java/slimeknights/mantle/client/screen/book/element/ElementItem.java index e97538a..750b237 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementItem.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementItem.java @@ -1,4 +1,4 @@ -package slimeknights.mantle.client.gui.book.element; +package slimeknights.mantle.client.screen.book.element; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.block.Block; @@ -10,12 +10,11 @@ import net.minecraft.util.NonNullList; import net.minecraft.util.math.MathHelper; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; +import slimeknights.mantle.client.book.action.StringActionProcessor; import java.util.Collection; import java.util.List; -import slimeknights.mantle.client.book.action.StringActionProcessor; - @OnlyIn(Dist.CLIENT) public class ElementItem extends SizedBookElement { @@ -39,7 +38,7 @@ public class ElementItem extends SizedBookElement { } public ElementItem(int x, int y, float scale, ItemStack item) { - this(x, y, scale, new ItemStack[]{item}); + this(x, y, scale, new ItemStack[] { item }); } public ElementItem(int x, int y, float scale, Collection itemCycle) { @@ -58,9 +57,9 @@ public class ElementItem extends SizedBookElement { super(x, y, MathHelper.floor(ITEM_SIZE_HARDCODED * scale), MathHelper.floor(ITEM_SIZE_HARDCODED * scale)); NonNullList nonNullStacks = NonNullList.withSize(itemCycle.length, ItemStack.EMPTY); - for(int i = 0; i < itemCycle.length; i++) { - if(!itemCycle[i].isEmpty()) { - nonNullStacks.set(i, itemCycle[i].copy()); + for (int i = 0; i < itemCycle.length; i++) { + if (!itemCycle[i].isEmpty()) { + nonNullStacks.set(i, itemCycle[i].copy()); } } @@ -73,11 +72,11 @@ public class ElementItem extends SizedBookElement { public void draw(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { this.renderTick++; - if(this.renderTick > ITEM_SWITCH_TICKS) { + if (this.renderTick > ITEM_SWITCH_TICKS) { this.renderTick = 0; this.currentItem++; - if(this.currentItem >= this.itemCycle.size()) { + if (this.currentItem >= this.itemCycle.size()) { this.currentItem = 0; } } @@ -87,7 +86,7 @@ public class ElementItem extends SizedBookElement { GlStateManager.translatef(this.x, this.y, 0); GlStateManager.scalef(this.scale, this.scale, 1.0F); - if(this.currentItem < this.itemCycle.size()) { + if (this.currentItem < this.itemCycle.size()) { this.mc.getItemRenderer().renderItemAndEffectIntoGUI(this.itemCycle.get(this.currentItem), 0, 0); } @@ -97,8 +96,8 @@ public class ElementItem extends SizedBookElement { @Override public void drawOverlay(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { - if(this.isHovered(mouseX, mouseY) && this.currentItem < this.itemCycle.size()) { - if(this.tooltip != null) { + if (this.isHovered(mouseX, mouseY) && this.currentItem < this.itemCycle.size()) { + if (this.tooltip != null) { this.drawHoveringText(this.tooltip, mouseX, mouseY, fontRenderer); } else { @@ -109,10 +108,11 @@ public class ElementItem extends SizedBookElement { @Override public void mouseClicked(double mouseX, double mouseY, int mouseButton) { - if(mouseButton == 0 && this.isHovered(mouseX, mouseY) && this.currentItem < this.itemCycle.size()) { - if(this.action != null) { + if (mouseButton == 0 && this.isHovered(mouseX, mouseY) && this.currentItem < this.itemCycle.size()) { + if (this.action != null) { StringActionProcessor.process(this.action, this.parent); - } else { + } + else { this.parent.itemClicked(this.itemCycle.get(this.currentItem)); } } diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementSection.java b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementSection.java similarity index 76% rename from src/main/java/slimeknights/mantle/client/gui/book/element/ElementSection.java rename to src/main/java/slimeknights/mantle/client/screen/book/element/ElementSection.java index 1c5096a..db4a02a 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementSection.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementSection.java @@ -1,97 +1,98 @@ -package slimeknights.mantle.client.gui.book.element; - -import com.mojang.blaze3d.platform.GlStateManager; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.util.text.TextFormatting; -import slimeknights.mantle.client.book.data.SectionData; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class ElementSection extends SizedBookElement { - - public static final int IMG_SIZE = 32; - - public static final int WIDTH = 42; - public static final int HEIGHT = 42; - - private SectionData section; - - public ElementSection(int x, int y, SectionData section) { - super(x, y, WIDTH, HEIGHT); - - this.section = section; - } - - @Override - public void draw(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { - boolean unlocked = this.section.isUnlocked(this.parent.advancementCache); - boolean hover = this.isHovered(mouseX, mouseY); - - if(this.section.icon != null) { - int iconX = this.x + WIDTH / 2 - IMG_SIZE / 2; - int iconY = this.y + HEIGHT / 2 - IMG_SIZE / 2; - if(hover) { - fill(iconX, iconY, iconX + IMG_SIZE, iconY + IMG_SIZE, this.parent.book.appearance.hoverColor); - } - if(unlocked) { - GlStateManager.color4f(1F, 1F, 1F, hover ? 1F : 0.5F); - } else { - float r = ((this.parent.book.appearance.lockedSectionColor >> 16) & 0xff) / 255.F; - float g = ((this.parent.book.appearance.lockedSectionColor >> 8) & 0xff) / 255.F; - float b = (this.parent.book.appearance.lockedSectionColor & 0xff) / 255.F; - GlStateManager.color4f(r, g, b, 0.75F); - } - - if(this.section.icon.item == null) { - if(this.section.icon.location != null) { - this.renderEngine.bindTexture(this.section.icon.location); - - blit(iconX, iconY, this.section.icon.u, this.section.icon.v, this.section.icon.uw, this.section.icon.vh, IMG_SIZE, IMG_SIZE, this.section.icon.texWidth, this.section.icon.texHeight); - } - } else { - GlStateManager.pushMatrix(); - GlStateManager.translatef(iconX, iconY, 0); - GlStateManager.scalef(2F, 2F, 1F); - RenderHelper.enableGUIStandardItemLighting(); - this.mc.getItemRenderer().renderItemAndEffectIntoGUI(this.section.icon.item.getItems().get(0), 0, 0); - RenderHelper.disableStandardItemLighting(); - GlStateManager.popMatrix(); - } - } - - if(this.section.parent.appearance.drawSectionListText) { - int textW = fontRenderer.getStringWidth(this.section.getTitle()); - int textX = this.x + WIDTH / 2 - textW / 2; - int textY = this.y + HEIGHT - fontRenderer.FONT_HEIGHT/2; - fontRenderer.drawString(this.section.getTitle(), - textX, - textY, - hover ? 0xFF000000 : 0x7F000000); - } - } - - @Override - public void drawOverlay(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { - if(this.section != null && this.isHovered(mouseX, mouseY)) { - List text = new ArrayList<>(); - text.add(this.section.getTitle()); - if(!this.section.isUnlocked(this.parent.advancementCache)) { - text.add(TextFormatting.RED + "Locked"); - text.add("Requirements:"); - - text.addAll(this.section.requirements); - } - this.drawHoveringText(text, mouseX, mouseY, fontRenderer); - } - } - - @Override - public void mouseClicked(double mouseX, double mouseY, int mouseButton) { - if(mouseButton == 0 && this.section != null && this.section.isUnlocked(this.parent.advancementCache) && this.isHovered(mouseX, mouseY)) { - this.parent.openPage(this.parent.book.getFirstPageNumber(this.section, this.parent.advancementCache)); - } - } -} +package slimeknights.mantle.client.screen.book.element; + +import com.mojang.blaze3d.platform.GlStateManager; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.util.text.TextFormatting; +import slimeknights.mantle.client.book.data.SectionData; + +import java.util.ArrayList; +import java.util.List; + +public class ElementSection extends SizedBookElement { + + public static final int IMG_SIZE = 32; + + public static final int WIDTH = 42; + public static final int HEIGHT = 42; + + private SectionData section; + + public ElementSection(int x, int y, SectionData section) { + super(x, y, WIDTH, HEIGHT); + + this.section = section; + } + + @Override + public void draw(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { + boolean unlocked = this.section.isUnlocked(this.parent.advancementCache); + boolean hover = this.isHovered(mouseX, mouseY); + + if (this.section.icon != null) { + int iconX = this.x + WIDTH / 2 - IMG_SIZE / 2; + int iconY = this.y + HEIGHT / 2 - IMG_SIZE / 2; + if (hover) { + fill(iconX, iconY, iconX + IMG_SIZE, iconY + IMG_SIZE, this.parent.book.appearance.hoverColor); + } + if (unlocked) { + GlStateManager.color4f(1F, 1F, 1F, hover ? 1F : 0.5F); + } + else { + float r = ((this.parent.book.appearance.lockedSectionColor >> 16) & 0xff) / 255.F; + float g = ((this.parent.book.appearance.lockedSectionColor >> 8) & 0xff) / 255.F; + float b = (this.parent.book.appearance.lockedSectionColor & 0xff) / 255.F; + GlStateManager.color4f(r, g, b, 0.75F); + } + + if (this.section.icon.item == null) { + if (this.section.icon.location != null) { + this.renderEngine.bindTexture(this.section.icon.location); + + blit(iconX, iconY, this.section.icon.u, this.section.icon.v, this.section.icon.uw, this.section.icon.vh, IMG_SIZE, IMG_SIZE, this.section.icon.texWidth, this.section.icon.texHeight); + } + } + else { + GlStateManager.pushMatrix(); + GlStateManager.translatef(iconX, iconY, 0); + GlStateManager.scalef(2F, 2F, 1F); + RenderHelper.enableGUIStandardItemLighting(); + this.mc.getItemRenderer().renderItemAndEffectIntoGUI(this.section.icon.item.getItems().get(0), 0, 0); + RenderHelper.disableStandardItemLighting(); + GlStateManager.popMatrix(); + } + } + + if (this.section.parent.appearance.drawSectionListText) { + int textW = fontRenderer.getStringWidth(this.section.getTitle()); + int textX = this.x + WIDTH / 2 - textW / 2; + int textY = this.y + HEIGHT - fontRenderer.FONT_HEIGHT / 2; + fontRenderer.drawString(this.section.getTitle(), + textX, + textY, + hover ? 0xFF000000 : 0x7F000000); + } + } + + @Override + public void drawOverlay(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { + if (this.section != null && this.isHovered(mouseX, mouseY)) { + List text = new ArrayList<>(); + text.add(this.section.getTitle()); + if (!this.section.isUnlocked(this.parent.advancementCache)) { + text.add(TextFormatting.RED + "Locked"); + text.add("Requirements:"); + + text.addAll(this.section.requirements); + } + this.drawHoveringText(text, mouseX, mouseY, fontRenderer); + } + } + + @Override + public void mouseClicked(double mouseX, double mouseY, int mouseButton) { + if (mouseButton == 0 && this.section != null && this.section.isUnlocked(this.parent.advancementCache) && this.isHovered(mouseX, mouseY)) { + this.parent.openPage(this.parent.book.getFirstPageNumber(this.section, this.parent.advancementCache)); + } + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementStructure.java b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementStructure.java similarity index 86% rename from src/main/java/slimeknights/mantle/client/gui/book/element/ElementStructure.java rename to src/main/java/slimeknights/mantle/client/screen/book/element/ElementStructure.java index 8cac5a1..fc97c0e 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementStructure.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementStructure.java @@ -1,33 +1,27 @@ -package slimeknights.mantle.client.gui.book.element; +package slimeknights.mantle.client.screen.book.element; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.block.BlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.BlockRendererDispatcher; +import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.texture.AtlasTexture; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; - import org.lwjgl.opengl.GL11; +import slimeknights.mantle.client.book.StructureBlockAccess; +import slimeknights.mantle.client.book.StructureInfo; +import slimeknights.mantle.client.book.data.element.BlockData; +import slimeknights.mantle.client.screen.book.BookScreen; import java.util.Random; import java.util.stream.IntStream; -import slimeknights.mantle.client.book.StructureBlockAccess; -import slimeknights.mantle.client.book.StructureInfo; -import slimeknights.mantle.client.book.data.element.BlockData; -import slimeknights.mantle.client.gui.book.GuiBook; - -public class ElementStructure extends SizedBookElement implements IButtonClickHandler { - - public static final int BUTTON_ID_LAYER_UP = 0; - public static final int BUTTON_ID_LAYER_DOWN = 1; - public static final int BUTTON_ID_ANIMATE = 2; +public class ElementStructure extends SizedBookElement { private float scale = 50.0F; private float xTranslate = 0F; @@ -38,11 +32,12 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa public ElementStructure(int x, int y, int width, int height, int[] size, BlockData[] structure) { super(x, y, width, height); - if(size.length == 3) { - this.scale = 100f / (float)IntStream.of(size).max().getAsInt(); - float sx = (float)width / (float)GuiBook.PAGE_WIDTH; - float sy = (float)height / (float)GuiBook.PAGE_HEIGHT; + if (size.length == 3) { + this.scale = 100f / (float) IntStream.of(size).max().getAsInt(); + + float sx = (float) width / (float) BookScreen.PAGE_WIDTH; + float sy = (float) height / (float) BookScreen.PAGE_HEIGHT; this.scale *= Math.min(sx, sy); @@ -52,6 +47,7 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa this.w = size[0] * this.scale; this.h = size[1] * this.scale; } + this.init(size, structure); } @@ -138,7 +134,7 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa componentTooltip.add(s); } }*/ -// super.initPage(gui, x, y+yOff, pageButtons); + // super.initPage(gui, x, y+yOff, pageButtons); } int[] lastClick = null; @@ -146,8 +142,8 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa @Override public void draw(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { - if(this.lastClick != null) { - if(Minecraft.getInstance().mouseHelper.isLeftDown() || Minecraft.getInstance().mouseHelper.isRightDown()) { + if (this.lastClick != null) { + if (Minecraft.getInstance().mouseHelper.isLeftDown() || Minecraft.getInstance().mouseHelper.isRightDown()) { int dx = mouseX - this.lastClick[0]; int dy = mouseY - this.lastClick[1]; float maxSpeed = 10f; @@ -162,9 +158,9 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa } } - if(this.canTick) { - if(++this.tick % 20 == 0) { - if(this.structureData.canStep() || ++this.fullStructureSteps >= 5) { + if (this.canTick) { + if (++this.tick % 20 == 0) { + if (this.structureData.canStep() || ++this.fullStructureSteps >= 5) { this.structureData.step(); this.fullStructureSteps = 0; } @@ -203,28 +199,28 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa GlStateManager.rotatef(this.rotX, 1, 0, 0); GlStateManager.rotatef(this.rotY, 0, 1, 0); - GlStateManager.translatef((float)structureLength/-2f, (float)structureHeight/-2f, (float)structureWidth/-2f); + GlStateManager.translatef((float) structureLength / -2f, (float) structureHeight / -2f, (float) structureWidth / -2f); GlStateManager.disableLighting(); - if(Minecraft.isAmbientOcclusionEnabled()) { + if (Minecraft.isAmbientOcclusionEnabled()) { GlStateManager.shadeModel(GL11.GL_SMOOTH); } else { GlStateManager.shadeModel(GL11.GL_FLAT); } - if(structureWidth % 2 == 1) { + if (structureWidth % 2 == 1) { //GlStateManager.translate(-.5f, 0, 0); } int iterator = 0; this.mc.getTextureManager().bindTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE); - for(int h = 0; h < this.structureData.structureHeight; h++) { - for(int l = 0; l < this.structureData.structureLength; l++) { - for(int w = 0; w < this.structureData.structureWidth; w++) { + for (int h = 0; h < this.structureData.structureHeight; h++) { + for (int l = 0; l < this.structureData.structureLength; l++) { + for (int w = 0; w < this.structureData.structureWidth; w++) { BlockPos pos = new BlockPos(l, h, w); - if(!this.blockAccess.isAirBlock(pos)) { + if (!this.blockAccess.isAirBlock(pos)) { BlockState state = this.blockAccess.getBlockState(pos); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder buffer = tessellator.getBuffer(); @@ -268,7 +264,7 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa //lastX = mouseX; //lastY = mouseY; - this.lastClick = new int[] {(int) mouseX, (int) mouseY}; + this.lastClick = new int[] { (int) mouseX, (int) mouseY }; } @Override @@ -277,8 +273,8 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa int dy = (int) mouseX - this.lastY; float maxSpeed = 1f; - float changeX = Math.min(maxSpeed, dx/100f); - float changeY = Math.min(maxSpeed, dy/100f); + float changeX = Math.min(maxSpeed, dx / 100f); + float changeY = Math.min(maxSpeed, dy / 100f); //rotX += changeX; //rotY += changeX; @@ -299,8 +295,8 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa @Override public void mouseDragged(int clickX, int clickY, int mx, int my, int lastX, int lastY, int button) { //if((clickX >= 40 && clickX < 144 && mx >= 20 && mx < 164) && (clickY >= 30 && clickY < 130 && my >= 30 && my < 180)) { - int dx = mx - lastX; - int dy = my - lastY; + int dx = mx - lastX; + int dy = my - lastY; this.rotY = this.rotY + (dx / 104f);// * 80; this.rotX = this.rotX + (dy / 100f);// * 80; //} @@ -333,14 +329,4 @@ public class ElementStructure extends SizedBookElement implements IButtonClickHa public void changeActiveLayer(int direction) { } - - @Override - public boolean onButtonClick(int buttonId, ElementButton button) { - switch(buttonId) { - case BUTTON_ID_ANIMATE: - this.canTick = !this.canTick; - return true; - } - return false; - } } diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementText.java b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementText.java similarity index 89% rename from src/main/java/slimeknights/mantle/client/gui/book/element/ElementText.java rename to src/main/java/slimeknights/mantle/client/screen/book/element/ElementText.java index 6608e4f..0c4443e 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/ElementText.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/ElementText.java @@ -1,19 +1,19 @@ -package slimeknights.mantle.client.gui.book.element; +package slimeknights.mantle.client.screen.book.element; import net.minecraft.client.gui.FontRenderer; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import slimeknights.mantle.client.book.action.StringActionProcessor; +import slimeknights.mantle.client.book.data.element.TextData; +import slimeknights.mantle.client.screen.book.TextDataRenderer; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import slimeknights.mantle.client.book.action.StringActionProcessor; -import slimeknights.mantle.client.book.data.element.TextData; -import slimeknights.mantle.client.gui.book.TextDataRenderer; - @OnlyIn(Dist.CLIENT) public class ElementText extends SizedBookElement { + public TextData[] text; private List tooltip = new ArrayList(); @@ -37,7 +37,7 @@ public class ElementText extends SizedBookElement { public void draw(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { String action = TextDataRenderer.drawText(this.x, this.y, this.width, this.height, this.text, mouseX, mouseY, fontRenderer, this.tooltip); - if(this.doAction) { + if (this.doAction) { this.doAction = false; StringActionProcessor.process(action, this.parent); } @@ -45,7 +45,7 @@ public class ElementText extends SizedBookElement { @Override public void drawOverlay(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer) { - if(this.tooltip.size() > 0){ + if (this.tooltip.size() > 0) { TextDataRenderer.drawTooltip(this.tooltip, mouseX, mouseY, fontRenderer); this.tooltip.clear(); } @@ -53,7 +53,7 @@ public class ElementText extends SizedBookElement { @Override public void mouseClicked(double mouseX, double mouseY, int mouseButton) { - if(mouseButton == 0) { + if (mouseButton == 0) { this.doAction = true; } } diff --git a/src/main/java/slimeknights/mantle/client/gui/book/element/SizedBookElement.java b/src/main/java/slimeknights/mantle/client/screen/book/element/SizedBookElement.java similarity index 90% rename from src/main/java/slimeknights/mantle/client/gui/book/element/SizedBookElement.java rename to src/main/java/slimeknights/mantle/client/screen/book/element/SizedBookElement.java index b676a20..c9292c5 100644 --- a/src/main/java/slimeknights/mantle/client/gui/book/element/SizedBookElement.java +++ b/src/main/java/slimeknights/mantle/client/screen/book/element/SizedBookElement.java @@ -1,4 +1,4 @@ -package slimeknights.mantle.client.gui.book.element; +package slimeknights.mantle.client.screen.book.element; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; diff --git a/src/main/java/slimeknights/mantle/common/CommonProxy.java b/src/main/java/slimeknights/mantle/common/CommonProxy.java deleted file mode 100644 index de915fa..0000000 --- a/src/main/java/slimeknights/mantle/common/CommonProxy.java +++ /dev/null @@ -1,10 +0,0 @@ -package slimeknights.mantle.common; - -public class CommonProxy { - public void preInit() { - } - - public void init() {} - - public void postInit() {} -} diff --git a/src/main/java/slimeknights/mantle/common/GuiHandler.java b/src/main/java/slimeknights/mantle/common/GuiHandler.java deleted file mode 100644 index 810b13d..0000000 --- a/src/main/java/slimeknights/mantle/common/GuiHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -package slimeknights.mantle.common; - -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.fml.common.network.IGuiHandler; - -/** - * A GuiHandler implementation that forwards the container/gui creation to the TEs, eliminating the need for GUI IDs. - */ -public class GuiHandler implements IGuiHandler { - - @Override - public Object getServerGuiElement(int ID, PlayerEntity player, World world, int x, int y, int z) { - TileEntity te = world.getTileEntity(new BlockPos(x, y, z)); - if(te instanceof IInventoryGui) { - return ((IInventoryGui) te).createContainer(player.inventory, world, new BlockPos(x, y, z)); - } - return null; - } - - @Override - public Object getClientGuiElement(int ID, PlayerEntity player, World world, int x, int y, int z) { - TileEntity te = world.getTileEntity(new BlockPos(x, y, z)); - if(te instanceof IInventoryGui) { - return ((IInventoryGui) te).createGui(player.inventory, world, new BlockPos(x, y, z)); - } - return null; - } -} diff --git a/src/main/java/slimeknights/mantle/common/IInventoryGui.java b/src/main/java/slimeknights/mantle/common/IInventoryGui.java deleted file mode 100644 index cb166f0..0000000 --- a/src/main/java/slimeknights/mantle/common/IInventoryGui.java +++ /dev/null @@ -1,20 +0,0 @@ -package slimeknights.mantle.common; - -import net.minecraft.client.gui.screen.inventory.ContainerScreen; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.container.Container; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -/** - * Used in conjunction with GuiHandler. Implement in a TE to have it open its GUI/Container. - */ -public interface IInventoryGui { - - Container createContainer(PlayerInventory inventoryplayer, World world, BlockPos pos); - - @OnlyIn(Dist.CLIENT) - ContainerScreen createGui(PlayerInventory inventoryplayer, World world, BlockPos pos); -} diff --git a/src/main/java/slimeknights/mantle/common/IRegisterUtil.java b/src/main/java/slimeknights/mantle/common/IRegisterUtil.java index 067f433..0b48c48 100644 --- a/src/main/java/slimeknights/mantle/common/IRegisterUtil.java +++ b/src/main/java/slimeknights/mantle/common/IRegisterUtil.java @@ -34,7 +34,7 @@ public interface IRegisterUtil { * @return Resource location in this mod */ default ResourceLocation getResource(String name) { - return new ResourceLocation(getModId(), name); + return new ResourceLocation(this.getModId(), name); } /** @@ -48,7 +48,7 @@ public interface IRegisterUtil { * @return Thing that was registered */ default > I register(IForgeRegistry registry, I thing, String name) { - return register(registry, thing, getResource(name)); + return this.register(registry, thing, this.getResource(name)); } /** @@ -79,7 +79,7 @@ public interface IRegisterUtil { */ default BlockItem registerItemBlock(IForgeRegistry registry, Block block) { BlockItem itemBlock = new BlockItem(block, new Item.Properties()); - return register(registry, itemBlock, block.getRegistryName()); + return this.register(registry, itemBlock, block.getRegistryName()); } /** @@ -92,7 +92,7 @@ public interface IRegisterUtil { */ default BlockItem registerItemBlock(IForgeRegistry registry, Block block, ItemGroup group) { BlockItem itemBlock = new BlockItem(block, new Item.Properties().group(group)); - return register(registry, itemBlock, block.getRegistryName()); + return this.register(registry, itemBlock, block.getRegistryName()); } /** @@ -103,7 +103,7 @@ public interface IRegisterUtil { * @return Registered item block */ default T registerItemBlock(IForgeRegistry registry, T itemBlock) { - return register(registry, itemBlock, itemBlock.getBlock().getRegistryName()); + return this.register(registry, itemBlock, itemBlock.getBlock().getRegistryName()); } /** @@ -115,10 +115,9 @@ public interface IRegisterUtil { */ default TileEntityType registerTE(IForgeRegistry> registry, Supplier constructor, String name) { TileEntityType type = TileEntityType.Builder.create(constructor).build(null); - return register(registry, type, name); + return this.register(registry, type, name); } - /* List methods */ /** @@ -132,9 +131,9 @@ public interface IRegisterUtil { * @param Block type * @return List of blocks registered */ - default List registerBlocks(IForgeRegistry registry, Function constructor, IStringSerializable[] variants, Block.Properties props, String baseName) { + default List registerBlocks(IForgeRegistry registry, Function constructor, IStringSerializable[] variants, Block.Properties props, String baseName) { return Arrays.stream(variants).map((s) -> { - return register(registry, constructor.apply(props), baseName + "_" + s.getName()); + return this.register(registry, constructor.apply(props), baseName + "_" + s.getName()); }).collect(Collectors.toList()); } @@ -147,7 +146,7 @@ public interface IRegisterUtil { */ default List registerItemBlocks(IForgeRegistry registry, List blocks) { return blocks.stream().map((block) -> { - return registerItemBlock(registry, block); + return this.registerItemBlock(registry, block); }).collect(Collectors.toList()); } @@ -161,7 +160,7 @@ public interface IRegisterUtil { */ default List registerItemBlocks(IForgeRegistry registry, List blocks, ItemGroup group) { return blocks.stream().map((block) -> { - return registerItemBlock(registry, block, group); + return this.registerItemBlock(registry, block, group); }).collect(Collectors.toList()); } @@ -173,9 +172,9 @@ public interface IRegisterUtil { * @param constructor ItemBlock constructor * @return Registered item block */ - default List registerItemBlocks(IForgeRegistry registry, List blocks, Function constructor) { + default List registerItemBlocks(IForgeRegistry registry, List blocks, Function constructor) { return blocks.stream().map((block) -> { - return registerItemBlock(registry, constructor.apply(block)); + return this.registerItemBlock(registry, constructor.apply(block)); }).collect(Collectors.toList()); } } diff --git a/src/main/java/slimeknights/mantle/common/ServerProxy.java b/src/main/java/slimeknights/mantle/common/ServerProxy.java new file mode 100644 index 0000000..63dc2c0 --- /dev/null +++ b/src/main/java/slimeknights/mantle/common/ServerProxy.java @@ -0,0 +1,10 @@ +package slimeknights.mantle.common; + +public class ServerProxy { + + public void preInit() {} + + public void init() {} + + public void postInit() {} +} diff --git a/src/main/java/slimeknights/mantle/config/AbstractConfig.java b/src/main/java/slimeknights/mantle/config/AbstractConfig.java index 43ecae3..ee3fd2b 100644 --- a/src/main/java/slimeknights/mantle/config/AbstractConfig.java +++ b/src/main/java/slimeknights/mantle/config/AbstractConfig.java @@ -1,8 +1,8 @@ package slimeknights.mantle.config; import com.google.common.reflect.TypeToken; - -import net.minecraftforge.common.MinecraftForge; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; import java.io.IOException; import java.util.ArrayList; @@ -10,16 +10,13 @@ import java.util.Iterator; import java.util.List; import java.util.function.Function; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; - public abstract class AbstractConfig { List configFileList = new ArrayList<>(); private List> configFiles = new ArrayList<>(); public void save() { - configFiles.forEach(function -> function.apply(null)); + this.configFiles.forEach(function -> function.apply(null)); } public T load(T configFile, Class clazz) { @@ -32,28 +29,30 @@ public abstract class AbstractConfig { val.insertDefaults(); val.setConfigVersion(); - configFileList.add(val); + this.configFileList.add(val); // note: this is a workaround for generics because the generic info has to match the same class - configFiles.add(configFile1 -> { + this.configFiles.add(configFile1 -> { this.save(val, clazz); return true; }); return val; - } catch(IOException | ObjectMappingException e) { + } + catch (IOException | ObjectMappingException e) { e.printStackTrace(); } return configFile; } public void save(T configFile, Class clazz) { - if(configFile.needsSaving()) { + if (configFile.needsSaving()) { try { CommentedConfigurationNode node = configFile.load(); node.setValue(TypeToken.of(clazz), configFile); configFile.save(node); - } catch(IOException | ObjectMappingException e) { + } + catch (IOException | ObjectMappingException e) { e.printStackTrace(); } } @@ -67,18 +66,18 @@ public abstract class AbstractConfig { public static boolean syncConfig(AbstractConfig config, List files) { boolean changed = false; - if(config.configFileList.size() != files.size()) { + if (config.configFileList.size() != files.size()) { return false; } Iterator iterLocal = config.configFileList.iterator(); Iterator iterRemote = files.iterator(); - while(iterLocal.hasNext() && iterRemote.hasNext()) { + while (iterLocal.hasNext() && iterRemote.hasNext()) { changed |= iterLocal.next().sync(iterRemote.next()); } - if(changed) { + if (changed) { config.save(); } return changed; diff --git a/src/main/java/slimeknights/mantle/config/AbstractConfigFile.java b/src/main/java/slimeknights/mantle/config/AbstractConfigFile.java index e29a63d..008b965 100644 --- a/src/main/java/slimeknights/mantle/config/AbstractConfigFile.java +++ b/src/main/java/slimeknights/mantle/config/AbstractConfigFile.java @@ -1,14 +1,23 @@ package slimeknights.mantle.config; import com.google.common.reflect.TypeToken; - import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; - import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.IForgeRegistry; import net.minecraftforge.registries.IForgeRegistryEntry; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.ConfigurationOptions; +import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import ninja.leaping.configurate.hocon.HoconConfigurationLoader; +import ninja.leaping.configurate.loader.AtomicFiles; +import ninja.leaping.configurate.loader.ConfigurationLoader; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import ninja.leaping.configurate.objectmapping.Setting; +import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -24,18 +33,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.ConfigurationOptions; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.hocon.HoconConfigurationLoader; -import ninja.leaping.configurate.loader.AtomicFiles; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; - public abstract class AbstractConfigFile implements Serializable { private static boolean initialized = false; @@ -51,8 +48,8 @@ public abstract class AbstractConfigFile implements Serializable { // required constructor for deserialization public AbstractConfigFile() { - file = null; - loader = null; + this.file = null; + this.loader = null; } public AbstractConfigFile(File configFolder, String name) { @@ -61,20 +58,20 @@ public abstract class AbstractConfigFile implements Serializable { public AbstractConfigFile(File configFile) { configFile.getParentFile().mkdirs(); - file = configFile; - loader = HoconConfigurationLoader.builder().setFile(file).build(); + this.file = configFile; + this.loader = HoconConfigurationLoader.builder().setFile(this.file).build(); } public CommentedConfigurationNode load() throws IOException { - return loader.load(ConfigurationOptions.defaults().setShouldCopyDefaults(true)); + return this.loader.load(ConfigurationOptions.defaults().setShouldCopyDefaults(true)); } public void save(ConfigurationNode node) throws IOException { - loader.save(node); + this.loader.save(node); } public String getName() { - return file.getName(); + return this.file.getName(); } public abstract void insertDefaults(); @@ -87,39 +84,40 @@ public abstract class AbstractConfigFile implements Serializable { protected abstract int getConfigVersion(); void setConfigVersion() { - if(configVersion != getConfigVersion()) { - configVersion = getConfigVersion(); - setNeedsSaving(); + if (this.configVersion != this.getConfigVersion()) { + this.configVersion = this.getConfigVersion(); + this.setNeedsSaving(); } } - public AbstractConfigFile loadFromPacket(byte[] packetData) { ConfigurationLoader packetDataLoader = HoconConfigurationLoader - .builder() - .setSource(() -> new BufferedReader(new InputStreamReader(new ByteArrayInputStream(packetData)))) - .setSink(AtomicFiles.createAtomicWriterFactory(file.toPath(), StandardCharsets.UTF_8)) - .build(); + .builder() + .setSource(() -> new BufferedReader(new InputStreamReader(new ByteArrayInputStream(packetData)))) + .setSink(AtomicFiles.createAtomicWriterFactory(this.file.toPath(), StandardCharsets.UTF_8)) + .build(); try { CommentedConfigurationNode node = packetDataLoader.load(ConfigurationOptions.defaults().setShouldCopyDefaults(true)); try { return node.getValue(TypeToken.of(this.getClass())); - } catch(ObjectMappingException e) { + } + catch (ObjectMappingException e) { e.printStackTrace(); } - } catch(IOException e) { + } + catch (IOException e) { e.printStackTrace(); } return null; } public static List getAllFields(List fields, Class type) { - if(type != AbstractConfigFile.class) { + if (type != AbstractConfigFile.class) { fields.addAll(Arrays.asList(type.getDeclaredFields())); - if(type.getSuperclass() != null && AbstractConfigFile.class.isAssignableFrom(type.getSuperclass())) { + if (type.getSuperclass() != null && AbstractConfigFile.class.isAssignableFrom(type.getSuperclass())) { fields = getAllFields(fields, type.getSuperclass()); } } @@ -129,42 +127,43 @@ public abstract class AbstractConfigFile implements Serializable { public byte[] getPacketData() { try { - return Files.readAllBytes(file.toPath()); - } catch(IOException e) { + return Files.readAllBytes(this.file.toPath()); + } + catch (IOException e) { e.printStackTrace(); } return null; } public boolean sync(AbstractConfigFile other) { - return sync(other, this); + return this.sync(other, this); } public boolean sync(Object other, Object that) { - if(other.getClass() != that.getClass()) { + if (other.getClass() != that.getClass()) { return false; } List fieldsToProcess = new ArrayList<>(); getAllFields(fieldsToProcess, that.getClass()); - for(Field field : fieldsToProcess) { - syncField(other, that, field); + for (Field field : fieldsToProcess) { + this.syncField(other, that, field); } - return needsSaving(); + return this.needsSaving(); } private void syncField(Object other, Object that, Field field) { try { // don't sync transient fields - if(Modifier.isTransient(field.getModifiers())) { + if (Modifier.isTransient(field.getModifiers())) { return; } - if(Modifier.isStatic(field.getModifiers())) { + if (Modifier.isStatic(field.getModifiers())) { return; } - if(!field.isAccessible()) { + if (!field.isAccessible()) { field.setAccessible(true); } @@ -172,34 +171,35 @@ public abstract class AbstractConfigFile implements Serializable { Object remote = field.get(other); // is this a subclass that contains entries itself? - if(field.getType().isAnnotationPresent(ConfigSerializable.class)) { - sync(remote, original); + if (field.getType().isAnnotationPresent(ConfigSerializable.class)) { + this.sync(remote, original); } else { - if(!original.equals(remote)) { + if (!original.equals(remote)) { field.set(that, remote); - setNeedsSaving(); + this.setNeedsSaving(); } } - } catch(IllegalAccessException e) { + } + catch (IllegalAccessException e) { e.printStackTrace(); } } public void setNeedsSaving() { - needsSaving = true; + this.needsSaving = true; } public boolean needsSaving() { - return needsSaving; + return this.needsSaving; } public void clearNeedsSaving() { - needsSaving = false; + this.needsSaving = false; } public static void init() { - if(initialized) { + if (initialized) { return; } @@ -218,7 +218,7 @@ public abstract class AbstractConfigFile implements Serializable { } }); - TypeSerializers.getDefaultSerializers().registerType(TypeToken.of(BlockMeta.class), BlockMeta.SERIALIZER); + TypeSerializers.getDefaultSerializers().registerType(TypeToken.of(BlockState.class), BlockState.SERIALIZER); initialized = true; } @@ -230,12 +230,11 @@ public abstract class AbstractConfigFile implements Serializable { @Override public T deserialize(TypeToken typeToken, ConfigurationNode configurationNode) throws ObjectMappingException { - return getRegistry().getValue(new ResourceLocation(configurationNode.getString())); + return this.getRegistry().getValue(new ResourceLocation(configurationNode.getString())); } @Override - public void serialize(TypeToken typeToken, T t, ConfigurationNode configurationNode) - throws ObjectMappingException { + public void serialize(TypeToken typeToken, T t, ConfigurationNode configurationNode) throws ObjectMappingException { configurationNode.setValue(t.getRegistryName()); } } diff --git a/src/main/java/slimeknights/mantle/config/AbstractConfigSyncPacket.java b/src/main/java/slimeknights/mantle/config/AbstractConfigSyncPacket.java index 9a3c163..ec78424 100644 --- a/src/main/java/slimeknights/mantle/config/AbstractConfigSyncPacket.java +++ b/src/main/java/slimeknights/mantle/config/AbstractConfigSyncPacket.java @@ -1,58 +1,52 @@ package slimeknights.mantle.config; -import net.minecraft.client.network.play.ClientPlayNetHandler; -import net.minecraft.network.play.ServerPlayNetHandler; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.fml.DistExecutor; +import net.minecraftforge.fml.network.NetworkEvent; +import slimeknights.mantle.network.AbstractPacket; import java.util.ArrayList; import java.util.List; - -import io.netty.buffer.ByteBuf; -import slimeknights.mantle.network.AbstractPacket; +import java.util.function.Supplier; public abstract class AbstractConfigSyncPacket extends AbstractPacket { private List config; + public AbstractConfigSyncPacket(PacketBuffer buffer) { + this.config = new ArrayList<>(); + for (AbstractConfigFile configFile : this.getConfig().configFileList) { + int length = buffer.readInt(); + byte[] data = new byte[length]; + buffer.readBytes(data); + this.config.add(configFile.loadFromPacket(data)); + } + } + public AbstractConfigSyncPacket() { } + protected boolean sync() { + return AbstractConfig.syncConfig(this.getConfig(), this.config); + } + protected abstract AbstractConfig getConfig(); @Override - public IMessage handleClient(ClientPlayNetHandler netHandler) { - sync(); - return null; - } - - @Override - public IMessage handleServer(ServerPlayNetHandler netHandler) { - // We sync from server to client, not vice versa - throw new UnsupportedOperationException("Trying to sync client configs to the server. You registered the packet for the wrong side."); - } - - protected boolean sync() { - return AbstractConfig.syncConfig(getConfig(), config); - } - - - @Override - public void fromBytes(ByteBuf buf) { - config = new ArrayList<>(); - for(AbstractConfigFile configFile : getConfig().configFileList) { - int length = buf.readInt(); - byte[] data = new byte[length]; - buf.readBytes(data); - config.add(configFile.loadFromPacket(data)); - } - } - - @Override - public void toBytes(ByteBuf buf) { - for(AbstractConfigFile configFile : getConfig().configFileList) { + public void encode(PacketBuffer buf) { + for (AbstractConfigFile configFile : this.getConfig().configFileList) { byte[] data = configFile.getPacketData(); buf.writeInt(data.length); buf.writeBytes(data); } } + + @Override + public void handle(Supplier context) { + context.get().enqueueWork(() -> DistExecutor.runForDist(() -> this::sync, () -> { + throw new UnsupportedOperationException("Trying to sync client configs to the server. You registered the packet for the wrong side."); + })); + + context.get().setPacketHandled(true); + } } diff --git a/src/main/java/slimeknights/mantle/config/BlockMeta.java b/src/main/java/slimeknights/mantle/config/BlockMeta.java deleted file mode 100644 index bfe8f5b..0000000 --- a/src/main/java/slimeknights/mantle/config/BlockMeta.java +++ /dev/null @@ -1,95 +0,0 @@ -package slimeknights.mantle.config; - -import com.google.common.reflect.TypeToken; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.util.ResourceLocation; - -import net.minecraftforge.registries.ForgeRegistries; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; - - -public class BlockMeta { - - private static final BlockMeta MISSING = new BlockMeta(Blocks.AIR, 0); - - public transient static final TypeSerializer SERIALIZER = new TypeSerializer() { - @Override - public BlockMeta deserialize(TypeToken typeToken, ConfigurationNode configurationNode) - throws ObjectMappingException { - String val = configurationNode.getString(); - String[] parts = val.split(":"); - - Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(parts[0], parts[1])); - if(block == Blocks.AIR) { - return MISSING; - } - int meta = -1; - if(parts.length > 2) { - meta = Integer.valueOf(parts[2]); - } - - return new BlockMeta(block, meta); - } - - @Override - public void serialize(TypeToken typeToken, BlockMeta blockMeta, ConfigurationNode configurationNode) - throws ObjectMappingException { - configurationNode.setValue(blockMeta.toString()); - } - }; - - public Block block; - public int metadata; - - public BlockMeta() { - } - - public BlockMeta(Block block, int metadata) { - this.block = block; - this.metadata = metadata; - } - - public static BlockMeta of(BlockState state) { - return new BlockMeta(state.getBlock(), state.getBlock().getMetaFromState(state)); - } - - - @Override - public boolean equals(Object o) { - if(this == o) { - return true; - } - if(o == null || getClass() != o.getClass()) { - return false; - } - - BlockMeta blockMeta = (BlockMeta) o; - - if(metadata != blockMeta.metadata) { - return false; - } - return block != null ? block.equals(blockMeta.block) : blockMeta.block == null; - - } - - @Override - public int hashCode() { - int result = block != null ? block.hashCode() : 0; - result = 31 * result + metadata; - return result; - } - - @Override - public String toString() { - String val = block.getRegistryName().toString(); - if(metadata > -1) { - val += ":" + metadata; - } - return val; - } -} diff --git a/src/main/java/slimeknights/mantle/config/BlockState.java b/src/main/java/slimeknights/mantle/config/BlockState.java new file mode 100644 index 0000000..d368007 --- /dev/null +++ b/src/main/java/slimeknights/mantle/config/BlockState.java @@ -0,0 +1,89 @@ +package slimeknights.mantle.config; + +import com.google.common.reflect.TypeToken; +import net.minecraft.block.Block; +import net.minecraft.block.Blocks; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.registries.ForgeRegistries; +import ninja.leaping.configurate.ConfigurationNode; +import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; + +public class BlockState { + + private static final BlockState MISSING = new BlockState(Blocks.AIR, ""); + + public transient static final TypeSerializer SERIALIZER = new TypeSerializer() { + @Override + public BlockState deserialize(TypeToken typeToken, ConfigurationNode configurationNode) throws ObjectMappingException { + String val = configurationNode.getString(); + String[] parts = val.split(":"); + + Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(parts[0], parts[1])); + if (block == Blocks.AIR) { + return MISSING; + } + String state = ""; + if (parts.length > 2) { + state = parts[2]; + } + + return new BlockState(block, state); + } + + @Override + public void serialize(TypeToken typeToken, BlockState blockMeta, ConfigurationNode configurationNode) throws ObjectMappingException { + configurationNode.setValue(blockMeta.toString()); + } + }; + + public Block block; + public String state; + + public BlockState() { + + } + + public BlockState(Block block, String state) { + this.block = block; + this.state = state; + } + + public static BlockState of(net.minecraft.block.BlockState state) { + return new BlockState(state.getBlock(), state.toString()); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || this.getClass() != o.getClass()) { + return false; + } + + BlockState blockState = (BlockState) o; + + if (!this.state.equalsIgnoreCase(blockState.state)) { + return false; + } + return this.block != null ? this.block.equals(blockState.block) : blockState.block == null; + + } + + @Override + public int hashCode() { + int result = this.block != null ? this.block.hashCode() : 0; + result = 31 * result + this.state.hashCode(); + return result; + } + + @Override + public String toString() { + String val = this.block.getRegistryName().toString(); + if (!this.state.equals("")) { + val += ":" + this.state; + } + return val; + } +} diff --git a/src/main/java/slimeknights/mantle/config/ExampleSync.java b/src/main/java/slimeknights/mantle/config/ExampleSync.java index 851cf46..cf87462 100644 --- a/src/main/java/slimeknights/mantle/config/ExampleSync.java +++ b/src/main/java/slimeknights/mantle/config/ExampleSync.java @@ -3,6 +3,7 @@ package slimeknights.mantle.config; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.network.PacketBuffer; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -13,22 +14,19 @@ import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.fml.loading.FMLPaths; +import slimeknights.mantle.network.NetworkWrapper; import java.io.File; -import slimeknights.mantle.network.NetworkWrapper; - -class ExampleSync -{ +class ExampleSync { static NetworkWrapper networkWrapper; static ExampleSync INSTANCE; - static void setup() - { + static void setup() { networkWrapper = new NetworkWrapper("mantle:example"); - networkWrapper.registerPacket(ExampleSyncPacketImpl.class, ExampleSyncPacketImpl::encode, ExampleSyncPacketImpl::decode, ExampleSyncPacketImpl.Handler::handle); + networkWrapper.registerPacket(ExampleSyncPacketImpl.class, ExampleSyncPacketImpl::encode, ExampleSyncPacketImpl::new, ExampleSyncPacketImpl::handle); INSTANCE = new ExampleSync(); } @@ -37,10 +35,8 @@ class ExampleSync @SubscribeEvent @OnlyIn(Dist.DEDICATED_SERVER) - public void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) - { - if (event.getPlayer() instanceof ServerPlayerEntity && FMLEnvironment.dist.isDedicatedServer()) - { + public void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { + if (event.getPlayer() instanceof ServerPlayerEntity && FMLEnvironment.dist.isDedicatedServer()) { ExampleSyncPacketImpl packet = new ExampleSyncPacketImpl(); networkWrapper.sendTo(packet, (ServerPlayerEntity) event.getPlayer()); } @@ -48,73 +44,69 @@ class ExampleSync @SubscribeEvent @OnlyIn(Dist.CLIENT) - public void playerJoinedWorld(TickEvent.ClientTickEvent event) - { + public void playerJoinedWorld(TickEvent.ClientTickEvent event) { ClientPlayerEntity player = Minecraft.getInstance().player; - if (needsRestart) - { + if (needsRestart) { player.sendMessage(new StringTextComponent("Configs synced with server. Configs require a restart")); } - else - { + else { player.sendMessage(new StringTextComponent("Configs synced with server.")); } MinecraftForge.EVENT_BUS.unregister(this); } - static class ExampleConfig extends AbstractConfig - { + static class ExampleConfig extends AbstractConfig { + static ExampleConfig INSTANCE = new ExampleConfig(); ExampleConfigFile exampleConfigFile; // call from preinit or something - public void onPreInit(final FMLCommonSetupEvent event) - { - exampleConfigFile = this.load(new ExampleConfigFile(FMLPaths.CONFIGDIR.get().toFile()), ExampleConfigFile.class); + public void onPreInit(final FMLCommonSetupEvent event) { + this.exampleConfigFile = this.load(new ExampleConfigFile(FMLPaths.CONFIGDIR.get().toFile()), ExampleConfigFile.class); // register this serverside to sync - if (FMLEnvironment.dist.isDedicatedServer()) - { + if (FMLEnvironment.dist.isDedicatedServer()) { MinecraftForge.EVENT_BUS.register(INSTANCE); } } } - static class ExampleConfigFile extends AbstractConfigFile - { + static class ExampleConfigFile extends AbstractConfigFile { - public ExampleConfigFile(File configFolder) - { + public ExampleConfigFile(File configFolder) { super(configFolder, "exampleconfigfile"); } @Override - public void insertDefaults() - { + public void insertDefaults() { // no default values that need to initialized dynamically } @Override - protected int getConfigVersion() - { + protected int getConfigVersion() { return 1; } } - static class ExampleSyncPacketImpl extends AbstractConfigSyncPacket - { + static class ExampleSyncPacketImpl extends AbstractConfigSyncPacket { - protected static AbstractConfig getConfig() - { + public ExampleSyncPacketImpl(PacketBuffer buffer) { + super(buffer); + } + + public ExampleSyncPacketImpl() { + super(); + } + + @Override + protected AbstractConfig getConfig() { return ExampleConfig.INSTANCE; } @Override - protected boolean sync() - { - if (super.sync()) - { + protected boolean sync() { + if (super.sync()) { // clientside register only MinecraftForge.EVENT_BUS.register(INSTANCE); return true; diff --git a/src/main/java/slimeknights/mantle/inventory/BaseContainer.java b/src/main/java/slimeknights/mantle/inventory/BaseContainer.java index 1705c6b..3f58d4d 100644 --- a/src/main/java/slimeknights/mantle/inventory/BaseContainer.java +++ b/src/main/java/slimeknights/mantle/inventory/BaseContainer.java @@ -1,35 +1,29 @@ package slimeknights.mantle.inventory; import com.google.common.collect.Lists; - import net.minecraft.block.Block; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.ServerPlayerEntity; -import net.minecraft.entity.player.PlayerInventory; import net.minecraft.block.Blocks; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.entity.player.PlayerInventory; +import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.ContainerType; import net.minecraft.inventory.container.Slot; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; -import net.minecraft.util.INameable; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.world.World; import net.minecraft.world.ServerWorld; +import net.minecraft.world.World; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.wrapper.EmptyHandler; -import net.minecraftforge.items.wrapper.InvWrapper; - -import java.util.List; +import slimeknights.mantle.util.SlimeknightException; import javax.annotation.Nonnull; - -import slimeknights.mantle.util.SlimeknightException; +import java.util.List; /** Same as Container but provides some extra functionality to simplify things */ public abstract class BaseContainer extends Container { @@ -51,7 +45,7 @@ public abstract class BaseContainer extends Container { super(containerType, windowId); this.tile = tile; - if(tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, invDir).isPresent()) { + if (tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, invDir).isPresent()) { this.itemHandler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, invDir); } else { @@ -66,12 +60,12 @@ public abstract class BaseContainer extends Container { public void syncOnOpen(ServerPlayerEntity playerOpened) { // find another player that already has the gui for this tile open ServerWorld server = playerOpened.getServerWorld(); - for(PlayerEntity player : server.getPlayers()) { - if(player == playerOpened) { + for (PlayerEntity player : server.getPlayers()) { + if (player == playerOpened) { continue; } - if(player.openContainer instanceof BaseContainer) { - if(this.sameGui((BaseContainer) player.openContainer)) { + if (player.openContainer instanceof BaseContainer) { + if (this.sameGui((BaseContainer) player.openContainer)) { this.syncWithOtherContainer((BaseContainer) player.openContainer, playerOpened); return; } @@ -112,14 +106,14 @@ public abstract class BaseContainer extends Container { public boolean canInteractWith(@Nonnull PlayerEntity playerIn) { Block block = this.world.getBlockState(this.pos).getBlock(); // does the block we interacted with still exist? - if(block == Blocks.AIR || block != this.originalBlock) { + if (block == Blocks.AIR || block != this.originalBlock) { return false; } // too far away from block? return playerIn.getDistanceSq((double) this.pos.getX() + 0.5d, - (double) this.pos.getY() + 0.5d, - (double) this.pos.getZ() + 0.5d) <= this.maxDist; + (double) this.pos.getY() + 0.5d, + (double) this.pos.getZ() + 0.5d) <= this.maxDist; } @Nonnull @@ -165,15 +159,15 @@ public abstract class BaseContainer extends Container { int start = this.inventorySlots.size(); - for(int row = 0; row < 3; row++) { - for(int col = 0; col < 9; col++) { + for (int row = 0; row < 3; row++) { + for (int col = 0; col < 9; col++) { this.addSlot(new Slot(playerInventory, index, xCorner + col * 18, yCorner + row * 18)); index++; } } index = 0; - for(int col = 0; col < 9; col++) { + for (int col = 0; col < 9; col++) { this.addSlot(new Slot(playerInventory, index, xCorner + col * 18, yCorner + 58)); index++; } @@ -184,7 +178,7 @@ public abstract class BaseContainer extends Container { @Nonnull @Override protected Slot addSlot(Slot slotIn) { - if(this.playerInventoryStart >= 0) { + if (this.playerInventoryStart >= 0) { throw new SlimeknightException("BaseContainer: Player inventory has to be last slots. Add all slots before adding the player inventory."); } return super.addSlot(slotIn); @@ -194,7 +188,7 @@ public abstract class BaseContainer extends Container { @Override public ItemStack transferStackInSlot(PlayerEntity playerIn, int index) { // we can only support inventory <-> playerInventory - if(this.playerInventoryStart < 0) { + if (this.playerInventoryStart < 0) { // so we don't do anything if no player inventory is present because we don't know what to do return ItemStack.EMPTY; } @@ -203,24 +197,24 @@ public abstract class BaseContainer extends Container { Slot slot = this.inventorySlots.get(index); // slot that was clicked on not empty? - if(slot != null && slot.getHasStack()) { + if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); int end = this.inventorySlots.size(); // Is it a slot in the main inventory? (aka not player inventory) - if(index < this.playerInventoryStart) { + if (index < this.playerInventoryStart) { // try to put it into the player inventory (if we have a player inventory) - if(!this.mergeItemStack(itemstack1, this.playerInventoryStart, end, true)) { + if (!this.mergeItemStack(itemstack1, this.playerInventoryStart, end, true)) { return ItemStack.EMPTY; } } // Slot is in the player inventory (if it exists), transfer to main inventory - else if(!this.mergeItemStack(itemstack1, 0, this.playerInventoryStart, false)) { + else if (!this.mergeItemStack(itemstack1, 0, this.playerInventoryStart, false)) { return ItemStack.EMPTY; } - if(itemstack1.isEmpty()) { + if (itemstack1.isEmpty()) { slot.putStack(ItemStack.EMPTY); } else { @@ -235,7 +229,7 @@ public abstract class BaseContainer extends Container { @Override protected boolean mergeItemStack(@Nonnull ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) { boolean ret = this.mergeItemStackRefill(stack, startIndex, endIndex, useEndIndex); - if(!stack.isEmpty() && stack.getCount() > 0) { + if (!stack.isEmpty() && stack.getCount() > 0) { ret |= this.mergeItemStackMove(stack, startIndex, endIndex, useEndIndex); } return ret; @@ -243,39 +237,39 @@ public abstract class BaseContainer extends Container { // only refills items that are already present protected boolean mergeItemStackRefill(@Nonnull ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) { - if(stack.getCount() <= 0) { + if (stack.getCount() <= 0) { return false; } boolean flag1 = false; int k = startIndex; - if(useEndIndex) { + if (useEndIndex) { k = endIndex - 1; } Slot slot; ItemStack itemstack1; - if(stack.isStackable()) { - while(stack.getCount() > 0 && (!useEndIndex && k < endIndex || useEndIndex && k >= startIndex)) { + if (stack.isStackable()) { + while (stack.getCount() > 0 && (!useEndIndex && k < endIndex || useEndIndex && k >= startIndex)) { slot = this.inventorySlots.get(k); itemstack1 = slot.getStack(); - if(!itemstack1.isEmpty() - && itemstack1.getItem() == stack.getItem() - && ItemStack.areItemStackTagsEqual(stack, itemstack1) - && this.canMergeSlot(stack, slot)) { + if (!itemstack1.isEmpty() + && itemstack1.getItem() == stack.getItem() + && ItemStack.areItemStackTagsEqual(stack, itemstack1) + && this.canMergeSlot(stack, slot)) { int l = itemstack1.getCount() + stack.getCount(); int limit = Math.min(stack.getMaxStackSize(), slot.getItemStackLimit(stack)); - if(l <= limit) { + if (l <= limit) { stack.setCount(0); itemstack1.setCount(l); slot.onSlotChanged(); flag1 = true; } - else if(itemstack1.getCount() < limit) { + else if (itemstack1.getCount() < limit) { stack.shrink(limit - itemstack1.getCount()); itemstack1.setCount(limit); slot.onSlotChanged(); @@ -283,7 +277,7 @@ public abstract class BaseContainer extends Container { } } - if(useEndIndex) { + if (useEndIndex) { --k; } else { @@ -297,29 +291,29 @@ public abstract class BaseContainer extends Container { // only moves items into empty slots protected boolean mergeItemStackMove(@Nonnull ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) { - if(stack.getCount() <= 0) { + if (stack.getCount() <= 0) { return false; } boolean flag1 = false; int k; - if(useEndIndex) { + if (useEndIndex) { k = endIndex - 1; } else { k = startIndex; } - while(!useEndIndex && k < endIndex || useEndIndex && k >= startIndex) { + while (!useEndIndex && k < endIndex || useEndIndex && k >= startIndex) { Slot slot = this.inventorySlots.get(k); ItemStack itemstack1 = slot.getStack(); - if(itemstack1.isEmpty() && slot.isItemValid(stack) && this.canMergeSlot(stack, slot)) // Forge: Make sure to respect isItemValid in the slot. + if (itemstack1.isEmpty() && slot.isItemValid(stack) && this.canMergeSlot(stack, slot)) // Forge: Make sure to respect isItemValid in the slot. { int limit = slot.getItemStackLimit(stack); ItemStack stack2 = stack.copy(); - if(stack2.getCount() > limit) { + if (stack2.getCount() > limit) { stack2.setCount(limit); stack.shrink(limit); } @@ -330,12 +324,12 @@ public abstract class BaseContainer extends Container { slot.onSlotChanged(); flag1 = true; - if(stack.isEmpty()) { + if (stack.isEmpty()) { break; } } - if(useEndIndex) { + if (useEndIndex) { --k; } else { @@ -343,7 +337,7 @@ public abstract class BaseContainer extends Container { } } - return flag1; } + } diff --git a/src/main/java/slimeknights/mantle/inventory/SlotCraftingCustom.java b/src/main/java/slimeknights/mantle/inventory/CraftingCustomSlot.java similarity index 91% rename from src/main/java/slimeknights/mantle/inventory/SlotCraftingCustom.java rename to src/main/java/slimeknights/mantle/inventory/CraftingCustomSlot.java index 0b82c68..6415b0d 100644 --- a/src/main/java/slimeknights/mantle/inventory/SlotCraftingCustom.java +++ b/src/main/java/slimeknights/mantle/inventory/CraftingCustomSlot.java @@ -1,15 +1,14 @@ package slimeknights.mantle.inventory; import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.IInventory; import net.minecraft.inventory.CraftingInventory; +import net.minecraft.inventory.IInventory; import net.minecraft.inventory.container.CraftingResultSlot; import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; -public class SlotCraftingCustom extends CraftingResultSlot -{ +public class CraftingCustomSlot extends CraftingResultSlot { private final CraftingInventory craftMatrix; private final IContainerCraftingCustom callback; @@ -20,7 +19,7 @@ public class SlotCraftingCustom extends CraftingResultSlot * @param craftingInventory Inventory where the ingredients are taken from * @param craftResult Inventory where the result is put */ - public SlotCraftingCustom(IContainerCraftingCustom callback, PlayerEntity player, CraftingInventory craftingInventory, IInventory craftResult, int slotIndex, int xPosition, int yPosition) { + public CraftingCustomSlot(IContainerCraftingCustom callback, PlayerEntity player, CraftingInventory craftingInventory, IInventory craftResult, int slotIndex, int xPosition, int yPosition) { super(player, craftingInventory, craftResult, slotIndex, xPosition, yPosition); this.craftMatrix = craftingInventory; diff --git a/src/main/java/slimeknights/mantle/inventory/ContainerMultiModule.java b/src/main/java/slimeknights/mantle/inventory/MultiModuleContainer.java similarity index 80% rename from src/main/java/slimeknights/mantle/inventory/ContainerMultiModule.java rename to src/main/java/slimeknights/mantle/inventory/MultiModuleContainer.java index cf0dcd8..7728b52 100644 --- a/src/main/java/slimeknights/mantle/inventory/ContainerMultiModule.java +++ b/src/main/java/slimeknights/mantle/inventory/MultiModuleContainer.java @@ -3,28 +3,25 @@ package slimeknights.mantle.inventory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.inventory.IInventory; import net.minecraft.inventory.container.ClickType; import net.minecraft.inventory.container.Container; -import net.minecraft.inventory.IInventory; import net.minecraft.inventory.container.ContainerType; import net.minecraft.inventory.container.Slot; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; - import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.tuple.Pair; +import javax.annotation.Nonnull; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; -import javax.annotation.Nonnull; - -public class ContainerMultiModule extends BaseContainer { +public class MultiModuleContainer extends BaseContainer { public List subContainers = Lists.newArrayList(); @@ -34,28 +31,27 @@ public class ContainerMultiModule extends Bas protected int subContainerSlotStart = -1; protected Set shiftClickContainers = Sets.newHashSet(); - public ContainerMultiModule(ContainerType containerType, int windowId, T tile) { + public MultiModuleContainer(ContainerType containerType, int windowId, T tile) { super(containerType, windowId, tile); } - /** * @param subcontainer The container to add * @param preferForShiftClick If true shift clicking on slots of the main-container will try to move to this module before the player inventory */ public void addSubContainer(Container subcontainer, boolean preferForShiftClick) { - if(this.subContainers.isEmpty()) { + if (this.subContainers.isEmpty()) { this.subContainerSlotStart = this.inventorySlots.size(); } this.subContainers.add(subcontainer); - if(preferForShiftClick) { + if (preferForShiftClick) { this.shiftClickContainers.add(subcontainer); } int begin = this.inventorySlots.size(); - for(Object slot : subcontainer.inventorySlots) { - SlotWrapper wrapper = new SlotWrapper((Slot) slot); + for (Object slot : subcontainer.inventorySlots) { + WrapperSlot wrapper = new WrapperSlot((Slot) slot); this.addSlot(wrapper); this.slotContainerMap.put(wrapper.slotNumber, subcontainer); } @@ -68,11 +64,11 @@ public class ContainerMultiModule extends Bas } public TC getSubContainer(Class clazz, int index) { - for(Container sub : this.subContainers) { - if(clazz.isAssignableFrom(sub.getClass())) { + for (Container sub : this.subContainers) { + if (clazz.isAssignableFrom(sub.getClass())) { index--; } - if(index < 0) { + if (index < 0) { return (TC) sub; } } @@ -81,7 +77,7 @@ public class ContainerMultiModule extends Bas } public Container getSlotContainer(int slotNumber) { - if(this.slotContainerMap.containsKey(slotNumber)) { + if (this.slotContainerMap.containsKey(slotNumber)) { return this.slotContainerMap.get(slotNumber); } @@ -91,8 +87,8 @@ public class ContainerMultiModule extends Bas @Override public boolean canInteractWith(@Nonnull PlayerEntity playerIn) { // check if subcontainers are valid - for(Container sub : this.subContainers) { - if(!sub.canInteractWith(playerIn)) { + for (Container sub : this.subContainers) { + if (!sub.canInteractWith(playerIn)) { return false; } } @@ -100,10 +96,9 @@ public class ContainerMultiModule extends Bas return super.canInteractWith(playerIn); } - @Override public void onContainerClosed(PlayerEntity playerIn) { - for(Container sub : this.subContainers) { + for (Container sub : this.subContainers) { sub.onContainerClosed(playerIn); } @@ -113,8 +108,8 @@ public class ContainerMultiModule extends Bas @Nonnull @Override public ItemStack slotClick(int slotId, int dragType, ClickType type, PlayerEntity player) { - if(slotId == -999 && type == ClickType.QUICK_CRAFT) { - for(Container container : this.subContainers) { + if (slotId == -999 && type == ClickType.QUICK_CRAFT) { + for (Container container : this.subContainers) { container.slotClick(slotId, dragType, type, player); } } @@ -129,7 +124,7 @@ public class ContainerMultiModule extends Bas public ItemStack transferStackInSlot(PlayerEntity playerIn, int index) { Slot slot = this.inventorySlots.get(index); - if(slot == null || !slot.getHasStack()) { + if (slot == null || !slot.getHasStack()) { return ItemStack.EMPTY; } @@ -140,7 +135,7 @@ public class ContainerMultiModule extends Bas boolean nothingDone = true; // Is the slot from a module? - if(container != this) { + if (container != this) { // Try moving module -> tile inventory nothingDone &= this.moveToTileInventory(itemstack); @@ -148,7 +143,7 @@ public class ContainerMultiModule extends Bas nothingDone &= this.moveToPlayerInventory(itemstack); } // Is the slot from the tile? - else if(index < this.subContainerSlotStart || (index < this.playerInventoryStart && this.subContainerSlotStart < 0)) { + else if (index < this.subContainerSlotStart || (index < this.playerInventoryStart && this.subContainerSlotStart < 0)) { // Try moving tile -> preferred modules nothingDone &= this.refillAnyContainer(itemstack, this.subContainers); @@ -159,7 +154,7 @@ public class ContainerMultiModule extends Bas nothingDone &= this.moveToAnyContainer(itemstack, this.subContainers); } // Slot is from the player inventory (if present) - else if(index >= this.playerInventoryStart && this.playerInventoryStart >= 0) { + else if (index >= this.playerInventoryStart && this.playerInventoryStart >= 0) { // Try moving player -> tile inventory nothingDone &= this.moveToTileInventory(itemstack); @@ -171,7 +166,7 @@ public class ContainerMultiModule extends Bas return ItemStack.EMPTY; } - if(nothingDone) { + if (nothingDone) { return ItemStack.EMPTY; } @@ -183,7 +178,7 @@ public class ContainerMultiModule extends Bas // notify slot slot.onSlotChange(stack, original); - if(stack.getCount() == original.getCount()) { + if (stack.getCount() == original.getCount()) { return ItemStack.EMPTY; } @@ -191,7 +186,7 @@ public class ContainerMultiModule extends Bas slot.putStack(stack); slot.onTake(player, stack); - if(slot.getHasStack() && slot.getStack().isEmpty()) { + if (slot.getHasStack() && slot.getStack().isEmpty()) { slot.putStack(ItemStack.EMPTY); } @@ -199,33 +194,33 @@ public class ContainerMultiModule extends Bas } protected boolean moveToTileInventory(@Nonnull ItemStack itemstack) { - if(itemstack.isEmpty()) { + if (itemstack.isEmpty()) { return false; } int end = this.subContainerSlotStart; - if(end < 0) { + if (end < 0) { end = this.playerInventoryStart; } return !this.mergeItemStack(itemstack, 0, end, false); } protected boolean moveToPlayerInventory(@Nonnull ItemStack itemstack) { - if(itemstack.isEmpty()) { + if (itemstack.isEmpty()) { return false; } return this.playerInventoryStart > 0 && !this - .mergeItemStack(itemstack, this.playerInventoryStart, this.inventorySlots.size(), true); + .mergeItemStack(itemstack, this.playerInventoryStart, this.inventorySlots.size(), true); } protected boolean moveToAnyContainer(@Nonnull ItemStack itemstack, Collection containers) { - if(itemstack.isEmpty()) { + if (itemstack.isEmpty()) { return false; } - for(Container submodule : containers) { - if(this.moveToContainer(itemstack, submodule)) { + for (Container submodule : containers) { + if (this.moveToContainer(itemstack, submodule)) { return true; } } @@ -238,14 +233,13 @@ public class ContainerMultiModule extends Bas return !this.mergeItemStack(itemstack, range.getLeft(), range.getRight(), false); } - protected boolean refillAnyContainer(@Nonnull ItemStack itemstack, Collection containers) { - if(itemstack.isEmpty()) { + if (itemstack.isEmpty()) { return false; } - for(Container submodule : containers) { - if(this.refillContainer(itemstack, submodule)) { + for (Container submodule : containers) { + if (this.refillContainer(itemstack, submodule)) { return true; } } @@ -269,7 +263,7 @@ public class ContainerMultiModule extends Bas private TE detectChest(BlockPos pos, Class clazz) { TileEntity te = this.world.getTileEntity(pos); - if(te != null && clazz.isAssignableFrom(te.getClass())) { + if (te != null && clazz.isAssignableFrom(te.getClass())) { return (TE) te; } return null; diff --git a/src/main/java/slimeknights/mantle/inventory/SlotOut.java b/src/main/java/slimeknights/mantle/inventory/OutSlot.java similarity index 80% rename from src/main/java/slimeknights/mantle/inventory/SlotOut.java rename to src/main/java/slimeknights/mantle/inventory/OutSlot.java index 0739dfe..93e73e4 100644 --- a/src/main/java/slimeknights/mantle/inventory/SlotOut.java +++ b/src/main/java/slimeknights/mantle/inventory/OutSlot.java @@ -7,10 +7,9 @@ import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; /** Slot that can only be taken out of */ -public class SlotOut extends Slot -{ +public class OutSlot extends Slot { - public SlotOut(IInventory inventoryIn, int index, int xPosition, int yPosition) { + public OutSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) { super(inventoryIn, index, xPosition, yPosition); } diff --git a/src/main/java/slimeknights/mantle/inventory/SlotRestrictedItem.java b/src/main/java/slimeknights/mantle/inventory/RestrictedItemSlot.java similarity index 83% rename from src/main/java/slimeknights/mantle/inventory/SlotRestrictedItem.java rename to src/main/java/slimeknights/mantle/inventory/RestrictedItemSlot.java index a032035..1a96a98 100644 --- a/src/main/java/slimeknights/mantle/inventory/SlotRestrictedItem.java +++ b/src/main/java/slimeknights/mantle/inventory/RestrictedItemSlot.java @@ -7,11 +7,11 @@ import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; -public class SlotRestrictedItem extends Slot { +public class RestrictedItemSlot extends Slot { private final Item allowedItem; - public SlotRestrictedItem(Item item, IInventory inventoryIn, int index, int xPosition, int yPosition) { + public RestrictedItemSlot(Item item, IInventory inventoryIn, int index, int xPosition, int yPosition) { super(inventoryIn, index, xPosition, yPosition); this.allowedItem = item; } diff --git a/src/main/java/slimeknights/mantle/inventory/ContainerSimpleChest.java b/src/main/java/slimeknights/mantle/inventory/SimpleChestContainer.java similarity index 62% rename from src/main/java/slimeknights/mantle/inventory/ContainerSimpleChest.java rename to src/main/java/slimeknights/mantle/inventory/SimpleChestContainer.java index bd51cf3..aebf646 100644 --- a/src/main/java/slimeknights/mantle/inventory/ContainerSimpleChest.java +++ b/src/main/java/slimeknights/mantle/inventory/SimpleChestContainer.java @@ -4,21 +4,20 @@ import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.container.ContainerType; import net.minecraft.inventory.container.Slot; +import slimeknights.mantle.tileentity.InventoryTileEntity; -import slimeknights.mantle.tileentity.TileInventory; +public class SimpleChestContainer extends BaseContainer { -public class ContainerSimpleChest extends BaseContainer { - - public ContainerSimpleChest(ContainerType containerType, int windowId, TileInventory tile, int rows, int columns, PlayerInventory playerInventory) { + public SimpleChestContainer(ContainerType containerType, int windowId, InventoryTileEntity tile, int rows, int columns, PlayerInventory playerInventory) { super(containerType, windowId, tile); int index = 0; // chest inventory - for(int i = 0; i < rows; ++i) { - for(int j = 0; j < columns; ++j) { + for (int i = 0; i < rows; ++i) { + for (int j = 0; j < columns; ++j) { // safety - if(index > tile.getSizeInventory()) { + if (index > tile.getSizeInventory()) { break; } diff --git a/src/main/java/slimeknights/mantle/inventory/SlotWrapper.java b/src/main/java/slimeknights/mantle/inventory/WrapperSlot.java similarity index 95% rename from src/main/java/slimeknights/mantle/inventory/SlotWrapper.java rename to src/main/java/slimeknights/mantle/inventory/WrapperSlot.java index c2b767b..d17e854 100644 --- a/src/main/java/slimeknights/mantle/inventory/SlotWrapper.java +++ b/src/main/java/slimeknights/mantle/inventory/WrapperSlot.java @@ -2,7 +2,6 @@ package slimeknights.mantle.inventory; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.IInventory; import net.minecraft.inventory.container.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; @@ -14,11 +13,11 @@ import javax.annotation.Nonnull; /** * Used to wrap the slots inside Modules/Subcontainers */ -public class SlotWrapper extends Slot { +public class WrapperSlot extends Slot { public final Slot parent; - public SlotWrapper(Slot slot) { + public WrapperSlot(Slot slot) { super(slot.inventory, slot.getSlotIndex(), slot.xPos, slot.yPos); this.parent = slot; } diff --git a/src/main/java/slimeknights/mantle/item/ItemArmorTooltip.java b/src/main/java/slimeknights/mantle/item/ArmorTooltip.java similarity index 78% rename from src/main/java/slimeknights/mantle/item/ItemArmorTooltip.java rename to src/main/java/slimeknights/mantle/item/ArmorTooltip.java index fb4b510..48f3b4a 100644 --- a/src/main/java/slimeknights/mantle/item/ItemArmorTooltip.java +++ b/src/main/java/slimeknights/mantle/item/ArmorTooltip.java @@ -8,25 +8,22 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; - -import java.util.List; - -import javax.annotation.Nullable; - import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -public class ItemArmorTooltip extends ArmorItem -{ +import javax.annotation.Nullable; +import java.util.List; - public ItemArmorTooltip(IArmorMaterial armorMaterial, EquipmentSlotType equipmentSlot, Item.Properties builder) { +public class ArmorTooltip extends ArmorItem { + + public ArmorTooltip(IArmorMaterial armorMaterial, EquipmentSlotType equipmentSlot, Item.Properties builder) { super(armorMaterial, equipmentSlot, builder); } @Override @OnlyIn(Dist.CLIENT) public void addInformation(ItemStack stack, @Nullable World worldIn, List tooltip, ITooltipFlag flagIn) { - ItemTooltip.addOptionalTooltip(stack, tooltip); + TooltipItem.addOptionalTooltip(stack, tooltip); super.addInformation(stack, worldIn, tooltip, flagIn); } } diff --git a/src/main/java/slimeknights/mantle/item/ItemTooltip.java b/src/main/java/slimeknights/mantle/item/TooltipItem.java similarity index 71% rename from src/main/java/slimeknights/mantle/item/ItemTooltip.java rename to src/main/java/slimeknights/mantle/item/TooltipItem.java index 84844e7..4e30a65 100644 --- a/src/main/java/slimeknights/mantle/item/ItemTooltip.java +++ b/src/main/java/slimeknights/mantle/item/TooltipItem.java @@ -9,17 +9,15 @@ import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; - -import java.util.List; - -import javax.annotation.Nullable; - import slimeknights.mantle.util.LocUtils; -// Item with automatic tooltip support -public class ItemTooltip extends Item { +import javax.annotation.Nullable; +import java.util.List; - public ItemTooltip(Properties properties) { +// Item with automatic tooltip support +public class TooltipItem extends Item { + + public TooltipItem(Properties properties) { super(properties); } @@ -31,13 +29,13 @@ public class ItemTooltip extends Item { } public static void addOptionalTooltip(ItemStack stack, List tooltip) { - if(I18n.hasKey(stack.getDisplayName() + ".tooltip")) { + if (I18n.hasKey(stack.getDisplayName() + ".tooltip")) { tooltip.addAll(LocUtils.getTooltips(TextFormatting.GRAY.toString() + - LocUtils.translateRecursive(stack.getDisplayName() + ".tooltip"))); + LocUtils.translateRecursive(stack.getDisplayName() + ".tooltip"))); } - else if(I18n.hasKey(stack.getDisplayName() + ".tooltip")) { + else if (I18n.hasKey(stack.getDisplayName() + ".tooltip")) { tooltip.addAll(LocUtils.getTooltips( - TextFormatting.GRAY.toString() + LocUtils.translateRecursive(stack.getDisplayName() + ".tooltip"))); + TextFormatting.GRAY.toString() + LocUtils.translateRecursive(stack.getDisplayName() + ".tooltip"))); } } } diff --git a/src/main/java/slimeknights/mantle/multiblock/MultiServantLogic.java b/src/main/java/slimeknights/mantle/multiblock/MultiServantLogic.java index cde5cd7..c4668f0 100644 --- a/src/main/java/slimeknights/mantle/multiblock/MultiServantLogic.java +++ b/src/main/java/slimeknights/mantle/multiblock/MultiServantLogic.java @@ -34,12 +34,11 @@ public class MultiServantLogic extends MantleTileEntity implements IServantLogic } public boolean hasValidMaster() { - if(!this.hasMaster) { + if (!this.hasMaster) { return false; } - if(this.world.getBlockState(this.master).getBlock() == this.masterBlock - && this.world.getBlockState(this.master) == this.state) { + if (this.world.getBlockState(this.master).getBlock() == this.masterBlock && this.world.getBlockState(this.master) == this.state) { return true; } else { @@ -78,12 +77,12 @@ public class MultiServantLogic extends MantleTileEntity implements IServantLogic @Deprecated public boolean verifyMaster(IMasterLogic logic, BlockPos pos) { return this.master.equals(pos) && this.world.getBlockState(pos) == this.state - && this.world.getBlockState(pos).getBlock() == this.masterBlock; + && this.world.getBlockState(pos).getBlock() == this.masterBlock; } @Override public boolean verifyMaster(IMasterLogic logic, World world, BlockPos pos) { - if(this.hasMaster) { + if (this.hasMaster) { return this.hasValidMaster(); } else { @@ -99,7 +98,7 @@ public class MultiServantLogic extends MantleTileEntity implements IServantLogic @Override public void notifyMasterOfChange() { - if(this.hasValidMaster()) { + if (this.hasValidMaster()) { IMasterLogic logic = (IMasterLogic) this.world.getTileEntity(this.master); logic.notifyChange(this, this.pos); } @@ -107,7 +106,7 @@ public class MultiServantLogic extends MantleTileEntity implements IServantLogic public void readCustomNBT(CompoundNBT tags) { this.hasMaster = tags.getBoolean("hasMaster"); - if(this.hasMaster) { + if (this.hasMaster) { int xCenter = tags.getInt("xCenter"); int yCenter = tags.getInt("yCenter"); int zCenter = tags.getInt("zCenter"); @@ -119,7 +118,7 @@ public class MultiServantLogic extends MantleTileEntity implements IServantLogic public CompoundNBT writeCustomNBT(CompoundNBT tags) { tags.putBoolean("hasMaster", this.hasMaster); - if(this.hasMaster) { + if (this.hasMaster) { tags.putInt("xCenter", this.master.getX()); tags.putInt("yCenter", this.master.getY()); tags.putInt("zCenter", this.master.getZ()); @@ -167,9 +166,7 @@ public class MultiServantLogic extends MantleTileEntity implements IServantLogic @Deprecated public boolean setMaster(BlockPos pos) { - if(!this.hasMaster || this.world.getBlockState(this.master) != this.state || (this.world - .getBlockState(this.master) - .getBlock() != this.masterBlock)) { + if (!this.hasMaster || this.world.getBlockState(this.master) != this.state || (this.world.getBlockState(this.master).getBlock() != this.masterBlock)) { this.overrideMaster(pos); return true; } diff --git a/src/main/java/slimeknights/mantle/network/AbstractPacket.java b/src/main/java/slimeknights/mantle/network/AbstractPacket.java index c38939f..42841aa 100644 --- a/src/main/java/slimeknights/mantle/network/AbstractPacket.java +++ b/src/main/java/slimeknights/mantle/network/AbstractPacket.java @@ -1,17 +1,17 @@ package slimeknights.mantle.network; -import net.minecraft.client.network.play.ClientPlayNetHandler; -import net.minecraft.network.play.ServerPlayNetHandler; -import net.minecraft.util.math.BlockPos; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; - import io.netty.buffer.ByteBuf; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.fml.network.NetworkEvent; -public abstract class AbstractPacket implements IMessage { +import java.util.function.Supplier; - public abstract IMessage handleClient(ClientPlayNetHandler netHandler); +public abstract class AbstractPacket { - public abstract IMessage handleServer(ServerPlayNetHandler netHandler); + public abstract void encode(PacketBuffer buf); + + public abstract void handle(Supplier context); protected void writePos(BlockPos pos, ByteBuf buf) { buf.writeInt(pos.getX()); @@ -25,4 +25,5 @@ public abstract class AbstractPacket implements IMessage { int z = buf.readInt(); return new BlockPos(x, y, z); } + } diff --git a/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java b/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java index 5533744..97f0f5d 100644 --- a/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java +++ b/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java @@ -2,8 +2,6 @@ package slimeknights.mantle.network; import net.minecraft.client.network.play.ClientPlayNetHandler; import net.minecraft.network.play.ServerPlayNetHandler; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; /** * Threadsafe integration of the abstract packet. @@ -12,6 +10,8 @@ import net.minecraftforge.fml.common.network.simpleimpl.IMessage; */ public abstract class AbstractPacketThreadsafe extends AbstractPacket { + //TODO fix! + /* @Override public final IMessage handleClient(final ClientPlayNetHandler netHandler) { FMLCommonHandler.instance().getWorldThread(netHandler).addScheduledTask(new Runnable() { @@ -36,5 +36,5 @@ public abstract class AbstractPacketThreadsafe extends AbstractPacket { public abstract void handleClientSafe(ClientPlayNetHandler netHandler); - public abstract void handleServerSafe(ServerPlayNetHandler netHandler); + public abstract void handleServerSafe(ServerPlayNetHandler netHandler);*/ } diff --git a/src/main/java/slimeknights/mantle/network/NetworkWrapper.java b/src/main/java/slimeknights/mantle/network/NetworkWrapper.java index db8974e..29e7b3b 100644 --- a/src/main/java/slimeknights/mantle/network/NetworkWrapper.java +++ b/src/main/java/slimeknights/mantle/network/NetworkWrapper.java @@ -24,24 +24,24 @@ public class NetworkWrapper { private static final String PROTOCOL_VERSION = Integer.toString(1); public NetworkWrapper(String channelName) { - network = NetworkRegistry.ChannelBuilder.named(new ResourceLocation(channelName)) - .clientAcceptedVersions(PROTOCOL_VERSION::equals) - .serverAcceptedVersions(PROTOCOL_VERSION::equals) - .networkProtocolVersion(() -> PROTOCOL_VERSION) - .simpleChannel(); + this.network = NetworkRegistry.ChannelBuilder.named(new ResourceLocation(channelName)) + .clientAcceptedVersions(PROTOCOL_VERSION::equals) + .serverAcceptedVersions(PROTOCOL_VERSION::equals) + .networkProtocolVersion(() -> PROTOCOL_VERSION) + .simpleChannel(); } public void registerPacket(Class packetClazz, BiConsumer encoder, Function decoder, BiConsumer> messageConsumer) { - network.registerMessage(id++, packetClazz, encoder, decoder, messageConsumer); + this.network.registerMessage(this.id++, packetClazz, encoder, decoder, messageConsumer); } public void sendToServer(Object msg) { - network.sendToServer(msg); + this.network.sendToServer(msg); } public void sendTo(Object msg, ServerPlayerEntity player) { - if(!(player instanceof FakePlayer)) { - network.sendTo(msg, player.connection.netManager, NetworkDirection.PLAY_TO_CLIENT); + if (!(player instanceof FakePlayer)) { + this.network.sendTo(msg, player.connection.netManager, NetworkDirection.PLAY_TO_CLIENT); } } } diff --git a/src/main/java/slimeknights/mantle/network/book/PacketUpdateSavedPage.java b/src/main/java/slimeknights/mantle/network/book/PacketUpdateSavedPage.java index b433901..e17cfb3 100644 --- a/src/main/java/slimeknights/mantle/network/book/PacketUpdateSavedPage.java +++ b/src/main/java/slimeknights/mantle/network/book/PacketUpdateSavedPage.java @@ -4,47 +4,43 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Hand; - import net.minecraftforge.fml.network.NetworkEvent; import slimeknights.mantle.client.book.BookHelper; +import slimeknights.mantle.network.AbstractPacket; import java.util.function.Supplier; -public class PacketUpdateSavedPage { +public class PacketUpdateSavedPage extends AbstractPacket { private String pageName; - public PacketUpdateSavedPage() { - - } - public PacketUpdateSavedPage(String pageName) { this.pageName = pageName; } - public static void encode(PacketUpdateSavedPage msg, PacketBuffer buf) { - buf.writeString(msg.pageName); + public PacketUpdateSavedPage(PacketBuffer buffer) { + this.pageName = buffer.readString(32767); } - public static PacketUpdateSavedPage decode(PacketBuffer buf) { - return new PacketUpdateSavedPage(buf.readString(32767)); + @Override + public void encode(PacketBuffer buf) { + buf.writeString(this.pageName); } - public static class Handler { - public static void handle(final PacketUpdateSavedPage pkt, final Supplier ctx) { - ctx.get().enqueueWork(() -> { - if(ctx.get().getSender() != null && pkt.pageName != null) { - PlayerEntity player = ctx.get().getSender(); + @Override + public void handle(Supplier context) { + context.get().enqueueWork(() -> { + if (context.get().getSender() != null && this.pageName != null) { + PlayerEntity player = context.get().getSender(); - ItemStack is = player.getHeldItem(Hand.MAIN_HAND); + ItemStack is = player.getHeldItem(Hand.MAIN_HAND); - if(!is.isEmpty()) { - BookHelper.writeSavedPage(is, pkt.pageName); - } + if (!is.isEmpty()) { + BookHelper.writeSavedPage(is, this.pageName); } - }); + } + }); - ctx.get().setPacketHandled(true); - } + context.get().setPacketHandled(true); } } diff --git a/src/main/java/slimeknights/mantle/property/PropertyString.java b/src/main/java/slimeknights/mantle/property/PropertyString.java deleted file mode 100644 index 4fc3f20..0000000 --- a/src/main/java/slimeknights/mantle/property/PropertyString.java +++ /dev/null @@ -1,32 +0,0 @@ -package slimeknights.mantle.property; - -import net.minecraftforge.common.property.IUnlistedProperty; - -public class PropertyString implements IUnlistedProperty { - - private final String name; - - public PropertyString(String name) { - this.name = name; - } - - @Override - public String getName() { - return name; - } - - @Override - public boolean isValid(String value) { - return !value.isEmpty(); - } - - @Override - public Class getType() { - return String.class; - } - - @Override - public String valueToString(String value) { - return value; - } -} diff --git a/src/main/java/slimeknights/mantle/property/PropertyUnlistedDirection.java b/src/main/java/slimeknights/mantle/property/PropertyUnlistedDirection.java deleted file mode 100644 index 90583ec..0000000 --- a/src/main/java/slimeknights/mantle/property/PropertyUnlistedDirection.java +++ /dev/null @@ -1,38 +0,0 @@ -package slimeknights.mantle.property; - -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; -import com.google.common.collect.Lists; - -import net.minecraft.state.DirectionProperty; -import net.minecraft.util.Direction; -import net.minecraftforge.common.property.IUnlistedProperty; - -import java.util.Collection; - -public class PropertyUnlistedDirection extends DirectionProperty implements IUnlistedProperty { - - public PropertyUnlistedDirection(String name, Collection values) { - super(name, values); - } - - public PropertyUnlistedDirection(String name, Predicate filter) { - this(name, Collections2.filter(Lists.newArrayList(Direction.values()), filter)); - } - - @Override - public boolean isValid(Direction value) { - return true; - } - - @Override - public Class getType() { - return this.getValueClass(); - } - - @Override - public String valueToString(Direction value) { - return getName(value); - } - -} diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java index 0b78359..d406291 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java @@ -26,7 +26,7 @@ public final class BusExceptionHandler implements IExceptionHandler { @Override public void handle(Exception ex) { - this.logger.error("Exception caught from a pulse on flightpath for mod ID " + id + ": ", ex); + this.logger.error("Exception caught from a pulse on flightpath for mod ID " + this.id + ": ", ex); // if its a runtime exception, we can just throw it as is if(ex instanceof RuntimeException) { throw (RuntimeException)ex; diff --git a/src/main/java/slimeknights/mantle/tileentity/TileInventory.java b/src/main/java/slimeknights/mantle/tileentity/InventoryTileEntity.java similarity index 80% rename from src/main/java/slimeknights/mantle/tileentity/TileInventory.java rename to src/main/java/slimeknights/mantle/tileentity/InventoryTileEntity.java index e686505..4c531db 100644 --- a/src/main/java/slimeknights/mantle/tileentity/TileInventory.java +++ b/src/main/java/slimeknights/mantle/tileentity/InventoryTileEntity.java @@ -2,9 +2,7 @@ package slimeknights.mantle.tileentity; import net.minecraft.block.Blocks; import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.INamedContainerProvider; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; @@ -21,14 +19,13 @@ import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.wrapper.InvWrapper; +import slimeknights.mantle.util.ItemStackList; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import slimeknights.mantle.util.ItemStackList; - -// Updated version of InventoryLogic in Mantle. Also contains a few bugfixes -public class TileInventory extends MantleTileEntity implements IInventory, INamedContainerProvider, INameable { +// Updated version of InventoryLogic in Mantle. Also contains a few bugfixes DOES NOT OVERRIDE createMenu +public abstract class InventoryTileEntity extends MantleTileEntity implements IInventory, INamedContainerProvider, INameable { private NonNullList inventory; protected ITextComponent inventoryTitle; @@ -40,14 +37,14 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName /** * @param name Localization String for the inventory title. Can be overridden through setCustomName */ - public TileInventory(TileEntityType tileEntityTypeIn, ITextComponent name, int inventorySize) { + public InventoryTileEntity(TileEntityType tileEntityTypeIn, ITextComponent name, int inventorySize) { this(tileEntityTypeIn, name, inventorySize, 64); } /** * @param name Localization String for the inventory title. Can be overridden through setCustomName */ - public TileInventory(TileEntityType tileEntityTypeIn, ITextComponent name, int inventorySize, int maxStackSize) { + public InventoryTileEntity(TileEntityType tileEntityTypeIn, ITextComponent name, int inventorySize, int maxStackSize) { super(tileEntityTypeIn); this.inventory = NonNullList.withSize(inventorySize, ItemStack.EMPTY); this.stackSizeLimit = maxStackSize; @@ -59,7 +56,7 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName @SuppressWarnings("unchecked") @Override public net.minecraftforge.common.util.LazyOptional getCapability(@Nonnull Capability capability, Direction facing) { - if(capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { return this.itemHandlerCap.cast(); } return super.getCapability(capability, facing); @@ -74,7 +71,7 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName @Nonnull @Override public ItemStack getStackInSlot(int slot) { - if(slot < 0 || slot >= this.inventory.size()) { + if (slot < 0 || slot >= this.inventory.size()) { return ItemStack.EMPTY; } @@ -88,7 +85,7 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName /** Same as resize, but does not call markDirty. Used on loading from NBT */ private void resizeInternal(int size) { // save effort if the size did not change - if(size == this.inventory.size()) { + if (size == this.inventory.size()) { return; } ItemStackList newInventory = ItemStackList.withSize(size); @@ -116,17 +113,17 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName @Override public void setInventorySlotContents(int slot, @Nonnull ItemStack itemstack) { - if(slot < 0 || slot >= this.inventory.size()) { + if (slot < 0 || slot >= this.inventory.size()) { return; } ItemStack current = this.inventory.get(slot); this.inventory.set(slot, itemstack); - if(!itemstack.isEmpty() && itemstack.getCount() > this.getInventoryStackLimit()) { + if (!itemstack.isEmpty() && itemstack.getCount() > this.getInventoryStackLimit()) { itemstack.setCount(this.getInventoryStackLimit()); } - if(!ItemStack.areItemStacksEqual(current, itemstack)) { + if (!ItemStack.areItemStacksEqual(current, itemstack)) { this.markDirtyFast(); } } @@ -134,17 +131,17 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName @Nonnull @Override public ItemStack decrStackSize(int slot, int quantity) { - if(quantity <= 0) { + if (quantity <= 0) { return ItemStack.EMPTY; } ItemStack itemStack = this.getStackInSlot(slot); - if(itemStack.isEmpty()) { + if (itemStack.isEmpty()) { return ItemStack.EMPTY; } // whole itemstack taken out - if(itemStack.getCount() <= quantity) { + if (itemStack.getCount() <= quantity) { this.setInventorySlotContents(slot, ItemStack.EMPTY); this.markDirtyFast(); return itemStack; @@ -154,7 +151,7 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName itemStack = itemStack.split(quantity); // slot is empty, set to ItemStack.EMPTY // isn't this redundant to the above check? - if(this.getStackInSlot(slot).getCount() == 0) { + if (this.getStackInSlot(slot).getCount() == 0) { this.setInventorySlotContents(slot, ItemStack.EMPTY); } @@ -173,7 +170,7 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName @Override public boolean isItemValidForSlot(int slot, @Nonnull ItemStack itemstack) { - if(slot < this.getSizeInventory()) { + if (slot < this.getSizeInventory()) { return this.inventory.get(slot).isEmpty() || itemstack.getCount() + this.inventory.get(slot).getCount() <= this.getInventoryStackLimit(); } return false; @@ -181,7 +178,7 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName @Override public void clear() { - for(int i = 0; i < this.inventory.size(); i++) { + for (int i = 0; i < this.inventory.size(); i++) { this.inventory.set(i, ItemStack.EMPTY); } } @@ -211,25 +208,24 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName @Nonnull @Override public ITextComponent getDisplayName() { - if(this.hasCustomName()) { + if (this.hasCustomName()) { return new StringTextComponent(this.getName().getFormattedText()); } return new TranslationTextComponent(this.getName().getFormattedText()); } - /* Supporting methods */ @Override public boolean isUsableByPlayer(@Nonnull PlayerEntity entityplayer) { // block changed/got broken? - if(this.world.getTileEntity(this.pos) != this || this.world.getBlockState(this.pos).getBlock() == Blocks.AIR) { + if (this.world.getTileEntity(this.pos) != this || this.world.getBlockState(this.pos).getBlock() == Blocks.AIR) { return false; } return - entityplayer.getDistanceSq(this.pos.getX() + 0.5D, this.pos.getY() + 0.5D, this.pos.getZ() + 0.5D) - <= 64D; + entityplayer.getDistanceSq(this.pos.getX() + 0.5D, this.pos.getY() + 0.5D, this.pos.getZ() + 0.5D) + <= 64D; } @Override @@ -250,7 +246,7 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName this.readInventoryFromNBT(tags); - if(tags.contains("CustomName", 8)) { + if (tags.contains("CustomName", 8)) { this.inventoryTitle = ITextComponent.Serializer.fromJson(tags.getString("CustomName")); } } @@ -264,7 +260,7 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName this.writeInventoryToNBT(tags); - if(this.hasCustomName()) { + if (this.hasCustomName()) { tags.putString("CustomName", ITextComponent.Serializer.toJson(this.inventoryTitle)); } return tags; @@ -275,8 +271,8 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName IInventory inventory = this; ListNBT nbttaglist = new ListNBT(); - for(int i = 0; i < inventory.getSizeInventory(); i++) { - if(!inventory.getStackInSlot(i).isEmpty()) { + for (int i = 0; i < inventory.getSizeInventory(); i++) { + if (!inventory.getStackInSlot(i).isEmpty()) { CompoundNBT itemTag = new CompoundNBT(); itemTag.putByte("Slot", (byte) i); inventory.getStackInSlot(i).write(itemTag); @@ -293,13 +289,13 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName int limit = this.getInventoryStackLimit(); ItemStack stack; - for(int i = 0; i < nbttaglist.size(); ++i) { + for (int i = 0; i < nbttaglist.size(); ++i) { CompoundNBT itemTag = nbttaglist.getCompound(i); int slot = itemTag.getByte("Slot") & 255; - if(slot >= 0 && slot < this.inventory.size()) { + if (slot >= 0 && slot < this.inventory.size()) { stack = ItemStack.read(itemTag); - if(!stack.isEmpty() && stack.getCount() > limit) { + if (!stack.isEmpty() && stack.getCount() > limit) { stack.setCount(limit); } this.inventory.set(slot, stack); @@ -323,10 +319,4 @@ public class TileInventory extends MantleTileEntity implements IInventory, IName return true; } - - @Nullable - @Override - public Container createMenu(int id, PlayerInventory playerInventory, PlayerEntity playerEntity) { - return null; - } } diff --git a/src/main/java/slimeknights/mantle/tileentity/MantleTileEntity.java b/src/main/java/slimeknights/mantle/tileentity/MantleTileEntity.java index 1a694ce..bdc6f31 100644 --- a/src/main/java/slimeknights/mantle/tileentity/MantleTileEntity.java +++ b/src/main/java/slimeknights/mantle/tileentity/MantleTileEntity.java @@ -22,4 +22,4 @@ public class MantleTileEntity extends TileEntity { world.markChunkDirty(pos, this); } } -} +} \ No newline at end of file diff --git a/src/main/java/slimeknights/mantle/util/ImmutableConcatList.java b/src/main/java/slimeknights/mantle/util/ImmutableConcatList.java index 85c8446..18cc199 100644 --- a/src/main/java/slimeknights/mantle/util/ImmutableConcatList.java +++ b/src/main/java/slimeknights/mantle/util/ImmutableConcatList.java @@ -4,14 +4,13 @@ import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import com.google.common.collect.UnmodifiableListIterator; +import javax.annotation.Nonnull; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; -import javax.annotation.Nonnull; - import static com.google.common.base.Preconditions.checkPositionIndex; public class ImmutableConcatList implements List { @@ -71,9 +70,11 @@ public class ImmutableConcatList implements List { @Override public boolean containsAll(@Nonnull Collection c) { - for (Object e : c) - if (!this.contains(e)) + for (Object e : c) { + if (!this.contains(e)) { return false; + } + } return true; } @@ -126,7 +127,7 @@ public class ImmutableConcatList implements List { public int indexOf(final Object o) { Iterator iterator = this.iterable.iterator(); for (int i = 0; iterator.hasNext(); i++) { - if(o == iterator.next()) { + if (o == iterator.next()) { return i; } } @@ -139,7 +140,7 @@ public class ImmutableConcatList implements List { Iterator iterator = this.iterable.iterator(); int j = -1; for (int i = 0; iterator.hasNext(); i++) { - if(o == iterator.next()) { + if (o == iterator.next()) { j = i; } } diff --git a/src/main/java/slimeknights/mantle/util/ItemStackList.java b/src/main/java/slimeknights/mantle/util/ItemStackList.java index 8890f2f..102fc2b 100644 --- a/src/main/java/slimeknights/mantle/util/ItemStackList.java +++ b/src/main/java/slimeknights/mantle/util/ItemStackList.java @@ -55,7 +55,7 @@ public class ItemStackList extends NonNullList { */ public static ItemStackList of(IInventory inventory) { ItemStackList itemStackList = withSize(inventory.getSizeInventory()); - for(int i = 0; i < inventory.getSizeInventory(); i++) { + for (int i = 0; i < inventory.getSizeInventory(); i++) { itemStackList.add(inventory.getStackInSlot(i)); } return itemStackList; @@ -78,7 +78,7 @@ public class ItemStackList extends NonNullList { * @param index The index to set empty */ public void setEmpty(int index) { - if(index >= 0 && index < size()) { + if (index >= 0 && index < size()) { set(index, ItemStack.EMPTY); } } @@ -89,7 +89,7 @@ public class ItemStackList extends NonNullList { */ public ItemStackList copy(boolean fixed) { ItemStackList copy = fixed ? withSize(this.size()) : create(); - for(int i = 0; i < size(); i++) { + for (int i = 0; i < size(); i++) { copy.set(i, get(i)); } return copy; @@ -102,7 +102,7 @@ public class ItemStackList extends NonNullList { */ public ItemStackList deepCopy(boolean fixed) { ItemStackList copy = fixed ? withSize(this.size()) : create(); - for(int i = 0; i < size(); i++) { + for (int i = 0; i < size(); i++) { copy.set(i, get(i).copy()); } return copy; diff --git a/src/main/java/slimeknights/mantle/util/JeiPlugin.java b/src/main/java/slimeknights/mantle/util/JeiPlugin.java index 5a4dd16..ebafb4a 100644 --- a/src/main/java/slimeknights/mantle/util/JeiPlugin.java +++ b/src/main/java/slimeknights/mantle/util/JeiPlugin.java @@ -1,12 +1,5 @@ package slimeknights.mantle.util; -import java.awt.*; -import java.util.Collections; -import java.util.List; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - import mezz.jei.api.IModPlugin; import mezz.jei.api.gui.handlers.IGuiContainerHandler; import mezz.jei.api.registration.IGuiHandlerRegistration; @@ -16,16 +9,19 @@ import mezz.jei.api.runtime.IJeiRuntime; import net.minecraft.client.renderer.Rectangle2d; import net.minecraft.util.ResourceLocation; import slimeknights.mantle.Mantle; -import slimeknights.mantle.client.gui.GuiMultiModule; +import slimeknights.mantle.client.screen.MultiModuleScreen; + +import javax.annotation.Nonnull; +import java.util.List; @mezz.jei.api.JeiPlugin public class JeiPlugin implements IModPlugin { @Override public void registerGuiHandlers(IGuiHandlerRegistration registration) { - registration.addGuiContainerHandler(GuiMultiModule.class, new IGuiContainerHandler() { + registration.addGuiContainerHandler(MultiModuleScreen.class, new IGuiContainerHandler() { @Override - public List getGuiExtraAreas(@Nonnull GuiMultiModule guiContainer) { + public List getGuiExtraAreas(@Nonnull MultiModuleScreen guiContainer) { return guiContainer.getModuleAreas(); } }); @@ -36,17 +32,16 @@ public class JeiPlugin implements IModPlugin { } @Override - public ResourceLocation getPluginUid() - { + public ResourceLocation getPluginUid() { return new ResourceLocation(Mantle.modId, "internal"); } @Override - public void registerItemSubtypes(ISubtypeRegistration subtypeRegistry){ + public void registerItemSubtypes(ISubtypeRegistration subtypeRegistry) { } @Override - public void registerIngredients(IModIngredientRegistration registry){ + public void registerIngredients(IModIngredientRegistration registry) { } } diff --git a/src/main/java/slimeknights/mantle/util/LocUtils.java b/src/main/java/slimeknights/mantle/util/LocUtils.java index b21ee8f..a6f9906 100644 --- a/src/main/java/slimeknights/mantle/util/LocUtils.java +++ b/src/main/java/slimeknights/mantle/util/LocUtils.java @@ -27,14 +27,14 @@ public abstract class LocUtils { public static List getTooltips(String text) { List list = Lists.newLinkedList(); - if(text == null) + if (text == null) { return list; + } int j = 0; int k; - while((k = text.indexOf("\\n", j)) >= 0) - { + while ((k = text.indexOf("\\n", j)) >= 0) { list.add(new StringTextComponent(text.substring(j, k))); - j = k+2; + j = k + 2; } list.add(new StringTextComponent(text.substring(j, text.length()))); @@ -42,14 +42,13 @@ public abstract class LocUtils { return list; } - public static String convertNewlines(String line) { - if(line == null) + if (line == null) { return null; + } int j; - while((j = line.indexOf("\\n")) >= 0) - { - line = line.substring(0, j) + '\n' + line.substring(j+2); + while ((j = line.indexOf("\\n")) >= 0) { + line = line.substring(0, j) + '\n' + line.substring(j + 2); } return line; diff --git a/src/main/java/slimeknights/mantle/util/RecipeMatch.java b/src/main/java/slimeknights/mantle/util/RecipeMatch.java index 39ff03a..4caad3e 100644 --- a/src/main/java/slimeknights/mantle/util/RecipeMatch.java +++ b/src/main/java/slimeknights/mantle/util/RecipeMatch.java @@ -3,23 +3,18 @@ package slimeknights.mantle.util; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; - import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; -import net.minecraftforge.oredict.OreDictionary; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.stream.IntStream; - -import slimeknights.mantle.Mantle; /** * Utility class that allows to find a specific subset of items in a list of itemstacks. - * Matches can be found through oredictionary, simple nbt-independant item-meta combinations etc. + * Matches can be found through tags, simple nbt-independant item-meta combinations etc. * * The match returned by this class can then be used to remove the found recipe match from the items. */ @@ -44,30 +39,6 @@ public abstract class RecipeMatch { public abstract Optional matches(NonNullList stacks); - public static RecipeMatch of(String oredict) { - return of(oredict, 1); - } - - public static RecipeMatch of(String oredict, int matched) { - return of(oredict, 1, matched); - } - - public static RecipeMatch of(String oredict, int amount, int matched) { - return new RecipeMatch.Oredict(oredict, amount, matched); - } - - public static RecipeMatch of(List oredict) { - return of(oredict, 1); - } - - public static RecipeMatch of(List oredict, int matched) { - return of(oredict, 1, matched); - } - - public static RecipeMatch of(List oredict, int amount, int matched) { - return new RecipeMatch.Oredict(oredict, amount, matched); - } - public static RecipeMatch of(net.minecraft.item.Item item) { return of(item, 1); } @@ -122,14 +93,14 @@ public abstract class RecipeMatch { private static void removeOrder(NonNullList stacks, List toRemove, int[] amountsRemoved) { int i = 0; - for(int j = 0; j < amountsRemoved.length; j++) { + for (int j = 0; j < amountsRemoved.length; j++) { ItemStack stack = toRemove.get(j); - for(; i < stacks.size(); i++) { + for (; i < stacks.size(); i++) { // nbt sensitive since toolparts etc. use nbt - if(ItemStack.areItemsEqual(stack, stacks.get(i)) && ItemStack.areItemStackTagsEqual(stack, stacks.get(i))) { - if(stacks.get(i).getCount() >= stack.getCount()) { + if (ItemStack.areItemsEqual(stack, stacks.get(i)) && ItemStack.areItemStackTagsEqual(stack, stacks.get(i))) { + if (stacks.get(i).getCount() >= stack.getCount()) { stacks.get(i).shrink(stack.getCount()); - if(stacks.get(i).getCount() == 0) { + if (stacks.get(i).getCount() == 0) { stacks.set(i, ItemStack.EMPTY); } amountsRemoved[j] += stack.getCount(); @@ -142,14 +113,14 @@ public abstract class RecipeMatch { } private static void removeRemaining(NonNullList stacks, List toRemove, int[] amountsRemoved) { - for(int j = 0; j < amountsRemoved.length; j++) { + for (int j = 0; j < amountsRemoved.length; j++) { ItemStack stack = toRemove.get(j); int needed = stack.getCount() - amountsRemoved[j]; - for(int i = 0; i < stacks.size() && needed > 0; i++) { - if(ItemStack.areItemsEqual(stack, stacks.get(i)) && ItemStack.areItemStackTagsEqual(stack, stacks.get(i))) { + for (int i = 0; i < stacks.size() && needed > 0; i++) { + if (ItemStack.areItemsEqual(stack, stacks.get(i)) && ItemStack.areItemStackTagsEqual(stack, stacks.get(i))) { int change = Math.min(stacks.get(i).getCount(), needed); stacks.get(i).shrink(change); - if(stacks.get(i).getCount() == 0) { + if (stacks.get(i).getCount() == 0) { stacks.set(i, ItemStack.EMPTY); } needed -= change; @@ -187,8 +158,8 @@ public abstract class RecipeMatch { List found = Lists.newLinkedList(); int stillNeeded = this.amountNeeded; - for(ItemStack stack : stacks) { - if(OreDictionary.itemMatches(this.template, stack, false)) { + for (ItemStack stack : stacks) { + if (this.template.getItem() == stack.getItem()) { // add the amount found to the list ItemStack copy = stack.copy(); copy.setCount(Math.min(copy.getCount(), stillNeeded)); @@ -196,7 +167,7 @@ public abstract class RecipeMatch { stillNeeded -= copy.getCount(); // we found enough - if(stillNeeded <= 0) { + if (stillNeeded <= 0) { return Optional.of(new Match(found, this.amountMatched)); } } @@ -218,9 +189,9 @@ public abstract class RecipeMatch { super(amountMatched, 0); NonNullList nonNullStacks = NonNullList.withSize(stacks.length, ItemStack.EMPTY); - for(int i = 0; i < stacks.length; i++) { - if(!stacks[i].isEmpty()) { - nonNullStacks.set(i, stacks[i].copy()); + for (int i = 0; i < stacks.length; i++) { + if (!stacks[i].isEmpty()) { + nonNullStacks.set(i, stacks[i].copy()); } } @@ -237,18 +208,18 @@ public abstract class RecipeMatch { List found = Lists.newLinkedList(); Set needed = Sets.newHashSet(); - for(int i = 0; i < this.itemStacks.size(); i++) { - if(!this.itemStacks.get(i).isEmpty()) { + for (int i = 0; i < this.itemStacks.size(); i++) { + if (!this.itemStacks.get(i).isEmpty()) { needed.add(i); } } - for(ItemStack stack : stacks) { + for (ItemStack stack : stacks) { Iterator iter = needed.iterator(); - while(iter.hasNext()) { + while (iter.hasNext()) { int index = iter.next(); ItemStack template = this.itemStacks.get(index); - if(ItemStack.areItemsEqual(template, stack) && ItemStack.areItemStackTagsEqual(template, stack)) { + if (ItemStack.areItemsEqual(template, stack) && ItemStack.areItemStackTagsEqual(template, stack)) { // add the amount found to the list ItemStack copy = stack.copy(); copy.setCount(1); @@ -259,70 +230,13 @@ public abstract class RecipeMatch { } } - if(needed.isEmpty()) { + if (needed.isEmpty()) { return Optional.of(new Match(found, this.amountMatched)); } return Optional.empty(); } } - /** A specific amount of an oredicted material is needed to match. */ - public static class Oredict extends RecipeMatch { - - private final List oredictEntry; // todo: change this to the actual list in the oredict - - public Oredict(List oredictEntry, int amountNeeded) { - this(oredictEntry, amountNeeded, 1); - } - - public Oredict(List oredictEntry, int amountNeeded, int amountMatched) { - super(amountMatched, amountNeeded); - this.oredictEntry = oredictEntry; - } - - public Oredict(String oredictEntry, int amountNeeded) { - this(oredictEntry, amountNeeded, 1); - } - - public Oredict(String oredictEntry, int amountNeeded, int amountMatched) { - super(amountMatched, amountNeeded); - this.oredictEntry = OreDictionary.getOres(oredictEntry); - } - - @Override - public List getInputs() { - // transform "Requires 2 Cobblestone" into "2x require 1 Cobblestone" since the oredictEntry only contains stacksize 1 usually - ImmutableList.Builder builder = ImmutableList.builder(); - this.oredictEntry.forEach(stack -> IntStream.range(0, this.amountNeeded).forEach(i -> builder.add(stack))); - return builder.build(); - } - - @Override - public Optional matches(NonNullList stacks) { - List found = Lists.newLinkedList(); - int stillNeeded = this.amountNeeded; - - for(ItemStack ore : this.oredictEntry) { - for(ItemStack stack : stacks) { - if(OreDictionary.itemMatches(ore, stack, false)) { - // add the amount found to the list - ItemStack copy = stack.copy(); - copy.setCount(Math.min(copy.getCount(), stillNeeded)); - found.add(copy); - stillNeeded -= copy.getCount(); - - // we found enough - if(stillNeeded <= 0) { - return Optional.of(new Match(found, this.amountMatched)); - } - } - } - } - - return Optional.empty(); - } - } - /** Represents a collection of items that match the recipies */ public static class Match { diff --git a/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java b/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java index 7ac4604..0912531 100644 --- a/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java +++ b/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java @@ -1,13 +1,11 @@ package slimeknights.mantle.util; import com.google.common.collect.Lists; - import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; -import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Optional; @@ -23,8 +21,8 @@ public class RecipeMatchRegistry { // looks for a match in the given itemstacks public Optional matches(ItemStack... stacks) { NonNullList nonNullStacks = NonNullList.withSize(stacks.length, ItemStack.EMPTY); - for(int i = 0; i < stacks.length; i++) { - if(!stacks[i].isEmpty()) { + for (int i = 0; i < stacks.length; i++) { + if (!stacks[i].isEmpty()) { nonNullStacks.set(i, stacks[i].copy()); } } @@ -34,9 +32,9 @@ public class RecipeMatchRegistry { // looks for a match in the given itemstacks public Optional matches(NonNullList stacks) { - for(RecipeMatch recipe : this.items) { + for (RecipeMatch recipe : this.items) { Optional match = recipe.matches(stacks); - if(match.isPresent()) { + if (match.isPresent()) { return match; } } @@ -52,7 +50,7 @@ public class RecipeMatchRegistry { Optional matchOptional; int sum = 0; - while(sum < minAmount && (matchOptional = this.matches(stacks)).isPresent()) { + while (sum < minAmount && (matchOptional = this.matches(stacks)).isPresent()) { RecipeMatch.Match match = matchOptional.get(); matches.add(match); RecipeMatch.removeMatch(stacks, match); @@ -61,13 +59,13 @@ public class RecipeMatchRegistry { } // not enough found - if(sum < minAmount) { + if (sum < minAmount) { return Optional.empty(); } // merge all found matches into one match List foundStacks = Lists.newLinkedList(); - for(RecipeMatch.Match m : matches) { + for (RecipeMatch.Match m : matches) { foundStacks.addAll(m.stacks); } @@ -81,7 +79,7 @@ public class RecipeMatchRegistry { Optional matchOptional; int sum = 0; - while((matchOptional = this.matches(stacks)).isPresent()) { + while ((matchOptional = this.matches(stacks)).isPresent()) { RecipeMatch.Match match = matchOptional.get(); matches.add(match); RecipeMatch.removeMatch(stacks, match); @@ -91,28 +89,13 @@ public class RecipeMatchRegistry { // merge all found matches into one match List foundStacks = Lists.newLinkedList(); - for(RecipeMatch.Match m : matches) { + for (RecipeMatch.Match m : matches) { foundStacks.addAll(m.stacks); } return Optional.of(new RecipeMatch.Match(foundStacks, sum)); } - /** - * Associates an oredict entry with this material. Used for repairing and other. - * - * @param oredictItem Oredict-String - * @param amountNeeded How many of this item are needed to count as one full material item. - * @param amountMatched If both item and amount are present, how often did they match? - */ - public void addItem(String oredictItem, int amountNeeded, int amountMatched) { - this.items.add(new RecipeMatch.Oredict(oredictItem, amountNeeded, amountMatched)); - } - - public void addItem(String oredictItem) { - this.addItem(oredictItem, 1, 1); - } - /** * Associates a block with this material. Used for repairing and other. * @@ -155,11 +138,10 @@ public class RecipeMatchRegistry { this.items.add(match); } - public static NonNullList copyItemStackArray(NonNullList in) { NonNullList stacksCopy = NonNullList.withSize(in.size(), ItemStack.EMPTY); - for(int i = 0; i < in.size(); i++) { - if(!in.get(i).isEmpty()) { + for (int i = 0; i < in.size(); i++) { + if (!in.get(i).isEmpty()) { stacksCopy.set(i, in.get(i).copy()); } } diff --git a/src/main/java/slimeknights/mantle/util/TagHelper.java b/src/main/java/slimeknights/mantle/util/TagHelper.java index d4c8477..147eff5 100644 --- a/src/main/java/slimeknights/mantle/util/TagHelper.java +++ b/src/main/java/slimeknights/mantle/util/TagHelper.java @@ -15,7 +15,7 @@ public class TagHelper { /* Generic Tag Operations */ public static CompoundNBT getTagSafe(ItemStack stack) { - if(stack.isEmpty() || !stack.hasTag()) { + if (stack.isEmpty() || !stack.hasTag()) { return new CompoundNBT(); } @@ -23,7 +23,7 @@ public class TagHelper { } public static CompoundNBT getTagSafe(CompoundNBT tag, String key) { - if(tag == null || !tag.contains(key)) { + if (tag == null || !tag.contains(key)) { return new CompoundNBT(); } @@ -31,7 +31,7 @@ public class TagHelper { } public static ListNBT getTagListSafe(CompoundNBT tag, String key, int type) { - if(tag == null || !tag.contains(key)) { + if (tag == null || !tag.contains(key)) { return new ListNBT(); } diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info deleted file mode 100644 index 65dd6b3..0000000 --- a/src/main/resources/mcmod.info +++ /dev/null @@ -1,18 +0,0 @@ -[{ - "modid": "mantle", - "name": "Mantle", - "description": "Shared code for Slime Knights mods and others.", - "version": "${version}", - "logoFile": "Mantle.png", - "mcversion": "${MCversion}", - "url": "https://github.com/SlimeKnights/Mantle", - "updateUrl": "", - "authorList": [ "boni", "progWML6", "Alexbegt" ], - "credits": "mDiyo, Sunstrike", - "screenshots": [], - "parent": "", - "requiredMods": [], - "dependencies": [], - "dependants": [], - "useDependencyInformation": false -}]