From 7b5f055d224dc1bf3f758753a1c7df9778ad331b Mon Sep 17 00:00:00 2001 From: grimmauld Date: Fri, 29 Jan 2021 23:12:11 +0100 Subject: [PATCH 1/2] Get stuff running on 1.16.3 --- .gitignore | 1 + build.gradle | 7 +- .../effortlessbuilding/BuildConfig.java | 208 ++-- .../EffortlessBuilding.java | 167 ++-- .../effortlessbuilding/EventHandler.java | 256 +++-- .../ModClientEventHandler.java | 50 +- .../effortlessbuilding/ModEventHandler.java | 34 +- .../buildmode/BaseBuildMode.java | 48 +- .../buildmode/BuildModes.java | 392 ++++---- .../buildmode/IBuildMode.java | 20 +- .../buildmode/ModeOptions.java | 310 +++--- .../buildmode/ModeSettingsManager.java | 124 +-- .../buildmode/ThreeClicksBuildMode.java | 322 +++--- .../buildmode/TwoClicksBuildMode.java | 117 ++- .../buildmode/buildmodes/Circle.java | 121 +-- .../buildmode/buildmodes/Cube.java | 143 +-- .../buildmode/buildmodes/Cylinder.java | 60 +- .../buildmode/buildmodes/DiagonalLine.java | 68 +- .../buildmode/buildmodes/DiagonalWall.java | 62 +- .../buildmode/buildmodes/Floor.java | 123 +-- .../buildmode/buildmodes/Line.java | 217 ++-- .../buildmode/buildmodes/Normal.java | 48 +- .../buildmode/buildmodes/NormalPlus.java | 48 +- .../buildmode/buildmodes/SlopeFloor.java | 124 +-- .../buildmode/buildmodes/Sphere.java | 150 +-- .../buildmode/buildmodes/Wall.java | 195 ++-- .../buildmodifier/Array.java | 132 ++- .../buildmodifier/BlockSet.java | 68 +- .../buildmodifier/BuildModifiers.java | 377 +++---- .../buildmodifier/Mirror.java | 341 ++++--- .../ModifierSettingsManager.java | 318 +++--- .../buildmodifier/RadialMirror.java | 279 +++--- .../buildmodifier/UndoRedo.java | 342 ++++--- .../ItemHandlerCapabilityProvider.java | 28 +- .../capability/ModeCapabilityManager.java | 122 +-- .../capability/ModifierCapabilityManager.java | 261 +++-- .../command/CommandReach.java | 42 +- .../compatibility/CompatHelper.java | 134 ++- .../gui/FontRenderHelper.java | 71 ++ .../gui/RandomizerBagContainer.java | 198 ++-- .../gui/RandomizerBagScreen.java | 54 +- .../gui/buildmode/PlayerSettingsGui.java | 451 ++++----- .../gui/buildmode/RadialMenu.java | 925 +++++++++--------- .../gui/buildmodifier/ArraySettingsGui.java | 293 +++--- .../gui/buildmodifier/MirrorSettingsGui.java | 441 ++++----- .../buildmodifier/ModifierSettingsGui.java | 180 ++-- .../RadialMirrorSettingsGui.java | 447 ++++----- .../gui/elements/GuiCheckBoxFixed.java | 89 +- .../elements/GuiCollapsibleScrollEntry.java | 116 +-- .../gui/elements/GuiIconButton.java | 108 +- .../gui/elements/GuiNumberField.java | 196 ++-- .../gui/elements/GuiScrollPane.java | 686 ++++++------- .../gui/elements/SlotGui.java | 421 ++++++++ .../effortlessbuilding/helper/FixedStack.java | 74 +- .../helper/InventoryHelper.java | 38 +- .../helper/ReachHelper.java | 74 +- .../helper/SurvivalHelper.java | 394 ++++---- .../item/ItemRandomizerBag.java | 348 +++---- .../item/ItemReachUpgrade1.java | 71 +- .../item/ItemReachUpgrade2.java | 81 +- .../item/ItemReachUpgrade3.java | 87 +- .../network/AddUndoMessage.java | 118 +-- .../network/BlockBrokenMessage.java | 129 ++- .../network/BlockPlacedMessage.java | 157 ++- .../network/CancelModeMessage.java | 30 +- .../network/ClearUndoMessage.java | 42 +- .../network/ModeActionMessage.java | 46 +- .../network/ModeSettingsMessage.java | 50 +- .../network/ModifierSettingsMessage.java | 206 ++-- .../network/PacketHandler.java | 38 +- .../network/RequestLookAtMessage.java | 74 +- .../network/TranslatedLogMessage.java | 106 +- .../effortlessbuilding/proxy/ClientProxy.java | 553 ++++++----- .../effortlessbuilding/proxy/IProxy.java | 8 +- .../effortlessbuilding/proxy/ServerProxy.java | 27 +- .../render/BlockPreviewRenderer.java | 689 +++++++------ .../render/BuildRenderTypes.java | 277 +++--- .../render/ModifierRenderer.java | 238 +++-- .../render/RenderHandler.java | 292 +++--- .../render/ShaderHandler.java | 275 +++--- .../resources/META-INF/accesstransformer.cfg | 2 + src/main/resources/META-INF/mods.toml | 7 +- 82 files changed, 7751 insertions(+), 7315 deletions(-) create mode 100644 src/main/java/nl/requios/effortlessbuilding/gui/FontRenderHelper.java create mode 100644 src/main/java/nl/requios/effortlessbuilding/gui/elements/SlotGui.java create mode 100644 src/main/resources/META-INF/accesstransformer.cfg diff --git a/.gitignore b/.gitignore index 12f8644..74c1d06 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,7 @@ build # other eclipse run +logs/* # Files from Forge MDK forge*changelog.txt diff --git a/build.gradle b/build.gradle index 34f91c2..159d178 100644 --- a/build.gradle +++ b/build.gradle @@ -13,7 +13,7 @@ apply plugin: 'net.minecraftforge.gradle' apply plugin: 'eclipse' apply plugin: 'maven-publish' -version = '1.15.2-2.20' +version = '1.16.3-2.20' group = 'nl.requios.effortlessbuilding' // http://maven.apache.org/guides/mini/guide-naming-conventions.html archivesBaseName = 'effortlessbuilding' @@ -25,7 +25,8 @@ minecraft { // stable_# Stables are built at the discretion of the MCP team. // Use non-default mappings at your own risk. they may not always work. // Simply re-run your setup task after changing the mappings to update your workspace. - mappings channel: 'snapshot', version: '20200514-1.15.1' + mappings channel: 'snapshot', version: '20201028-1.16.3' + accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable. // accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') @@ -89,7 +90,7 @@ dependencies { // Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed // that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied. // The userdev artifact is a special name and will get all sorts of transformations applied to it. - minecraft 'net.minecraftforge:forge:1.15.2-31.2.0' + minecraft 'net.minecraftforge:forge:1.16.3-34.0.9' // You may put jars on which you depend on in ./libs or you may define them like so.. // compile "some.group:artifact:version:classifier" diff --git a/src/main/java/nl/requios/effortlessbuilding/BuildConfig.java b/src/main/java/nl/requios/effortlessbuilding/BuildConfig.java index 003af42..48a255a 100644 --- a/src/main/java/nl/requios/effortlessbuilding/BuildConfig.java +++ b/src/main/java/nl/requios/effortlessbuilding/BuildConfig.java @@ -4,131 +4,131 @@ import net.minecraftforge.common.ForgeConfigSpec; public class BuildConfig { - private static final ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder(); - public static final Reach reach = new Reach(builder); - public static final SurvivalBalancers survivalBalancers = new SurvivalBalancers(builder); - public static final Visuals visuals = new Visuals(builder); - public static final ForgeConfigSpec spec = builder.build(); + private static final ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder(); + public static final Reach reach = new Reach(builder); + public static final SurvivalBalancers survivalBalancers = new SurvivalBalancers(builder); + public static final Visuals visuals = new Visuals(builder); + public static final ForgeConfigSpec spec = builder.build(); - public static class Reach { - public final ForgeConfigSpec.ConfigValue enableReachUpgrades; - public final ForgeConfigSpec.ConfigValue maxReachCreative; - public final ForgeConfigSpec.ConfigValue maxReachLevel0; - public final ForgeConfigSpec.ConfigValue maxReachLevel1; - public final ForgeConfigSpec.ConfigValue maxReachLevel2; - public final ForgeConfigSpec.ConfigValue maxReachLevel3; + public static class Reach { + public final ForgeConfigSpec.ConfigValue enableReachUpgrades; + public final ForgeConfigSpec.ConfigValue maxReachCreative; + public final ForgeConfigSpec.ConfigValue maxReachLevel0; + public final ForgeConfigSpec.ConfigValue maxReachLevel1; + public final ForgeConfigSpec.ConfigValue maxReachLevel2; + public final ForgeConfigSpec.ConfigValue maxReachLevel3; - public Reach(ForgeConfigSpec.Builder builder) { - builder.push("Reach"); - enableReachUpgrades = builder - .comment("Reach: how far away the player can place blocks using mirror/array etc.", - "Enable the crafting of reach upgrades to increase reach.", - "If disabled, reach is set to level 3 for survival players.") - .define("enableReachUpgrades", true); + public Reach(ForgeConfigSpec.Builder builder) { + builder.push("Reach"); + enableReachUpgrades = builder + .comment("Reach: how far away the player can place blocks using mirror/array etc.", + "Enable the crafting of reach upgrades to increase reach.", + "If disabled, reach is set to level 3 for survival players.") + .define("enableReachUpgrades", true); - maxReachCreative = builder - .comment("Maximum reach in creative", - "Keep in mind that chunks need to be loaded to be able to place blocks inside.") - .define("maxReachCreative", 200); + maxReachCreative = builder + .comment("Maximum reach in creative", + "Keep in mind that chunks need to be loaded to be able to place blocks inside.") + .define("maxReachCreative", 200); - maxReachLevel0 = builder - .comment("Maximum reach in survival without upgrades", - "Reach upgrades are craftable consumables that permanently increase reach.", - "Set to 0 to disable Effortless Building until the player has consumed a reach upgrade.") - .define("maxReachLevel0", 20); + maxReachLevel0 = builder + .comment("Maximum reach in survival without upgrades", + "Reach upgrades are craftable consumables that permanently increase reach.", + "Set to 0 to disable Effortless Building until the player has consumed a reach upgrade.") + .define("maxReachLevel0", 20); - maxReachLevel1 = builder - .comment("Maximum reach in survival with one upgrade") - .define("maxReachLevel1", 50); + maxReachLevel1 = builder + .comment("Maximum reach in survival with one upgrade") + .define("maxReachLevel1", 50); - maxReachLevel2 = builder - .comment("Maximum reach in survival with two upgrades") - .define("maxReachLevel2", 100); + maxReachLevel2 = builder + .comment("Maximum reach in survival with two upgrades") + .define("maxReachLevel2", 100); - maxReachLevel3 = builder - .comment("Maximum reach in survival with three upgrades") - .define("maxReachLevel3", 200); + maxReachLevel3 = builder + .comment("Maximum reach in survival with three upgrades") + .define("maxReachLevel3", 200); - builder.pop(); - } - } + builder.pop(); + } + } - public static class SurvivalBalancers { - public final ForgeConfigSpec.ConfigValue breakFar; - public final ForgeConfigSpec.ConfigValue increasedMiningTime; - public final ForgeConfigSpec.ConfigValue miningTimePercentage; - public final ForgeConfigSpec.ConfigValue quickReplaceMiningLevel; - public final ForgeConfigSpec.ConfigValue undoStackSize; + public static class SurvivalBalancers { + public final ForgeConfigSpec.ConfigValue breakFar; + public final ForgeConfigSpec.ConfigValue increasedMiningTime; + public final ForgeConfigSpec.ConfigValue miningTimePercentage; + public final ForgeConfigSpec.ConfigValue quickReplaceMiningLevel; + public final ForgeConfigSpec.ConfigValue undoStackSize; - public SurvivalBalancers(ForgeConfigSpec.Builder builder) { - builder.push("SurvivalBalancers"); + public SurvivalBalancers(ForgeConfigSpec.Builder builder) { + builder.push("SurvivalBalancers"); - breakFar = builder - .comment("Allows a survival player to break blocks that are far away, in addition to placing blocks.", - "Note: this allows insta-breaking of blocks in survival.") - .define("breakFar", false); + breakFar = builder + .comment("Allows a survival player to break blocks that are far away, in addition to placing blocks.", + "Note: this allows insta-breaking of blocks in survival.") + .define("breakFar", false); - increasedMiningTime = builder - .comment("Increases the time to mine a block when breaking multiple at once.", - "Mining time depends on how many blocks, what type of blocks, and the percentage below.", - "Example: breaking 1 dirt + 1 obsidian takes the time of breaking 1 dirt + 1 obsidian.") - .define("increasedMiningTime", true); + increasedMiningTime = builder + .comment("Increases the time to mine a block when breaking multiple at once.", + "Mining time depends on how many blocks, what type of blocks, and the percentage below.", + "Example: breaking 1 dirt + 1 obsidian takes the time of breaking 1 dirt + 1 obsidian.") + .define("increasedMiningTime", true); - miningTimePercentage = builder - .comment("How much the mining time of each additional block counts towards an increased mining time.", - "A percentage between 0% and 100%, where 0% is the same as disabling it,", - "and 100% takes as much time as breaking each block individually.", - "The block in front of you always counts as 100%.") - .defineInRange("miningTimePercentage", 50, 0, 200); + miningTimePercentage = builder + .comment("How much the mining time of each additional block counts towards an increased mining time.", + "A percentage between 0% and 100%, where 0% is the same as disabling it,", + "and 100% takes as much time as breaking each block individually.", + "The block in front of you always counts as 100%.") + .defineInRange("miningTimePercentage", 50, 0, 200); - quickReplaceMiningLevel = builder - .comment("Determines what blocks can be replaced in survival.", - "-1: only blocks that can be harvested by hand (default)", - "0: blocks that can be harvested with wooden or gold tools", - "1: blocks that can be harvested with stone tools", - "2: blocks that can be harvested with iron tools", - "3: blocks that can be harvested with diamond tools") - .defineInRange("quickReplaceMiningLevel", -1, -1, 3); + quickReplaceMiningLevel = builder + .comment("Determines what blocks can be replaced in survival.", + "-1: only blocks that can be harvested by hand (default)", + "0: blocks that can be harvested with wooden or gold tools", + "1: blocks that can be harvested with stone tools", + "2: blocks that can be harvested with iron tools", + "3: blocks that can be harvested with diamond tools") + .defineInRange("quickReplaceMiningLevel", -1, -1, 3); - undoStackSize = builder - .comment("How many placements are remembered for the undo functionality.") - .worldRestart() - .define("undoStackSize", 10); + undoStackSize = builder + .comment("How many placements are remembered for the undo functionality.") + .worldRestart() + .define("undoStackSize", 10); - builder.pop(); - } - } + builder.pop(); + } + } - public static class Visuals { - public final ForgeConfigSpec.ConfigValue alwaysShowBlockPreview; - public final ForgeConfigSpec.ConfigValue dissolveTimeMultiplier; - public final ForgeConfigSpec.ConfigValue shaderTreshold; - public final ForgeConfigSpec.ConfigValue useShaders; + public static class Visuals { + public final ForgeConfigSpec.ConfigValue alwaysShowBlockPreview; + public final ForgeConfigSpec.ConfigValue dissolveTimeMultiplier; + public final ForgeConfigSpec.ConfigValue shaderTreshold; + public final ForgeConfigSpec.ConfigValue useShaders; - public Visuals(ForgeConfigSpec.Builder builder) { - builder.push("Visuals"); + public Visuals(ForgeConfigSpec.Builder builder) { + builder.push("Visuals"); - alwaysShowBlockPreview = builder - .comment("Show a block preview if you have a block in hand even in the 'Normal' build mode") - .define("alwaysShowBlockPreview", false); + alwaysShowBlockPreview = builder + .comment("Show a block preview if you have a block in hand even in the 'Normal' build mode") + .define("alwaysShowBlockPreview", false); - dissolveTimeMultiplier = builder - .comment("How long the dissolve effect takes when placing blocks.", - "Default between 30 and 60 ticks, you can multiply that here.", - "Recommended values:", - "Snappy: 0.7", - "Relaxing: 1.5") - .define("dissolveTimeMultiplier", 1.0); + dissolveTimeMultiplier = builder + .comment("How long the dissolve effect takes when placing blocks.", + "Default between 30 and 60 ticks, you can multiply that here.", + "Recommended values:", + "Snappy: 0.7", + "Relaxing: 1.5") + .define("dissolveTimeMultiplier", 1.0); - shaderTreshold = builder - .comment("Switch to using the simple performance shader when placing more than this many blocks.") - .define("shaderTreshold", 1500); + shaderTreshold = builder + .comment("Switch to using the simple performance shader when placing more than this many blocks.") + .define("shaderTreshold", 1500); - useShaders = builder - .comment("Use fancy shaders while placing blocks") - .define("useShaders", true); + useShaders = builder + .comment("Use fancy shaders while placing blocks") + .define("useShaders", true); - builder.pop(); - } - } + builder.pop(); + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/EffortlessBuilding.java b/src/main/java/nl/requios/effortlessbuilding/EffortlessBuilding.java index 1ac3486..d12f8cb 100644 --- a/src/main/java/nl/requios/effortlessbuilding/EffortlessBuilding.java +++ b/src/main/java/nl/requios/effortlessbuilding/EffortlessBuilding.java @@ -10,10 +10,8 @@ import net.minecraft.util.registry.Registry; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.CapabilityManager; -import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.ExtensionPoint; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; @@ -41,117 +39,108 @@ import org.apache.logging.log4j.Logger; // The value here should match an entry in the META-INF/mods.toml file @Mod(EffortlessBuilding.MODID) -@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD) -public class EffortlessBuilding -{ - public static final String MODID = "effortlessbuilding"; - public static final String NAME = "Effortless Building"; - public static final String VERSION = "1.15.2-2.20"; +@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) +public class EffortlessBuilding { + public static final String MODID = "effortlessbuilding"; + public static final String NAME = "Effortless Building"; + public static final String VERSION = "1.15.2-2.20"; + public static final Logger logger = LogManager.getLogger(); + public static final ItemRandomizerBag ITEM_RANDOMIZER_BAG = new ItemRandomizerBag(); + public static final ItemReachUpgrade1 ITEM_REACH_UPGRADE_1 = new ItemReachUpgrade1(); + public static final ItemReachUpgrade2 ITEM_REACH_UPGRADE_2 = new ItemReachUpgrade2(); + public static final ItemReachUpgrade3 ITEM_REACH_UPGRADE_3 = new ItemReachUpgrade3(); + public static final Block[] BLOCKS = { + }; + public static final Item[] ITEMS = { + ITEM_RANDOMIZER_BAG, + ITEM_REACH_UPGRADE_1, + ITEM_REACH_UPGRADE_2, + ITEM_REACH_UPGRADE_3 + }; + public static final ContainerType RANDOMIZER_BAG_CONTAINER = register("randomizer_bag", RandomizerBagContainer::new); + public static final ResourceLocation RANDOMIZER_BAG_GUI = new ResourceLocation(EffortlessBuilding.MODID, "randomizer_bag"); + public static EffortlessBuilding instance; + public static IProxy proxy = DistExecutor.runForDist(() -> ClientProxy::new, () -> ServerProxy::new); - public static EffortlessBuilding instance; + public EffortlessBuilding() { + instance = this; - public static final Logger logger = LogManager.getLogger(); + // Register the setup method for modloading + FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); + // Register the enqueueIMC method for modloading + FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); + // Register the processIMC method for modloading + FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC); + // Register the clientSetup method for modloading + FMLJavaModLoadingContext.get().getModEventBus().addListener(this::clientSetup); - public static IProxy proxy = DistExecutor.runForDist(() -> ClientProxy::new, () -> ServerProxy::new); + //Register config + ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, BuildConfig.spec); - public static final ItemRandomizerBag ITEM_RANDOMIZER_BAG = new ItemRandomizerBag(); - public static final ItemReachUpgrade1 ITEM_REACH_UPGRADE_1 = new ItemReachUpgrade1(); - public static final ItemReachUpgrade2 ITEM_REACH_UPGRADE_2 = new ItemReachUpgrade2(); - public static final ItemReachUpgrade3 ITEM_REACH_UPGRADE_3 = new ItemReachUpgrade3(); + // Register ourselves for server and other game events we are interested in + MinecraftForge.EVENT_BUS.register(this); + } - public static final Block[] BLOCKS = { - }; + private static ContainerType register(String key, ContainerType.IFactory factory) { + return Registry.register(Registry.MENU, key, new ContainerType<>(factory)); + } - public static final Item[] ITEMS = { - ITEM_RANDOMIZER_BAG, - ITEM_REACH_UPGRADE_1, - ITEM_REACH_UPGRADE_2, - ITEM_REACH_UPGRADE_3 - }; + public static void log(String msg) { + logger.info(msg); + } - public static final ContainerType RANDOMIZER_BAG_CONTAINER = register("randomizer_bag", RandomizerBagContainer::new); - public static final ResourceLocation RANDOMIZER_BAG_GUI = new ResourceLocation(EffortlessBuilding.MODID, "randomizer_bag"); + public static void log(PlayerEntity player, String msg) { + log(player, msg, false); + } - public EffortlessBuilding() { - instance = this; + public static void log(PlayerEntity player, String msg, boolean actionBar) { + player.sendStatusMessage(new StringTextComponent(msg), actionBar); + } - // Register the setup method for modloading - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); - // Register the enqueueIMC method for modloading - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); - // Register the processIMC method for modloading - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC); - // Register the clientSetup method for modloading - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::clientSetup); + //Log with translation supported, call either on client or server (which then sends a message) + public static void logTranslate(PlayerEntity player, String prefix, String translationKey, String suffix, boolean actionBar) { + proxy.logTranslate(player, prefix, translationKey, suffix, actionBar); + } - //Register config - ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, BuildConfig.spec); + @SubscribeEvent + public void setup(final FMLCommonSetupEvent event) { + CapabilityManager.INSTANCE.register(ModifierCapabilityManager.IModifierCapability.class, new ModifierCapabilityManager.Storage(), ModifierCapabilityManager.ModifierCapability::new); + CapabilityManager.INSTANCE.register(ModeCapabilityManager.IModeCapability.class, new ModeCapabilityManager.Storage(), ModeCapabilityManager.ModeCapability::new); - // Register ourselves for server and other game events we are interested in - MinecraftForge.EVENT_BUS.register(this); - } + PacketHandler.register(); - @SubscribeEvent - public void setup(final FMLCommonSetupEvent event) - { - CapabilityManager.INSTANCE.register(ModifierCapabilityManager.IModifierCapability.class, new ModifierCapabilityManager.Storage(), ModifierCapabilityManager.ModifierCapability::new); - CapabilityManager.INSTANCE.register(ModeCapabilityManager.IModeCapability.class, new ModeCapabilityManager.Storage(), ModeCapabilityManager.ModeCapability::new); - - PacketHandler.register(); - - //TODO 1.13 config + //TODO 1.13 config // ConfigManager.sync(MODID, Config.Type.INSTANCE); - proxy.setup(event); + proxy.setup(event); - CompatHelper.setup(); - } + CompatHelper.setup(); + } - @SubscribeEvent - public void clientSetup(final FMLClientSetupEvent event) { + @SubscribeEvent + public void clientSetup(final FMLClientSetupEvent event) { - proxy.clientSetup(event); - } + proxy.clientSetup(event); + } - @SubscribeEvent - public void enqueueIMC(final InterModEnqueueEvent event) { + @SubscribeEvent + public void enqueueIMC(final InterModEnqueueEvent event) { - // some example code to dispatch IMC to another mod + // some example code to dispatch IMC to another mod // InterModComms.sendTo("examplemod", "helloworld", () -> { logger.info("Hello world from the MDK"); return "Hello world";}); - } + } - @SubscribeEvent - public void processIMC(final InterModProcessEvent event) { + @SubscribeEvent + public void processIMC(final InterModProcessEvent event) { - // some example code to receive and process InterModComms from other mods + // some example code to receive and process InterModComms from other mods // logger.info("Got IMC {}", event.getIMCStream(). // map(m->m.getMessageSupplier().get()). // collect(Collectors.toList())); - } + } - @SubscribeEvent - public void onServerStarting(FMLServerStartingEvent event) { - CommandReach.register(event.getCommandDispatcher()); - } - - private static ContainerType register(String key, ContainerType.IFactory factory) { - return Registry.register(Registry.MENU, key, new ContainerType<>(factory)); - } - - public static void log(String msg){ - logger.info(msg); - } - - public static void log(PlayerEntity player, String msg){ - log(player, msg, false); - } - - public static void log(PlayerEntity player, String msg, boolean actionBar){ - player.sendStatusMessage(new StringTextComponent(msg), actionBar); - } - - //Log with translation supported, call either on client or server (which then sends a message) - public static void logTranslate(PlayerEntity player, String prefix, String translationKey, String suffix, boolean actionBar){ - proxy.logTranslate(player, prefix, translationKey, suffix, actionBar); - } + @SubscribeEvent + public void onServerStarting(FMLServerStartingEvent event) { + CommandReach.register(event.getServer().getCommandManager().getDispatcher()); + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/EventHandler.java b/src/main/java/nl/requios/effortlessbuilding/EventHandler.java index ae26eb6..d6ee46f 100644 --- a/src/main/java/nl/requios/effortlessbuilding/EventHandler.java +++ b/src/main/java/nl/requios/effortlessbuilding/EventHandler.java @@ -8,7 +8,6 @@ import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.world.BlockEvent; @@ -32,18 +31,17 @@ import nl.requios.effortlessbuilding.network.RequestLookAtMessage; import java.util.List; @Mod.EventBusSubscriber -public class EventHandler -{ +public class EventHandler { - @SubscribeEvent - public static void attachCapabilities(AttachCapabilitiesEvent event) { - if (event.getObject() instanceof PlayerEntity) { - event.addCapability(new ResourceLocation(EffortlessBuilding.MODID, "build_modifier"), new ModifierCapabilityManager.Provider()); - event.addCapability(new ResourceLocation(EffortlessBuilding.MODID, "build_mode"), new ModeCapabilityManager.Provider()); - } - } + @SubscribeEvent + public static void attachCapabilities(AttachCapabilitiesEvent event) { + if (event.getObject() instanceof PlayerEntity) { + event.addCapability(new ResourceLocation(EffortlessBuilding.MODID, "build_modifier"), new ModifierCapabilityManager.Provider()); + event.addCapability(new ResourceLocation(EffortlessBuilding.MODID, "build_mode"), new ModeCapabilityManager.Provider()); + } + } - //TODO 1.13 config + //TODO 1.13 config // @SubscribeEvent // public static void onConfigChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) // { @@ -58,152 +56,152 @@ public class EventHandler // // } - @SubscribeEvent - //Only called serverside (except with lilypads...) - public static void onBlockPlaced(BlockEvent.EntityPlaceEvent event) { - if (event.getWorld().isRemote()) return; + @SubscribeEvent + //Only called serverside (except with lilypads...) + public static void onBlockPlaced(BlockEvent.EntityPlaceEvent event) { + if (event.getWorld().isRemote()) return; - if (!(event.getEntity() instanceof PlayerEntity)) return; + if (!(event.getEntity() instanceof PlayerEntity)) return; - //Cancel event if necessary - ServerPlayerEntity player = ((ServerPlayerEntity) event.getEntity()); - BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(player).getBuildMode(); - ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); + //Cancel event if necessary + ServerPlayerEntity player = ((ServerPlayerEntity) event.getEntity()); + BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(player).getBuildMode(); + ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); - if (buildMode != BuildModes.BuildModeEnum.NORMAL) { - event.setCanceled(true); - } else if (modifierSettings.doQuickReplace()) { - //Cancel event and send message if QuickReplace - event.setCanceled(true); - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new RequestLookAtMessage(true)); - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new AddUndoMessage(event.getPos(), event.getBlockSnapshot().getReplacedBlock(), event.getState())); - } else { - //NORMAL mode, let vanilla handle block placing - //But modifiers should still work + if (buildMode != BuildModes.BuildModeEnum.NORMAL) { + event.setCanceled(true); + } else if (modifierSettings.doQuickReplace()) { + //Cancel event and send message if QuickReplace + event.setCanceled(true); + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new RequestLookAtMessage(true)); + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new AddUndoMessage(event.getPos(), event.getBlockSnapshot().getReplacedBlock(), event.getState())); + } else { + //NORMAL mode, let vanilla handle block placing + //But modifiers should still work - //Send message to client, which sends message back with raytrace info - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new RequestLookAtMessage(false)); - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new AddUndoMessage(event.getPos(), event.getBlockSnapshot().getReplacedBlock(), event.getState())); - } + //Send message to client, which sends message back with raytrace info + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new RequestLookAtMessage(false)); + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new AddUndoMessage(event.getPos(), event.getBlockSnapshot().getReplacedBlock(), event.getState())); + } // Stat blocksPlacedStat = StatList.CUSTOM.get(new ResourceLocation(EffortlessBuilding.MODID, "blocks_placed")); // player.getStats().increment(player, blocksPlacedStat, 1); // // System.out.println(player.getStats().getValue(blocksPlacedStat)); - } + } - @SubscribeEvent - public static void onBlockBroken(BlockEvent.BreakEvent event) { - if (event.getWorld().isRemote()) return; + @SubscribeEvent + public static void onBlockBroken(BlockEvent.BreakEvent event) { + if (event.getWorld().isRemote()) return; - //Cancel event if necessary - //If cant break far then dont cancel event ever - BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(event.getPlayer()).getBuildMode(); - if (buildMode != BuildModes.BuildModeEnum.NORMAL && ReachHelper.canBreakFar(event.getPlayer())) { - event.setCanceled(true); - } else { - //NORMAL mode, let vanilla handle block breaking - //But modifiers and QuickReplace should still work - //Dont break the original block yourself, otherwise Tinkers Hammer and Veinminer won't work - BuildModes.onBlockBroken(event.getPlayer(), event.getPos(), false); + //Cancel event if necessary + //If cant break far then dont cancel event ever + BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(event.getPlayer()).getBuildMode(); + if (buildMode != BuildModes.BuildModeEnum.NORMAL && ReachHelper.canBreakFar(event.getPlayer())) { + event.setCanceled(true); + } else { + //NORMAL mode, let vanilla handle block breaking + //But modifiers and QuickReplace should still work + //Dont break the original block yourself, otherwise Tinkers Hammer and Veinminer won't work + BuildModes.onBlockBroken(event.getPlayer(), event.getPos(), false); - //Add to undo stack in client - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) event.getPlayer()), new AddUndoMessage(event.getPos(), event.getState(), Blocks.AIR.getDefaultState())); - } - } + //Add to undo stack in client + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) event.getPlayer()), new AddUndoMessage(event.getPos(), event.getState(), Blocks.AIR.getDefaultState())); + } + } - @SubscribeEvent - public static void breakSpeed(PlayerEvent.BreakSpeed event) { - //Disable if config says so - if (!BuildConfig.survivalBalancers.increasedMiningTime.get()) return; + @SubscribeEvent + public static void breakSpeed(PlayerEvent.BreakSpeed event) { + //Disable if config says so + if (!BuildConfig.survivalBalancers.increasedMiningTime.get()) return; - PlayerEntity player = event.getPlayer(); - World world = player.world; - BlockPos pos = event.getPos(); + PlayerEntity player = event.getPlayer(); + World world = player.world; + BlockPos pos = event.getPos(); - //EffortlessBuilding.log(player, String.valueOf(event.getNewSpeed())); + //EffortlessBuilding.log(player, String.valueOf(event.getNewSpeed())); - float originalBlockHardness = event.getState().getBlockHardness(world, pos); - if (originalBlockHardness < 0) return; //Dont break bedrock - float totalBlockHardness = 0; - //get coordinates - List coordinates = BuildModifiers.findCoordinates(player, pos); - for (int i = 1; i < coordinates.size(); i++) { - BlockPos coordinate = coordinates.get(i); - //get existing blockstates at those coordinates - BlockState blockState = world.getBlockState(coordinate); - //add hardness for each blockstate, if can break - if (SurvivalHelper.canBreak(world, player, coordinate)) - totalBlockHardness += blockState.getBlockHardness(world, coordinate); - } + float originalBlockHardness = event.getState().getBlockHardness(world, pos); + if (originalBlockHardness < 0) return; //Dont break bedrock + float totalBlockHardness = 0; + //get coordinates + List coordinates = BuildModifiers.findCoordinates(player, pos); + for (int i = 1; i < coordinates.size(); i++) { + BlockPos coordinate = coordinates.get(i); + //get existing blockstates at those coordinates + BlockState blockState = world.getBlockState(coordinate); + //add hardness for each blockstate, if can break + if (SurvivalHelper.canBreak(world, player, coordinate)) + totalBlockHardness += blockState.getBlockHardness(world, coordinate); + } - //Grabbing percentage from config - float percentage = (float) BuildConfig.survivalBalancers.miningTimePercentage.get() / 100; - totalBlockHardness *= percentage; - totalBlockHardness += originalBlockHardness; + //Grabbing percentage from config + float percentage = (float) BuildConfig.survivalBalancers.miningTimePercentage.get() / 100; + totalBlockHardness *= percentage; + totalBlockHardness += originalBlockHardness; - float newSpeed = event.getOriginalSpeed() / totalBlockHardness * originalBlockHardness; - if (Float.isNaN(newSpeed) || newSpeed == 0f) newSpeed = 1f; - event.setNewSpeed(newSpeed); + float newSpeed = event.getOriginalSpeed() / totalBlockHardness * originalBlockHardness; + if (Float.isNaN(newSpeed) || newSpeed == 0f) newSpeed = 1f; + event.setNewSpeed(newSpeed); - //EffortlessBuilding.log(player, String.valueOf(event.getNewSpeed())); - } + //EffortlessBuilding.log(player, String.valueOf(event.getNewSpeed())); + } - @SubscribeEvent - public static void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { - PlayerEntity player = event.getPlayer(); - ModifierSettingsManager.handleNewPlayer(player); - ModeSettingsManager.handleNewPlayer(player); - } + @SubscribeEvent + public static void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { + PlayerEntity player = event.getPlayer(); + ModifierSettingsManager.handleNewPlayer(player); + ModeSettingsManager.handleNewPlayer(player); + } - @SubscribeEvent - public static void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) { - PlayerEntity player = event.getPlayer(); - if (player.getEntityWorld().isRemote) return; + @SubscribeEvent + public static void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) { + PlayerEntity player = event.getPlayer(); + if (player.getEntityWorld().isRemote) return; - UndoRedo.clear(player); - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new ClearUndoMessage()); - } + UndoRedo.clear(player); + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new ClearUndoMessage()); + } - @SubscribeEvent - public static void onPlayerRespawn(PlayerEvent.PlayerRespawnEvent event) { - PlayerEntity player = event.getPlayer(); - ModifierSettingsManager.handleNewPlayer(player); - ModeSettingsManager.handleNewPlayer(player); - } + @SubscribeEvent + public static void onPlayerRespawn(PlayerEvent.PlayerRespawnEvent event) { + PlayerEntity player = event.getPlayer(); + ModifierSettingsManager.handleNewPlayer(player); + ModeSettingsManager.handleNewPlayer(player); + } - @SubscribeEvent - public static void onPlayerChangedDimension(PlayerEvent.PlayerChangedDimensionEvent event) { - PlayerEntity player = event.getPlayer(); - if (player.getEntityWorld().isRemote) return; + @SubscribeEvent + public static void onPlayerChangedDimension(PlayerEvent.PlayerChangedDimensionEvent event) { + PlayerEntity player = event.getPlayer(); + if (player.getEntityWorld().isRemote) return; - //Set build mode to normal - ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); - modeSettings.setBuildMode(BuildModes.BuildModeEnum.NORMAL); - ModeSettingsManager.setModeSettings(player, modeSettings); + //Set build mode to normal + ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); + modeSettings.setBuildMode(BuildModes.BuildModeEnum.NORMAL); + ModeSettingsManager.setModeSettings(player, modeSettings); - //Disable modifiers - ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); - modifierSettings.getMirrorSettings().enabled = false; - modifierSettings.getRadialMirrorSettings().enabled = false; - modifierSettings.getArraySettings().enabled = false; - ModifierSettingsManager.setModifierSettings(player, modifierSettings); + //Disable modifiers + ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); + modifierSettings.getMirrorSettings().enabled = false; + modifierSettings.getRadialMirrorSettings().enabled = false; + modifierSettings.getArraySettings().enabled = false; + ModifierSettingsManager.setModifierSettings(player, modifierSettings); - ModifierSettingsManager.handleNewPlayer(player); - ModeSettingsManager.handleNewPlayer(player); + ModifierSettingsManager.handleNewPlayer(player); + ModeSettingsManager.handleNewPlayer(player); - UndoRedo.clear(player); - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new ClearUndoMessage()); - } + UndoRedo.clear(player); + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new ClearUndoMessage()); + } - @SubscribeEvent - public static void onPlayerClone(PlayerEvent.Clone event) { - //Attach capabilities on death, otherwise crash - PlayerEntity oldPlayer = event.getOriginal(); - oldPlayer.revive(); + @SubscribeEvent + public static void onPlayerClone(PlayerEvent.Clone event) { + //Attach capabilities on death, otherwise crash + PlayerEntity oldPlayer = event.getOriginal(); + oldPlayer.revive(); - PlayerEntity newPlayer = event.getPlayer(); - ModifierSettingsManager.setModifierSettings(newPlayer, ModifierSettingsManager.getModifierSettings(oldPlayer)); - ModeSettingsManager.setModeSettings(newPlayer, ModeSettingsManager.getModeSettings(oldPlayer)); - } + PlayerEntity newPlayer = event.getPlayer(); + ModifierSettingsManager.setModifierSettings(newPlayer, ModifierSettingsManager.getModifierSettings(oldPlayer)); + ModeSettingsManager.setModeSettings(newPlayer, ModeSettingsManager.getModeSettings(oldPlayer)); + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/ModClientEventHandler.java b/src/main/java/nl/requios/effortlessbuilding/ModClientEventHandler.java index 153c918..e88a05b 100644 --- a/src/main/java/nl/requios/effortlessbuilding/ModClientEventHandler.java +++ b/src/main/java/nl/requios/effortlessbuilding/ModClientEventHandler.java @@ -13,36 +13,34 @@ import nl.requios.effortlessbuilding.buildmode.ModeOptions; import java.util.HashMap; -@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD, value = {Dist.CLIENT}) +@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD, value = {Dist.CLIENT}) public class ModClientEventHandler { - private static final HashMap buildModeIcons = new HashMap<>(); - private static final HashMap modeOptionIcons = new HashMap<>(); + private static final HashMap buildModeIcons = new HashMap<>(); + private static final HashMap modeOptionIcons = new HashMap<>(); - @SubscribeEvent - public static void onTextureStitch(final TextureStitchEvent.Pre event) { - EffortlessBuilding.log("Stitching textures"); - //register icon textures - for (final BuildModes.BuildModeEnum mode : BuildModes.BuildModeEnum.values()) - { - final ResourceLocation spriteLocation = new ResourceLocation(EffortlessBuilding.MODID, "icons/" + mode.name().toLowerCase()); - event.addSprite(spriteLocation); - buildModeIcons.put(mode, spriteLocation); - } + @SubscribeEvent + public static void onTextureStitch(final TextureStitchEvent.Pre event) { + EffortlessBuilding.log("Stitching textures"); + //register icon textures + for (final BuildModes.BuildModeEnum mode : BuildModes.BuildModeEnum.values()) { + final ResourceLocation spriteLocation = new ResourceLocation(EffortlessBuilding.MODID, "icons/" + mode.name().toLowerCase()); + event.addSprite(spriteLocation); + buildModeIcons.put(mode, spriteLocation); + } - for (final ModeOptions.ActionEnum action : ModeOptions.ActionEnum.values()) - { - final ResourceLocation spriteLocation = new ResourceLocation(EffortlessBuilding.MODID, "icons/" + action.name().toLowerCase()); - event.addSprite(spriteLocation); - modeOptionIcons.put(action, spriteLocation); - } - } + for (final ModeOptions.ActionEnum action : ModeOptions.ActionEnum.values()) { + final ResourceLocation spriteLocation = new ResourceLocation(EffortlessBuilding.MODID, "icons/" + action.name().toLowerCase()); + event.addSprite(spriteLocation); + modeOptionIcons.put(action, spriteLocation); + } + } - public static TextureAtlasSprite getBuildModeIcon(BuildModes.BuildModeEnum mode) { - return Minecraft.getInstance().getModelManager().getAtlasTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE).getSprite(buildModeIcons.get(mode)); - } + public static TextureAtlasSprite getBuildModeIcon(BuildModes.BuildModeEnum mode) { + return Minecraft.getInstance().getModelManager().getAtlasTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE).getSprite(buildModeIcons.get(mode)); + } - public static TextureAtlasSprite getModeOptionIcon(ModeOptions.ActionEnum action) { - return Minecraft.getInstance().getModelManager().getAtlasTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE).getSprite(modeOptionIcons.get(action)); - } + public static TextureAtlasSprite getModeOptionIcon(ModeOptions.ActionEnum action) { + return Minecraft.getInstance().getModelManager().getAtlasTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE).getSprite(modeOptionIcons.get(action)); + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/ModEventHandler.java b/src/main/java/nl/requios/effortlessbuilding/ModEventHandler.java index b4f28d3..7001f50 100644 --- a/src/main/java/nl/requios/effortlessbuilding/ModEventHandler.java +++ b/src/main/java/nl/requios/effortlessbuilding/ModEventHandler.java @@ -1,40 +1,30 @@ package nl.requios.effortlessbuilding; import net.minecraft.block.Block; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; -import nl.requios.effortlessbuilding.buildmode.BuildModes; -import nl.requios.effortlessbuilding.buildmode.ModeOptions; - -import java.util.HashMap; // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD // Event bus for receiving Registry Events) -@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD) +@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public class ModEventHandler { - @SubscribeEvent - public static void registerBlocks(RegistryEvent.Register event) { - event.getRegistry().registerAll(EffortlessBuilding.BLOCKS); - } + @SubscribeEvent + public static void registerBlocks(RegistryEvent.Register event) { + event.getRegistry().registerAll(EffortlessBuilding.BLOCKS); + } - @SubscribeEvent - public static void registerItems(RegistryEvent.Register event) { - event.getRegistry().registerAll(EffortlessBuilding.ITEMS); + @SubscribeEvent + public static void registerItems(RegistryEvent.Register event) { + event.getRegistry().registerAll(EffortlessBuilding.ITEMS); - for (Block block : EffortlessBuilding.BLOCKS) - { - event.getRegistry().register(new BlockItem(block, new Item.Properties()).setRegistryName(block.getRegistryName())); - } - } + for (Block block : EffortlessBuilding.BLOCKS) { + event.getRegistry().register(new BlockItem(block, new Item.Properties()).setRegistryName(block.getRegistryName())); + } + } // @SubscribeEvent // public static void registerContainerTypes(RegistryEvent.Register> event) { diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/BaseBuildMode.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/BaseBuildMode.java index 3a88aea..bbbcfd5 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/BaseBuildMode.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/BaseBuildMode.java @@ -3,37 +3,37 @@ package nl.requios.effortlessbuilding.buildmode; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import java.util.Dictionary; import java.util.Hashtable; import java.util.UUID; public abstract class BaseBuildMode implements IBuildMode { - //In singleplayer client and server variables are shared - //Split everything that needs separate values and may not be called twice in one click - protected Dictionary rightClickClientTable = new Hashtable<>(); - protected Dictionary rightClickServerTable = new Hashtable<>(); - protected Dictionary firstPosTable = new Hashtable<>(); - protected Dictionary sideHitTable = new Hashtable<>(); - protected Dictionary hitVecTable = new Hashtable<>(); + //In singleplayer client and server variables are shared + //Split everything that needs separate values and may not be called twice in one click + protected Dictionary rightClickClientTable = new Hashtable<>(); + protected Dictionary rightClickServerTable = new Hashtable<>(); + protected Dictionary firstPosTable = new Hashtable<>(); + protected Dictionary sideHitTable = new Hashtable<>(); + protected Dictionary hitVecTable = new Hashtable<>(); - @Override - public void initialize(PlayerEntity player) { - rightClickClientTable.put(player.getUniqueID(), 0); - rightClickServerTable.put(player.getUniqueID(), 0); - firstPosTable.put(player.getUniqueID(), BlockPos.ZERO); - sideHitTable.put(player.getUniqueID(), Direction.UP); - hitVecTable.put(player.getUniqueID(), Vec3d.ZERO); - } + @Override + public void initialize(PlayerEntity player) { + rightClickClientTable.put(player.getUniqueID(), 0); + rightClickServerTable.put(player.getUniqueID(), 0); + firstPosTable.put(player.getUniqueID(), BlockPos.ZERO); + sideHitTable.put(player.getUniqueID(), Direction.UP); + hitVecTable.put(player.getUniqueID(), Vector3d.ZERO); + } - @Override - public Direction getSideHit(PlayerEntity player) { - return sideHitTable.get(player.getUniqueID()); - } + @Override + public Direction getSideHit(PlayerEntity player) { + return sideHitTable.get(player.getUniqueID()); + } - @Override - public Vec3d getHitVec(PlayerEntity player) { - return hitVecTable.get(player.getUniqueID()); - } + @Override + public Vector3d getHitVec(PlayerEntity player) { + return hitVecTable.get(player.getUniqueID()); + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/BuildModes.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/BuildModes.java index ef563a0..db0bf3a 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/BuildModes.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/BuildModes.java @@ -5,7 +5,7 @@ import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceContext; import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.buildmode.buildmodes.*; import nl.requios.effortlessbuilding.buildmodifier.BuildModifiers; @@ -20,252 +20,252 @@ import java.util.Dictionary; import java.util.Hashtable; import java.util.List; -import static nl.requios.effortlessbuilding.buildmode.ModeOptions.*; +import static nl.requios.effortlessbuilding.buildmode.ModeOptions.OptionEnum; public class BuildModes { - //Static variables are shared between client and server in singleplayer - //We need them separate - public static Dictionary currentlyBreakingClient = new Hashtable<>(); - public static Dictionary currentlyBreakingServer = new Hashtable<>(); + //Static variables are shared between client and server in singleplayer + //We need them separate + public static Dictionary currentlyBreakingClient = new Hashtable<>(); + public static Dictionary currentlyBreakingServer = new Hashtable<>(); - public enum BuildModeEnum { - NORMAL("effortlessbuilding.mode.normal", new Normal()), - NORMAL_PLUS("effortlessbuilding.mode.normal_plus", new NormalPlus(), OptionEnum.BUILD_SPEED), - LINE("effortlessbuilding.mode.line", new Line() /*, OptionEnum.THICKNESS*/), - WALL("effortlessbuilding.mode.wall", new Wall(), OptionEnum.FILL), - FLOOR("effortlessbuilding.mode.floor", new Floor(), OptionEnum.FILL), - DIAGONAL_LINE("effortlessbuilding.mode.diagonal_line", new DiagonalLine() /*, OptionEnum.THICKNESS*/), - DIAGONAL_WALL("effortlessbuilding.mode.diagonal_wall", new DiagonalWall() /*, OptionEnum.FILL*/), - SLOPE_FLOOR("effortlessbuilding.mode.slope_floor", new SlopeFloor(), OptionEnum.RAISED_EDGE), - CIRCLE("effortlessbuilding.mode.circle", new Circle(), OptionEnum.CIRCLE_START, OptionEnum.FILL), - CYLINDER("effortlessbuilding.mode.cylinder", new Cylinder(), OptionEnum.CIRCLE_START, OptionEnum.FILL), - SPHERE("effortlessbuilding.mode.sphere", new Sphere(), OptionEnum.CIRCLE_START, OptionEnum.FILL), - CUBE("effortlessbuilding.mode.cube", new Cube(), OptionEnum.CUBE_FILL); + //Uses a network message to get the previous raytraceresult from the player + //The server could keep track of all raytraceresults but this might lag with many players + //Raytraceresult is needed for sideHit and hitVec + public static void onBlockPlacedMessage(PlayerEntity player, BlockPlacedMessage message) { - public String name; - public IBuildMode instance; - public OptionEnum[] options; + //Check if not in the middle of breaking + Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; + if (currentlyBreaking.get(player) != null && currentlyBreaking.get(player)) { + //Cancel breaking + initializeMode(player); + return; + } - BuildModeEnum(String name, IBuildMode instance, OptionEnum... options) { - this.name = name; - this.instance = instance; - this.options = options; - } - } + ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); + ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); + BuildModeEnum buildMode = modeSettings.getBuildMode(); - //Uses a network message to get the previous raytraceresult from the player - //The server could keep track of all raytraceresults but this might lag with many players - //Raytraceresult is needed for sideHit and hitVec - public static void onBlockPlacedMessage(PlayerEntity player, BlockPlacedMessage message) { + BlockPos startPos = null; - //Check if not in the middle of breaking - Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; - if (currentlyBreaking.get(player) != null && currentlyBreaking.get(player)) { - //Cancel breaking - initializeMode(player); - return; - } + if (message.isBlockHit() && message.getBlockPos() != null) { + startPos = message.getBlockPos(); - ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); - ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); - BuildModeEnum buildMode = modeSettings.getBuildMode(); + //Offset in direction of sidehit if not quickreplace and not replaceable + //TODO 1.13 replaceable + boolean replaceable = player.world.getBlockState(startPos).getMaterial().isReplaceable(); + boolean becomesDoubleSlab = SurvivalHelper.doesBecomeDoubleSlab(player, startPos, message.getSideHit()); + if (!modifierSettings.doQuickReplace() && !replaceable && !becomesDoubleSlab) { + startPos = startPos.offset(message.getSideHit()); + } - BlockPos startPos = null; + //Get under tall grass and other replaceable blocks + if (modifierSettings.doQuickReplace() && replaceable) { + startPos = startPos.down(); + } - if (message.isBlockHit() && message.getBlockPos() != null) { - startPos = message.getBlockPos(); + //Check if player reach does not exceed startpos + int maxReach = ReachHelper.getMaxReach(player); + if (buildMode != BuildModeEnum.NORMAL && player.getPosition().distanceSq(startPos) > maxReach * maxReach) { + EffortlessBuilding.log(player, "Placement exceeds your reach."); + return; + } + } - //Offset in direction of sidehit if not quickreplace and not replaceable - //TODO 1.13 replaceable - boolean replaceable = player.world.getBlockState(startPos).getMaterial().isReplaceable(); - boolean becomesDoubleSlab = SurvivalHelper.doesBecomeDoubleSlab(player, startPos, message.getSideHit()); - if (!modifierSettings.doQuickReplace() && !replaceable && !becomesDoubleSlab) { - startPos = startPos.offset(message.getSideHit()); - } + //Even when no starting block is found, call buildmode instance + //We might want to place things in the air + List coordinates = buildMode.instance.onRightClick(player, startPos, message.getSideHit(), message.getHitVec(), modifierSettings.doQuickReplace()); - //Get under tall grass and other replaceable blocks - if (modifierSettings.doQuickReplace() && replaceable) { - startPos = startPos.down(); - } + if (coordinates.isEmpty()) { + currentlyBreaking.put(player, false); + return; + } - //Check if player reach does not exceed startpos - int maxReach = ReachHelper.getMaxReach(player); - if (buildMode != BuildModeEnum.NORMAL && player.getPosition().distanceSq(startPos) > maxReach * maxReach) { - EffortlessBuilding.log(player, "Placement exceeds your reach."); - return; - } - } + //Limit number of blocks you can place + int limit = ReachHelper.getMaxBlocksPlacedAtOnce(player); + if (coordinates.size() > limit) { + coordinates = coordinates.subList(0, limit); + } - //Even when no starting block is found, call buildmode instance - //We might want to place things in the air - List coordinates = buildMode.instance.onRightClick(player, startPos, message.getSideHit(), message.getHitVec(), modifierSettings.doQuickReplace()); + Direction sideHit = buildMode.instance.getSideHit(player); + if (sideHit == null) sideHit = message.getSideHit(); - if (coordinates.isEmpty()) { - currentlyBreaking.put(player, false); - return; - } + Vector3d hitVec = buildMode.instance.getHitVec(player); + if (hitVec == null) hitVec = message.getHitVec(); - //Limit number of blocks you can place - int limit = ReachHelper.getMaxBlocksPlacedAtOnce(player); - if (coordinates.size() > limit) { - coordinates = coordinates.subList(0, limit); - } + BuildModifiers.onBlockPlaced(player, coordinates, sideHit, hitVec, message.getPlaceStartPos()); - Direction sideHit = buildMode.instance.getSideHit(player); - if (sideHit == null) sideHit = message.getSideHit(); + //Only works when finishing a buildmode is equal to placing some blocks + //No intermediate blocks allowed + currentlyBreaking.remove(player); - Vec3d hitVec = buildMode.instance.getHitVec(player); - if (hitVec == null) hitVec = message.getHitVec(); + } - BuildModifiers.onBlockPlaced(player, coordinates, sideHit, hitVec, message.getPlaceStartPos()); + //Use a network message to break blocks in the distance using clientside mouse input + public static void onBlockBrokenMessage(PlayerEntity player, BlockBrokenMessage message) { + BlockPos startPos = message.isBlockHit() ? message.getBlockPos() : null; + onBlockBroken(player, startPos, true); + } - //Only works when finishing a buildmode is equal to placing some blocks - //No intermediate blocks allowed - currentlyBreaking.remove(player); + public static void onBlockBroken(PlayerEntity player, BlockPos startPos, boolean breakStartPos) { - } + //Check if not in the middle of placing + Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; + if (currentlyBreaking.get(player) != null && !currentlyBreaking.get(player)) { + //Cancel placing + initializeMode(player); + return; + } - //Use a network message to break blocks in the distance using clientside mouse input - public static void onBlockBrokenMessage(PlayerEntity player, BlockBrokenMessage message) { - BlockPos startPos = message.isBlockHit() ? message.getBlockPos() : null; - onBlockBroken(player, startPos, true); - } + //If first click + if (currentlyBreaking.get(player) == null) { + //If startpos is null, dont do anything + if (startPos == null) return; + } - public static void onBlockBroken(PlayerEntity player, BlockPos startPos, boolean breakStartPos) { + ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); + ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); - //Check if not in the middle of placing - Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; - if (currentlyBreaking.get(player) != null && !currentlyBreaking.get(player)) { - //Cancel placing - initializeMode(player); - return; - } + //Get coordinates + BuildModeEnum buildMode = modeSettings.getBuildMode(); + List coordinates = buildMode.instance.onRightClick(player, startPos, Direction.UP, Vector3d.ZERO, true); - //If first click - if (currentlyBreaking.get(player) == null) { - //If startpos is null, dont do anything - if (startPos == null) return; - } + if (coordinates.isEmpty()) { + currentlyBreaking.put(player, true); + return; + } - ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); - ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); + //Let buildmodifiers break blocks + BuildModifiers.onBlockBroken(player, coordinates, breakStartPos); - //Get coordinates - BuildModeEnum buildMode = modeSettings.getBuildMode(); - List coordinates = buildMode.instance.onRightClick(player, startPos, Direction.UP, Vec3d.ZERO, true); + //Only works when finishing a buildmode is equal to breaking some blocks + //No intermediate blocks allowed + currentlyBreaking.remove(player); + } - if (coordinates.isEmpty()) { - currentlyBreaking.put(player, true); - return; - } + public static List findCoordinates(PlayerEntity player, BlockPos startPos, boolean skipRaytrace) { + List coordinates = new ArrayList<>(); - //Let buildmodifiers break blocks - BuildModifiers.onBlockBroken(player, coordinates, breakStartPos); + ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); + coordinates.addAll(modeSettings.getBuildMode().instance.findCoordinates(player, startPos, skipRaytrace)); - //Only works when finishing a buildmode is equal to breaking some blocks - //No intermediate blocks allowed - currentlyBreaking.remove(player); - } + return coordinates; + } - public static List findCoordinates(PlayerEntity player, BlockPos startPos, boolean skipRaytrace) { - List coordinates = new ArrayList<>(); + public static void initializeMode(PlayerEntity player) { + //Resetting mode, so not placing or breaking + Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; + currentlyBreaking.remove(player); - ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); - coordinates.addAll(modeSettings.getBuildMode().instance.findCoordinates(player, startPos, skipRaytrace)); + ModeSettingsManager.getModeSettings(player).getBuildMode().instance.initialize(player); + } - return coordinates; - } + public static boolean isCurrentlyPlacing(PlayerEntity player) { + Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; + return currentlyBreaking.get(player) != null && !currentlyBreaking.get(player); + } - public static void initializeMode(PlayerEntity player) { - //Resetting mode, so not placing or breaking - Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; - currentlyBreaking.remove(player); + public static boolean isCurrentlyBreaking(PlayerEntity player) { + Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; + return currentlyBreaking.get(player) != null && currentlyBreaking.get(player); + } - ModeSettingsManager.getModeSettings(player).getBuildMode().instance.initialize(player); - } + //Either placing or breaking + public static boolean isActive(PlayerEntity player) { + Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; + return currentlyBreaking.get(player) != null; + } - public static boolean isCurrentlyPlacing(PlayerEntity player) { - Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; - return currentlyBreaking.get(player) != null && !currentlyBreaking.get(player); - } + //Find coordinates on a line bound by a plane + public static Vector3d findXBound(double x, Vector3d start, Vector3d look) { + //then y and z are + double y = (x - start.x) / look.x * look.y + start.y; + double z = (x - start.x) / look.x * look.z + start.z; - public static boolean isCurrentlyBreaking(PlayerEntity player) { - Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; - return currentlyBreaking.get(player) != null && currentlyBreaking.get(player); - } - - //Either placing or breaking - public static boolean isActive(PlayerEntity player) { - Dictionary currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; - return currentlyBreaking.get(player) != null; - } + return new Vector3d(x, y, z); + } - //-- Common build mode functionality --// + //-- Common build mode functionality --// - //Find coordinates on a line bound by a plane - public static Vec3d findXBound(double x, Vec3d start, Vec3d look) { - //then y and z are - double y = (x - start.x) / look.x * look.y + start.y; - double z = (x - start.x) / look.x * look.z + start.z; + public static Vector3d findYBound(double y, Vector3d start, Vector3d look) { + //then x and z are + double x = (y - start.y) / look.y * look.x + start.x; + double z = (y - start.y) / look.y * look.z + start.z; - return new Vec3d(x, y, z); - } + return new Vector3d(x, y, z); + } - public static Vec3d findYBound(double y, Vec3d start, Vec3d look) { - //then x and z are - double x = (y - start.y) / look.y * look.x + start.x; - double z = (y - start.y) / look.y * look.z + start.z; + public static Vector3d findZBound(double z, Vector3d start, Vector3d look) { + //then x and y are + double x = (z - start.z) / look.z * look.x + start.x; + double y = (z - start.z) / look.z * look.y + start.y; - return new Vec3d(x, y, z); - } + return new Vector3d(x, y, z); + } - public static Vec3d findZBound(double z, Vec3d start, Vec3d look) { - //then x and y are - double x = (z - start.z) / look.z * look.x + start.x; - double y = (z - start.z) / look.z * look.y + start.y; + //Use this instead of player.getLookVec() in any buildmodes code + public static Vector3d getPlayerLookVec(PlayerEntity player) { + Vector3d lookVec = player.getLookVec(); + double x = lookVec.x; + double y = lookVec.y; + double z = lookVec.z; - return new Vec3d(x, y, z); - } + //Further calculations (findXBound etc) don't like any component being 0 or 1 (e.g. dividing by 0) + //isCriteriaValid below will take up to 2 minutes to raytrace blocks towards infinity if that is the case + //So make sure they are close to but never exactly 0 or 1 + if (Math.abs(x) < 0.0001) x = 0.0001; + if (Math.abs(x - 1.0) < 0.0001) x = 0.9999; + if (Math.abs(x + 1.0) < 0.0001) x = -0.9999; - //Use this instead of player.getLookVec() in any buildmodes code - public static Vec3d getPlayerLookVec(PlayerEntity player){ - Vec3d lookVec = player.getLookVec(); - double x = lookVec.x; - double y = lookVec.y; - double z = lookVec.z; + if (Math.abs(y) < 0.0001) y = 0.0001; + if (Math.abs(y - 1.0) < 0.0001) y = 0.9999; + if (Math.abs(y + 1.0) < 0.0001) y = -0.9999; - //Further calculations (findXBound etc) don't like any component being 0 or 1 (e.g. dividing by 0) - //isCriteriaValid below will take up to 2 minutes to raytrace blocks towards infinity if that is the case - //So make sure they are close to but never exactly 0 or 1 - if (Math.abs(x) < 0.0001) x = 0.0001; - if (Math.abs(x - 1.0) < 0.0001) x = 0.9999; - if (Math.abs(x + 1.0) < 0.0001) x = -0.9999; + if (Math.abs(z) < 0.0001) z = 0.0001; + if (Math.abs(z - 1.0) < 0.0001) z = 0.9999; + if (Math.abs(z + 1.0) < 0.0001) z = -0.9999; - if (Math.abs(y) < 0.0001) y = 0.0001; - if (Math.abs(y - 1.0) < 0.0001) y = 0.9999; - if (Math.abs(y + 1.0) < 0.0001) y = -0.9999; + return new Vector3d(x, y, z); + } - if (Math.abs(z) < 0.0001) z = 0.0001; - if (Math.abs(z - 1.0) < 0.0001) z = 0.9999; - if (Math.abs(z + 1.0) < 0.0001) z = -0.9999; + public static boolean isCriteriaValid(Vector3d start, Vector3d look, int reach, PlayerEntity player, boolean skipRaytrace, Vector3d lineBound, Vector3d planeBound, double distToPlayerSq) { + boolean intersects = false; + if (!skipRaytrace) { + //collision within a 1 block radius to selected is fine + RayTraceContext rayTraceContext = new RayTraceContext(start, lineBound, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, player); + RayTraceResult rayTraceResult = player.world.rayTraceBlocks(rayTraceContext); + intersects = rayTraceResult != null && rayTraceResult.getType() == RayTraceResult.Type.BLOCK && + planeBound.subtract(rayTraceResult.getHitVec()).lengthSquared() > 4; + } - return new Vec3d(x, y, z); - } + return planeBound.subtract(start).dotProduct(look) > 0 && + distToPlayerSq > 2 && distToPlayerSq < reach * reach && + !intersects; + } - public static boolean isCriteriaValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace, Vec3d lineBound, Vec3d planeBound, double distToPlayerSq) { - boolean intersects = false; - if (!skipRaytrace) { - //collision within a 1 block radius to selected is fine - RayTraceContext rayTraceContext = new RayTraceContext(start, lineBound, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, player); - RayTraceResult rayTraceResult = player.world.rayTraceBlocks(rayTraceContext); - intersects = rayTraceResult != null && rayTraceResult.getType() == RayTraceResult.Type.BLOCK && - planeBound.subtract(rayTraceResult.getHitVec()).lengthSquared() > 4; - } + public enum BuildModeEnum { + NORMAL("effortlessbuilding.mode.normal", new Normal()), + NORMAL_PLUS("effortlessbuilding.mode.normal_plus", new NormalPlus(), OptionEnum.BUILD_SPEED), + LINE("effortlessbuilding.mode.line", new Line() /*, OptionEnum.THICKNESS*/), + WALL("effortlessbuilding.mode.wall", new Wall(), OptionEnum.FILL), + FLOOR("effortlessbuilding.mode.floor", new Floor(), OptionEnum.FILL), + DIAGONAL_LINE("effortlessbuilding.mode.diagonal_line", new DiagonalLine() /*, OptionEnum.THICKNESS*/), + DIAGONAL_WALL("effortlessbuilding.mode.diagonal_wall", new DiagonalWall() /*, OptionEnum.FILL*/), + SLOPE_FLOOR("effortlessbuilding.mode.slope_floor", new SlopeFloor(), OptionEnum.RAISED_EDGE), + CIRCLE("effortlessbuilding.mode.circle", new Circle(), OptionEnum.CIRCLE_START, OptionEnum.FILL), + CYLINDER("effortlessbuilding.mode.cylinder", new Cylinder(), OptionEnum.CIRCLE_START, OptionEnum.FILL), + SPHERE("effortlessbuilding.mode.sphere", new Sphere(), OptionEnum.CIRCLE_START, OptionEnum.FILL), + CUBE("effortlessbuilding.mode.cube", new Cube(), OptionEnum.CUBE_FILL); - return planeBound.subtract(start).dotProduct(look) > 0 && - distToPlayerSq > 2 && distToPlayerSq < reach * reach && - !intersects; - } + public String name; + public IBuildMode instance; + public OptionEnum[] options; + + BuildModeEnum(String name, IBuildMode instance, OptionEnum... options) { + this.name = name; + this.instance = instance; + this.options = options; + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/IBuildMode.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/IBuildMode.java index d435085..f097edc 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/IBuildMode.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/IBuildMode.java @@ -3,23 +3,23 @@ package nl.requios.effortlessbuilding.buildmode; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import java.util.List; public interface IBuildMode { - //Fired when a player selects a buildmode and when it needs to initializeMode - void initialize(PlayerEntity player); + //Fired when a player selects a buildmode and when it needs to initializeMode + void initialize(PlayerEntity player); - //Fired when a block would be placed - //Return a list of coordinates where you want to place blocks - List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace); + //Fired when a block would be placed + //Return a list of coordinates where you want to place blocks + List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vector3d hitVec, boolean skipRaytrace); - //Fired continuously for visualization purposes - List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace); + //Fired continuously for visualization purposes + List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace); - Direction getSideHit(PlayerEntity player); + Direction getSideHit(PlayerEntity player); - Vec3d getHitVec(PlayerEntity player); + Vector3d getHitVec(PlayerEntity player); } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/ModeOptions.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/ModeOptions.java index de309d1..1bdc4ff 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/ModeOptions.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/ModeOptions.java @@ -9,183 +9,183 @@ import nl.requios.effortlessbuilding.proxy.ClientProxy; public class ModeOptions { - public enum ActionEnum { - UNDO("effortlessbuilding.action.undo"), - REDO("effortlessbuilding.action.redo"), - REPLACE("effortlessbuilding.action.replace"), - OPEN_MODIFIER_SETTINGS("effortlessbuilding.action.open_modifier_settings"), - OPEN_PLAYER_SETTINGS("effortlessbuilding.action.open_player_settings"), + private static ActionEnum buildSpeed = ActionEnum.NORMAL_SPEED; + private static ActionEnum fill = ActionEnum.FULL; + private static ActionEnum cubeFill = ActionEnum.CUBE_FULL; + private static ActionEnum raisedEdge = ActionEnum.SHORT_EDGE; + private static ActionEnum lineThickness = ActionEnum.THICKNESS_1; + private static ActionEnum circleStart = ActionEnum.CIRCLE_START_CORNER; - NORMAL_SPEED("effortlessbuilding.action.normal_speed"), - FAST_SPEED("effortlessbuilding.action.fast_speed"), + public static ActionEnum getOptionSetting(OptionEnum option) { + switch (option) { + case BUILD_SPEED: + return getBuildSpeed(); + case FILL: + return getFill(); + case CUBE_FILL: + return getCubeFill(); + case RAISED_EDGE: + return getRaisedEdge(); + case LINE_THICKNESS: + return getLineThickness(); + case CIRCLE_START: + return getCircleStart(); + default: + return null; + } + } - FULL("effortlessbuilding.action.full"), - HOLLOW("effortlessbuilding.action.hollow"), + public static ActionEnum getBuildSpeed() { + return buildSpeed; + } - CUBE_FULL("effortlessbuilding.action.full"), - CUBE_HOLLOW("effortlessbuilding.action.hollow"), - CUBE_SKELETON("effortlessbuilding.action.skeleton"), + public static ActionEnum getFill() { + return fill; + } - SHORT_EDGE("effortlessbuilding.action.short_edge"), - LONG_EDGE("effortlessbuilding.action.long_edge"), + public static ActionEnum getCubeFill() { + return cubeFill; + } - THICKNESS_1("effortlessbuilding.action.thickness_1"), - THICKNESS_3("effortlessbuilding.action.thickness_3"), - THICKNESS_5("effortlessbuilding.action.thickness_5"), + public static ActionEnum getRaisedEdge() { + return raisedEdge; + } - CIRCLE_START_CORNER("effortlessbuilding.action.start_corner"), - CIRCLE_START_CENTER("effortlessbuilding.action.start_center"); + public static ActionEnum getLineThickness() { + return lineThickness; + } - public String name; + public static ActionEnum getCircleStart() { + return circleStart; + } - ActionEnum(String name) { - this.name = name; - } - } + //Called on both client and server + public static void performAction(PlayerEntity player, ActionEnum action) { + if (action == null) return; - public enum OptionEnum { - BUILD_SPEED("effortlessbuilding.action.build_speed", ActionEnum.NORMAL_SPEED, ActionEnum.FAST_SPEED), - FILL("effortlessbuilding.action.filling", ActionEnum.FULL, ActionEnum.HOLLOW), - CUBE_FILL("effortlessbuilding.action.filling", ActionEnum.CUBE_FULL, ActionEnum.CUBE_HOLLOW, ActionEnum.CUBE_SKELETON), - RAISED_EDGE("effortlessbuilding.action.raised_edge", ActionEnum.SHORT_EDGE, ActionEnum.LONG_EDGE), - LINE_THICKNESS("effortlessbuilding.action.thickness", ActionEnum.THICKNESS_1, ActionEnum.THICKNESS_3, ActionEnum.THICKNESS_5), - CIRCLE_START("effortlessbuilding.action.circle_start", ActionEnum.CIRCLE_START_CORNER, ActionEnum.CIRCLE_START_CENTER); + switch (action) { + case UNDO: + UndoRedo.undo(player); + break; + case REDO: + UndoRedo.redo(player); + break; + case REPLACE: + ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); + modifierSettings.setQuickReplace(!modifierSettings.doQuickReplace()); + EffortlessBuilding.log(player, "Set " + TextFormatting.GOLD + "Quick Replace " + TextFormatting.RESET + ( + modifierSettings.doQuickReplace() ? "on" : "off"), true); + break; + case OPEN_MODIFIER_SETTINGS: + if (player.world.isRemote) + ClientProxy.openModifierSettings(); + break; + case OPEN_PLAYER_SETTINGS: + if (player.world.isRemote) + ClientProxy.openPlayerSettings(); + break; - public String name; - public ActionEnum[] actions; + case NORMAL_SPEED: + buildSpeed = ActionEnum.NORMAL_SPEED; + break; + case FAST_SPEED: + buildSpeed = ActionEnum.FAST_SPEED; + break; + case FULL: + fill = ActionEnum.FULL; + break; + case HOLLOW: + fill = ActionEnum.HOLLOW; + break; + case CUBE_FULL: + cubeFill = ActionEnum.CUBE_FULL; + break; + case CUBE_HOLLOW: + cubeFill = ActionEnum.CUBE_HOLLOW; + break; + case CUBE_SKELETON: + cubeFill = ActionEnum.CUBE_SKELETON; + break; + case SHORT_EDGE: + raisedEdge = ActionEnum.SHORT_EDGE; + break; + case LONG_EDGE: + raisedEdge = ActionEnum.LONG_EDGE; + break; + case THICKNESS_1: + lineThickness = ActionEnum.THICKNESS_1; + break; + case THICKNESS_3: + lineThickness = ActionEnum.THICKNESS_3; + break; + case THICKNESS_5: + lineThickness = ActionEnum.THICKNESS_5; + break; + case CIRCLE_START_CENTER: + circleStart = ActionEnum.CIRCLE_START_CENTER; + break; + case CIRCLE_START_CORNER: + circleStart = ActionEnum.CIRCLE_START_CORNER; + break; + } - OptionEnum(String name, ActionEnum... actions){ - this.name = name; - this.actions = actions; - } - } + if (player.world.isRemote && + action != ActionEnum.REPLACE && + action != ActionEnum.OPEN_MODIFIER_SETTINGS && + action != ActionEnum.OPEN_PLAYER_SETTINGS) { - private static ActionEnum buildSpeed = ActionEnum.NORMAL_SPEED; - private static ActionEnum fill = ActionEnum.FULL; - private static ActionEnum cubeFill = ActionEnum.CUBE_FULL; - private static ActionEnum raisedEdge = ActionEnum.SHORT_EDGE; - private static ActionEnum lineThickness = ActionEnum.THICKNESS_1; - private static ActionEnum circleStart = ActionEnum.CIRCLE_START_CORNER; + EffortlessBuilding.logTranslate(player, "", action.name, "", true); + } + } - public static ActionEnum getOptionSetting(OptionEnum option) { - switch (option) { - case BUILD_SPEED: - return getBuildSpeed(); - case FILL: - return getFill(); - case CUBE_FILL: - return getCubeFill(); - case RAISED_EDGE: - return getRaisedEdge(); - case LINE_THICKNESS: - return getLineThickness(); - case CIRCLE_START: - return getCircleStart(); - default: - return null; - } - } + public enum ActionEnum { + UNDO("effortlessbuilding.action.undo"), + REDO("effortlessbuilding.action.redo"), + REPLACE("effortlessbuilding.action.replace"), + OPEN_MODIFIER_SETTINGS("effortlessbuilding.action.open_modifier_settings"), + OPEN_PLAYER_SETTINGS("effortlessbuilding.action.open_player_settings"), - public static ActionEnum getBuildSpeed() { - return buildSpeed; - } + NORMAL_SPEED("effortlessbuilding.action.normal_speed"), + FAST_SPEED("effortlessbuilding.action.fast_speed"), - public static ActionEnum getFill() { - return fill; - } + FULL("effortlessbuilding.action.full"), + HOLLOW("effortlessbuilding.action.hollow"), - public static ActionEnum getCubeFill() { - return cubeFill; - } + CUBE_FULL("effortlessbuilding.action.full"), + CUBE_HOLLOW("effortlessbuilding.action.hollow"), + CUBE_SKELETON("effortlessbuilding.action.skeleton"), - public static ActionEnum getRaisedEdge() { - return raisedEdge; - } + SHORT_EDGE("effortlessbuilding.action.short_edge"), + LONG_EDGE("effortlessbuilding.action.long_edge"), - public static ActionEnum getLineThickness() { - return lineThickness; - } + THICKNESS_1("effortlessbuilding.action.thickness_1"), + THICKNESS_3("effortlessbuilding.action.thickness_3"), + THICKNESS_5("effortlessbuilding.action.thickness_5"), - public static ActionEnum getCircleStart() { - return circleStart; - } + CIRCLE_START_CORNER("effortlessbuilding.action.start_corner"), + CIRCLE_START_CENTER("effortlessbuilding.action.start_center"); - //Called on both client and server - public static void performAction(PlayerEntity player, ActionEnum action) { - if (action == null) return; + public String name; - switch (action) { - case UNDO: - UndoRedo.undo(player); - break; - case REDO: - UndoRedo.redo(player); - break; - case REPLACE: - ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); - modifierSettings.setQuickReplace(!modifierSettings.doQuickReplace()); - EffortlessBuilding.log(player, "Set " + TextFormatting.GOLD + "Quick Replace " + TextFormatting.RESET + ( - modifierSettings.doQuickReplace() ? "on" : "off"), true); - break; - case OPEN_MODIFIER_SETTINGS: - if (player.world.isRemote) - ClientProxy.openModifierSettings(); - break; - case OPEN_PLAYER_SETTINGS: - if (player.world.isRemote) - ClientProxy.openPlayerSettings(); - break; + ActionEnum(String name) { + this.name = name; + } + } - case NORMAL_SPEED: - buildSpeed = ActionEnum.NORMAL_SPEED; - break; - case FAST_SPEED: - buildSpeed = ActionEnum.FAST_SPEED; - break; - case FULL: - fill = ActionEnum.FULL; - break; - case HOLLOW: - fill = ActionEnum.HOLLOW; - break; - case CUBE_FULL: - cubeFill = ActionEnum.CUBE_FULL; - break; - case CUBE_HOLLOW: - cubeFill = ActionEnum.CUBE_HOLLOW; - break; - case CUBE_SKELETON: - cubeFill = ActionEnum.CUBE_SKELETON; - break; - case SHORT_EDGE: - raisedEdge = ActionEnum.SHORT_EDGE; - break; - case LONG_EDGE: - raisedEdge = ActionEnum.LONG_EDGE; - break; - case THICKNESS_1: - lineThickness = ActionEnum.THICKNESS_1; - break; - case THICKNESS_3: - lineThickness = ActionEnum.THICKNESS_3; - break; - case THICKNESS_5: - lineThickness = ActionEnum.THICKNESS_5; - break; - case CIRCLE_START_CENTER: - circleStart = ActionEnum.CIRCLE_START_CENTER; - break; - case CIRCLE_START_CORNER: - circleStart = ActionEnum.CIRCLE_START_CORNER; - break; - } + public enum OptionEnum { + BUILD_SPEED("effortlessbuilding.action.build_speed", ActionEnum.NORMAL_SPEED, ActionEnum.FAST_SPEED), + FILL("effortlessbuilding.action.filling", ActionEnum.FULL, ActionEnum.HOLLOW), + CUBE_FILL("effortlessbuilding.action.filling", ActionEnum.CUBE_FULL, ActionEnum.CUBE_HOLLOW, ActionEnum.CUBE_SKELETON), + RAISED_EDGE("effortlessbuilding.action.raised_edge", ActionEnum.SHORT_EDGE, ActionEnum.LONG_EDGE), + LINE_THICKNESS("effortlessbuilding.action.thickness", ActionEnum.THICKNESS_1, ActionEnum.THICKNESS_3, ActionEnum.THICKNESS_5), + CIRCLE_START("effortlessbuilding.action.circle_start", ActionEnum.CIRCLE_START_CORNER, ActionEnum.CIRCLE_START_CENTER); - if (player.world.isRemote && - action != ActionEnum.REPLACE && - action != ActionEnum.OPEN_MODIFIER_SETTINGS && - action != ActionEnum.OPEN_PLAYER_SETTINGS) { + public String name; + public ActionEnum[] actions; - EffortlessBuilding.logTranslate(player, "", action.name, "", true); - } - } + OptionEnum(String name, ActionEnum... actions) { + this.name = name; + this.actions = actions; + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/ModeSettingsManager.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/ModeSettingsManager.java index 13e0c90..5999a70 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/ModeSettingsManager.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/ModeSettingsManager.java @@ -16,83 +16,83 @@ import javax.annotation.Nonnull; @Mod.EventBusSubscriber public class ModeSettingsManager { - //Retrieves the buildsettings of a player through the modifierCapability capability - //Never returns null - @Nonnull - public static ModeSettings getModeSettings(PlayerEntity player) { - LazyOptional modeCapability = - player.getCapability(ModeCapabilityManager.modeCapability, null); + //Retrieves the buildsettings of a player through the modifierCapability capability + //Never returns null + @Nonnull + public static ModeSettings getModeSettings(PlayerEntity player) { + LazyOptional modeCapability = + player.getCapability(ModeCapabilityManager.modeCapability, null); - if (modeCapability.isPresent()) { - ModeCapabilityManager.IModeCapability capability = modeCapability.orElse(null); - if (capability.getModeData() == null) { - capability.setModeData(new ModeSettings()); - } - return capability.getModeData(); - } + if (modeCapability.isPresent()) { + ModeCapabilityManager.IModeCapability capability = modeCapability.orElse(null); + if (capability.getModeData() == null) { + capability.setModeData(new ModeSettings()); + } + return capability.getModeData(); + } - //Player does not have modeCapability capability - //Return dummy settings - return new ModeSettings(); + //Player does not have modeCapability capability + //Return dummy settings + return new ModeSettings(); // throw new IllegalArgumentException("Player does not have modeCapability capability"); - } + } - public static void setModeSettings(PlayerEntity player, ModeSettings modeSettings) { - if (player == null) { - EffortlessBuilding.log("Cannot set buildmode settings, player is null"); - return; - } - LazyOptional modeCapability = - player.getCapability(ModeCapabilityManager.modeCapability, null); + public static void setModeSettings(PlayerEntity player, ModeSettings modeSettings) { + if (player == null) { + EffortlessBuilding.log("Cannot set buildmode settings, player is null"); + return; + } + LazyOptional modeCapability = + player.getCapability(ModeCapabilityManager.modeCapability, null); - modeCapability.ifPresent((capability) -> { - capability.setModeData(modeSettings); + modeCapability.ifPresent((capability) -> { + capability.setModeData(modeSettings); - BuildModes.initializeMode(player); - }); + BuildModes.initializeMode(player); + }); - if (!modeCapability.isPresent()) { - EffortlessBuilding.log(player, "Saving buildmode settings failed."); - } - } + if (!modeCapability.isPresent()) { + EffortlessBuilding.log(player, "Saving buildmode settings failed."); + } + } - public static String sanitize(ModeSettings modeSettings, PlayerEntity player) { - int maxReach = ReachHelper.getMaxReach(player); - String error = ""; + public static String sanitize(ModeSettings modeSettings, PlayerEntity player) { + int maxReach = ReachHelper.getMaxReach(player); + String error = ""; - //TODO sanitize + //TODO sanitize - return error; - } + return error; + } - public static class ModeSettings { - private BuildModes.BuildModeEnum buildMode = BuildModes.BuildModeEnum.NORMAL; + public static void handleNewPlayer(PlayerEntity player) { + //Makes sure player has mode settings (if it doesnt it will create it) + getModeSettings(player); - public ModeSettings() { - } + //Only on server + if (!player.world.isRemote) { + //Send to client + ModeSettingsMessage msg = new ModeSettingsMessage(getModeSettings(player)); + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), msg); + } + } - public ModeSettings(BuildModes.BuildModeEnum buildMode) { - this.buildMode = buildMode; - } + public static class ModeSettings { + private BuildModes.BuildModeEnum buildMode = BuildModes.BuildModeEnum.NORMAL; - public BuildModes.BuildModeEnum getBuildMode() { - return this.buildMode; - } + public ModeSettings() { + } - public void setBuildMode(BuildModes.BuildModeEnum buildMode) { - this.buildMode = buildMode; - } - } + public ModeSettings(BuildModes.BuildModeEnum buildMode) { + this.buildMode = buildMode; + } - public static void handleNewPlayer(PlayerEntity player){ - //Makes sure player has mode settings (if it doesnt it will create it) - getModeSettings(player); + public BuildModes.BuildModeEnum getBuildMode() { + return this.buildMode; + } - //Only on server - if (!player.world.isRemote) { - //Send to client - ModeSettingsMessage msg = new ModeSettingsMessage(getModeSettings(player)); - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), msg); - } - } + public void setBuildMode(BuildModes.BuildModeEnum buildMode) { + this.buildMode = buildMode; + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/ThreeClicksBuildMode.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/ThreeClicksBuildMode.java index 3d8308b..94dc23a 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/ThreeClicksBuildMode.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/ThreeClicksBuildMode.java @@ -3,211 +3,211 @@ package nl.requios.effortlessbuilding.buildmode; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import nl.requios.effortlessbuilding.helper.ReachHelper; import java.util.*; public abstract class ThreeClicksBuildMode extends BaseBuildMode { - protected Dictionary secondPosTable = new Hashtable<>(); + protected Dictionary secondPosTable = new Hashtable<>(); - static class HeightCriteria { - Vec3d planeBound; - Vec3d lineBound; - double distToLineSq; - double distToPlayerSq; + //Finds height after floor has been chosen in buildmodes with 3 clicks + public static BlockPos findHeight(PlayerEntity player, BlockPos secondPos, boolean skipRaytrace) { + Vector3d look = BuildModes.getPlayerLookVec(player); + Vector3d start = new Vector3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ()); - HeightCriteria(Vec3d planeBound, BlockPos secondPos, Vec3d start) { - this.planeBound = planeBound; - this.lineBound = toLongestLine(this.planeBound, secondPos); - this.distToLineSq = this.lineBound.subtract(this.planeBound).lengthSquared(); - this.distToPlayerSq = this.planeBound.subtract(start).lengthSquared(); - } + List criteriaList = new ArrayList<>(3); - //Make it from a plane into a line, on y axis only - private Vec3d toLongestLine(Vec3d boundVec, BlockPos secondPos) { - BlockPos bound = new BlockPos(boundVec); - return new Vec3d(secondPos.getX(), bound.getY(), secondPos.getZ()); - } + //X + Vector3d xBound = BuildModes.findXBound(secondPos.getX(), start, look); + criteriaList.add(new HeightCriteria(xBound, secondPos, start)); - //check if its not behind the player and its not too close and not too far - //also check if raytrace from player to block does not intersect blocks - public boolean isValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace) { + //Z + Vector3d zBound = BuildModes.findZBound(secondPos.getZ(), start, look); + criteriaList.add(new HeightCriteria(zBound, secondPos, start)); - return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, lineBound, planeBound, distToPlayerSq); - } - } + //Remove invalid criteria + int reach = ReachHelper.getPlacementReach(player) * 4; //4 times as much as normal placement reach + criteriaList.removeIf(criteria -> !criteria.isValid(start, look, reach, player, skipRaytrace)); - @Override - public void initialize(PlayerEntity player) { - super.initialize(player); - secondPosTable.put(player.getUniqueID(), BlockPos.ZERO); - } + //If none are valid, return empty list of blocks + if (criteriaList.isEmpty()) return null; - @Override - public List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace) { - List list = new ArrayList<>(); + //If only 1 is valid, choose that one + HeightCriteria selected = criteriaList.get(0); - Dictionary rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; - int rightClickNr = rightClickTable.get(player.getUniqueID()); - rightClickNr++; - rightClickTable.put(player.getUniqueID(), rightClickNr); + //If multiple are valid, choose based on criteria + if (criteriaList.size() > 1) { + //Select the one that is closest (from wall position to its line counterpart) + for (int i = 1; i < criteriaList.size(); i++) { + HeightCriteria criteria = criteriaList.get(i); + if (criteria.distToLineSq < 2.0 && selected.distToLineSq < 2.0) { + //Both very close to line, choose closest to player + if (criteria.distToPlayerSq < selected.distToPlayerSq) + selected = criteria; + } else { + //Pick closest to line + if (criteria.distToLineSq < selected.distToLineSq) + selected = criteria; + } + } + } + return new BlockPos(selected.lineBound); + } - if (rightClickNr == 1) { - //If clicking in air, reset and try again - if (blockPos == null) { - rightClickTable.put(player.getUniqueID(), 0); - return list; - } + @Override + public void initialize(PlayerEntity player) { + super.initialize(player); + secondPosTable.put(player.getUniqueID(), BlockPos.ZERO); + } - //First click, remember starting position - firstPosTable.put(player.getUniqueID(), blockPos); - sideHitTable.put(player.getUniqueID(), sideHit); - hitVecTable.put(player.getUniqueID(), hitVec); - //Keep list empty, dont place any blocks yet - } else if (rightClickNr == 2) { - //Second click, find other floor point - BlockPos firstPos = firstPosTable.get(player.getUniqueID()); - BlockPos secondPos = findSecondPos(player, firstPos, true); + @Override + public List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vector3d hitVec, boolean skipRaytrace) { + List list = new ArrayList<>(); - if (secondPos == null) { - rightClickTable.put(player.getUniqueID(), 1); - return list; - } + Dictionary rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; + int rightClickNr = rightClickTable.get(player.getUniqueID()); + rightClickNr++; + rightClickTable.put(player.getUniqueID(), rightClickNr); - secondPosTable.put(player.getUniqueID(), secondPos); + if (rightClickNr == 1) { + //If clicking in air, reset and try again + if (blockPos == null) { + rightClickTable.put(player.getUniqueID(), 0); + return list; + } - } else { - //Third click, place diagonal wall with height - list = findCoordinates(player, blockPos, skipRaytrace); - rightClickTable.put(player.getUniqueID(), 0); - } + //First click, remember starting position + firstPosTable.put(player.getUniqueID(), blockPos); + sideHitTable.put(player.getUniqueID(), sideHit); + hitVecTable.put(player.getUniqueID(), hitVec); + //Keep list empty, dont place any blocks yet + } else if (rightClickNr == 2) { + //Second click, find other floor point + BlockPos firstPos = firstPosTable.get(player.getUniqueID()); + BlockPos secondPos = findSecondPos(player, firstPos, true); - return list; - } + if (secondPos == null) { + rightClickTable.put(player.getUniqueID(), 1); + return list; + } - @Override - public List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) { - List list = new ArrayList<>(); - Dictionary rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; - int rightClickNr = rightClickTable.get(player.getUniqueID()); + secondPosTable.put(player.getUniqueID(), secondPos); - if (rightClickNr == 0) { - if (blockPos != null) - list.add(blockPos); - } else if (rightClickNr == 1) { - BlockPos firstPos = firstPosTable.get(player.getUniqueID()); + } else { + //Third click, place diagonal wall with height + list = findCoordinates(player, blockPos, skipRaytrace); + rightClickTable.put(player.getUniqueID(), 0); + } - BlockPos secondPos = findSecondPos(player, firstPos, true); - if (secondPos == null) return list; + return list; + } - //Limit amount of blocks you can place per row - int axisLimit = ReachHelper.getMaxBlocksPerAxis(player); + @Override + public List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) { + List list = new ArrayList<>(); + Dictionary rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; + int rightClickNr = rightClickTable.get(player.getUniqueID()); - int x1 = firstPos.getX(), x2 = secondPos.getX(); - int y1 = firstPos.getY(), y2 = secondPos.getY(); - int z1 = firstPos.getZ(), z2 = secondPos.getZ(); + if (rightClickNr == 0) { + if (blockPos != null) + list.add(blockPos); + } else if (rightClickNr == 1) { + BlockPos firstPos = firstPosTable.get(player.getUniqueID()); - //limit axis - if (x2 - x1 >= axisLimit) x2 = x1 + axisLimit - 1; - if (x1 - x2 >= axisLimit) x2 = x1 - axisLimit + 1; - if (y2 - y1 >= axisLimit) y2 = y1 + axisLimit - 1; - if (y1 - y2 >= axisLimit) y2 = y1 - axisLimit + 1; - if (z2 - z1 >= axisLimit) z2 = z1 + axisLimit - 1; - if (z1 - z2 >= axisLimit) z2 = z1 - axisLimit + 1; + BlockPos secondPos = findSecondPos(player, firstPos, true); + if (secondPos == null) return list; - //Add diagonal line from first to second - list.addAll(getIntermediateBlocks(player, x1, y1, z1, x2, y2, z2)); + //Limit amount of blocks you can place per row + int axisLimit = ReachHelper.getMaxBlocksPerAxis(player); - } else { - BlockPos firstPos = firstPosTable.get(player.getUniqueID()); - BlockPos secondPos = secondPosTable.get(player.getUniqueID()); + int x1 = firstPos.getX(), x2 = secondPos.getX(); + int y1 = firstPos.getY(), y2 = secondPos.getY(); + int z1 = firstPos.getZ(), z2 = secondPos.getZ(); - BlockPos thirdPos = findThirdPos(player, firstPos, secondPos, skipRaytrace); - if (thirdPos == null) return list; + //limit axis + if (x2 - x1 >= axisLimit) x2 = x1 + axisLimit - 1; + if (x1 - x2 >= axisLimit) x2 = x1 - axisLimit + 1; + if (y2 - y1 >= axisLimit) y2 = y1 + axisLimit - 1; + if (y1 - y2 >= axisLimit) y2 = y1 - axisLimit + 1; + if (z2 - z1 >= axisLimit) z2 = z1 + axisLimit - 1; + if (z1 - z2 >= axisLimit) z2 = z1 - axisLimit + 1; - //Limit amount of blocks you can place per row - int axisLimit = ReachHelper.getMaxBlocksPerAxis(player); + //Add diagonal line from first to second + list.addAll(getIntermediateBlocks(player, x1, y1, z1, x2, y2, z2)); - int x1 = firstPos.getX(), x2 = secondPos.getX(), x3 = thirdPos.getX(); - int y1 = firstPos.getY(), y2 = secondPos.getY(), y3 = thirdPos.getY(); - int z1 = firstPos.getZ(), z2 = secondPos.getZ(), z3 = thirdPos.getZ(); + } else { + BlockPos firstPos = firstPosTable.get(player.getUniqueID()); + BlockPos secondPos = secondPosTable.get(player.getUniqueID()); - //limit axis - if (x2 - x1 >= axisLimit) x2 = x1 + axisLimit - 1; - if (x1 - x2 >= axisLimit) x2 = x1 - axisLimit + 1; - if (y2 - y1 >= axisLimit) y2 = y1 + axisLimit - 1; - if (y1 - y2 >= axisLimit) y2 = y1 - axisLimit + 1; - if (z2 - z1 >= axisLimit) z2 = z1 + axisLimit - 1; - if (z1 - z2 >= axisLimit) z2 = z1 - axisLimit + 1; + BlockPos thirdPos = findThirdPos(player, firstPos, secondPos, skipRaytrace); + if (thirdPos == null) return list; - if (x3 - x1 >= axisLimit) x3 = x1 + axisLimit - 1; - if (x1 - x3 >= axisLimit) x3 = x1 - axisLimit + 1; - if (y3 - y1 >= axisLimit) y3 = y1 + axisLimit - 1; - if (y1 - y3 >= axisLimit) y3 = y1 - axisLimit + 1; - if (z3 - z1 >= axisLimit) z3 = z1 + axisLimit - 1; - if (z1 - z3 >= axisLimit) z3 = z1 - axisLimit + 1; + //Limit amount of blocks you can place per row + int axisLimit = ReachHelper.getMaxBlocksPerAxis(player); - //Add diagonal line from first to third - list.addAll(getFinalBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3)); - } + int x1 = firstPos.getX(), x2 = secondPos.getX(), x3 = thirdPos.getX(); + int y1 = firstPos.getY(), y2 = secondPos.getY(), y3 = thirdPos.getY(); + int z1 = firstPos.getZ(), z2 = secondPos.getZ(), z3 = thirdPos.getZ(); - return list; - } + //limit axis + if (x2 - x1 >= axisLimit) x2 = x1 + axisLimit - 1; + if (x1 - x2 >= axisLimit) x2 = x1 - axisLimit + 1; + if (y2 - y1 >= axisLimit) y2 = y1 + axisLimit - 1; + if (y1 - y2 >= axisLimit) y2 = y1 - axisLimit + 1; + if (z2 - z1 >= axisLimit) z2 = z1 + axisLimit - 1; + if (z1 - z2 >= axisLimit) z2 = z1 - axisLimit + 1; - //Finds the place of the second block pos - protected abstract BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace); + if (x3 - x1 >= axisLimit) x3 = x1 + axisLimit - 1; + if (x1 - x3 >= axisLimit) x3 = x1 - axisLimit + 1; + if (y3 - y1 >= axisLimit) y3 = y1 + axisLimit - 1; + if (y1 - y3 >= axisLimit) y3 = y1 - axisLimit + 1; + if (z3 - z1 >= axisLimit) z3 = z1 + axisLimit - 1; + if (z1 - z3 >= axisLimit) z3 = z1 - axisLimit + 1; - //Finds the place of the third block pos - protected abstract BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace); + //Add diagonal line from first to third + list.addAll(getFinalBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3)); + } - //After first and second pos are known, we want to visualize the blocks in a way (like floor for cube) - protected abstract List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2); + return list; + } - //After first, second and third pos are known, we want all the blocks - protected abstract List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3); + //Finds the place of the second block pos + protected abstract BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace); - //Finds height after floor has been chosen in buildmodes with 3 clicks - public static BlockPos findHeight(PlayerEntity player, BlockPos secondPos, boolean skipRaytrace) { - Vec3d look = BuildModes.getPlayerLookVec(player); - Vec3d start = new Vec3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ()); + //Finds the place of the third block pos + protected abstract BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace); - List criteriaList = new ArrayList<>(3); + //After first and second pos are known, we want to visualize the blocks in a way (like floor for cube) + protected abstract List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2); - //X - Vec3d xBound = BuildModes.findXBound(secondPos.getX(), start, look); - criteriaList.add(new HeightCriteria(xBound, secondPos, start)); + //After first, second and third pos are known, we want all the blocks + protected abstract List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3); - //Z - Vec3d zBound = BuildModes.findZBound(secondPos.getZ(), start, look); - criteriaList.add(new HeightCriteria(zBound, secondPos, start)); + static class HeightCriteria { + Vector3d planeBound; + Vector3d lineBound; + double distToLineSq; + double distToPlayerSq; - //Remove invalid criteria - int reach = ReachHelper.getPlacementReach(player) * 4; //4 times as much as normal placement reach - criteriaList.removeIf(criteria -> !criteria.isValid(start, look, reach, player, skipRaytrace)); + HeightCriteria(Vector3d planeBound, BlockPos secondPos, Vector3d start) { + this.planeBound = planeBound; + this.lineBound = toLongestLine(this.planeBound, secondPos); + this.distToLineSq = this.lineBound.subtract(this.planeBound).lengthSquared(); + this.distToPlayerSq = this.planeBound.subtract(start).lengthSquared(); + } - //If none are valid, return empty list of blocks - if (criteriaList.isEmpty()) return null; + //Make it from a plane into a line, on y axis only + private Vector3d toLongestLine(Vector3d boundVec, BlockPos secondPos) { + BlockPos bound = new BlockPos(boundVec); + return new Vector3d(secondPos.getX(), bound.getY(), secondPos.getZ()); + } - //If only 1 is valid, choose that one - HeightCriteria selected = criteriaList.get(0); + //check if its not behind the player and its not too close and not too far + //also check if raytrace from player to block does not intersect blocks + public boolean isValid(Vector3d start, Vector3d look, int reach, PlayerEntity player, boolean skipRaytrace) { - //If multiple are valid, choose based on criteria - if (criteriaList.size() > 1) { - //Select the one that is closest (from wall position to its line counterpart) - for (int i = 1; i < criteriaList.size(); i++) { - HeightCriteria criteria = criteriaList.get(i); - if (criteria.distToLineSq < 2.0 && selected.distToLineSq < 2.0) { - //Both very close to line, choose closest to player - if (criteria.distToPlayerSq < selected.distToPlayerSq) - selected = criteria; - } else { - //Pick closest to line - if (criteria.distToLineSq < selected.distToLineSq) - selected = criteria; - } - } - } - return new BlockPos(selected.lineBound); - } + return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, lineBound, planeBound, distToPlayerSq); + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/TwoClicksBuildMode.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/TwoClicksBuildMode.java index 15d53e3..816710e 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/TwoClicksBuildMode.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/TwoClicksBuildMode.java @@ -3,8 +3,7 @@ package nl.requios.effortlessbuilding.buildmode; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import nl.requios.effortlessbuilding.EffortlessBuilding; +import net.minecraft.util.math.vector.Vector3d; import nl.requios.effortlessbuilding.helper.ReachHelper; import java.util.ArrayList; @@ -14,74 +13,74 @@ import java.util.UUID; public abstract class TwoClicksBuildMode extends BaseBuildMode { - @Override - public List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace) { - List list = new ArrayList<>(); + @Override + public List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vector3d hitVec, boolean skipRaytrace) { + List list = new ArrayList<>(); - Dictionary rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; - int rightClickNr = rightClickTable.get(player.getUniqueID()); - rightClickNr++; - rightClickTable.put(player.getUniqueID(), rightClickNr); + Dictionary rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; + int rightClickNr = rightClickTable.get(player.getUniqueID()); + rightClickNr++; + rightClickTable.put(player.getUniqueID(), rightClickNr); - if (rightClickNr == 1) { - //If clicking in air, reset and try again - if (blockPos == null) { - rightClickTable.put(player.getUniqueID(), 0); - return list; - } + if (rightClickNr == 1) { + //If clicking in air, reset and try again + if (blockPos == null) { + rightClickTable.put(player.getUniqueID(), 0); + return list; + } - //First click, remember starting position - firstPosTable.put(player.getUniqueID(), blockPos); - sideHitTable.put(player.getUniqueID(), sideHit); - hitVecTable.put(player.getUniqueID(), hitVec); - //Keep list empty, dont place any blocks yet - } else { - //Second click, place blocks - list = findCoordinates(player, blockPos, skipRaytrace); - rightClickTable.put(player.getUniqueID(), 0); - } + //First click, remember starting position + firstPosTable.put(player.getUniqueID(), blockPos); + sideHitTable.put(player.getUniqueID(), sideHit); + hitVecTable.put(player.getUniqueID(), hitVec); + //Keep list empty, dont place any blocks yet + } else { + //Second click, place blocks + list = findCoordinates(player, blockPos, skipRaytrace); + rightClickTable.put(player.getUniqueID(), 0); + } - return list; - } + return list; + } - @Override - public List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) { - List list = new ArrayList<>(); - Dictionary rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; - int rightClickNr = rightClickTable.get(player.getUniqueID()); - BlockPos firstPos = firstPosTable.get(player.getUniqueID()); + @Override + public List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) { + List list = new ArrayList<>(); + Dictionary rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; + int rightClickNr = rightClickTable.get(player.getUniqueID()); + BlockPos firstPos = firstPosTable.get(player.getUniqueID()); - if (rightClickNr == 0) { - if (blockPos != null) - list.add(blockPos); - } else { - BlockPos secondPos = findSecondPos(player, firstPos, skipRaytrace); - if (secondPos == null) return list; + if (rightClickNr == 0) { + if (blockPos != null) + list.add(blockPos); + } else { + BlockPos secondPos = findSecondPos(player, firstPos, skipRaytrace); + if (secondPos == null) return list; - //Limit amount of blocks we can place per row - int axisLimit = ReachHelper.getMaxBlocksPerAxis(player); + //Limit amount of blocks we can place per row + int axisLimit = ReachHelper.getMaxBlocksPerAxis(player); - int x1 = firstPos.getX(), x2 = secondPos.getX(); - int y1 = firstPos.getY(), y2 = secondPos.getY(); - int z1 = firstPos.getZ(), z2 = secondPos.getZ(); + int x1 = firstPos.getX(), x2 = secondPos.getX(); + int y1 = firstPos.getY(), y2 = secondPos.getY(); + int z1 = firstPos.getZ(), z2 = secondPos.getZ(); - //limit axis - if (x2 - x1 >= axisLimit) x2 = x1 + axisLimit - 1; - if (x1 - x2 >= axisLimit) x2 = x1 - axisLimit + 1; - if (y2 - y1 >= axisLimit) y2 = y1 + axisLimit - 1; - if (y1 - y2 >= axisLimit) y2 = y1 - axisLimit + 1; - if (z2 - z1 >= axisLimit) z2 = z1 + axisLimit - 1; - if (z1 - z2 >= axisLimit) z2 = z1 - axisLimit + 1; + //limit axis + if (x2 - x1 >= axisLimit) x2 = x1 + axisLimit - 1; + if (x1 - x2 >= axisLimit) x2 = x1 - axisLimit + 1; + if (y2 - y1 >= axisLimit) y2 = y1 + axisLimit - 1; + if (y1 - y2 >= axisLimit) y2 = y1 - axisLimit + 1; + if (z2 - z1 >= axisLimit) z2 = z1 + axisLimit - 1; + if (z1 - z2 >= axisLimit) z2 = z1 - axisLimit + 1; - list.addAll(getAllBlocks(player, x1, y1, z1, x2, y2, z2)); - } + list.addAll(getAllBlocks(player, x1, y1, z1, x2, y2, z2)); + } - return list; - } + return list; + } - //Finds the place of the second block pos based on criteria (floor must be on same height as first click, wall on same plane etc) - protected abstract BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace); + //Finds the place of the second block pos based on criteria (floor must be on same height as first click, wall on same plane etc) + protected abstract BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace); - //After first and second pos are known, we want all the blocks - protected abstract List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2); + //After first and second pos are known, we want all the blocks + protected abstract List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2); } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Circle.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Circle.java index 3f7aa62..837e653 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Circle.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Circle.java @@ -3,86 +3,87 @@ package nl.requios.effortlessbuilding.buildmode.buildmodes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; -import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.ModeOptions; +import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode; -import java.util.*; +import java.util.ArrayList; +import java.util.List; public class Circle extends TwoClicksBuildMode { - @Override - protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return Floor.findFloor(player, firstPos, skipRaytrace); - } + public static List getCircleBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + List list = new ArrayList<>(); - @Override - protected List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - return getCircleBlocks(player, x1, y1, z1, x2, y2, z2); - } + float centerX = x1; + float centerZ = z1; - public static List getCircleBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - List list = new ArrayList<>(); + //Adjust for CIRCLE_START + if (ModeOptions.getCircleStart() == ModeOptions.ActionEnum.CIRCLE_START_CORNER) { + centerX = x1 + (x2 - x1) / 2f; + centerZ = z1 + (z2 - z1) / 2f; + } else { + x1 = (int) (centerX - (x2 - centerX)); + z1 = (int) (centerZ - (z2 - centerZ)); + } - float centerX = x1; - float centerZ = z1; + float radiusX = MathHelper.abs(x2 - centerX); + float radiusZ = MathHelper.abs(z2 - centerZ); - //Adjust for CIRCLE_START - if (ModeOptions.getCircleStart() == ModeOptions.ActionEnum.CIRCLE_START_CORNER) { - centerX = x1 + (x2 - x1) / 2f; - centerZ = z1 + (z2 - z1) / 2f; - } else { - x1 = (int) (centerX - (x2 - centerX)); - z1 = (int) (centerZ - (z2 - centerZ)); - } + if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) + addCircleBlocks(list, x1, y1, z1, x2, y2, z2, centerX, centerZ, radiusX, radiusZ); + else + addHollowCircleBlocks(list, x1, y1, z1, x2, y2, z2, centerX, centerZ, radiusX, radiusZ); - float radiusX = MathHelper.abs(x2 - centerX); - float radiusZ = MathHelper.abs(z2 - centerZ); + return list; + } - if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) - addCircleBlocks(list, x1, y1, z1, x2, y2, z2, centerX, centerZ, radiusX, radiusZ); - else - addHollowCircleBlocks(list, x1, y1, z1, x2, y2, z2, centerX, centerZ, radiusX, radiusZ); + public static void addCircleBlocks(List list, int x1, int y1, int z1, int x2, int y2, int z2, float centerX, float centerZ, float radiusX, float radiusZ) { - return list; - } + for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { - public static void addCircleBlocks(List list, int x1, int y1, int z1, int x2, int y2, int z2, float centerX, float centerZ, float radiusX, float radiusZ) { + for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { - for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { + float distance = distance(l, n, centerX, centerZ); + float radius = calculateEllipseRadius(centerX, centerZ, radiusX, radiusZ, l, n); + if (distance < radius + 0.4f) + list.add(new BlockPos(l, y1, n)); + } + } + } - for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { + public static void addHollowCircleBlocks(List list, int x1, int y1, int z1, int x2, int y2, int z2, float centerX, float centerZ, float radiusX, float radiusZ) { - float distance = distance(l, n, centerX, centerZ); - float radius = calculateEllipseRadius(centerX, centerZ, radiusX, radiusZ, l, n); - if (distance < radius + 0.4f) - list.add(new BlockPos(l, y1, n)); - } - } - } + for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { - public static void addHollowCircleBlocks(List list, int x1, int y1, int z1, int x2, int y2, int z2, float centerX, float centerZ, float radiusX, float radiusZ) { + for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { - for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { + float distance = distance(l, n, centerX, centerZ); + float radius = calculateEllipseRadius(centerX, centerZ, radiusX, radiusZ, l, n); + if (distance < radius + 0.4f && distance > radius - 0.6f) + list.add(new BlockPos(l, y1, n)); + } + } + } - for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { + private static float distance(float x1, float z1, float x2, float z2) { + return MathHelper.sqrt((x2 - x1) * (x2 - x1) + (z2 - z1) * (z2 - z1)); + } - float distance = distance(l, n, centerX, centerZ); - float radius = calculateEllipseRadius(centerX, centerZ, radiusX, radiusZ, l, n); - if (distance < radius + 0.4f && distance > radius - 0.6f) - list.add(new BlockPos(l, y1, n)); - } - } - } + public static float calculateEllipseRadius(float centerX, float centerZ, float radiusX, float radiusZ, int x, int z) { + //https://math.stackexchange.com/questions/432902/how-to-get-the-radius-of-an-ellipse-at-a-specific-angle-by-knowing-its-semi-majo + float theta = (float) MathHelper.atan2(z - centerZ, x - centerX); + float part1 = radiusX * radiusX * MathHelper.sin(theta) * MathHelper.sin(theta); + float part2 = radiusZ * radiusZ * MathHelper.cos(theta) * MathHelper.cos(theta); + return radiusX * radiusZ / MathHelper.sqrt(part1 + part2); + } - private static float distance(float x1, float z1, float x2, float z2) { - return MathHelper.sqrt((x2 - x1) * (x2 - x1) + (z2 - z1) * (z2 - z1)); - } + @Override + protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return Floor.findFloor(player, firstPos, skipRaytrace); + } - public static float calculateEllipseRadius(float centerX, float centerZ, float radiusX, float radiusZ, int x, int z) { - //https://math.stackexchange.com/questions/432902/how-to-get-the-radius-of-an-ellipse-at-a-specific-angle-by-knowing-its-semi-majo - float theta = (float) MathHelper.atan2(z - centerZ, x - centerX); - float part1 = radiusX * radiusX * MathHelper.sin(theta) * MathHelper.sin(theta); - float part2 = radiusZ * radiusZ * MathHelper.cos(theta) * MathHelper.cos(theta); - return radiusX * radiusZ / MathHelper.sqrt(part1 + part2); - } + @Override + protected List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + return getCircleBlocks(player, x1, y1, z1, x2, y2, z2); + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Cube.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Cube.java index e53e52b..0348d7a 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Cube.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Cube.java @@ -5,96 +5,97 @@ import net.minecraft.util.math.BlockPos; import nl.requios.effortlessbuilding.buildmode.ModeOptions; import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode; -import java.util.*; +import java.util.ArrayList; +import java.util.List; public class Cube extends ThreeClicksBuildMode { - @Override - protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return Floor.findFloor(player, firstPos, skipRaytrace); - } + public static List getFloorBlocksUsingCubeFill(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + List list = new ArrayList<>(); - @Override - protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { - return findHeight(player, secondPos, skipRaytrace); - } + if (ModeOptions.getCubeFill() == ModeOptions.ActionEnum.CUBE_SKELETON) + Floor.addHollowFloorBlocks(list, x1, x2, y1, z1, z2); + else + Floor.addFloorBlocks(list, x1, x2, y1, z1, z2); - @Override - protected List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - return getFloorBlocksUsingCubeFill(player, x1, y1, z1, x2, y2, z2); - } + return list; + } - @Override - protected List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - return getCubeBlocks(player, x1, y1, z1, x3, y3, z3); - } + public static List getCubeBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + List list = new ArrayList<>(); - public static List getFloorBlocksUsingCubeFill(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - List list = new ArrayList<>(); + switch (ModeOptions.getCubeFill()) { + case CUBE_FULL: + addCubeBlocks(list, x1, x2, y1, y2, z1, z2); + break; + case CUBE_HOLLOW: + addHollowCubeBlocks(list, x1, x2, y1, y2, z1, z2); + break; + case CUBE_SKELETON: + addSkeletonCubeBlocks(list, x1, x2, y1, y2, z1, z2); + break; + } - if (ModeOptions.getCubeFill() == ModeOptions.ActionEnum.CUBE_SKELETON) - Floor.addHollowFloorBlocks(list, x1, x2, y1, z1, z2); - else - Floor.addFloorBlocks(list, x1, x2, y1, z1, z2); + return list; + } - return list; - } + public static void addCubeBlocks(List list, int x1, int x2, int y1, int y2, int z1, int z2) { + for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { - public static List getCubeBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - List list = new ArrayList<>(); + for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { - switch (ModeOptions.getCubeFill()) { - case CUBE_FULL: - addCubeBlocks(list, x1, x2, y1, y2, z1, z2); - break; - case CUBE_HOLLOW: - addHollowCubeBlocks(list, x1, x2, y1, y2, z1, z2); - break; - case CUBE_SKELETON: - addSkeletonCubeBlocks(list, x1, x2, y1, y2, z1, z2); - break; - } + for (int m = y1; y1 < y2 ? m <= y2 : m >= y2; m += y1 < y2 ? 1 : -1) { + list.add(new BlockPos(l, m, n)); + } + } + } + } - return list; - } + public static void addHollowCubeBlocks(List list, int x1, int x2, int y1, int y2, int z1, int z2) { + Wall.addXWallBlocks(list, x1, y1, y2, z1, z2); + Wall.addXWallBlocks(list, x2, y1, y2, z1, z2); - public static void addCubeBlocks(List list, int x1, int x2, int y1, int y2, int z1, int z2) { - for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { + Wall.addZWallBlocks(list, x1, x2, y1, y2, z1); + Wall.addZWallBlocks(list, x1, x2, y1, y2, z2); - for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { + Floor.addFloorBlocks(list, x1, x2, y1, z1, z2); + Floor.addFloorBlocks(list, x1, x2, y2, z1, z2); + } - for (int m = y1; y1 < y2 ? m <= y2 : m >= y2; m += y1 < y2 ? 1 : -1) { - list.add(new BlockPos(l, m, n)); - } - } - } - } + public static void addSkeletonCubeBlocks(List list, int x1, int x2, int y1, int y2, int z1, int z2) { + Line.addXLineBlocks(list, x1, x2, y1, z1); + Line.addXLineBlocks(list, x1, x2, y1, z2); + Line.addXLineBlocks(list, x1, x2, y2, z1); + Line.addXLineBlocks(list, x1, x2, y2, z2); - public static void addHollowCubeBlocks(List list, int x1, int x2, int y1, int y2, int z1, int z2) { - Wall.addXWallBlocks(list, x1, y1, y2, z1, z2); - Wall.addXWallBlocks(list, x2, y1, y2, z1, z2); + Line.addYLineBlocks(list, y1, y2, x1, z1); + Line.addYLineBlocks(list, y1, y2, x1, z2); + Line.addYLineBlocks(list, y1, y2, x2, z1); + Line.addYLineBlocks(list, y1, y2, x2, z2); - Wall.addZWallBlocks(list, x1, x2, y1, y2, z1); - Wall.addZWallBlocks(list, x1, x2, y1, y2, z2); + Line.addZLineBlocks(list, z1, z2, x1, y1); + Line.addZLineBlocks(list, z1, z2, x1, y2); + Line.addZLineBlocks(list, z1, z2, x2, y1); + Line.addZLineBlocks(list, z1, z2, x2, y2); + } - Floor.addFloorBlocks(list, x1, x2, y1, z1, z2); - Floor.addFloorBlocks(list, x1, x2, y2, z1, z2); - } + @Override + protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return Floor.findFloor(player, firstPos, skipRaytrace); + } - public static void addSkeletonCubeBlocks(List list, int x1, int x2, int y1, int y2, int z1, int z2) { - Line.addXLineBlocks(list, x1, x2, y1, z1); - Line.addXLineBlocks(list, x1, x2, y1, z2); - Line.addXLineBlocks(list, x1, x2, y2, z1); - Line.addXLineBlocks(list, x1, x2, y2, z2); + @Override + protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { + return findHeight(player, secondPos, skipRaytrace); + } - Line.addYLineBlocks(list, y1, y2, x1, z1); - Line.addYLineBlocks(list, y1, y2, x1, z2); - Line.addYLineBlocks(list, y1, y2, x2, z1); - Line.addYLineBlocks(list, y1, y2, x2, z2); + @Override + protected List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + return getFloorBlocksUsingCubeFill(player, x1, y1, z1, x2, y2, z2); + } - Line.addZLineBlocks(list, z1, z2, x1, y1); - Line.addZLineBlocks(list, z1, z2, x1, y2); - Line.addZLineBlocks(list, z1, z2, x2, y1); - Line.addZLineBlocks(list, z1, z2, x2, y2); - } + @Override + protected List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + return getCubeBlocks(player, x1, y1, z1, x3, y3, z3); + } } \ No newline at end of file diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Cylinder.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Cylinder.java index c334372..0568faf 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Cylinder.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Cylinder.java @@ -9,42 +9,42 @@ import java.util.List; public class Cylinder extends ThreeClicksBuildMode { - @Override - public BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return Floor.findFloor(player, firstPos, skipRaytrace); - } + public static List getCylinderBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + List list = new ArrayList<>(); - @Override - public BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { - return findHeight(player, secondPos, skipRaytrace); - } + //Get circle blocks (using CIRCLE_START and FILL options built-in) + List circleBlocks = Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2); - @Override - public List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - return Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2); - } + int lowest = Math.min(y1, y3); + int highest = Math.max(y1, y3); - @Override - public List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - return getCylinderBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); - } + //Copy circle on y axis + for (int y = lowest; y <= highest; y++) { + for (BlockPos blockPos : circleBlocks) { + list.add(new BlockPos(blockPos.getX(), y, blockPos.getZ())); + } + } - public static List getCylinderBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - List list = new ArrayList<>(); + return list; + } - //Get circle blocks (using CIRCLE_START and FILL options built-in) - List circleBlocks = Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2); + @Override + public BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return Floor.findFloor(player, firstPos, skipRaytrace); + } - int lowest = Math.min(y1, y3); - int highest = Math.max(y1, y3); + @Override + public BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { + return findHeight(player, secondPos, skipRaytrace); + } - //Copy circle on y axis - for (int y = lowest; y <= highest; y++) { - for (BlockPos blockPos : circleBlocks) { - list.add(new BlockPos(blockPos.getX(), y, blockPos.getZ())); - } - } + @Override + public List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + return Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2); + } - return list; - } + @Override + public List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + return getCylinderBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); + } } \ No newline at end of file diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/DiagonalLine.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/DiagonalLine.java index aa47567..847d0ee 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/DiagonalLine.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/DiagonalLine.java @@ -2,7 +2,7 @@ package nl.requios.effortlessbuilding.buildmode.buildmodes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode; import java.util.ArrayList; @@ -10,44 +10,44 @@ import java.util.List; public class DiagonalLine extends ThreeClicksBuildMode { - @Override - protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return Floor.findFloor(player, firstPos, skipRaytrace); - } + //Add diagonal line from first to second + public static List getDiagonalLineBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, float sampleMultiplier) { + List list = new ArrayList<>(); - @Override - protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { - return findHeight(player, secondPos, skipRaytrace); - } + Vector3d first = new Vector3d(x1, y1, z1).add(0.5, 0.5, 0.5); + Vector3d second = new Vector3d(x2, y2, z2).add(0.5, 0.5, 0.5); - @Override - protected List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - //Add diagonal line from first to second - return getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 10); - } + int iterations = (int) Math.ceil(first.distanceTo(second) * sampleMultiplier); + for (double t = 0; t <= 1.0; t += 1.0 / iterations) { + Vector3d lerp = first.add(second.subtract(first).scale(t)); + BlockPos candidate = new BlockPos(lerp); + //Only add if not equal to the last in the list + if (list.isEmpty() || !list.get(list.size() - 1).equals(candidate)) + list.add(candidate); + } - @Override - protected List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - //Add diagonal line from first to third - return getDiagonalLineBlocks(player, x1, y1, z1, x3, y3, z3, 10); - } + return list; + } - //Add diagonal line from first to second - public static List getDiagonalLineBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, float sampleMultiplier) { - List list = new ArrayList<>(); + @Override + protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return Floor.findFloor(player, firstPos, skipRaytrace); + } - Vec3d first = new Vec3d(x1, y1, z1).add(0.5, 0.5, 0.5); - Vec3d second = new Vec3d(x2, y2, z2).add(0.5, 0.5, 0.5); + @Override + protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { + return findHeight(player, secondPos, skipRaytrace); + } - int iterations = (int) Math.ceil(first.distanceTo(second) * sampleMultiplier); - for (double t = 0; t <= 1.0; t += 1.0/iterations) { - Vec3d lerp = first.add(second.subtract(first).scale(t)); - BlockPos candidate = new BlockPos(lerp); - //Only add if not equal to the last in the list - if (list.isEmpty() || !list.get(list.size() - 1).equals(candidate)) - list.add(candidate); - } + @Override + protected List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + //Add diagonal line from first to second + return getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 10); + } - return list; - } + @Override + protected List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + //Add diagonal line from first to third + return getDiagonalLineBlocks(player, x1, y1, z1, x3, y3, z3, 10); + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/DiagonalWall.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/DiagonalWall.java index f37ef08..89895c1 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/DiagonalWall.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/DiagonalWall.java @@ -9,43 +9,43 @@ import java.util.List; public class DiagonalWall extends ThreeClicksBuildMode { - @Override - protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return Floor.findFloor(player, firstPos, skipRaytrace); - } + //Add diagonal wall from first to second + public static List getDiagonalWallBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + List list = new ArrayList<>(); - @Override - protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { - return findHeight(player, secondPos, skipRaytrace); - } + //Get diagonal line blocks + List diagonalLineBlocks = DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 1); - @Override - protected List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - return DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 1); - } + int lowest = Math.min(y1, y3); + int highest = Math.max(y1, y3); - @Override - protected List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - return getDiagonalWallBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); - } + //Copy diagonal line on y axis + for (int y = lowest; y <= highest; y++) { + for (BlockPos blockPos : diagonalLineBlocks) { + list.add(new BlockPos(blockPos.getX(), y, blockPos.getZ())); + } + } - //Add diagonal wall from first to second - public static List getDiagonalWallBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - List list = new ArrayList<>(); + return list; + } - //Get diagonal line blocks - List diagonalLineBlocks = DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 1); + @Override + protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return Floor.findFloor(player, firstPos, skipRaytrace); + } - int lowest = Math.min(y1, y3); - int highest = Math.max(y1, y3); + @Override + protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { + return findHeight(player, secondPos, skipRaytrace); + } - //Copy diagonal line on y axis - for (int y = lowest; y <= highest; y++) { - for (BlockPos blockPos : diagonalLineBlocks) { - list.add(new BlockPos(blockPos.getX(), y, blockPos.getZ())); - } - } + @Override + protected List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + return DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 1); + } - return list; - } + @Override + protected List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + return getDiagonalWallBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); + } } \ No newline at end of file diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Floor.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Floor.java index 6f7fc7f..7d8571c 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Floor.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Floor.java @@ -2,92 +2,93 @@ package nl.requios.effortlessbuilding.buildmode.buildmodes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import nl.requios.effortlessbuilding.buildmode.BuildModes; -import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.ModeOptions; +import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode; import nl.requios.effortlessbuilding.helper.ReachHelper; -import java.util.*; +import java.util.ArrayList; +import java.util.List; public class Floor extends TwoClicksBuildMode { - static class Criteria { - Vec3d planeBound; - double distToPlayerSq; + public static BlockPos findFloor(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + Vector3d look = BuildModes.getPlayerLookVec(player); + Vector3d start = new Vector3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ()); - Criteria(Vec3d planeBound, Vec3d start) { - this.planeBound = planeBound; - this.distToPlayerSq = this.planeBound.subtract(start).lengthSquared(); - } + List criteriaList = new ArrayList<>(3); - //check if its not behind the player and its not too close and not too far - //also check if raytrace from player to block does not intersect blocks - public boolean isValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace) { + //Y + Vector3d yBound = BuildModes.findYBound(firstPos.getY(), start, look); + criteriaList.add(new Criteria(yBound, start)); - return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, planeBound, planeBound, distToPlayerSq); - } - } + //Remove invalid criteria + int reach = ReachHelper.getPlacementReach(player) * 4; //4 times as much as normal placement reach + criteriaList.removeIf(criteria -> !criteria.isValid(start, look, reach, player, skipRaytrace)); - @Override - protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return findFloor(player, firstPos, skipRaytrace); - } + //If none are valid, return empty list of blocks + if (criteriaList.isEmpty()) return null; - public static BlockPos findFloor(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - Vec3d look = BuildModes.getPlayerLookVec(player); - Vec3d start = new Vec3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ()); + //Then only 1 can be valid, return that one + Criteria selected = criteriaList.get(0); - List criteriaList = new ArrayList<>(3); + return new BlockPos(selected.planeBound); + } - //Y - Vec3d yBound = BuildModes.findYBound(firstPos.getY(), start, look); - criteriaList.add(new Criteria(yBound, start)); + public static List getFloorBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + List list = new ArrayList<>(); - //Remove invalid criteria - int reach = ReachHelper.getPlacementReach(player) * 4; //4 times as much as normal placement reach - criteriaList.removeIf(criteria -> !criteria.isValid(start, look, reach, player, skipRaytrace)); + if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) + addFloorBlocks(list, x1, x2, y1, z1, z2); + else + addHollowFloorBlocks(list, x1, x2, y1, z1, z2); - //If none are valid, return empty list of blocks - if (criteriaList.isEmpty()) return null; + return list; + } - //Then only 1 can be valid, return that one - Criteria selected = criteriaList.get(0); + public static void addFloorBlocks(List list, int x1, int x2, int y, int z1, int z2) { - return new BlockPos(selected.planeBound); - } + for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { - @Override - protected List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - return getFloorBlocks(player, x1, y1, z1, x2, y2, z2); - } + for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { - public static List getFloorBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - List list = new ArrayList<>(); + list.add(new BlockPos(l, y, n)); + } + } + } - if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) - addFloorBlocks(list, x1, x2, y1, z1, z2); - else - addHollowFloorBlocks(list, x1, x2, y1, z1, z2); + public static void addHollowFloorBlocks(List list, int x1, int x2, int y, int z1, int z2) { + Line.addXLineBlocks(list, x1, x2, y, z1); + Line.addXLineBlocks(list, x1, x2, y, z2); + Line.addZLineBlocks(list, z1, z2, x1, y); + Line.addZLineBlocks(list, z1, z2, x2, y); + } - return list; - } + @Override + protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return findFloor(player, firstPos, skipRaytrace); + } - public static void addFloorBlocks(List list, int x1, int x2, int y, int z1, int z2) { + @Override + protected List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + return getFloorBlocks(player, x1, y1, z1, x2, y2, z2); + } - for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { + static class Criteria { + Vector3d planeBound; + double distToPlayerSq; - for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { + Criteria(Vector3d planeBound, Vector3d start) { + this.planeBound = planeBound; + this.distToPlayerSq = this.planeBound.subtract(start).lengthSquared(); + } - list.add(new BlockPos(l, y, n)); - } - } - } + //check if its not behind the player and its not too close and not too far + //also check if raytrace from player to block does not intersect blocks + public boolean isValid(Vector3d start, Vector3d look, int reach, PlayerEntity player, boolean skipRaytrace) { - public static void addHollowFloorBlocks(List list, int x1, int x2, int y, int z1, int z2) { - Line.addXLineBlocks(list, x1, x2, y, z1); - Line.addXLineBlocks(list, x1, x2, y, z2); - Line.addZLineBlocks(list, z1, z2, x1, y); - Line.addZLineBlocks(list, z1, z2, x2, y); - } + return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, planeBound, planeBound, distToPlayerSq); + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Line.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Line.java index a49413b..4032bd6 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Line.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Line.java @@ -2,8 +2,7 @@ package nl.requios.effortlessbuilding.buildmode.buildmodes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import nl.requios.effortlessbuilding.EffortlessBuilding; +import net.minecraft.util.math.vector.Vector3d; import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode; import nl.requios.effortlessbuilding.helper.ReachHelper; @@ -13,136 +12,136 @@ import java.util.List; public class Line extends TwoClicksBuildMode { - static class Criteria { - Vec3d planeBound; - Vec3d lineBound; - double distToLineSq; - double distToPlayerSq; + public static BlockPos findLine(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + Vector3d look = BuildModes.getPlayerLookVec(player); + Vector3d start = new Vector3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ()); - Criteria(Vec3d planeBound, BlockPos firstPos, Vec3d start) { - this.planeBound = planeBound; - this.lineBound = toLongestLine(this.planeBound, firstPos); - this.distToLineSq = this.lineBound.subtract(this.planeBound).lengthSquared(); - this.distToPlayerSq = this.planeBound.subtract(start).lengthSquared(); - } + List criteriaList = new ArrayList<>(3); - //Make it from a plane into a line - //Select the axis that is longest - private Vec3d toLongestLine(Vec3d boundVec, BlockPos firstPos) { - BlockPos bound = new BlockPos(boundVec); + //X + Vector3d xBound = BuildModes.findXBound(firstPos.getX(), start, look); + criteriaList.add(new Criteria(xBound, firstPos, start)); - BlockPos firstToSecond = bound.subtract(firstPos); - firstToSecond = new BlockPos(Math.abs(firstToSecond.getX()), Math.abs(firstToSecond.getY()), Math.abs(firstToSecond.getZ())); - int longest = Math.max(firstToSecond.getX(), Math.max(firstToSecond.getY(), firstToSecond.getZ())); - if (longest == firstToSecond.getX()) { - return new Vec3d(bound.getX(), firstPos.getY(), firstPos.getZ()); - } - if (longest == firstToSecond.getY()) { - return new Vec3d(firstPos.getX(), bound.getY(), firstPos.getZ()); - } - if (longest == firstToSecond.getZ()) { - return new Vec3d(firstPos.getX(), firstPos.getY(), bound.getZ()); - } - return null; - } + //Y + Vector3d yBound = BuildModes.findYBound(firstPos.getY(), start, look); + criteriaList.add(new Criteria(yBound, firstPos, start)); - //check if its not behind the player and its not too close and not too far - //also check if raytrace from player to block does not intersect blocks - public boolean isValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace) { + //Z + Vector3d zBound = BuildModes.findZBound(firstPos.getZ(), start, look); + criteriaList.add(new Criteria(zBound, firstPos, start)); - return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, lineBound, planeBound, distToPlayerSq); - } + //Remove invalid criteria + int reach = ReachHelper.getPlacementReach(player) * 4; //4 times as much as normal placement reach + criteriaList.removeIf(criteria -> !criteria.isValid(start, look, reach, player, skipRaytrace)); - } + //If none are valid, return empty list of blocks + if (criteriaList.isEmpty()) return null; - @Override - protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return findLine(player, firstPos, skipRaytrace); - } + //If only 1 is valid, choose that one + Criteria selected = criteriaList.get(0); - public static BlockPos findLine(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - Vec3d look = BuildModes.getPlayerLookVec(player); - Vec3d start = new Vec3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ()); + //If multiple are valid, choose based on criteria + if (criteriaList.size() > 1) { + //Select the one that is closest (from wall position to its line counterpart) + for (int i = 1; i < criteriaList.size(); i++) { + Criteria criteria = criteriaList.get(i); + if (criteria.distToLineSq < 2.0 && selected.distToLineSq < 2.0) { + //Both very close to line, choose closest to player + if (criteria.distToPlayerSq < selected.distToPlayerSq) + selected = criteria; + } else { + //Pick closest to line + if (criteria.distToLineSq < selected.distToLineSq) + selected = criteria; + } + } - List criteriaList = new ArrayList<>(3); + } - //X - Vec3d xBound = BuildModes.findXBound(firstPos.getX(), start, look); - criteriaList.add(new Criteria(xBound, firstPos, start)); + return new BlockPos(selected.lineBound); + } - //Y - Vec3d yBound = BuildModes.findYBound(firstPos.getY(), start, look); - criteriaList.add(new Criteria(yBound, firstPos, start)); + public static List getLineBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + List list = new ArrayList<>(); - //Z - Vec3d zBound = BuildModes.findZBound(firstPos.getZ(), start, look); - criteriaList.add(new Criteria(zBound, firstPos, start)); + if (x1 != x2) { + addXLineBlocks(list, x1, x2, y1, z1); + } else if (y1 != y2) { + addYLineBlocks(list, y1, y2, x1, z1); + } else { + addZLineBlocks(list, z1, z2, x1, y1); + } - //Remove invalid criteria - int reach = ReachHelper.getPlacementReach(player) * 4; //4 times as much as normal placement reach - criteriaList.removeIf(criteria -> !criteria.isValid(start, look, reach, player, skipRaytrace)); + return list; + } - //If none are valid, return empty list of blocks - if (criteriaList.isEmpty()) return null; + public static void addXLineBlocks(List list, int x1, int x2, int y, int z) { + for (int x = x1; x1 < x2 ? x <= x2 : x >= x2; x += x1 < x2 ? 1 : -1) { + list.add(new BlockPos(x, y, z)); + } + } - //If only 1 is valid, choose that one - Criteria selected = criteriaList.get(0); + public static void addYLineBlocks(List list, int y1, int y2, int x, int z) { + for (int y = y1; y1 < y2 ? y <= y2 : y >= y2; y += y1 < y2 ? 1 : -1) { + list.add(new BlockPos(x, y, z)); + } + } - //If multiple are valid, choose based on criteria - if (criteriaList.size() > 1) { - //Select the one that is closest (from wall position to its line counterpart) - for (int i = 1; i < criteriaList.size(); i++) { - Criteria criteria = criteriaList.get(i); - if (criteria.distToLineSq < 2.0 && selected.distToLineSq < 2.0) { - //Both very close to line, choose closest to player - if (criteria.distToPlayerSq < selected.distToPlayerSq) - selected = criteria; - } else { - //Pick closest to line - if (criteria.distToLineSq < selected.distToLineSq) - selected = criteria; - } - } + public static void addZLineBlocks(List list, int z1, int z2, int x, int y) { + for (int z = z1; z1 < z2 ? z <= z2 : z >= z2; z += z1 < z2 ? 1 : -1) { + list.add(new BlockPos(x, y, z)); + } + } - } + @Override + protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return findLine(player, firstPos, skipRaytrace); + } - return new BlockPos(selected.lineBound); - } + @Override + protected List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + return getLineBlocks(player, x1, y1, z1, x2, y2, z2); + } - @Override - protected List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - return getLineBlocks(player, x1, y1, z1, x2, y2, z2); - } + static class Criteria { + Vector3d planeBound; + Vector3d lineBound; + double distToLineSq; + double distToPlayerSq; - public static List getLineBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - List list = new ArrayList<>(); + Criteria(Vector3d planeBound, BlockPos firstPos, Vector3d start) { + this.planeBound = planeBound; + this.lineBound = toLongestLine(this.planeBound, firstPos); + this.distToLineSq = this.lineBound.subtract(this.planeBound).lengthSquared(); + this.distToPlayerSq = this.planeBound.subtract(start).lengthSquared(); + } - if (x1 != x2) { - addXLineBlocks(list, x1, x2, y1, z1); - } else if (y1 != y2) { - addYLineBlocks(list, y1, y2, x1, z1); - } else { - addZLineBlocks(list, z1, z2, x1, y1); - } + //Make it from a plane into a line + //Select the axis that is longest + private Vector3d toLongestLine(Vector3d boundVec, BlockPos firstPos) { + BlockPos bound = new BlockPos(boundVec); - return list; - } + BlockPos firstToSecond = bound.subtract(firstPos); + firstToSecond = new BlockPos(Math.abs(firstToSecond.getX()), Math.abs(firstToSecond.getY()), Math.abs(firstToSecond.getZ())); + int longest = Math.max(firstToSecond.getX(), Math.max(firstToSecond.getY(), firstToSecond.getZ())); + if (longest == firstToSecond.getX()) { + return new Vector3d(bound.getX(), firstPos.getY(), firstPos.getZ()); + } + if (longest == firstToSecond.getY()) { + return new Vector3d(firstPos.getX(), bound.getY(), firstPos.getZ()); + } + if (longest == firstToSecond.getZ()) { + return new Vector3d(firstPos.getX(), firstPos.getY(), bound.getZ()); + } + return null; + } - public static void addXLineBlocks(List list, int x1, int x2, int y, int z) { - for (int x = x1; x1 < x2 ? x <= x2 : x >= x2; x += x1 < x2 ? 1 : -1) { - list.add(new BlockPos(x, y, z)); - } - } + //check if its not behind the player and its not too close and not too far + //also check if raytrace from player to block does not intersect blocks + public boolean isValid(Vector3d start, Vector3d look, int reach, PlayerEntity player, boolean skipRaytrace) { - public static void addYLineBlocks(List list, int y1, int y2, int x, int z) { - for (int y = y1; y1 < y2 ? y <= y2 : y >= y2; y += y1 < y2 ? 1 : -1) { - list.add(new BlockPos(x, y, z)); - } - } + return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, lineBound, planeBound, distToPlayerSq); + } - public static void addZLineBlocks(List list, int z1, int z2, int x, int y) { - for (int z = z1; z1 < z2 ? z <= z2 : z >= z2; z += z1 < z2 ? 1 : -1) { - list.add(new BlockPos(x, y, z)); - } - } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Normal.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Normal.java index 4623c52..582a9be 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Normal.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Normal.java @@ -3,39 +3,39 @@ package nl.requios.effortlessbuilding.buildmode.buildmodes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import nl.requios.effortlessbuilding.buildmode.IBuildMode; import java.util.ArrayList; import java.util.List; public class Normal implements IBuildMode { - @Override - public void initialize(PlayerEntity player) { + @Override + public void initialize(PlayerEntity player) { - } + } - @Override - public List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace) { - List list = new ArrayList<>(); - if (blockPos != null) list.add(blockPos); - return list; - } + @Override + public List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vector3d hitVec, boolean skipRaytrace) { + List list = new ArrayList<>(); + if (blockPos != null) list.add(blockPos); + return list; + } - @Override - public List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) { - List list = new ArrayList<>(); - if (blockPos != null) list.add(blockPos); - return list; - } + @Override + public List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) { + List list = new ArrayList<>(); + if (blockPos != null) list.add(blockPos); + return list; + } - @Override - public Direction getSideHit(PlayerEntity player) { - return null; - } + @Override + public Direction getSideHit(PlayerEntity player) { + return null; + } - @Override - public Vec3d getHitVec(PlayerEntity player) { - return null; - } + @Override + public Vector3d getHitVec(PlayerEntity player) { + return null; + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/NormalPlus.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/NormalPlus.java index 3b2f4de..9a03f38 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/NormalPlus.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/NormalPlus.java @@ -3,39 +3,39 @@ package nl.requios.effortlessbuilding.buildmode.buildmodes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import nl.requios.effortlessbuilding.buildmode.IBuildMode; import java.util.ArrayList; import java.util.List; public class NormalPlus implements IBuildMode { - @Override - public void initialize(PlayerEntity player) { + @Override + public void initialize(PlayerEntity player) { - } + } - @Override - public List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace) { - List list = new ArrayList<>(); - if (blockPos != null) list.add(blockPos); - return list; - } + @Override + public List onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vector3d hitVec, boolean skipRaytrace) { + List list = new ArrayList<>(); + if (blockPos != null) list.add(blockPos); + return list; + } - @Override - public List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) { - List list = new ArrayList<>(); - if (blockPos != null) list.add(blockPos); - return list; - } + @Override + public List findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) { + List list = new ArrayList<>(); + if (blockPos != null) list.add(blockPos); + return list; + } - @Override - public Direction getSideHit(PlayerEntity player) { - return null; - } + @Override + public Direction getSideHit(PlayerEntity player) { + return null; + } - @Override - public Vec3d getHitVec(PlayerEntity player) { - return null; - } + @Override + public Vector3d getHitVec(PlayerEntity player) { + return null; + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/SlopeFloor.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/SlopeFloor.java index 6d60b33..a897156 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/SlopeFloor.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/SlopeFloor.java @@ -11,85 +11,85 @@ import java.util.List; public class SlopeFloor extends ThreeClicksBuildMode { - @Override - protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return Floor.findFloor(player, firstPos, skipRaytrace); - } + //Add slope floor from first to second + public static List getSlopeFloorBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + List list = new ArrayList<>(); - @Override - protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { - return findHeight(player, secondPos, skipRaytrace); - } + int axisLimit = ReachHelper.getMaxBlocksPerAxis(player); - @Override - protected List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - return Floor.getFloorBlocks(player, x1, y1, z1, x2, y2, z2); - } + //Determine whether to use x or z axis to slope up + boolean onXAxis = true; - @Override - protected List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - return getSlopeFloorBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); - } + int xLength = Math.abs(x2 - x1); + int zLength = Math.abs(z2 - z1); - //Add slope floor from first to second - public static List getSlopeFloorBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - List list = new ArrayList<>(); + if (ModeOptions.getRaisedEdge() == ModeOptions.ActionEnum.SHORT_EDGE) { + //Slope along short edge + if (zLength > xLength) onXAxis = false; + } else { + //Slope along long edge + if (zLength <= xLength) onXAxis = false; + } - int axisLimit = ReachHelper.getMaxBlocksPerAxis(player); + if (onXAxis) { + //Along X goes up - //Determine whether to use x or z axis to slope up - boolean onXAxis = true; + //Get diagonal line blocks + List diagonalLineBlocks = DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x2, y3, z1, 1f); - int xLength = Math.abs(x2 - x1); - int zLength = Math.abs(z2 - z1); + //Limit amount of blocks we can place + int lowest = Math.min(z1, z2); + int highest = Math.max(z1, z2); - if (ModeOptions.getRaisedEdge() == ModeOptions.ActionEnum.SHORT_EDGE) { - //Slope along short edge - if (zLength > xLength) onXAxis = false; - } else { - //Slope along long edge - if (zLength <= xLength) onXAxis = false; - } + if (highest - lowest >= axisLimit) highest = lowest + axisLimit - 1; - if (onXAxis) { - //Along X goes up + //Copy diagonal line on x axis + for (int z = lowest; z <= highest; z++) { + for (BlockPos blockPos : diagonalLineBlocks) { + list.add(new BlockPos(blockPos.getX(), blockPos.getY(), z)); + } + } - //Get diagonal line blocks - List diagonalLineBlocks = DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x2, y3, z1, 1f); + } else { + //Along Z goes up - //Limit amount of blocks we can place - int lowest = Math.min(z1, z2); - int highest = Math.max(z1, z2); + //Get diagonal line blocks + List diagonalLineBlocks = DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x1, y3, z2, 1f); - if (highest - lowest >= axisLimit) highest = lowest + axisLimit - 1; + //Limit amount of blocks we can place + int lowest = Math.min(x1, x2); + int highest = Math.max(x1, x2); - //Copy diagonal line on x axis - for (int z = lowest; z <= highest; z++) { - for (BlockPos blockPos : diagonalLineBlocks) { - list.add(new BlockPos(blockPos.getX(), blockPos.getY(), z)); - } - } + if (highest - lowest >= axisLimit) highest = lowest + axisLimit - 1; - } else { - //Along Z goes up + //Copy diagonal line on x axis + for (int x = lowest; x <= highest; x++) { + for (BlockPos blockPos : diagonalLineBlocks) { + list.add(new BlockPos(x, blockPos.getY(), blockPos.getZ())); + } + } + } - //Get diagonal line blocks - List diagonalLineBlocks = DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x1, y3, z2, 1f); + return list; + } - //Limit amount of blocks we can place - int lowest = Math.min(x1, x2); - int highest = Math.max(x1, x2); + @Override + protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return Floor.findFloor(player, firstPos, skipRaytrace); + } - if (highest - lowest >= axisLimit) highest = lowest + axisLimit - 1; + @Override + protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { + return findHeight(player, secondPos, skipRaytrace); + } - //Copy diagonal line on x axis - for (int x = lowest; x <= highest; x++) { - for (BlockPos blockPos : diagonalLineBlocks) { - list.add(new BlockPos(x, blockPos.getY(), blockPos.getZ())); - } - } - } + @Override + protected List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + return Floor.getFloorBlocks(player, x1, y1, z1, x2, y2, z2); + } - return list; - } + @Override + protected List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + return getSlopeFloorBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); + } } \ No newline at end of file diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Sphere.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Sphere.java index 7739440..bd6ed40 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Sphere.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Sphere.java @@ -11,100 +11,100 @@ import java.util.List; public class Sphere extends ThreeClicksBuildMode { - @Override - public BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return Floor.findFloor(player, firstPos, skipRaytrace); - } + public static List getSphereBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + List list = new ArrayList<>(); - @Override - public BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { - return findHeight(player, secondPos, skipRaytrace); - } + float centerX = x1; + float centerY = y1; + float centerZ = z1; - @Override - public List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - return Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2); - } + //Adjust for CIRCLE_START + if (ModeOptions.getCircleStart() == ModeOptions.ActionEnum.CIRCLE_START_CORNER) { + centerX = x1 + (x2 - x1) / 2f; + centerY = y1 + (y3 - y1) / 2f; + centerZ = z1 + (z2 - z1) / 2f; + } else { + x1 = (int) (centerX - (x2 - centerX)); + y1 = (int) (centerY - (y3 - centerY)); + z1 = (int) (centerZ - (z2 - centerZ)); + } - @Override - public List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - return getSphereBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); - } + float radiusX = MathHelper.abs(x2 - centerX); + float radiusY = MathHelper.abs(y3 - centerY); + float radiusZ = MathHelper.abs(z2 - centerZ); - public static List getSphereBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { - List list = new ArrayList<>(); + if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) + addSphereBlocks(list, x1, y1, z1, x3, y3, z3, centerX, centerY, centerZ, radiusX, radiusY, radiusZ); + else + addHollowSphereBlocks(list, x1, y1, z1, x3, y3, z3, centerX, centerY, centerZ, radiusX, radiusY, radiusZ); - float centerX = x1; - float centerY = y1; - float centerZ = z1; + return list; + } - //Adjust for CIRCLE_START - if (ModeOptions.getCircleStart() == ModeOptions.ActionEnum.CIRCLE_START_CORNER) { - centerX = x1 + (x2 - x1) / 2f; - centerY = y1 + (y3 - y1) / 2f; - centerZ = z1 + (z2 - z1) / 2f; - } else { - x1 = (int) (centerX - (x2 - centerX)); - y1 = (int) (centerY - (y3 - centerY)); - z1 = (int) (centerZ - (z2 - centerZ)); - } + public static void addSphereBlocks(List list, int x1, int y1, int z1, int x2, int y2, int z2, + float centerX, float centerY, float centerZ, float radiusX, float radiusY, float radiusZ) { + for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { - float radiusX = MathHelper.abs(x2 - centerX); - float radiusY = MathHelper.abs(y3 - centerY); - float radiusZ = MathHelper.abs(z2 - centerZ); + for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { - if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) - addSphereBlocks(list, x1, y1, z1, x3, y3, z3, centerX, centerY, centerZ, radiusX, radiusY, radiusZ); - else - addHollowSphereBlocks(list, x1, y1, z1, x3, y3, z3, centerX, centerY, centerZ, radiusX, radiusY, radiusZ); + for (int m = y1; y1 < y2 ? m <= y2 : m >= y2; m += y1 < y2 ? 1 : -1) { - return list; - } + float distance = distance(l, m, n, centerX, centerY, centerZ); + float radius = calculateSpheroidRadius(centerX, centerY, centerZ, radiusX, radiusY, radiusZ, l, m, n); + if (distance < radius + 0.4f) + list.add(new BlockPos(l, m, n)); + } + } + } + } - public static void addSphereBlocks(List list, int x1, int y1, int z1, int x2, int y2, int z2, - float centerX, float centerY, float centerZ, float radiusX, float radiusY, float radiusZ) { - for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { + public static void addHollowSphereBlocks(List list, int x1, int y1, int z1, int x2, int y2, int z2, + float centerX, float centerY, float centerZ, float radiusX, float radiusY, float radiusZ) { + for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { - for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { + for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { - for (int m = y1; y1 < y2 ? m <= y2 : m >= y2; m += y1 < y2 ? 1 : -1) { + for (int m = y1; y1 < y2 ? m <= y2 : m >= y2; m += y1 < y2 ? 1 : -1) { - float distance = distance(l, m, n, centerX, centerY, centerZ); - float radius = calculateSpheroidRadius(centerX, centerY, centerZ, radiusX, radiusY, radiusZ, l, m, n); - if (distance < radius + 0.4f) - list.add(new BlockPos(l, m, n)); - } - } - } - } + float distance = distance(l, m, n, centerX, centerY, centerZ); + float radius = calculateSpheroidRadius(centerX, centerY, centerZ, radiusX, radiusY, radiusZ, l, m, n); + if (distance < radius + 0.4f && distance > radius - 0.6f) + list.add(new BlockPos(l, m, n)); + } + } + } + } - public static void addHollowSphereBlocks(List list, int x1, int y1, int z1, int x2, int y2, int z2, - float centerX, float centerY, float centerZ, float radiusX, float radiusY, float radiusZ) { - for (int l = x1; x1 < x2 ? l <= x2 : l >= x2; l += x1 < x2 ? 1 : -1) { + private static float distance(float x1, float y1, float z1, float x2, float y2, float z2) { + return MathHelper.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1)); + } - for (int n = z1; z1 < z2 ? n <= z2 : n >= z2; n += z1 < z2 ? 1 : -1) { + public static float calculateSpheroidRadius(float centerX, float centerY, float centerZ, float radiusX, float radiusY, float radiusZ, int x, int y, int z) { + //Twice ellipse radius + float radiusXZ = Circle.calculateEllipseRadius(centerX, centerZ, radiusX, radiusZ, x, z); - for (int m = y1; y1 < y2 ? m <= y2 : m >= y2; m += y1 < y2 ? 1 : -1) { + //TODO project x to plane - float distance = distance(l, m, n, centerX, centerY, centerZ); - float radius = calculateSpheroidRadius(centerX, centerY, centerZ, radiusX, radiusY, radiusZ, l, m, n); - if (distance < radius + 0.4f && distance > radius - 0.6f) - list.add(new BlockPos(l, m, n)); - } - } - } - } + return Circle.calculateEllipseRadius(centerX, centerY, radiusXZ, radiusY, x, y); + } - private static float distance(float x1, float y1, float z1, float x2, float y2, float z2) { - return MathHelper.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1)); - } + @Override + public BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return Floor.findFloor(player, firstPos, skipRaytrace); + } - public static float calculateSpheroidRadius(float centerX, float centerY, float centerZ, float radiusX, float radiusY, float radiusZ, int x, int y, int z) { - //Twice ellipse radius - float radiusXZ = Circle.calculateEllipseRadius(centerX, centerZ, radiusX, radiusZ, x, z); + @Override + public BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { + return findHeight(player, secondPos, skipRaytrace); + } - //TODO project x to plane + @Override + public List getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + return Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2); + } - return Circle.calculateEllipseRadius(centerX, centerY, radiusXZ, radiusY, x, y); - } + @Override + public List getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { + return getSphereBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); + } } \ No newline at end of file diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Wall.java b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Wall.java index 807dcbf..fdc4d08 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Wall.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmode/buildmodes/Wall.java @@ -2,133 +2,134 @@ package nl.requios.effortlessbuilding.buildmode.buildmodes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import nl.requios.effortlessbuilding.buildmode.BuildModes; -import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.ModeOptions; +import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode; import nl.requios.effortlessbuilding.helper.ReachHelper; -import java.util.*; +import java.util.ArrayList; +import java.util.List; public class Wall extends TwoClicksBuildMode { - static class Criteria { - Vec3d planeBound; - double distToPlayerSq; - double angle; + public static BlockPos findWall(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + Vector3d look = BuildModes.getPlayerLookVec(player); + Vector3d start = new Vector3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ()); - Criteria(Vec3d planeBound, BlockPos firstPos, Vec3d start, Vec3d look) { - this.planeBound = planeBound; - this.distToPlayerSq = this.planeBound.subtract(start).lengthSquared(); - Vec3d wall = this.planeBound.subtract(new Vec3d(firstPos)); - this.angle = wall.x * look.x + wall.z * look.z; //dot product ignoring y (looking up/down should not affect this angle) - } + List criteriaList = new ArrayList<>(3); - //check if its not behind the player and its not too close and not too far - //also check if raytrace from player to block does not intersect blocks - public boolean isValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace) { + //X + Vector3d xBound = BuildModes.findXBound(firstPos.getX(), start, look); + criteriaList.add(new Criteria(xBound, firstPos, start, look)); - return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, planeBound, planeBound, distToPlayerSq); - } - } + //Z + Vector3d zBound = BuildModes.findZBound(firstPos.getZ(), start, look); + criteriaList.add(new Criteria(zBound, firstPos, start, look)); - @Override - protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - return findWall(player, firstPos, skipRaytrace); - } + //Remove invalid criteria + int reach = ReachHelper.getPlacementReach(player) * 4; //4 times as much as normal placement reach + criteriaList.removeIf(criteria -> !criteria.isValid(start, look, reach, player, skipRaytrace)); - public static BlockPos findWall(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { - Vec3d look = BuildModes.getPlayerLookVec(player); - Vec3d start = new Vec3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ()); + //If none are valid, return empty list of blocks + if (criteriaList.isEmpty()) return null; - List criteriaList = new ArrayList<>(3); + //If only 1 is valid, choose that one + Criteria selected = criteriaList.get(0); - //X - Vec3d xBound = BuildModes.findXBound(firstPos.getX(), start, look); - criteriaList.add(new Criteria(xBound, firstPos, start, look)); + //If multiple are valid, choose based on criteria + if (criteriaList.size() > 1) { + //Select the one that is closest + //Limit the angle to not be too extreme + for (int i = 1; i < criteriaList.size(); i++) { + Criteria criteria = criteriaList.get(i); + if (criteria.distToPlayerSq < selected.distToPlayerSq && Math.abs(criteria.angle) - Math.abs(selected.angle) < 3) + selected = criteria; + } + } - //Z - Vec3d zBound = BuildModes.findZBound(firstPos.getZ(), start, look); - criteriaList.add(new Criteria(zBound, firstPos, start, look)); + return new BlockPos(selected.planeBound); + } - //Remove invalid criteria - int reach = ReachHelper.getPlacementReach(player) * 4; //4 times as much as normal placement reach - criteriaList.removeIf(criteria -> !criteria.isValid(start, look, reach, player, skipRaytrace)); + public static List getWallBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + List list = new ArrayList<>(); - //If none are valid, return empty list of blocks - if (criteriaList.isEmpty()) return null; + if (x1 == x2) { + if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) + addXWallBlocks(list, x1, y1, y2, z1, z2); + else + addXHollowWallBlocks(list, x1, y1, y2, z1, z2); + } else { + if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) + addZWallBlocks(list, x1, x2, y1, y2, z1); + else + addZHollowWallBlocks(list, x1, x2, y1, y2, z1); + } - //If only 1 is valid, choose that one - Criteria selected = criteriaList.get(0); + return list; + } - //If multiple are valid, choose based on criteria - if (criteriaList.size() > 1) { - //Select the one that is closest - //Limit the angle to not be too extreme - for (int i = 1; i < criteriaList.size(); i++) { - Criteria criteria = criteriaList.get(i); - if (criteria.distToPlayerSq < selected.distToPlayerSq && Math.abs(criteria.angle) - Math.abs(selected.angle) < 3) - selected = criteria; - } - } + public static void addXWallBlocks(List list, int x, int y1, int y2, int z1, int z2) { - return new BlockPos(selected.planeBound); - } + for (int z = z1; z1 < z2 ? z <= z2 : z >= z2; z += z1 < z2 ? 1 : -1) { - @Override - protected List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - return getWallBlocks(player, x1, y1, z1, x2, y2, z2); - } + for (int y = y1; y1 < y2 ? y <= y2 : y >= y2; y += y1 < y2 ? 1 : -1) { + list.add(new BlockPos(x, y, z)); + } + } + } - public static List getWallBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { - List list = new ArrayList<>(); + public static void addZWallBlocks(List list, int x1, int x2, int y1, int y2, int z) { - if (x1 == x2) { - if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) - addXWallBlocks(list, x1, y1, y2, z1, z2); - else - addXHollowWallBlocks(list, x1, y1, y2, z1, z2); - } else { - if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) - addZWallBlocks(list, x1, x2, y1, y2, z1); - else - addZHollowWallBlocks(list, x1, x2, y1, y2, z1); - } + for (int x = x1; x1 < x2 ? x <= x2 : x >= x2; x += x1 < x2 ? 1 : -1) { - return list; - } + for (int y = y1; y1 < y2 ? y <= y2 : y >= y2; y += y1 < y2 ? 1 : -1) { + list.add(new BlockPos(x, y, z)); + } + } + } - public static void addXWallBlocks(List list, int x, int y1, int y2, int z1, int z2) { + public static void addXHollowWallBlocks(List list, int x, int y1, int y2, int z1, int z2) { + Line.addZLineBlocks(list, z1, z2, x, y1); + Line.addZLineBlocks(list, z1, z2, x, y2); + Line.addYLineBlocks(list, y1, y2, x, z1); + Line.addYLineBlocks(list, y1, y2, x, z2); + } - for (int z = z1; z1 < z2 ? z <= z2 : z >= z2; z += z1 < z2 ? 1 : -1) { + public static void addZHollowWallBlocks(List list, int x1, int x2, int y1, int y2, int z) { + Line.addXLineBlocks(list, x1, x2, y1, z); + Line.addXLineBlocks(list, x1, x2, y2, z); + Line.addYLineBlocks(list, y1, y2, x1, z); + Line.addYLineBlocks(list, y1, y2, x2, z); + } - for (int y = y1; y1 < y2 ? y <= y2 : y >= y2; y += y1 < y2 ? 1 : -1) { - list.add(new BlockPos(x, y, z)); - } - } - } + @Override + protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) { + return findWall(player, firstPos, skipRaytrace); + } - public static void addZWallBlocks(List list, int x1, int x2, int y1, int y2, int z) { + @Override + protected List getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) { + return getWallBlocks(player, x1, y1, z1, x2, y2, z2); + } - for (int x = x1; x1 < x2 ? x <= x2 : x >= x2; x += x1 < x2 ? 1 : -1) { + static class Criteria { + Vector3d planeBound; + double distToPlayerSq; + double angle; - for (int y = y1; y1 < y2 ? y <= y2 : y >= y2; y += y1 < y2 ? 1 : -1) { - list.add(new BlockPos(x, y, z)); - } - } - } + Criteria(Vector3d planeBound, BlockPos firstPos, Vector3d start, Vector3d look) { + this.planeBound = planeBound; + this.distToPlayerSq = this.planeBound.subtract(start).lengthSquared(); + Vector3d wall = this.planeBound.subtract(Vector3d.copy(firstPos)); + this.angle = wall.x * look.x + wall.z * look.z; //dot product ignoring y (looking up/down should not affect this angle) + } - public static void addXHollowWallBlocks(List list, int x, int y1, int y2, int z1, int z2) { - Line.addZLineBlocks(list, z1, z2, x, y1); - Line.addZLineBlocks(list, z1, z2, x, y2); - Line.addYLineBlocks(list, y1, y2, x, z1); - Line.addYLineBlocks(list, y1, y2, x, z2); - } + //check if its not behind the player and its not too close and not too far + //also check if raytrace from player to block does not intersect blocks + public boolean isValid(Vector3d start, Vector3d look, int reach, PlayerEntity player, boolean skipRaytrace) { - public static void addZHollowWallBlocks(List list, int x1, int x2, int y1, int y2, int z) { - Line.addXLineBlocks(list, x1, x2, y1, z); - Line.addXLineBlocks(list, x1, x2, y2, z); - Line.addYLineBlocks(list, y1, y2, x1, z); - Line.addYLineBlocks(list, y1, y2, x2, z); - } + return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, planeBound, planeBound, distToPlayerSq); + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/Array.java b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/Array.java index d0ce13a..7c8e321 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/Array.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/Array.java @@ -6,8 +6,8 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.math.Vec3i; +import net.minecraft.util.math.vector.Vector3d; +import net.minecraft.util.math.vector.Vector3i; import net.minecraftforge.items.IItemHandler; import nl.requios.effortlessbuilding.item.ItemRandomizerBag; @@ -16,89 +16,87 @@ import java.util.List; public class Array { - public static class ArraySettings{ - public boolean enabled = false; - public BlockPos offset = BlockPos.ZERO; - public int count = 5; + public static List findCoordinates(PlayerEntity player, BlockPos startPos) { + List coordinates = new ArrayList<>(); - public ArraySettings() { - } + //find arraysettings for the player + ArraySettings a = ModifierSettingsManager.getModifierSettings(player).getArraySettings(); + if (!isEnabled(a)) return coordinates; - public ArraySettings(boolean enabled, BlockPos offset, int count) { - this.enabled = enabled; - this.offset = offset; - this.count = count; - } + BlockPos pos = startPos; + Vector3i offset = new Vector3i(a.offset.getX(), a.offset.getY(), a.offset.getZ()); - public int getReach() { - //find largest offset - int x = Math.abs(offset.getX()); - int y = Math.abs(offset.getY()); - int z = Math.abs(offset.getZ()); - int largestOffset = Math.max(Math.max(x, y), z); + for (int i = 0; i < a.count; i++) { + pos = pos.add(offset); + coordinates.add(pos); + } - return largestOffset * count; - } - } + return coordinates; + } - public static List findCoordinates(PlayerEntity player, BlockPos startPos) { - List coordinates = new ArrayList<>(); + public static List findBlockStates(PlayerEntity player, BlockPos startPos, BlockState blockState, ItemStack itemStack, List itemStacks) { + List blockStates = new ArrayList<>(); - //find arraysettings for the player - ArraySettings a = ModifierSettingsManager.getModifierSettings(player).getArraySettings(); - if (!isEnabled(a)) return coordinates; + //find arraysettings for the player that placed the block + ArraySettings a = ModifierSettingsManager.getModifierSettings(player).getArraySettings(); + if (!isEnabled(a)) return blockStates; - BlockPos pos = startPos; - Vec3i offset = new Vec3i(a.offset.getX(), a.offset.getY(), a.offset.getZ()); + BlockPos pos = startPos; + Vector3i offset = new Vector3i(a.offset.getX(), a.offset.getY(), a.offset.getZ()); - for (int i = 0; i < a.count; i++) { - pos = pos.add(offset); - coordinates.add(pos); - } + //Randomizer bag synergy + IItemHandler bagInventory = null; + if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemRandomizerBag) { + bagInventory = ItemRandomizerBag.getBagInventory(itemStack); + } - return coordinates; - } + for (int i = 0; i < a.count; i++) { + pos = pos.add(offset); - public static List findBlockStates(PlayerEntity player, BlockPos startPos, BlockState blockState, ItemStack itemStack, List itemStacks) { - List blockStates = new ArrayList<>(); + //Randomizer bag synergy + if (bagInventory != null) { + itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); + blockState = BuildModifiers + .getBlockStateFromItem(itemStack, player, startPos, Direction.UP, new Vector3d(0, 0, 0), Hand.MAIN_HAND); + } - //find arraysettings for the player that placed the block - ArraySettings a = ModifierSettingsManager.getModifierSettings(player).getArraySettings(); - if (!isEnabled(a)) return blockStates; + //blockState = blockState.getBlock().getStateForPlacement(player.world, pos, ) + blockStates.add(blockState); + itemStacks.add(itemStack); + } - BlockPos pos = startPos; - Vec3i offset = new Vec3i(a.offset.getX(), a.offset.getY(), a.offset.getZ()); + return blockStates; + } - //Randomizer bag synergy - IItemHandler bagInventory = null; - if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemRandomizerBag) { - bagInventory = ItemRandomizerBag.getBagInventory(itemStack); - } + public static boolean isEnabled(ArraySettings a) { + if (a == null || !a.enabled) return false; - for (int i = 0; i < a.count; i++) { - pos = pos.add(offset); + return a.offset.getX() != 0 || a.offset.getY() != 0 || a.offset.getZ() != 0; + } - //Randomizer bag synergy - if (bagInventory != null) { - itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); - blockState = BuildModifiers - .getBlockStateFromItem(itemStack, player, startPos, Direction.UP, new Vec3d(0, 0, 0), Hand.MAIN_HAND); - } + public static class ArraySettings { + public boolean enabled = false; + public BlockPos offset = BlockPos.ZERO; + public int count = 5; - //blockState = blockState.getBlock().getStateForPlacement(player.world, pos, ) - blockStates.add(blockState); - itemStacks.add(itemStack); - } + public ArraySettings() { + } - return blockStates; - } + public ArraySettings(boolean enabled, BlockPos offset, int count) { + this.enabled = enabled; + this.offset = offset; + this.count = count; + } - public static boolean isEnabled(ArraySettings a) { - if (a == null || !a.enabled) return false; + public int getReach() { + //find largest offset + int x = Math.abs(offset.getX()); + int y = Math.abs(offset.getY()); + int z = Math.abs(offset.getZ()); + int largestOffset = Math.max(Math.max(x, y), z); - if (a.offset.getX() == 0 && a.offset.getY() == 0 && a.offset.getZ() == 0) return false; - - return true; - } + return largestOffset * count; + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/BlockSet.java b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/BlockSet.java index a341610..f9017ff 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/BlockSet.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/BlockSet.java @@ -2,49 +2,49 @@ package nl.requios.effortlessbuilding.buildmodifier; import net.minecraft.block.BlockState; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import java.util.List; public class BlockSet { - private List coordinates; - private List previousBlockStates; - private List newBlockStates; - private Vec3d hitVec; - private BlockPos firstPos; - private BlockPos secondPos; + private final List coordinates; + private final List previousBlockStates; + private final List newBlockStates; + private final Vector3d hitVec; + private final BlockPos firstPos; + private final BlockPos secondPos; - public BlockSet(List coordinates, List previousBlockStates, List newBlockStates, Vec3d hitVec, - BlockPos firstPos, BlockPos secondPos) { - this.coordinates = coordinates; - this.previousBlockStates = previousBlockStates; - this.newBlockStates = newBlockStates; - this.hitVec = hitVec; - this.firstPos = firstPos; - this.secondPos = secondPos; - } + public BlockSet(List coordinates, List previousBlockStates, List newBlockStates, Vector3d hitVec, + BlockPos firstPos, BlockPos secondPos) { + this.coordinates = coordinates; + this.previousBlockStates = previousBlockStates; + this.newBlockStates = newBlockStates; + this.hitVec = hitVec; + this.firstPos = firstPos; + this.secondPos = secondPos; + } - public List getCoordinates() { - return coordinates; - } + public List getCoordinates() { + return coordinates; + } - public List getPreviousBlockStates() { - return previousBlockStates; - } + public List getPreviousBlockStates() { + return previousBlockStates; + } - public List getNewBlockStates() { - return newBlockStates; - } + public List getNewBlockStates() { + return newBlockStates; + } - public Vec3d getHitVec() { - return hitVec; - } + public Vector3d getHitVec() { + return hitVec; + } - public BlockPos getFirstPos() { - return firstPos; - } + public BlockPos getFirstPos() { + return firstPos; + } - public BlockPos getSecondPos() { - return secondPos; - } + public BlockPos getSecondPos() { + return secondPos; + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/BuildModifiers.java b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/BuildModifiers.java index 46a634f..394011c 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/BuildModifiers.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/BuildModifiers.java @@ -2,8 +2,8 @@ package nl.requios.effortlessbuilding.buildmodifier; import net.minecraft.block.Block; import net.minecraft.block.BlockState; -import net.minecraft.entity.player.PlayerEntity; import net.minecraft.block.Blocks; +import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.BlockItem; import net.minecraft.item.BlockItemUseContext; import net.minecraft.item.ItemStack; @@ -12,7 +12,7 @@ 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.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import net.minecraft.world.World; import nl.requios.effortlessbuilding.compatibility.CompatHelper; import nl.requios.effortlessbuilding.helper.InventoryHelper; @@ -20,241 +20,244 @@ import nl.requios.effortlessbuilding.helper.SurvivalHelper; import nl.requios.effortlessbuilding.item.ItemRandomizerBag; import nl.requios.effortlessbuilding.render.BlockPreviewRenderer; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; public class BuildModifiers { - //Called from BuildModes - public static void onBlockPlaced(PlayerEntity player, List startCoordinates, Direction sideHit, Vec3d hitVec, boolean placeStartPos) { - World world = player.world; - ItemRandomizerBag.renewRandomness(); + //Called from BuildModes + public static void onBlockPlaced(PlayerEntity player, List startCoordinates, Direction sideHit, Vector3d hitVec, boolean placeStartPos) { + World world = player.world; + ItemRandomizerBag.renewRandomness(); - //Format hitvec to 0.x - hitVec = new Vec3d(Math.abs(hitVec.x - ((int) hitVec.x)), Math.abs(hitVec.y - ((int) hitVec.y)), Math.abs(hitVec.z - ((int) hitVec.z))); + //Format hitvec to 0.x + hitVec = new Vector3d(Math.abs(hitVec.x - ((int) hitVec.x)), Math.abs(hitVec.y - ((int) hitVec.y)), Math.abs(hitVec.z - ((int) hitVec.z))); - //find coordinates and blockstates - List coordinates = findCoordinates(player, startCoordinates); - List itemStacks = new ArrayList<>(); - List blockStates = findBlockStates(player, startCoordinates, hitVec, sideHit, itemStacks); + //find coordinates and blockstates + List coordinates = findCoordinates(player, startCoordinates); + List itemStacks = new ArrayList<>(); + List blockStates = findBlockStates(player, startCoordinates, hitVec, sideHit, itemStacks); - //check if valid blockstates - if (blockStates.size() == 0 || coordinates.size() != blockStates.size()) return; + //check if valid blockstates + if (blockStates.size() == 0 || coordinates.size() != blockStates.size()) return; - //remember previous blockstates for undo - List previousBlockStates = new ArrayList<>(coordinates.size()); - List newBlockStates = new ArrayList<>(coordinates.size()); - for (BlockPos coordinate : coordinates) { - previousBlockStates.add(world.getBlockState(coordinate)); - } + //remember previous blockstates for undo + List previousBlockStates = new ArrayList<>(coordinates.size()); + List newBlockStates = new ArrayList<>(coordinates.size()); + for (BlockPos coordinate : coordinates) { + previousBlockStates.add(world.getBlockState(coordinate)); + } - if (world.isRemote) { + if (world.isRemote) { - BlockPreviewRenderer.onBlocksPlaced(); + BlockPreviewRenderer.onBlocksPlaced(); - newBlockStates = blockStates; + newBlockStates = blockStates; - } else { + } else { - //place blocks - for (int i = placeStartPos ? 0 : 1; i < coordinates.size(); i++) { - BlockPos blockPos = coordinates.get(i); - BlockState blockState = blockStates.get(i); - ItemStack itemStack = itemStacks.get(i); + //place blocks + for (int i = placeStartPos ? 0 : 1; i < coordinates.size(); i++) { + BlockPos blockPos = coordinates.get(i); + BlockState blockState = blockStates.get(i); + ItemStack itemStack = itemStacks.get(i); - if (world.isBlockPresent(blockPos)) { - //check itemstack empty - if (itemStack.isEmpty()) { - //try to find new stack, otherwise continue - itemStack = InventoryHelper.findItemStackInInventory(player, blockState.getBlock()); - if (itemStack.isEmpty()) continue; - } - SurvivalHelper.placeBlock(world, player, blockPos, blockState, itemStack, Direction.UP, hitVec, false, false, false); - } - } + if (world.isBlockPresent(blockPos)) { + //check itemstack empty + if (itemStack.isEmpty()) { + //try to find new stack, otherwise continue + itemStack = InventoryHelper.findItemStackInInventory(player, blockState.getBlock()); + if (itemStack.isEmpty()) continue; + } + SurvivalHelper.placeBlock(world, player, blockPos, blockState, itemStack, Direction.UP, hitVec, false, false, false); + } + } - //find actual new blockstates for undo - for (BlockPos coordinate : coordinates) { - newBlockStates.add(world.getBlockState(coordinate)); - } - } + //find actual new blockstates for undo + for (BlockPos coordinate : coordinates) { + newBlockStates.add(world.getBlockState(coordinate)); + } + } - //Set first previousBlockState to empty if in NORMAL mode, to make undo/redo work - //(Block is placed by the time it gets here, and unplaced after this) - if (!placeStartPos) previousBlockStates.set(0, Blocks.AIR.getDefaultState()); + //Set first previousBlockState to empty if in NORMAL mode, to make undo/redo work + //(Block is placed by the time it gets here, and unplaced after this) + if (!placeStartPos) previousBlockStates.set(0, Blocks.AIR.getDefaultState()); - //If all new blockstates are air then no use in adding it, no block was actually placed - //Can happen when e.g. placing one block in yourself - if (Collections.frequency(newBlockStates, Blocks.AIR.getDefaultState()) != newBlockStates.size()) { - //add to undo stack - BlockPos firstPos = startCoordinates.get(0); - BlockPos secondPos = startCoordinates.get(startCoordinates.size() - 1); - UndoRedo.addUndo(player, new BlockSet(coordinates, previousBlockStates, newBlockStates, hitVec, firstPos, secondPos)); - } - } + //If all new blockstates are air then no use in adding it, no block was actually placed + //Can happen when e.g. placing one block in yourself + if (Collections.frequency(newBlockStates, Blocks.AIR.getDefaultState()) != newBlockStates.size()) { + //add to undo stack + BlockPos firstPos = startCoordinates.get(0); + BlockPos secondPos = startCoordinates.get(startCoordinates.size() - 1); + UndoRedo.addUndo(player, new BlockSet(coordinates, previousBlockStates, newBlockStates, hitVec, firstPos, secondPos)); + } + } - public static void onBlockBroken(PlayerEntity player, List startCoordinates, boolean breakStartPos) { - World world = player.world; + public static void onBlockBroken(PlayerEntity player, List startCoordinates, boolean breakStartPos) { + World world = player.world; - List coordinates = findCoordinates(player, startCoordinates); + List coordinates = findCoordinates(player, startCoordinates); - if (coordinates.isEmpty()) return; + if (coordinates.isEmpty()) return; - //remember previous blockstates for undo - List previousBlockStates = new ArrayList<>(coordinates.size()); - List newBlockStates = new ArrayList<>(coordinates.size()); - for (BlockPos coordinate : coordinates) { - previousBlockStates.add(world.getBlockState(coordinate)); - } + //remember previous blockstates for undo + List previousBlockStates = new ArrayList<>(coordinates.size()); + List newBlockStates = new ArrayList<>(coordinates.size()); + for (BlockPos coordinate : coordinates) { + previousBlockStates.add(world.getBlockState(coordinate)); + } - if (world.isRemote) { - BlockPreviewRenderer.onBlocksBroken(); + if (world.isRemote) { + BlockPreviewRenderer.onBlocksBroken(); - //list of air blockstates - for (int i = 0; i < coordinates.size(); i++) { - newBlockStates.add(Blocks.AIR.getDefaultState()); - } + //list of air blockstates + for (int i = 0; i < coordinates.size(); i++) { + newBlockStates.add(Blocks.AIR.getDefaultState()); + } - } else { + } else { - //If the player is going to instabreak grass or a plant, only break other instabreaking things - boolean onlyInstaBreaking = !player.isCreative() && - world.getBlockState(startCoordinates.get(0)).getBlockHardness(world, startCoordinates.get(0)) == 0f; + //If the player is going to instabreak grass or a plant, only break other instabreaking things + boolean onlyInstaBreaking = !player.isCreative() && + world.getBlockState(startCoordinates.get(0)).getBlockHardness(world, startCoordinates.get(0)) == 0f; - //break all those blocks - for (int i = breakStartPos ? 0 : 1; i < coordinates.size(); i++) { - BlockPos coordinate = coordinates.get(i); - if (world.isBlockPresent(coordinate) && !world.isAirBlock(coordinate)) { - if (!onlyInstaBreaking || world.getBlockState(coordinate).getBlockHardness(world, coordinate) == 0f) { - SurvivalHelper.breakBlock(world, player, coordinate, false); - } - } - } + //break all those blocks + for (int i = breakStartPos ? 0 : 1; i < coordinates.size(); i++) { + BlockPos coordinate = coordinates.get(i); + if (world.isBlockPresent(coordinate) && !world.isAirBlock(coordinate)) { + if (!onlyInstaBreaking || world.getBlockState(coordinate).getBlockHardness(world, coordinate) == 0f) { + SurvivalHelper.breakBlock(world, player, coordinate, false); + } + } + } - //find actual new blockstates for undo - for (BlockPos coordinate : coordinates) { - newBlockStates.add(world.getBlockState(coordinate)); - } - } + //find actual new blockstates for undo + for (BlockPos coordinate : coordinates) { + newBlockStates.add(world.getBlockState(coordinate)); + } + } - //Set first newBlockState to empty if in NORMAL mode, to make undo/redo work - //(Block isn't broken yet by the time it gets here, and broken after this) - if (!breakStartPos) newBlockStates.set(0, Blocks.AIR.getDefaultState()); + //Set first newBlockState to empty if in NORMAL mode, to make undo/redo work + //(Block isn't broken yet by the time it gets here, and broken after this) + if (!breakStartPos) newBlockStates.set(0, Blocks.AIR.getDefaultState()); - //add to undo stack - BlockPos firstPos = startCoordinates.get(0); - BlockPos secondPos = startCoordinates.get(startCoordinates.size() - 1); - Vec3d hitVec = new Vec3d(0.5, 0.5, 0.5); - UndoRedo.addUndo(player, new BlockSet(coordinates, previousBlockStates, newBlockStates, hitVec, firstPos, secondPos)); + //add to undo stack + BlockPos firstPos = startCoordinates.get(0); + BlockPos secondPos = startCoordinates.get(startCoordinates.size() - 1); + Vector3d hitVec = new Vector3d(0.5, 0.5, 0.5); + UndoRedo.addUndo(player, new BlockSet(coordinates, previousBlockStates, newBlockStates, hitVec, firstPos, secondPos)); - } + } - public static List findCoordinates(PlayerEntity player, List posList) { - List coordinates = new ArrayList<>(); - //Add current blocks being placed too - coordinates.addAll(posList); + public static List findCoordinates(PlayerEntity player, List posList) { + List coordinates = new ArrayList<>(); + //Add current blocks being placed too + coordinates.addAll(posList); - //Find mirror/array/radial mirror coordinates for each blockpos - for (BlockPos blockPos : posList) { - List arrayCoordinates = Array.findCoordinates(player, blockPos); - coordinates.addAll(arrayCoordinates); - coordinates.addAll(Mirror.findCoordinates(player, blockPos)); - coordinates.addAll(RadialMirror.findCoordinates(player, blockPos)); - //get mirror for each array coordinate - for (BlockPos coordinate : arrayCoordinates) { - coordinates.addAll(Mirror.findCoordinates(player, coordinate)); - coordinates.addAll(RadialMirror.findCoordinates(player, coordinate)); - } - } + //Find mirror/array/radial mirror coordinates for each blockpos + for (BlockPos blockPos : posList) { + List arrayCoordinates = Array.findCoordinates(player, blockPos); + coordinates.addAll(arrayCoordinates); + coordinates.addAll(Mirror.findCoordinates(player, blockPos)); + coordinates.addAll(RadialMirror.findCoordinates(player, blockPos)); + //get mirror for each array coordinate + for (BlockPos coordinate : arrayCoordinates) { + coordinates.addAll(Mirror.findCoordinates(player, coordinate)); + coordinates.addAll(RadialMirror.findCoordinates(player, coordinate)); + } + } - return coordinates; - } + return coordinates; + } - public static List findCoordinates(PlayerEntity player, BlockPos blockPos) { - return findCoordinates(player, new ArrayList<>(Arrays.asList(blockPos))); - } + public static List findCoordinates(PlayerEntity player, BlockPos blockPos) { + return findCoordinates(player, new ArrayList<>(Arrays.asList(blockPos))); + } - public static List findBlockStates(PlayerEntity player, List posList, Vec3d hitVec, Direction facing, List itemStacks) { - List blockStates = new ArrayList<>(); - itemStacks.clear(); + public static List findBlockStates(PlayerEntity player, List posList, Vector3d hitVec, Direction facing, List itemStacks) { + List blockStates = new ArrayList<>(); + itemStacks.clear(); - //Get itemstack - ItemStack itemStack = player.getHeldItem(Hand.MAIN_HAND); - if (itemStack.isEmpty() || !CompatHelper.isItemBlockProxy(itemStack)) { - itemStack = player.getHeldItem(Hand.OFF_HAND); - } - if (itemStack.isEmpty() || !CompatHelper.isItemBlockProxy(itemStack)) { - return blockStates; - } + //Get itemstack + ItemStack itemStack = player.getHeldItem(Hand.MAIN_HAND); + if (itemStack.isEmpty() || !CompatHelper.isItemBlockProxy(itemStack)) { + itemStack = player.getHeldItem(Hand.OFF_HAND); + } + if (itemStack.isEmpty() || !CompatHelper.isItemBlockProxy(itemStack)) { + return blockStates; + } - //Get ItemBlock stack - ItemStack itemBlock = ItemStack.EMPTY; - if (itemStack.getItem() instanceof BlockItem) itemBlock = itemStack; - else itemBlock = CompatHelper.getItemBlockFromStack(itemStack); - ItemRandomizerBag.resetRandomness(); + //Get ItemBlock stack + ItemStack itemBlock = ItemStack.EMPTY; + if (itemStack.getItem() instanceof BlockItem) itemBlock = itemStack; + else itemBlock = CompatHelper.getItemBlockFromStack(itemStack); + ItemRandomizerBag.resetRandomness(); - //Add blocks in posList first - for (BlockPos blockPos : posList) { - if (!(itemStack.getItem() instanceof BlockItem)) itemBlock = CompatHelper.getItemBlockFromStack(itemStack); - BlockState blockState = getBlockStateFromItem(itemBlock, player, blockPos, facing, hitVec, Hand.MAIN_HAND); - blockStates.add(blockState); - itemStacks.add(itemBlock); - } + //Add blocks in posList first + for (BlockPos blockPos : posList) { + if (!(itemStack.getItem() instanceof BlockItem)) itemBlock = CompatHelper.getItemBlockFromStack(itemStack); + BlockState blockState = getBlockStateFromItem(itemBlock, player, blockPos, facing, hitVec, Hand.MAIN_HAND); + blockStates.add(blockState); + itemStacks.add(itemBlock); + } - for (BlockPos blockPos : posList) { - BlockState blockState = getBlockStateFromItem(itemBlock, player, blockPos, facing, hitVec, Hand.MAIN_HAND); + for (BlockPos blockPos : posList) { + BlockState blockState = getBlockStateFromItem(itemBlock, player, blockPos, facing, hitVec, Hand.MAIN_HAND); - List arrayBlockStates = Array.findBlockStates(player, blockPos, blockState, itemStack, itemStacks); - blockStates.addAll(arrayBlockStates); - blockStates.addAll(Mirror.findBlockStates(player, blockPos, blockState, itemStack, itemStacks)); - blockStates.addAll(RadialMirror.findBlockStates(player, blockPos, blockState, itemStack, itemStacks)); - //add mirror for each array coordinate - List arrayCoordinates = Array.findCoordinates(player, blockPos); - for (int i = 0; i < arrayCoordinates.size(); i++) { - BlockPos coordinate = arrayCoordinates.get(i); - BlockState blockState1 = arrayBlockStates.get(i); - blockStates.addAll(Mirror.findBlockStates(player, coordinate, blockState1, itemStack, itemStacks)); - blockStates.addAll(RadialMirror.findBlockStates(player, coordinate, blockState1, itemStack, itemStacks)); - } + List arrayBlockStates = Array.findBlockStates(player, blockPos, blockState, itemStack, itemStacks); + blockStates.addAll(arrayBlockStates); + blockStates.addAll(Mirror.findBlockStates(player, blockPos, blockState, itemStack, itemStacks)); + blockStates.addAll(RadialMirror.findBlockStates(player, blockPos, blockState, itemStack, itemStacks)); + //add mirror for each array coordinate + List arrayCoordinates = Array.findCoordinates(player, blockPos); + for (int i = 0; i < arrayCoordinates.size(); i++) { + BlockPos coordinate = arrayCoordinates.get(i); + BlockState blockState1 = arrayBlockStates.get(i); + blockStates.addAll(Mirror.findBlockStates(player, coordinate, blockState1, itemStack, itemStacks)); + blockStates.addAll(RadialMirror.findBlockStates(player, coordinate, blockState1, itemStack, itemStacks)); + } - //Adjust blockstates for torches and ladders etc to place on a valid side - //TODO optimize findCoordinates (done twice now) - //TODO fix mirror + //Adjust blockstates for torches and ladders etc to place on a valid side + //TODO optimize findCoordinates (done twice now) + //TODO fix mirror // List coordinates = findCoordinates(player, startPos); // for (int i = 0; i < blockStates.size(); i++) { // blockStates.set(i, blockStates.get(i).getBlock().getStateForPlacement(player.world, coordinates.get(i), facing, // (float) hitVec.x, (float) hitVec.y, (float) hitVec.z, itemStacks.get(i).getMetadata(), player, EnumHand.MAIN_HAND)); // } - } + } - return blockStates; - } + return blockStates; + } - public static boolean isEnabled(ModifierSettingsManager.ModifierSettings modifierSettings, BlockPos startPos) { - return Mirror.isEnabled(modifierSettings.getMirrorSettings(), startPos) || - Array.isEnabled(modifierSettings.getArraySettings()) || - RadialMirror.isEnabled(modifierSettings.getRadialMirrorSettings(), startPos) || - modifierSettings.doQuickReplace(); - } + public static boolean isEnabled(ModifierSettingsManager.ModifierSettings modifierSettings, BlockPos startPos) { + return Mirror.isEnabled(modifierSettings.getMirrorSettings(), startPos) || + Array.isEnabled(modifierSettings.getArraySettings()) || + RadialMirror.isEnabled(modifierSettings.getRadialMirrorSettings(), startPos) || + modifierSettings.doQuickReplace(); + } - public static BlockState getBlockStateFromItem(ItemStack itemStack, PlayerEntity player, BlockPos blockPos, Direction facing, Vec3d hitVec, Hand hand) { - return Block.getBlockFromItem(itemStack.getItem()).getStateForPlacement(new BlockItemUseContext(new ItemUseContext(player, hand, new BlockRayTraceResult(hitVec, facing, blockPos, false)))); - } + public static BlockState getBlockStateFromItem(ItemStack itemStack, PlayerEntity player, BlockPos blockPos, Direction facing, Vector3d hitVec, Hand hand) { + return Block.getBlockFromItem(itemStack.getItem()).getStateForPlacement(new BlockItemUseContext(new ItemUseContext(player, hand, new BlockRayTraceResult(hitVec, facing, blockPos, false)))); + } - //Returns true if equal (or both null) - public static boolean compareCoordinates(List coordinates1, List coordinates2) { - if (coordinates1 == null && coordinates2 == null) return true; - if (coordinates1 == null || coordinates2 == null) return false; + //Returns true if equal (or both null) + public static boolean compareCoordinates(List coordinates1, List coordinates2) { + if (coordinates1 == null && coordinates2 == null) return true; + if (coordinates1 == null || coordinates2 == null) return false; - //Check count, not actual values - if (coordinates1.size() == coordinates2.size()){ - if (coordinates1.size() == 1){ - return coordinates1.get(0).equals(coordinates2.get(0)); - } - return true; - } else { - return false; - } + //Check count, not actual values + if (coordinates1.size() == coordinates2.size()) { + if (coordinates1.size() == 1) { + return coordinates1.get(0).equals(coordinates2.get(0)); + } + return true; + } else { + return false; + } // return coordinates1.equals(coordinates2); - } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/Mirror.java b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/Mirror.java index 590a8a9..afd1002 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/Mirror.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/Mirror.java @@ -1,10 +1,6 @@ package nl.requios.effortlessbuilding.buildmodifier; import net.minecraft.block.*; -import net.minecraft.block.StairsBlock; -import net.minecraft.block.DirectionalBlock; -import net.minecraft.block.SlabBlock; -import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.state.properties.Half; @@ -12,7 +8,7 @@ import net.minecraft.state.properties.SlabType; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import net.minecraftforge.items.IItemHandler; import nl.requios.effortlessbuilding.item.ItemRandomizerBag; @@ -21,208 +17,211 @@ import java.util.List; public class Mirror { - public static class MirrorSettings { - public boolean enabled = false; - public Vec3d position = new Vec3d(0.5, 64.5, 0.5); - public boolean mirrorX = true, mirrorY = false, mirrorZ = false; - public int radius = 10; - public boolean drawLines = true, drawPlanes = true; + public static List findCoordinates(PlayerEntity player, BlockPos startPos) { + List coordinates = new ArrayList<>(); - public MirrorSettings() { - } + //find mirrorsettings for the player + MirrorSettings m = ModifierSettingsManager.getModifierSettings(player).getMirrorSettings(); + if (!isEnabled(m, startPos)) return coordinates; - public MirrorSettings(boolean mirrorEnabled, Vec3d position, boolean mirrorX, boolean mirrorY, boolean mirrorZ, int radius, boolean drawLines, boolean drawPlanes) { - this.enabled = mirrorEnabled; - this.position = position; - this.mirrorX = mirrorX; - this.mirrorY = mirrorY; - this.mirrorZ = mirrorZ; - this.radius = radius; - this.drawLines = drawLines; - this.drawPlanes = drawPlanes; - } + if (m.mirrorX) coordinateMirrorX(m, startPos, coordinates); + if (m.mirrorY) coordinateMirrorY(m, startPos, coordinates); + if (m.mirrorZ) coordinateMirrorZ(m, startPos, coordinates); - public int getReach() { - return radius * 2; //Change ModifierSettings#setReachUpgrade too - } - } - - public static List findCoordinates(PlayerEntity player, BlockPos startPos) { - List coordinates = new ArrayList<>(); + return coordinates; + } - //find mirrorsettings for the player - MirrorSettings m = ModifierSettingsManager.getModifierSettings(player).getMirrorSettings(); - if (!isEnabled(m, startPos)) return coordinates; + private static void coordinateMirrorX(MirrorSettings m, BlockPos oldBlockPos, List coordinates) { + //find mirror position + double x = m.position.x + (m.position.x - oldBlockPos.getX() - 0.5); + BlockPos newBlockPos = new BlockPos(x, oldBlockPos.getY(), oldBlockPos.getZ()); + coordinates.add(newBlockPos); - if (m.mirrorX) coordinateMirrorX(m, startPos, coordinates); - if (m.mirrorY) coordinateMirrorY(m, startPos, coordinates); - if (m.mirrorZ) coordinateMirrorZ(m, startPos, coordinates); + if (m.mirrorY) coordinateMirrorY(m, newBlockPos, coordinates); + if (m.mirrorZ) coordinateMirrorZ(m, newBlockPos, coordinates); + } - return coordinates; - } + private static void coordinateMirrorY(MirrorSettings m, BlockPos oldBlockPos, List coordinates) { + //find mirror position + double y = m.position.y + (m.position.y - oldBlockPos.getY() - 0.5); + BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), y, oldBlockPos.getZ()); + coordinates.add(newBlockPos); - private static void coordinateMirrorX(MirrorSettings m, BlockPos oldBlockPos, List coordinates) { - //find mirror position - double x = m.position.x + (m.position.x - oldBlockPos.getX() - 0.5); - BlockPos newBlockPos = new BlockPos(x, oldBlockPos.getY(), oldBlockPos.getZ()); - coordinates.add(newBlockPos); + if (m.mirrorZ) coordinateMirrorZ(m, newBlockPos, coordinates); + } - if (m.mirrorY) coordinateMirrorY(m, newBlockPos, coordinates); - if (m.mirrorZ) coordinateMirrorZ(m, newBlockPos, coordinates); - } + private static void coordinateMirrorZ(MirrorSettings m, BlockPos oldBlockPos, List coordinates) { + //find mirror position + double z = m.position.z + (m.position.z - oldBlockPos.getZ() - 0.5); + BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), oldBlockPos.getY(), z); + coordinates.add(newBlockPos); + } - private static void coordinateMirrorY(MirrorSettings m, BlockPos oldBlockPos, List coordinates) { - //find mirror position - double y = m.position.y + (m.position.y - oldBlockPos.getY() - 0.5); - BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), y, oldBlockPos.getZ()); - coordinates.add(newBlockPos); + public static List findBlockStates(PlayerEntity player, BlockPos startPos, BlockState blockState, ItemStack itemStack, List itemStacks) { + List blockStates = new ArrayList<>(); - if (m.mirrorZ) coordinateMirrorZ(m, newBlockPos, coordinates); - } + //find mirrorsettings for the player + MirrorSettings m = ModifierSettingsManager.getModifierSettings(player).getMirrorSettings(); + if (!isEnabled(m, startPos)) return blockStates; - private static void coordinateMirrorZ(MirrorSettings m, BlockPos oldBlockPos, List coordinates) { - //find mirror position - double z = m.position.z + (m.position.z - oldBlockPos.getZ() - 0.5); - BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), oldBlockPos.getY(), z); - coordinates.add(newBlockPos); - } + //Randomizer bag synergy + IItemHandler bagInventory = null; + if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemRandomizerBag) { + bagInventory = ItemRandomizerBag.getBagInventory(itemStack); + } - public static List findBlockStates(PlayerEntity player, BlockPos startPos, BlockState blockState, ItemStack itemStack, List itemStacks) { - List blockStates = new ArrayList<>(); + if (m.mirrorX) + blockStateMirrorX(player, m, startPos, blockState, bagInventory, itemStack, Hand.MAIN_HAND, blockStates, itemStacks); + if (m.mirrorY) + blockStateMirrorY(player, m, startPos, blockState, bagInventory, itemStack, Hand.MAIN_HAND, blockStates, itemStacks); + if (m.mirrorZ) + blockStateMirrorZ(player, m, startPos, blockState, bagInventory, itemStack, Hand.MAIN_HAND, blockStates, itemStacks); - //find mirrorsettings for the player - MirrorSettings m = ModifierSettingsManager.getModifierSettings(player).getMirrorSettings(); - if (!isEnabled(m, startPos)) return blockStates; + return blockStates; + } - //Randomizer bag synergy - IItemHandler bagInventory = null; - if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemRandomizerBag) { - bagInventory = ItemRandomizerBag.getBagInventory(itemStack); - } + private static void blockStateMirrorX(PlayerEntity player, MirrorSettings m, BlockPos oldBlockPos, BlockState oldBlockState, + IItemHandler bagInventory, ItemStack itemStack, Hand hand, List blockStates, List itemStacks) { + //find mirror position + double x = m.position.x + (m.position.x - oldBlockPos.getX() - 0.5); + BlockPos newBlockPos = new BlockPos(x, oldBlockPos.getY(), oldBlockPos.getZ()); - if (m.mirrorX) blockStateMirrorX(player, m, startPos, blockState, bagInventory, itemStack, Hand.MAIN_HAND, blockStates, itemStacks); - if (m.mirrorY) blockStateMirrorY(player, m, startPos, blockState, bagInventory, itemStack, Hand.MAIN_HAND, blockStates, itemStacks); - if (m.mirrorZ) blockStateMirrorZ(player, m, startPos, blockState, bagInventory, itemStack, Hand.MAIN_HAND, blockStates, itemStacks); + //Randomizer bag synergy + if (bagInventory != null) { + itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); + oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, Direction.UP, new Vector3d(0, 0, 0), hand); + } - return blockStates; - } + //Find blockstate + BlockState newBlockState = oldBlockState == null ? null : oldBlockState.mirror(net.minecraft.util.Mirror.FRONT_BACK); - private static void blockStateMirrorX(PlayerEntity player, MirrorSettings m, BlockPos oldBlockPos, BlockState oldBlockState, - IItemHandler bagInventory, ItemStack itemStack, Hand hand, List blockStates, List itemStacks) { - //find mirror position - double x = m.position.x + (m.position.x - oldBlockPos.getX() - 0.5); - BlockPos newBlockPos = new BlockPos(x, oldBlockPos.getY(), oldBlockPos.getZ()); + //Store blockstate and itemstack + blockStates.add(newBlockState); + itemStacks.add(itemStack); - //Randomizer bag synergy - if (bagInventory != null) { - itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); - oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, Direction.UP, new Vec3d(0, 0, 0), hand); - } + if (m.mirrorY) + blockStateMirrorY(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks); + if (m.mirrorZ) + blockStateMirrorZ(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks); + } - //Find blockstate - BlockState newBlockState = oldBlockState == null ? null : oldBlockState.mirror(net.minecraft.util.Mirror.FRONT_BACK); + private static void blockStateMirrorY(PlayerEntity player, MirrorSettings m, BlockPos oldBlockPos, BlockState oldBlockState, + IItemHandler bagInventory, ItemStack itemStack, Hand hand, List blockStates, List itemStacks) { + //find mirror position + double y = m.position.y + (m.position.y - oldBlockPos.getY() - 0.5); + BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), y, oldBlockPos.getZ()); - //Store blockstate and itemstack - blockStates.add(newBlockState); - itemStacks.add(itemStack); + //Randomizer bag synergy + if (bagInventory != null) { + itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); + oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, Direction.UP, new Vector3d(0, 0, 0), hand); + } - if (m.mirrorY) blockStateMirrorY(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks); - if (m.mirrorZ) blockStateMirrorZ(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks); - } + //Find blockstate + BlockState newBlockState = oldBlockState == null ? null : getVerticalMirror(oldBlockState); - private static void blockStateMirrorY(PlayerEntity player, MirrorSettings m, BlockPos oldBlockPos, BlockState oldBlockState, - IItemHandler bagInventory, ItemStack itemStack, Hand hand, List blockStates, List itemStacks) { - //find mirror position - double y = m.position.y + (m.position.y - oldBlockPos.getY() - 0.5); - BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), y, oldBlockPos.getZ()); + //Store blockstate and itemstack + blockStates.add(newBlockState); + itemStacks.add(itemStack); - //Randomizer bag synergy - if (bagInventory != null) { - itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); - oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, Direction.UP, new Vec3d(0, 0, 0), hand); - } + if (m.mirrorZ) + blockStateMirrorZ(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks); + } - //Find blockstate - BlockState newBlockState = oldBlockState == null ? null : getVerticalMirror(oldBlockState); + private static void blockStateMirrorZ(PlayerEntity player, MirrorSettings m, BlockPos oldBlockPos, BlockState oldBlockState, + IItemHandler bagInventory, ItemStack itemStack, Hand hand, List blockStates, List itemStacks) { + //find mirror position + double z = m.position.z + (m.position.z - oldBlockPos.getZ() - 0.5); + BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), oldBlockPos.getY(), z); - //Store blockstate and itemstack - blockStates.add(newBlockState); - itemStacks.add(itemStack); + //Randomizer bag synergy + if (bagInventory != null) { + itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); + oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, Direction.UP, new Vector3d(0, 0, 0), hand); + } - if (m.mirrorZ) blockStateMirrorZ(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks); - } + //Find blockstate + BlockState newBlockState = oldBlockState == null ? null : oldBlockState.mirror(net.minecraft.util.Mirror.LEFT_RIGHT); - private static void blockStateMirrorZ(PlayerEntity player, MirrorSettings m, BlockPos oldBlockPos, BlockState oldBlockState, - IItemHandler bagInventory, ItemStack itemStack, Hand hand, List blockStates, List itemStacks) { - //find mirror position - double z = m.position.z + (m.position.z - oldBlockPos.getZ() - 0.5); - BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), oldBlockPos.getY(), z); + //Store blockstate and itemstack + blockStates.add(newBlockState); + itemStacks.add(itemStack); + } - //Randomizer bag synergy - if (bagInventory != null) { - itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); - oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, Direction.UP, new Vec3d(0, 0, 0), hand); - } + public static boolean isEnabled(MirrorSettings m, BlockPos startPos) { + if (m == null || !m.enabled || (!m.mirrorX && !m.mirrorY && !m.mirrorZ)) return false; - //Find blockstate - BlockState newBlockState = oldBlockState == null ? null : oldBlockState.mirror(net.minecraft.util.Mirror.LEFT_RIGHT); + //within mirror distance + return !(startPos.getX() + 0.5 < m.position.x - m.radius) && !(startPos.getX() + 0.5 > m.position.x + m.radius) && + !(startPos.getY() + 0.5 < m.position.y - m.radius) && !(startPos.getY() + 0.5 > m.position.y + m.radius) && + !(startPos.getZ() + 0.5 < m.position.z - m.radius) && !(startPos.getZ() + 0.5 > m.position.z + m.radius); + } - //Store blockstate and itemstack - blockStates.add(newBlockState); - itemStacks.add(itemStack); - } + private static BlockState getVerticalMirror(BlockState blockState) { + //Stairs + if (blockState.getBlock() instanceof StairsBlock) { + if (blockState.get(StairsBlock.HALF) == Half.BOTTOM) { + return blockState.with(StairsBlock.HALF, Half.TOP); + } else { + return blockState.with(StairsBlock.HALF, Half.BOTTOM); + } + } - public static boolean isEnabled(MirrorSettings m, BlockPos startPos) { - if (m == null || !m.enabled || (!m.mirrorX && !m.mirrorY && !m.mirrorZ)) return false; + //Slabs + if (blockState.getBlock() instanceof SlabBlock) { + if (blockState.get(SlabBlock.TYPE) == SlabType.DOUBLE) { + return blockState; + } else if (blockState.get(SlabBlock.TYPE) == SlabType.BOTTOM) { + return blockState.with(SlabBlock.TYPE, SlabType.TOP); + } else { + return blockState.with(SlabBlock.TYPE, SlabType.BOTTOM); + } + } - //within mirror distance - if (startPos.getX() + 0.5 < m.position.x - m.radius || startPos.getX() + 0.5 > m.position.x + m.radius || - startPos.getY() + 0.5 < m.position.y - m.radius || startPos.getY() + 0.5 > m.position.y + m.radius || - startPos.getZ() + 0.5 < m.position.z - m.radius || startPos.getZ() + 0.5 > m.position.z + m.radius) - return false; + //Buttons, endrod, observer, piston + if (blockState.getBlock() instanceof DirectionalBlock) { + if (blockState.get(DirectionalBlock.FACING) == Direction.DOWN) { + return blockState.with(DirectionalBlock.FACING, Direction.UP); + } else if (blockState.get(DirectionalBlock.FACING) == Direction.UP) { + return blockState.with(DirectionalBlock.FACING, Direction.DOWN); + } + } - return true; - } + //Dispenser, dropper + if (blockState.getBlock() instanceof DispenserBlock) { + if (blockState.get(DispenserBlock.FACING) == Direction.DOWN) { + return blockState.with(DispenserBlock.FACING, Direction.UP); + } else if (blockState.get(DispenserBlock.FACING) == Direction.UP) { + return blockState.with(DispenserBlock.FACING, Direction.DOWN); + } + } - private static BlockState getVerticalMirror(BlockState blockState) { - //Stairs - if (blockState.getBlock() instanceof StairsBlock) { - if (blockState.get(StairsBlock.HALF) == Half.BOTTOM) { - return blockState.with(StairsBlock.HALF, Half.TOP); - } else { - return blockState.with(StairsBlock.HALF, Half.BOTTOM); - } - } + return blockState; + } - //Slabs - if (blockState.getBlock() instanceof SlabBlock) { - if (blockState.get(SlabBlock.TYPE) == SlabType.DOUBLE) { - return blockState; - } else if (blockState.get(SlabBlock.TYPE) == SlabType.BOTTOM) { - return blockState.with(SlabBlock.TYPE, SlabType.TOP); - } else { - return blockState.with(SlabBlock.TYPE, SlabType.BOTTOM); - } - } + public static class MirrorSettings { + public boolean enabled = false; + public Vector3d position = new Vector3d(0.5, 64.5, 0.5); + public boolean mirrorX = true, mirrorY = false, mirrorZ = false; + public int radius = 10; + public boolean drawLines = true, drawPlanes = true; - //Buttons, endrod, observer, piston - if (blockState.getBlock() instanceof DirectionalBlock) { - if (blockState.get(DirectionalBlock.FACING) == Direction.DOWN) { - return blockState.with(DirectionalBlock.FACING, Direction.UP); - } else if (blockState.get(DirectionalBlock.FACING) == Direction.UP) { - return blockState.with(DirectionalBlock.FACING, Direction.DOWN); - } - } + public MirrorSettings() { + } - //Dispenser, dropper - if (blockState.getBlock() instanceof DispenserBlock) { - if (blockState.get(DispenserBlock.FACING) == Direction.DOWN) { - return blockState.with(DispenserBlock.FACING, Direction.UP); - } else if (blockState.get(DispenserBlock.FACING) == Direction.UP) { - return blockState.with(DispenserBlock.FACING, Direction.DOWN); - } - } + public MirrorSettings(boolean mirrorEnabled, Vector3d position, boolean mirrorX, boolean mirrorY, boolean mirrorZ, int radius, boolean drawLines, boolean drawPlanes) { + this.enabled = mirrorEnabled; + this.position = position; + this.mirrorX = mirrorX; + this.mirrorY = mirrorY; + this.mirrorZ = mirrorZ; + this.radius = radius; + this.drawLines = drawLines; + this.drawPlanes = drawPlanes; + } - return blockState; - } + public int getReach() { + return radius * 2; //Change ModifierSettings#setReachUpgrade too + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/ModifierSettingsManager.java b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/ModifierSettingsManager.java index e24e8b3..3d5fc12 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/ModifierSettingsManager.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/ModifierSettingsManager.java @@ -17,191 +17,199 @@ import javax.annotation.Nonnull; @Mod.EventBusSubscriber public class ModifierSettingsManager { - //Retrieves the buildsettings of a player through the modifierCapability capability - //Never returns null - @Nonnull - public static ModifierSettings getModifierSettings(PlayerEntity player){ - LazyOptional modifierCapability = - player.getCapability(ModifierCapabilityManager.modifierCapability, null); + //Retrieves the buildsettings of a player through the modifierCapability capability + //Never returns null + @Nonnull + public static ModifierSettings getModifierSettings(PlayerEntity player) { + LazyOptional modifierCapability = + player.getCapability(ModifierCapabilityManager.modifierCapability, null); - if (modifierCapability.isPresent()) { - ModifierCapabilityManager.IModifierCapability capability = modifierCapability.orElse(null); - if (capability.getModifierData() == null) { - capability.setModifierData(new ModifierSettings()); - } - return capability.getModifierData(); - } + if (modifierCapability.isPresent()) { + ModifierCapabilityManager.IModifierCapability capability = modifierCapability.orElse(null); + if (capability.getModifierData() == null) { + capability.setModifierData(new ModifierSettings()); + } + return capability.getModifierData(); + } - //Player does not have modifierCapability capability - //Return dummy settings - return new ModifierSettings(); + //Player does not have modifierCapability capability + //Return dummy settings + return new ModifierSettings(); // throw new IllegalArgumentException("Player does not have modifierCapability capability"); - } + } - public static void setModifierSettings(PlayerEntity player, ModifierSettings modifierSettings) { - if (player == null) { - EffortlessBuilding.log("Cannot set buildsettings, player is null"); - return; - } + public static void setModifierSettings(PlayerEntity player, ModifierSettings modifierSettings) { + if (player == null) { + EffortlessBuilding.log("Cannot set buildsettings, player is null"); + return; + } - LazyOptional modifierCapability = - player.getCapability(ModifierCapabilityManager.modifierCapability, null); + LazyOptional modifierCapability = + player.getCapability(ModifierCapabilityManager.modifierCapability, null); - modifierCapability.ifPresent((capability) -> { - capability.setModifierData(modifierSettings); - }); + modifierCapability.ifPresent((capability) -> { + capability.setModifierData(modifierSettings); + }); - if (!modifierCapability.isPresent()) { - EffortlessBuilding.log(player, "Saving buildsettings failed."); - } - } + if (!modifierCapability.isPresent()) { + EffortlessBuilding.log(player, "Saving buildsettings failed."); + } + } - public static String sanitize(ModifierSettings modifierSettings, PlayerEntity player) { - int maxReach = ReachHelper.getMaxReach(player); - String error = ""; + public static String sanitize(ModifierSettings modifierSettings, PlayerEntity player) { + int maxReach = ReachHelper.getMaxReach(player); + String error = ""; - //Mirror settings - Mirror.MirrorSettings m = modifierSettings.getMirrorSettings(); - if (m.radius < 1) { - m.radius = 1; - error += "Mirror size has to be at least 1. This has been corrected. "; - } - if (m.getReach() > maxReach) { - m.radius = maxReach / 2; - error += "Mirror exceeds your maximum reach of " + (maxReach / 2) + ". Radius has been set to "+ (maxReach / 2) + ". "; - } + //Mirror settings + Mirror.MirrorSettings m = modifierSettings.getMirrorSettings(); + if (m.radius < 1) { + m.radius = 1; + error += "Mirror size has to be at least 1. This has been corrected. "; + } + if (m.getReach() > maxReach) { + m.radius = maxReach / 2; + error += "Mirror exceeds your maximum reach of " + (maxReach / 2) + ". Radius has been set to " + (maxReach / 2) + ". "; + } - //Array settings - Array.ArraySettings a = modifierSettings.getArraySettings(); - if (a.count < 0) { - a.count = 0; - error += "Array count may not be negative. It has been reset to 0."; - } + //Array settings + Array.ArraySettings a = modifierSettings.getArraySettings(); + if (a.count < 0) { + a.count = 0; + error += "Array count may not be negative. It has been reset to 0."; + } - if (a.getReach() > maxReach) { - a.count = 0; - error += "Array exceeds your maximum reach of " + maxReach + ". Array count has been reset to 0. "; - } + if (a.getReach() > maxReach) { + a.count = 0; + error += "Array exceeds your maximum reach of " + maxReach + ". Array count has been reset to 0. "; + } - //Radial mirror settings - RadialMirror.RadialMirrorSettings r = modifierSettings.getRadialMirrorSettings(); - if (r.slices < 2) { - r.slices = 2; - error += "Radial mirror needs to have at least 2 slices. Slices has been set to 2."; - } + //Radial mirror settings + RadialMirror.RadialMirrorSettings r = modifierSettings.getRadialMirrorSettings(); + if (r.slices < 2) { + r.slices = 2; + error += "Radial mirror needs to have at least 2 slices. Slices has been set to 2."; + } - if (r.radius < 1) { - r.radius = 1; - error += "Radial mirror radius has to be at least 1. This has been corrected. "; - } - if (r.getReach() > maxReach) { - r.radius = maxReach / 2; - error += "Radial mirror exceeds your maximum reach of " + (maxReach / 2) + ". Radius has been set to "+ (maxReach / 2) + ". "; - } + if (r.radius < 1) { + r.radius = 1; + error += "Radial mirror radius has to be at least 1. This has been corrected. "; + } + if (r.getReach() > maxReach) { + r.radius = maxReach / 2; + error += "Radial mirror exceeds your maximum reach of " + (maxReach / 2) + ". Radius has been set to " + (maxReach / 2) + ". "; + } - //Other - if (modifierSettings.reachUpgrade < 0) { - modifierSettings.reachUpgrade = 0; - } - if (modifierSettings.reachUpgrade > 3) { - modifierSettings.reachUpgrade = 3; - } + //Other + if (modifierSettings.reachUpgrade < 0) { + modifierSettings.reachUpgrade = 0; + } + if (modifierSettings.reachUpgrade > 3) { + modifierSettings.reachUpgrade = 3; + } - return error; - } + return error; + } - public static class ModifierSettings { - private Mirror.MirrorSettings mirrorSettings; - private Array.ArraySettings arraySettings; - private RadialMirror.RadialMirrorSettings radialMirrorSettings; - private boolean quickReplace = false; - private int reachUpgrade = 0; + public static void handleNewPlayer(PlayerEntity player) { + //Makes sure player has modifier settings (if it doesnt it will create it) + getModifierSettings(player); - public ModifierSettings() { - mirrorSettings = new Mirror.MirrorSettings(); - arraySettings = new Array.ArraySettings(); - radialMirrorSettings = new RadialMirror.RadialMirrorSettings(); - } + //Only on server + if (!player.world.isRemote) { + //Send to client + ModifierSettingsMessage msg = new ModifierSettingsMessage(getModifierSettings(player)); + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), msg); + } + } - public ModifierSettings(Mirror.MirrorSettings mirrorSettings, Array.ArraySettings arraySettings, - RadialMirror.RadialMirrorSettings radialMirrorSettings, boolean quickReplace, int reachUpgrade) { - this.mirrorSettings = mirrorSettings; - this.arraySettings = arraySettings; - this.radialMirrorSettings = radialMirrorSettings; - this.quickReplace = quickReplace; - this.reachUpgrade = reachUpgrade; - } + public static class ModifierSettings { + private Mirror.MirrorSettings mirrorSettings; + private Array.ArraySettings arraySettings; + private RadialMirror.RadialMirrorSettings radialMirrorSettings; + private boolean quickReplace = false; + private int reachUpgrade = 0; - public Mirror.MirrorSettings getMirrorSettings() { - if (this.mirrorSettings == null) this.mirrorSettings = new Mirror.MirrorSettings(); - return this.mirrorSettings; - } + public ModifierSettings() { + mirrorSettings = new Mirror.MirrorSettings(); + arraySettings = new Array.ArraySettings(); + radialMirrorSettings = new RadialMirror.RadialMirrorSettings(); + } - public void setMirrorSettings(Mirror.MirrorSettings mirrorSettings) { - if (mirrorSettings == null) return; - this.mirrorSettings = mirrorSettings; - } + public ModifierSettings(Mirror.MirrorSettings mirrorSettings, Array.ArraySettings arraySettings, + RadialMirror.RadialMirrorSettings radialMirrorSettings, boolean quickReplace, int reachUpgrade) { + this.mirrorSettings = mirrorSettings; + this.arraySettings = arraySettings; + this.radialMirrorSettings = radialMirrorSettings; + this.quickReplace = quickReplace; + this.reachUpgrade = reachUpgrade; + } - public Array.ArraySettings getArraySettings() { - if (this.arraySettings == null) this.arraySettings = new Array.ArraySettings(); - return this.arraySettings; - } + public Mirror.MirrorSettings getMirrorSettings() { + if (this.mirrorSettings == null) this.mirrorSettings = new Mirror.MirrorSettings(); + return this.mirrorSettings; + } - public void setArraySettings(Array.ArraySettings arraySettings) { - if (arraySettings == null) return; - this.arraySettings = arraySettings; - } + public void setMirrorSettings(Mirror.MirrorSettings mirrorSettings) { + if (mirrorSettings == null) return; + this.mirrorSettings = mirrorSettings; + } - public RadialMirror.RadialMirrorSettings getRadialMirrorSettings() { - if (this.radialMirrorSettings == null) this.radialMirrorSettings = new RadialMirror.RadialMirrorSettings(); - return this.radialMirrorSettings; - } + public Array.ArraySettings getArraySettings() { + if (this.arraySettings == null) this.arraySettings = new Array.ArraySettings(); + return this.arraySettings; + } - public void setRadialMirrorSettings(RadialMirror.RadialMirrorSettings radialMirrorSettings) { - if (radialMirrorSettings == null) return; - this.radialMirrorSettings = radialMirrorSettings; - } + public void setArraySettings(Array.ArraySettings arraySettings) { + if (arraySettings == null) return; + this.arraySettings = arraySettings; + } - public boolean doQuickReplace() { - return quickReplace; - } + public RadialMirror.RadialMirrorSettings getRadialMirrorSettings() { + if (this.radialMirrorSettings == null) this.radialMirrorSettings = new RadialMirror.RadialMirrorSettings(); + return this.radialMirrorSettings; + } - public void setQuickReplace(boolean quickReplace) { - this.quickReplace = quickReplace; - } + public void setRadialMirrorSettings(RadialMirror.RadialMirrorSettings radialMirrorSettings) { + if (radialMirrorSettings == null) return; + this.radialMirrorSettings = radialMirrorSettings; + } - public int getReachUpgrade() { - return reachUpgrade; - } + public boolean doQuickReplace() { + return quickReplace; + } - public void setReachUpgrade(int reachUpgrade) { - this.reachUpgrade = reachUpgrade; - //Set mirror radius to max - int reach = 10; - switch (reachUpgrade) { - case 0: reach = BuildConfig.reach.maxReachLevel0.get(); break; - case 1: reach = BuildConfig.reach.maxReachLevel1.get(); break; - case 2: reach = BuildConfig.reach.maxReachLevel2.get(); break; - case 3: reach = BuildConfig.reach.maxReachLevel3.get(); break; - } + public void setQuickReplace(boolean quickReplace) { + this.quickReplace = quickReplace; + } - if (this.mirrorSettings != null) - this.mirrorSettings.radius = reach / 2; - if (this.radialMirrorSettings != null) - this.radialMirrorSettings.radius = reach / 2; - } - } + public int getReachUpgrade() { + return reachUpgrade; + } - public static void handleNewPlayer(PlayerEntity player){ - //Makes sure player has modifier settings (if it doesnt it will create it) - getModifierSettings(player); + public void setReachUpgrade(int reachUpgrade) { + this.reachUpgrade = reachUpgrade; + //Set mirror radius to max + int reach = 10; + switch (reachUpgrade) { + case 0: + reach = BuildConfig.reach.maxReachLevel0.get(); + break; + case 1: + reach = BuildConfig.reach.maxReachLevel1.get(); + break; + case 2: + reach = BuildConfig.reach.maxReachLevel2.get(); + break; + case 3: + reach = BuildConfig.reach.maxReachLevel3.get(); + break; + } - //Only on server - if (!player.world.isRemote) { - //Send to client - ModifierSettingsMessage msg = new ModifierSettingsMessage(getModifierSettings(player)); - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), msg); - } - } + if (this.mirrorSettings != null) + this.mirrorSettings.radius = reach / 2; + if (this.radialMirrorSettings != null) + this.radialMirrorSettings.radius = reach / 2; + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/RadialMirror.java b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/RadialMirror.java index ee81f9b..ce4efd7 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/RadialMirror.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/RadialMirror.java @@ -9,7 +9,7 @@ import net.minecraft.util.Mirror; import net.minecraft.util.Rotation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import net.minecraftforge.items.IItemHandler; import nl.requios.effortlessbuilding.item.ItemRandomizerBag; @@ -18,178 +18,175 @@ import java.util.List; public class RadialMirror { - public static class RadialMirrorSettings { - public boolean enabled = false; - public Vec3d position = new Vec3d(0.5, 64.5, 0.5); - public int slices = 4; - public boolean alternate = false; - public int radius = 20; - public boolean drawLines = true, drawPlanes = false; + public static List findCoordinates(PlayerEntity player, BlockPos startPos) { + List coordinates = new ArrayList<>(); - public RadialMirrorSettings() { - } + //find radial mirror settings for the player + RadialMirrorSettings r = ModifierSettingsManager.getModifierSettings(player).getRadialMirrorSettings(); + if (!isEnabled(r, startPos)) return coordinates; - public RadialMirrorSettings(boolean enabled, Vec3d position, int slices, boolean alternate, int radius, boolean drawLines, boolean drawPlanes) { - this.enabled = enabled; - this.position = position; - this.slices = slices; - this.alternate = alternate; - this.radius = radius; - this.drawLines = drawLines; - this.drawPlanes = drawPlanes; - } + //get angle between slices + double sliceAngle = 2 * Math.PI / r.slices; - public int getReach() { - return radius * 2; - } - } + Vector3d startVec = new Vector3d(startPos.getX() + 0.5f, startPos.getY() + 0.5f, startPos.getZ() + 0.5f); + Vector3d relStartVec = startVec.subtract(r.position); - public static List findCoordinates(PlayerEntity player, BlockPos startPos) { - List coordinates = new ArrayList<>(); + double startAngleToCenter = MathHelper.atan2(relStartVec.x, relStartVec.z); + if (startAngleToCenter < 0) startAngleToCenter += Math.PI; + double startAngleInSlice = startAngleToCenter % sliceAngle; - //find radial mirror settings for the player - RadialMirrorSettings r = ModifierSettingsManager.getModifierSettings(player).getRadialMirrorSettings(); - if (!isEnabled(r, startPos)) return coordinates; + for (int i = 1; i < r.slices; i++) { + double curAngle = sliceAngle * i; - //get angle between slices - double sliceAngle = 2 * Math.PI / r.slices; + //alternate mirroring of slices + if (r.alternate && i % 2 == 1) { + curAngle = curAngle - startAngleInSlice + (sliceAngle - startAngleInSlice); + } - Vec3d startVec = new Vec3d(startPos.getX() + 0.5f, startPos.getY() + 0.5f, startPos.getZ() + 0.5f); - Vec3d relStartVec = startVec.subtract(r.position); + Vector3d relNewVec = relStartVec.rotateYaw((float) curAngle); + BlockPos newBlockPos = new BlockPos(r.position.add(relNewVec)); + if (!coordinates.contains(newBlockPos) && !newBlockPos.equals(startPos)) coordinates.add(newBlockPos); + } - double startAngleToCenter = MathHelper.atan2(relStartVec.x, relStartVec.z); - if (startAngleToCenter < 0) startAngleToCenter += Math.PI; - double startAngleInSlice = startAngleToCenter % sliceAngle; + return coordinates; + } - for (int i = 1; i < r.slices; i++) { - double curAngle = sliceAngle * i; + public static List findBlockStates(PlayerEntity player, BlockPos startPos, BlockState blockState, ItemStack itemStack, List itemStacks) { + List blockStates = new ArrayList<>(); + List coordinates = new ArrayList<>(); //to keep track of duplicates - //alternate mirroring of slices - if (r.alternate && i%2 == 1) { - curAngle = curAngle - startAngleInSlice + (sliceAngle - startAngleInSlice); - } - - Vec3d relNewVec = relStartVec.rotateYaw((float) curAngle); - BlockPos newBlockPos = new BlockPos(r.position.add(relNewVec)); - if (!coordinates.contains(newBlockPos) && !newBlockPos.equals(startPos)) coordinates.add(newBlockPos); - } - - return coordinates; - } - - public static List findBlockStates(PlayerEntity player, BlockPos startPos, BlockState blockState, ItemStack itemStack, List itemStacks) { - List blockStates = new ArrayList<>(); - List coordinates = new ArrayList<>(); //to keep track of duplicates - - //find radial mirror settings for the player that placed the block - RadialMirrorSettings r = ModifierSettingsManager.getModifierSettings(player).getRadialMirrorSettings(); - if (!isEnabled(r, startPos)) return blockStates; + //find radial mirror settings for the player that placed the block + RadialMirrorSettings r = ModifierSettingsManager.getModifierSettings(player).getRadialMirrorSettings(); + if (!isEnabled(r, startPos)) return blockStates; - //get angle between slices - double sliceAngle = 2 * Math.PI / r.slices; + //get angle between slices + double sliceAngle = 2 * Math.PI / r.slices; - Vec3d startVec = new Vec3d(startPos.getX() + 0.5f, startPos.getY() + 0.5f, startPos.getZ() + 0.5f); - Vec3d relStartVec = startVec.subtract(r.position); + Vector3d startVec = new Vector3d(startPos.getX() + 0.5f, startPos.getY() + 0.5f, startPos.getZ() + 0.5f); + Vector3d relStartVec = startVec.subtract(r.position); - double startAngleToCenter = MathHelper.atan2(relStartVec.x, relStartVec.z); - double startAngleToCenterMod = startAngleToCenter < 0 ? startAngleToCenter + Math.PI : startAngleToCenter; - double startAngleInSlice = startAngleToCenterMod % sliceAngle; + double startAngleToCenter = MathHelper.atan2(relStartVec.x, relStartVec.z); + double startAngleToCenterMod = startAngleToCenter < 0 ? startAngleToCenter + Math.PI : startAngleToCenter; + double startAngleInSlice = startAngleToCenterMod % sliceAngle; - //Rotate the original blockstate - blockState = rotateOriginalBlockState(startAngleToCenter, blockState); + //Rotate the original blockstate + blockState = rotateOriginalBlockState(startAngleToCenter, blockState); - //Randomizer bag synergy - IItemHandler bagInventory = null; - if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemRandomizerBag) { - bagInventory = ItemRandomizerBag.getBagInventory(itemStack); - } + //Randomizer bag synergy + IItemHandler bagInventory = null; + if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemRandomizerBag) { + bagInventory = ItemRandomizerBag.getBagInventory(itemStack); + } - BlockState newBlockState; - for (int i = 1; i < r.slices; i++) { - newBlockState = blockState; - double curAngle = sliceAngle * i; + BlockState newBlockState; + for (int i = 1; i < r.slices; i++) { + newBlockState = blockState; + double curAngle = sliceAngle * i; - //alternate mirroring of slices - if (r.alternate && i%2 == 1) { - curAngle = curAngle - startAngleInSlice + (sliceAngle - startAngleInSlice); - } + //alternate mirroring of slices + if (r.alternate && i % 2 == 1) { + curAngle = curAngle - startAngleInSlice + (sliceAngle - startAngleInSlice); + } - Vec3d relNewVec = relStartVec.rotateYaw((float) curAngle); - BlockPos newBlockPos = new BlockPos(r.position.add(relNewVec)); - if (coordinates.contains(newBlockPos) || newBlockPos.equals(startPos)) continue; //filter out duplicates - coordinates.add(newBlockPos); + Vector3d relNewVec = relStartVec.rotateYaw((float) curAngle); + BlockPos newBlockPos = new BlockPos(r.position.add(relNewVec)); + if (coordinates.contains(newBlockPos) || newBlockPos.equals(startPos)) continue; //filter out duplicates + coordinates.add(newBlockPos); - //Randomizer bag synergy - if (bagInventory != null) { - itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); - newBlockState = BuildModifiers - .getBlockStateFromItem(itemStack, player, startPos, Direction.UP, new Vec3d(0, 0, 0), Hand.MAIN_HAND); + //Randomizer bag synergy + if (bagInventory != null) { + itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); + newBlockState = BuildModifiers + .getBlockStateFromItem(itemStack, player, startPos, Direction.UP, new Vector3d(0, 0, 0), Hand.MAIN_HAND); - newBlockState = rotateOriginalBlockState(startAngleToCenter, newBlockState); - } + newBlockState = rotateOriginalBlockState(startAngleToCenter, newBlockState); + } - //rotate - newBlockState = rotateBlockState(relNewVec, newBlockState, r.alternate && i%2 == 1); + //rotate + newBlockState = rotateBlockState(relNewVec, newBlockState, r.alternate && i % 2 == 1); - blockStates.add(newBlockState); - itemStacks.add(itemStack); - } + blockStates.add(newBlockState); + itemStacks.add(itemStack); + } - return blockStates; - } + return blockStates; + } - private static BlockState rotateOriginalBlockState(double startAngleToCenter, BlockState blockState) { - BlockState newBlockState = blockState; + private static BlockState rotateOriginalBlockState(double startAngleToCenter, BlockState blockState) { + BlockState newBlockState = blockState; - if (startAngleToCenter < -0.751 * Math.PI || startAngleToCenter > 0.749 * Math.PI) { - newBlockState = blockState.rotate(Rotation.CLOCKWISE_180); - } else if (startAngleToCenter < -0.251 * Math.PI) { - newBlockState = blockState.rotate(Rotation.COUNTERCLOCKWISE_90); - } else if (startAngleToCenter > 0.249 * Math.PI) { - newBlockState = blockState.rotate(Rotation.CLOCKWISE_90); - } + if (startAngleToCenter < -0.751 * Math.PI || startAngleToCenter > 0.749 * Math.PI) { + newBlockState = blockState.rotate(Rotation.CLOCKWISE_180); + } else if (startAngleToCenter < -0.251 * Math.PI) { + newBlockState = blockState.rotate(Rotation.COUNTERCLOCKWISE_90); + } else if (startAngleToCenter > 0.249 * Math.PI) { + newBlockState = blockState.rotate(Rotation.CLOCKWISE_90); + } - return newBlockState; - } + return newBlockState; + } - private static BlockState rotateBlockState(Vec3d relVec, BlockState blockState, boolean alternate) { - BlockState newBlockState; - double angleToCenter = MathHelper.atan2(relVec.x, relVec.z); //between -PI and PI + private static BlockState rotateBlockState(Vector3d relVec, BlockState blockState, boolean alternate) { + BlockState newBlockState; + double angleToCenter = MathHelper.atan2(relVec.x, relVec.z); //between -PI and PI - if (angleToCenter < -0.751 * Math.PI || angleToCenter > 0.749 * Math.PI) { - newBlockState = blockState.rotate(Rotation.CLOCKWISE_180); - if (alternate) { - newBlockState = newBlockState.mirror(Mirror.FRONT_BACK); - } - } else if (angleToCenter < -0.251 * Math.PI) { - newBlockState = blockState.rotate(Rotation.CLOCKWISE_90); - if (alternate) { - newBlockState = newBlockState.mirror(Mirror.LEFT_RIGHT); - } - } else if (angleToCenter > 0.249 * Math.PI) { - newBlockState = blockState.rotate(Rotation.COUNTERCLOCKWISE_90); - if (alternate) { - newBlockState = newBlockState.mirror(Mirror.LEFT_RIGHT); - } - } else { - newBlockState = blockState; - if (alternate) { - newBlockState = newBlockState.mirror(Mirror.FRONT_BACK); - } - } + if (angleToCenter < -0.751 * Math.PI || angleToCenter > 0.749 * Math.PI) { + newBlockState = blockState.rotate(Rotation.CLOCKWISE_180); + if (alternate) { + newBlockState = newBlockState.mirror(Mirror.FRONT_BACK); + } + } else if (angleToCenter < -0.251 * Math.PI) { + newBlockState = blockState.rotate(Rotation.CLOCKWISE_90); + if (alternate) { + newBlockState = newBlockState.mirror(Mirror.LEFT_RIGHT); + } + } else if (angleToCenter > 0.249 * Math.PI) { + newBlockState = blockState.rotate(Rotation.COUNTERCLOCKWISE_90); + if (alternate) { + newBlockState = newBlockState.mirror(Mirror.LEFT_RIGHT); + } + } else { + newBlockState = blockState; + if (alternate) { + newBlockState = newBlockState.mirror(Mirror.FRONT_BACK); + } + } - return newBlockState; - } + return newBlockState; + } - public static boolean isEnabled(RadialMirrorSettings r, BlockPos startPos) { - if (r == null || !r.enabled) return false; + public static boolean isEnabled(RadialMirrorSettings r, BlockPos startPos) { + if (r == null || !r.enabled) return false; - if (new Vec3d(startPos.getX() + 0.5, startPos.getY() + 0.5, startPos.getZ() + 0.5).subtract(r.position).lengthSquared() > - r.radius * r.radius) - return false; + return !(new Vector3d(startPos.getX() + 0.5, startPos.getY() + 0.5, startPos.getZ() + 0.5).subtract(r.position).lengthSquared() > + r.radius * r.radius); + } - return true; - } + public static class RadialMirrorSettings { + public boolean enabled = false; + public Vector3d position = new Vector3d(0.5, 64.5, 0.5); + public int slices = 4; + public boolean alternate = false; + public int radius = 20; + public boolean drawLines = true, drawPlanes = false; + + public RadialMirrorSettings() { + } + + public RadialMirrorSettings(boolean enabled, Vector3d position, int slices, boolean alternate, int radius, boolean drawLines, boolean drawPlanes) { + this.enabled = enabled; + this.position = position; + this.slices = slices; + this.alternate = alternate; + this.radius = radius; + this.drawLines = drawLines; + this.drawPlanes = drawPlanes; + } + + public int getReach() { + return radius * 2; + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/UndoRedo.java b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/UndoRedo.java index 076d613..72c334f 100644 --- a/src/main/java/nl/requios/effortlessbuilding/buildmodifier/UndoRedo.java +++ b/src/main/java/nl/requios/effortlessbuilding/buildmodifier/UndoRedo.java @@ -5,14 +5,11 @@ import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.BlockItem; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import net.minecraft.world.server.ServerWorld; -import net.minecraft.world.storage.loot.LootContext; -import net.minecraft.world.storage.loot.LootParameterSet; import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.helper.FixedStack; @@ -24,26 +21,26 @@ import java.util.*; public class UndoRedo { - //Undo and redo stacks per player - //Gets added to twice in singleplayer (server and client) if not careful. So separate stacks. - private static Map> undoStacksClient = new HashMap<>(); - private static Map> undoStacksServer = new HashMap<>(); - private static Map> redoStacksClient = new HashMap<>(); - private static Map> redoStacksServer = new HashMap<>(); + //Undo and redo stacks per player + //Gets added to twice in singleplayer (server and client) if not careful. So separate stacks. + private static final Map> undoStacksClient = new HashMap<>(); + private static final Map> undoStacksServer = new HashMap<>(); + private static final Map> redoStacksClient = new HashMap<>(); + private static final Map> redoStacksServer = new HashMap<>(); - //add to undo stack - public static void addUndo(PlayerEntity player, BlockSet blockSet) { - Map> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer; + //add to undo stack + public static void addUndo(PlayerEntity player, BlockSet blockSet) { + Map> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer; - //Assert coordinates is as long as previous and new blockstate lists - if (blockSet.getCoordinates().size() != blockSet.getPreviousBlockStates().size() || - blockSet.getCoordinates().size() != blockSet.getNewBlockStates().size()) { - EffortlessBuilding.logger.error("Coordinates and blockstate lists are not equal length. Coordinates: {}. Previous blockstates: {}. New blockstates: {}.", - blockSet.getCoordinates().size(), blockSet.getPreviousBlockStates().size(), blockSet.getNewBlockStates().size()); - } + //Assert coordinates is as long as previous and new blockstate lists + if (blockSet.getCoordinates().size() != blockSet.getPreviousBlockStates().size() || + blockSet.getCoordinates().size() != blockSet.getNewBlockStates().size()) { + EffortlessBuilding.logger.error("Coordinates and blockstate lists are not equal length. Coordinates: {}. Previous blockstates: {}. New blockstates: {}.", + blockSet.getCoordinates().size(), blockSet.getPreviousBlockStates().size(), blockSet.getNewBlockStates().size()); + } - //Warn if previous and new blockstate are equal - //Can happen in a lot of valid cases + //Warn if previous and new blockstate are equal + //Can happen in a lot of valid cases // for (int i = 0; i < blockSet.getCoordinates().size(); i++) { // if (blockSet.getPreviousBlockStates().get(i).equals(blockSet.getNewBlockStates().get(i))) { // EffortlessBuilding.logger.warn("Previous and new blockstates are equal at index {}. Blockstate: {}.", @@ -51,193 +48,192 @@ public class UndoRedo { // } // } - //If no stack exists, make one - if (!undoStacks.containsKey(player.getUniqueID())) { - undoStacks.put(player.getUniqueID(), new FixedStack<>(new BlockSet[BuildConfig.survivalBalancers.undoStackSize.get()])); - } + //If no stack exists, make one + if (!undoStacks.containsKey(player.getUniqueID())) { + undoStacks.put(player.getUniqueID(), new FixedStack<>(new BlockSet[BuildConfig.survivalBalancers.undoStackSize.get()])); + } - undoStacks.get(player.getUniqueID()).push(blockSet); - } + undoStacks.get(player.getUniqueID()).push(blockSet); + } - private static void addRedo(PlayerEntity player, BlockSet blockSet) { - Map> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer; + private static void addRedo(PlayerEntity player, BlockSet blockSet) { + Map> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer; - //(No asserts necessary, it's private) + //(No asserts necessary, it's private) - //If no stack exists, make one - if (!redoStacks.containsKey(player.getUniqueID())) { - redoStacks.put(player.getUniqueID(), new FixedStack<>(new BlockSet[BuildConfig.survivalBalancers.undoStackSize.get()])); - } + //If no stack exists, make one + if (!redoStacks.containsKey(player.getUniqueID())) { + redoStacks.put(player.getUniqueID(), new FixedStack<>(new BlockSet[BuildConfig.survivalBalancers.undoStackSize.get()])); + } - redoStacks.get(player.getUniqueID()).push(blockSet); - } + redoStacks.get(player.getUniqueID()).push(blockSet); + } - public static boolean undo(PlayerEntity player) { - Map> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer; + public static boolean undo(PlayerEntity player) { + Map> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer; - if (!undoStacks.containsKey(player.getUniqueID())) return false; + if (!undoStacks.containsKey(player.getUniqueID())) return false; - FixedStack undoStack = undoStacks.get(player.getUniqueID()); + FixedStack undoStack = undoStacks.get(player.getUniqueID()); - if (undoStack.isEmpty()) return false; + if (undoStack.isEmpty()) return false; - BlockSet blockSet = undoStack.pop(); - List coordinates = blockSet.getCoordinates(); - List previousBlockStates = blockSet.getPreviousBlockStates(); - List newBlockStates = blockSet.getNewBlockStates(); - Vec3d hitVec = blockSet.getHitVec(); + BlockSet blockSet = undoStack.pop(); + List coordinates = blockSet.getCoordinates(); + List previousBlockStates = blockSet.getPreviousBlockStates(); + List newBlockStates = blockSet.getNewBlockStates(); + Vector3d hitVec = blockSet.getHitVec(); - //Find up to date itemstacks in player inventory - List itemStacks = findItemStacksInInventory(player, previousBlockStates); + //Find up to date itemstacks in player inventory + List itemStacks = findItemStacksInInventory(player, previousBlockStates); - if (player.world.isRemote) { - BlockPreviewRenderer.onBlocksBroken(coordinates, itemStacks, newBlockStates, blockSet.getSecondPos(), blockSet.getFirstPos()); - } else { - //break all those blocks, reset to what they were - for (int i = 0; i < coordinates.size(); i++) { - BlockPos coordinate = coordinates.get(i); - ItemStack itemStack = itemStacks.get(i); + if (player.world.isRemote) { + BlockPreviewRenderer.onBlocksBroken(coordinates, itemStacks, newBlockStates, blockSet.getSecondPos(), blockSet.getFirstPos()); + } else { + //break all those blocks, reset to what they were + for (int i = 0; i < coordinates.size(); i++) { + BlockPos coordinate = coordinates.get(i); + ItemStack itemStack = itemStacks.get(i); - if (previousBlockStates.get(i).equals(newBlockStates.get(i))) continue; + if (previousBlockStates.get(i).equals(newBlockStates.get(i))) continue; - //get blockstate from itemstack - BlockState previousBlockState = Blocks.AIR.getDefaultState(); - if (itemStack.getItem() instanceof BlockItem) { - previousBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState(); - } + //get blockstate from itemstack + BlockState previousBlockState = Blocks.AIR.getDefaultState(); + if (itemStack.getItem() instanceof BlockItem) { + previousBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState(); + } - if (player.world.isBlockPresent(coordinate)) { - //check itemstack empty - if (itemStack.isEmpty()) { - itemStack = findItemStackInInventory(player, previousBlockStates.get(i)); - //get blockstate from new itemstack - if (!itemStack.isEmpty() && itemStack.getItem() instanceof BlockItem) { - previousBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState(); - } else { - if (previousBlockStates.get(i).getBlock() != Blocks.AIR) - EffortlessBuilding.logTranslate(player, "", previousBlockStates.get(i).getBlock().getTranslationKey(), " not found in inventory", true); - previousBlockState = Blocks.AIR.getDefaultState(); - } - } - if (itemStack.isEmpty()) SurvivalHelper.breakBlock(player.world, player, coordinate, true); - //if previousBlockState is air, placeBlock will set it to air - SurvivalHelper.placeBlock(player.world, player, coordinate, previousBlockState, itemStack, Direction.UP, hitVec, true, false, false); - } - } - } + if (player.world.isBlockPresent(coordinate)) { + //check itemstack empty + if (itemStack.isEmpty()) { + itemStack = findItemStackInInventory(player, previousBlockStates.get(i)); + //get blockstate from new itemstack + if (!itemStack.isEmpty() && itemStack.getItem() instanceof BlockItem) { + previousBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState(); + } else { + if (previousBlockStates.get(i).getBlock() != Blocks.AIR) + EffortlessBuilding.logTranslate(player, "", previousBlockStates.get(i).getBlock().getTranslationKey(), " not found in inventory", true); + previousBlockState = Blocks.AIR.getDefaultState(); + } + } + if (itemStack.isEmpty()) SurvivalHelper.breakBlock(player.world, player, coordinate, true); + //if previousBlockState is air, placeBlock will set it to air + SurvivalHelper.placeBlock(player.world, player, coordinate, previousBlockState, itemStack, Direction.UP, hitVec, true, false, false); + } + } + } - //add to redo - addRedo(player, blockSet); + //add to redo + addRedo(player, blockSet); - return true; - } + return true; + } - public static boolean redo(PlayerEntity player) { - Map> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer; + public static boolean redo(PlayerEntity player) { + Map> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer; - if (!redoStacks.containsKey(player.getUniqueID())) return false; + if (!redoStacks.containsKey(player.getUniqueID())) return false; - FixedStack redoStack = redoStacks.get(player.getUniqueID()); + FixedStack redoStack = redoStacks.get(player.getUniqueID()); - if (redoStack.isEmpty()) return false; + if (redoStack.isEmpty()) return false; - BlockSet blockSet = redoStack.pop(); - List coordinates = blockSet.getCoordinates(); - List previousBlockStates = blockSet.getPreviousBlockStates(); - List newBlockStates = blockSet.getNewBlockStates(); - Vec3d hitVec = blockSet.getHitVec(); + BlockSet blockSet = redoStack.pop(); + List coordinates = blockSet.getCoordinates(); + List previousBlockStates = blockSet.getPreviousBlockStates(); + List newBlockStates = blockSet.getNewBlockStates(); + Vector3d hitVec = blockSet.getHitVec(); - //Find up to date itemstacks in player inventory - List itemStacks = findItemStacksInInventory(player, newBlockStates); + //Find up to date itemstacks in player inventory + List itemStacks = findItemStacksInInventory(player, newBlockStates); - if (player.world.isRemote) { - BlockPreviewRenderer.onBlocksPlaced(coordinates, itemStacks, newBlockStates, blockSet.getFirstPos(), blockSet.getSecondPos()); - } else { - //place blocks - for (int i = 0; i < coordinates.size(); i++) { - BlockPos coordinate = coordinates.get(i); - ItemStack itemStack = itemStacks.get(i); + if (player.world.isRemote) { + BlockPreviewRenderer.onBlocksPlaced(coordinates, itemStacks, newBlockStates, blockSet.getFirstPos(), blockSet.getSecondPos()); + } else { + //place blocks + for (int i = 0; i < coordinates.size(); i++) { + BlockPos coordinate = coordinates.get(i); + ItemStack itemStack = itemStacks.get(i); - if (previousBlockStates.get(i).equals(newBlockStates.get(i))) continue; + if (previousBlockStates.get(i).equals(newBlockStates.get(i))) continue; - //get blockstate from itemstack - BlockState newBlockState = Blocks.AIR.getDefaultState(); - if (itemStack.getItem() instanceof BlockItem) { - newBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState(); - } + //get blockstate from itemstack + BlockState newBlockState = Blocks.AIR.getDefaultState(); + if (itemStack.getItem() instanceof BlockItem) { + newBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState(); + } - if (player.world.isBlockPresent(coordinate)) { - //check itemstack empty - if (itemStack.isEmpty()) { - itemStack = findItemStackInInventory(player, newBlockStates.get(i)); - //get blockstate from new itemstack - if (!itemStack.isEmpty() && itemStack.getItem() instanceof BlockItem) { - newBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState(); - } else { - if (newBlockStates.get(i).getBlock() != Blocks.AIR) - EffortlessBuilding.logTranslate(player, "", newBlockStates.get(i).getBlock().getTranslationKey(), " not found in inventory", true); - newBlockState = Blocks.AIR.getDefaultState(); - } - } - if (itemStack.isEmpty()) SurvivalHelper.breakBlock(player.world, player, coordinate, true); - SurvivalHelper.placeBlock(player.world, player, coordinate, newBlockState, itemStack, Direction.UP, hitVec, true, false, false); - } - } - } + if (player.world.isBlockPresent(coordinate)) { + //check itemstack empty + if (itemStack.isEmpty()) { + itemStack = findItemStackInInventory(player, newBlockStates.get(i)); + //get blockstate from new itemstack + if (!itemStack.isEmpty() && itemStack.getItem() instanceof BlockItem) { + newBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState(); + } else { + if (newBlockStates.get(i).getBlock() != Blocks.AIR) + EffortlessBuilding.logTranslate(player, "", newBlockStates.get(i).getBlock().getTranslationKey(), " not found in inventory", true); + newBlockState = Blocks.AIR.getDefaultState(); + } + } + if (itemStack.isEmpty()) SurvivalHelper.breakBlock(player.world, player, coordinate, true); + SurvivalHelper.placeBlock(player.world, player, coordinate, newBlockState, itemStack, Direction.UP, hitVec, true, false, false); + } + } + } - //add to undo - addUndo(player, blockSet); + //add to undo + addUndo(player, blockSet); - return true; - } + return true; + } - public static void clear(PlayerEntity player) { - Map> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer; - Map> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer; - if (undoStacks.containsKey(player.getUniqueID())) { - undoStacks.get(player.getUniqueID()).clear(); - } - if (redoStacks.containsKey(player.getUniqueID())) { - redoStacks.get(player.getUniqueID()).clear(); - } - } + public static void clear(PlayerEntity player) { + Map> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer; + Map> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer; + if (undoStacks.containsKey(player.getUniqueID())) { + undoStacks.get(player.getUniqueID()).clear(); + } + if (redoStacks.containsKey(player.getUniqueID())) { + redoStacks.get(player.getUniqueID()).clear(); + } + } - private static List findItemStacksInInventory(PlayerEntity player, List blockStates) { - List itemStacks = new ArrayList<>(blockStates.size()); - for (BlockState blockState : blockStates) { - itemStacks.add(findItemStackInInventory(player, blockState)); - } - return itemStacks; - } + private static List findItemStacksInInventory(PlayerEntity player, List blockStates) { + List itemStacks = new ArrayList<>(blockStates.size()); + for (BlockState blockState : blockStates) { + itemStacks.add(findItemStackInInventory(player, blockState)); + } + return itemStacks; + } - private static ItemStack findItemStackInInventory(PlayerEntity player, BlockState blockState) { - ItemStack itemStack = ItemStack.EMPTY; - if (blockState == null) return itemStack; + private static ItemStack findItemStackInInventory(PlayerEntity player, BlockState blockState) { + ItemStack itemStack = ItemStack.EMPTY; + if (blockState == null) return itemStack; - //First try previousBlockStates - //TODO try to find itemstack with right blockstate first - // then change line 103 back (get state from item) - itemStack = InventoryHelper.findItemStackInInventory(player, blockState.getBlock()); + //First try previousBlockStates + //TODO try to find itemstack with right blockstate first + // then change line 103 back (get state from item) + itemStack = InventoryHelper.findItemStackInInventory(player, blockState.getBlock()); - //then anything it drops - if (itemStack.isEmpty()) { - //Cannot check drops on clientside because loot tables are server only - if (!player.world.isRemote) - { - List itemsDropped = Block.getDrops(blockState, (ServerWorld) player.world, BlockPos.ZERO, null); - for (ItemStack itemStackDropped : itemsDropped) { - if (itemStackDropped.getItem() instanceof BlockItem) { - Block block = ((BlockItem) itemStackDropped.getItem()).getBlock(); - itemStack = InventoryHelper.findItemStackInInventory(player, block); - } - } - } - } + //then anything it drops + if (itemStack.isEmpty()) { + //Cannot check drops on clientside because loot tables are server only + if (!player.world.isRemote) { + List itemsDropped = Block.getDrops(blockState, (ServerWorld) player.world, BlockPos.ZERO, null); + for (ItemStack itemStackDropped : itemsDropped) { + if (itemStackDropped.getItem() instanceof BlockItem) { + Block block = ((BlockItem) itemStackDropped.getItem()).getBlock(); + itemStack = InventoryHelper.findItemStackInInventory(player, block); + } + } + } + } - //then air - //(already empty) + //then air + //(already empty) - return itemStack; - } + return itemStack; + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/capability/ItemHandlerCapabilityProvider.java b/src/main/java/nl/requios/effortlessbuilding/capability/ItemHandlerCapabilityProvider.java index ced8acc..875f6c1 100644 --- a/src/main/java/nl/requios/effortlessbuilding/capability/ItemHandlerCapabilityProvider.java +++ b/src/main/java/nl/requios/effortlessbuilding/capability/ItemHandlerCapabilityProvider.java @@ -14,21 +14,21 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; public class ItemHandlerCapabilityProvider implements ICapabilitySerializable { - IItemHandler itemHandler = new ItemStackHandler(ItemRandomizerBag.INV_SIZE); + IItemHandler itemHandler = new ItemStackHandler(ItemRandomizerBag.INV_SIZE); - @Nonnull - @Override - public LazyOptional getCapability(@Nonnull Capability cap, @Nullable Direction side) { - return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.orEmpty(cap, LazyOptional.of(() -> itemHandler)); - } + @Nonnull + @Override + public LazyOptional getCapability(@Nonnull Capability cap, @Nullable Direction side) { + return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.orEmpty(cap, LazyOptional.of(() -> itemHandler)); + } - @Override - public CompoundNBT serializeNBT() { - return ((ItemStackHandler) itemHandler).serializeNBT(); - } + @Override + public CompoundNBT serializeNBT() { + return ((ItemStackHandler) itemHandler).serializeNBT(); + } - @Override - public void deserializeNBT(CompoundNBT nbt) { - ((ItemStackHandler) itemHandler).deserializeNBT(nbt); - } + @Override + public void deserializeNBT(CompoundNBT nbt) { + ((ItemStackHandler) itemHandler).deserializeNBT(nbt); + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/capability/ModeCapabilityManager.java b/src/main/java/nl/requios/effortlessbuilding/capability/ModeCapabilityManager.java index c4188f3..a590a66 100644 --- a/src/main/java/nl/requios/effortlessbuilding/capability/ModeCapabilityManager.java +++ b/src/main/java/nl/requios/effortlessbuilding/capability/ModeCapabilityManager.java @@ -20,84 +20,84 @@ import static nl.requios.effortlessbuilding.buildmode.ModeSettingsManager.ModeSe @Mod.EventBusSubscriber public class ModeCapabilityManager { - @CapabilityInject(IModeCapability.class) - public final static Capability modeCapability = null; + @CapabilityInject(IModeCapability.class) + public final static Capability modeCapability = null; - public interface IModeCapability { - ModeSettings getModeData(); + // Allows for the capability to persist after death. + @SubscribeEvent + public static void clonePlayer(PlayerEvent.Clone event) { + LazyOptional original = event.getOriginal().getCapability(modeCapability, null); + LazyOptional clone = event.getEntity().getCapability(modeCapability, null); + clone.ifPresent(cloneModeCapability -> + original.ifPresent(originalModeCapability -> + cloneModeCapability.setModeData(originalModeCapability.getModeData()))); + } - void setModeData(ModeSettings modeSettings); - } + public interface IModeCapability { + ModeSettings getModeData(); - public static class ModeCapability implements IModeCapability { - private ModeSettings modeSettings; + void setModeData(ModeSettings modeSettings); + } - @Override - public ModeSettings getModeData() { - return modeSettings; - } + public static class ModeCapability implements IModeCapability { + private ModeSettings modeSettings; - @Override - public void setModeData(ModeSettings modeSettings) { - this.modeSettings = modeSettings; - } - } + @Override + public ModeSettings getModeData() { + return modeSettings; + } - public static class Storage implements Capability.IStorage { - @Override - public INBT writeNBT(Capability capability, IModeCapability instance, Direction side) { - CompoundNBT compound = new CompoundNBT(); - ModeSettings modeSettings = instance.getModeData(); - if (modeSettings == null) modeSettings = new ModeSettings(); + @Override + public void setModeData(ModeSettings modeSettings) { + this.modeSettings = modeSettings; + } + } - //compound.putInteger("buildMode", modeSettings.getBuildMode().ordinal()); + public static class Storage implements Capability.IStorage { + @Override + public INBT writeNBT(Capability capability, IModeCapability instance, Direction side) { + CompoundNBT compound = new CompoundNBT(); + ModeSettings modeSettings = instance.getModeData(); + if (modeSettings == null) modeSettings = new ModeSettings(); - //TODO add mode settings + //compound.putInteger("buildMode", modeSettings.getBuildMode().ordinal()); - return compound; - } + //TODO add mode settings - @Override - public void readNBT(Capability capability, IModeCapability instance, Direction side, INBT nbt) { - CompoundNBT compound = (CompoundNBT) nbt; + return compound; + } - //BuildModes.BuildModeEnum buildMode = BuildModes.BuildModeEnum.values()[compound.getInteger("buildMode")]; + @Override + public void readNBT(Capability capability, IModeCapability instance, Direction side, INBT nbt) { + CompoundNBT compound = (CompoundNBT) nbt; - //TODO add mode settings + //BuildModes.BuildModeEnum buildMode = BuildModes.BuildModeEnum.values()[compound.getInteger("buildMode")]; - ModeSettings modeSettings = new ModeSettings(BuildModes.BuildModeEnum.NORMAL); - instance.setModeData(modeSettings); - } - } + //TODO add mode settings - public static class Provider implements ICapabilitySerializable { - IModeCapability inst = modeCapability.getDefaultInstance(); + ModeSettings modeSettings = new ModeSettings(BuildModes.BuildModeEnum.NORMAL); + instance.setModeData(modeSettings); + } + } - @Nonnull - @Override - public LazyOptional getCapability(@Nonnull Capability cap, @Nullable Direction side) { - return modeCapability.orEmpty(cap, LazyOptional.of(() -> inst)); - } + public static class Provider implements ICapabilitySerializable { + IModeCapability inst = modeCapability.getDefaultInstance(); - @Override - public INBT serializeNBT() { - return modeCapability.getStorage().writeNBT(modeCapability, inst, null); - } + @Nonnull + @Override + public LazyOptional getCapability(@Nonnull Capability cap, @Nullable Direction side) { + return modeCapability.orEmpty(cap, LazyOptional.of(() -> inst)); + } - @Override - public void deserializeNBT(INBT nbt) { - modeCapability.getStorage().readNBT(modeCapability, inst, null, nbt); - } + @Override + public INBT serializeNBT() { + return modeCapability.getStorage().writeNBT(modeCapability, inst, null); + } - } + @Override + public void deserializeNBT(INBT nbt) { + modeCapability.getStorage().readNBT(modeCapability, inst, null, nbt); + } - // Allows for the capability to persist after death. - @SubscribeEvent - public static void clonePlayer(PlayerEvent.Clone event) { - LazyOptional original = event.getOriginal().getCapability(modeCapability, null); - LazyOptional clone = event.getEntity().getCapability(modeCapability, null); - clone.ifPresent(cloneModeCapability -> - original.ifPresent(originalModeCapability -> - cloneModeCapability.setModeData(originalModeCapability.getModeData()))); - } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/capability/ModifierCapabilityManager.java b/src/main/java/nl/requios/effortlessbuilding/capability/ModifierCapabilityManager.java index b855b5a..b7a5d53 100644 --- a/src/main/java/nl/requios/effortlessbuilding/capability/ModifierCapabilityManager.java +++ b/src/main/java/nl/requios/effortlessbuilding/capability/ModifierCapabilityManager.java @@ -4,7 +4,7 @@ import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.ICapabilitySerializable; @@ -19,164 +19,163 @@ import nl.requios.effortlessbuilding.buildmodifier.RadialMirror; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import static nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager.*; +import static nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager.ModifierSettings; @Mod.EventBusSubscriber public class ModifierCapabilityManager { - @CapabilityInject(IModifierCapability.class) - public final static Capability modifierCapability = null; + @CapabilityInject(IModifierCapability.class) + public final static Capability modifierCapability = null; - public interface IModifierCapability { - ModifierSettings getModifierData(); + // Allows for the capability to persist after death. + @SubscribeEvent + public static void clonePlayer(PlayerEvent.Clone event) { + LazyOptional original = event.getOriginal().getCapability(modifierCapability, null); + LazyOptional clone = event.getEntity().getCapability(modifierCapability, null); + clone.ifPresent(cloneModifierCapability -> + original.ifPresent(originalModifierCapability -> + cloneModifierCapability.setModifierData(originalModifierCapability.getModifierData()))); + } - void setModifierData(ModifierSettings modifierSettings); - } + public interface IModifierCapability { + ModifierSettings getModifierData(); - public static class ModifierCapability implements IModifierCapability { - private ModifierSettings modifierSettings; + void setModifierData(ModifierSettings modifierSettings); + } - @Override - public ModifierSettings getModifierData() { - return modifierSettings; - } + public static class ModifierCapability implements IModifierCapability { + private ModifierSettings modifierSettings; - @Override - public void setModifierData(ModifierSettings modifierSettings) { - this.modifierSettings = modifierSettings; - } - } + @Override + public ModifierSettings getModifierData() { + return modifierSettings; + } - public static class Storage implements Capability.IStorage { - @Override - public INBT writeNBT(Capability capability, IModifierCapability instance, Direction side) { - CompoundNBT compound = new CompoundNBT(); - ModifierSettings modifierSettings = instance.getModifierData(); - if (modifierSettings == null) modifierSettings = new ModifierSettings(); + @Override + public void setModifierData(ModifierSettings modifierSettings) { + this.modifierSettings = modifierSettings; + } + } - //MIRROR - Mirror.MirrorSettings m = modifierSettings.getMirrorSettings(); - if (m == null) m = new Mirror.MirrorSettings(); - compound.putBoolean("mirrorEnabled", m.enabled); - compound.putDouble("mirrorPosX", m.position.x); - compound.putDouble("mirrorPosY", m.position.y); - compound.putDouble("mirrorPosZ", m.position.z); - compound.putBoolean("mirrorX", m.mirrorX); - compound.putBoolean("mirrorY", m.mirrorY); - compound.putBoolean("mirrorZ", m.mirrorZ); - compound.putInt("mirrorRadius", m.radius); - compound.putBoolean("mirrorDrawLines", m.drawLines); - compound.putBoolean("mirrorDrawPlanes", m.drawPlanes); + public static class Storage implements Capability.IStorage { + @Override + public INBT writeNBT(Capability capability, IModifierCapability instance, Direction side) { + CompoundNBT compound = new CompoundNBT(); + ModifierSettings modifierSettings = instance.getModifierData(); + if (modifierSettings == null) modifierSettings = new ModifierSettings(); - //ARRAY - Array.ArraySettings a = modifierSettings.getArraySettings(); - if (a == null) a = new Array.ArraySettings(); - compound.putBoolean("arrayEnabled", a.enabled); - compound.putInt("arrayOffsetX", a.offset.getX()); - compound.putInt("arrayOffsetY", a.offset.getY()); - compound.putInt("arrayOffsetZ", a.offset.getZ()); - compound.putInt("arrayCount", a.count); + //MIRROR + Mirror.MirrorSettings m = modifierSettings.getMirrorSettings(); + if (m == null) m = new Mirror.MirrorSettings(); + compound.putBoolean("mirrorEnabled", m.enabled); + compound.putDouble("mirrorPosX", m.position.x); + compound.putDouble("mirrorPosY", m.position.y); + compound.putDouble("mirrorPosZ", m.position.z); + compound.putBoolean("mirrorX", m.mirrorX); + compound.putBoolean("mirrorY", m.mirrorY); + compound.putBoolean("mirrorZ", m.mirrorZ); + compound.putInt("mirrorRadius", m.radius); + compound.putBoolean("mirrorDrawLines", m.drawLines); + compound.putBoolean("mirrorDrawPlanes", m.drawPlanes); - compound.putInt("reachUpgrade", modifierSettings.getReachUpgrade()); + //ARRAY + Array.ArraySettings a = modifierSettings.getArraySettings(); + if (a == null) a = new Array.ArraySettings(); + compound.putBoolean("arrayEnabled", a.enabled); + compound.putInt("arrayOffsetX", a.offset.getX()); + compound.putInt("arrayOffsetY", a.offset.getY()); + compound.putInt("arrayOffsetZ", a.offset.getZ()); + compound.putInt("arrayCount", a.count); - //compound.putBoolean("quickReplace", buildSettings.doQuickReplace()); dont save quickreplace + compound.putInt("reachUpgrade", modifierSettings.getReachUpgrade()); - //RADIAL MIRROR - RadialMirror.RadialMirrorSettings r = modifierSettings.getRadialMirrorSettings(); - if (r == null) r = new RadialMirror.RadialMirrorSettings(); - compound.putBoolean("radialMirrorEnabled", r.enabled); - compound.putDouble("radialMirrorPosX", r.position.x); - compound.putDouble("radialMirrorPosY", r.position.y); - compound.putDouble("radialMirrorPosZ", r.position.z); - compound.putInt("radialMirrorSlices", r.slices); - compound.putBoolean("radialMirrorAlternate", r.alternate); - compound.putInt("radialMirrorRadius", r.radius); - compound.putBoolean("radialMirrorDrawLines", r.drawLines); - compound.putBoolean("radialMirrorDrawPlanes", r.drawPlanes); + //compound.putBoolean("quickReplace", buildSettings.doQuickReplace()); dont save quickreplace - return compound; - } + //RADIAL MIRROR + RadialMirror.RadialMirrorSettings r = modifierSettings.getRadialMirrorSettings(); + if (r == null) r = new RadialMirror.RadialMirrorSettings(); + compound.putBoolean("radialMirrorEnabled", r.enabled); + compound.putDouble("radialMirrorPosX", r.position.x); + compound.putDouble("radialMirrorPosY", r.position.y); + compound.putDouble("radialMirrorPosZ", r.position.z); + compound.putInt("radialMirrorSlices", r.slices); + compound.putBoolean("radialMirrorAlternate", r.alternate); + compound.putInt("radialMirrorRadius", r.radius); + compound.putBoolean("radialMirrorDrawLines", r.drawLines); + compound.putBoolean("radialMirrorDrawPlanes", r.drawPlanes); - @Override - public void readNBT(Capability capability, IModifierCapability instance, Direction side, INBT nbt) { - CompoundNBT compound = (CompoundNBT) nbt; + return compound; + } - //MIRROR - boolean mirrorEnabled = compound.getBoolean("mirrorEnabled"); - Vec3d mirrorPosition = new Vec3d( - compound.getDouble("mirrorPosX"), - compound.getDouble("mirrorPosY"), - compound.getDouble("mirrorPosZ")); - boolean mirrorX = compound.getBoolean("mirrorX"); - boolean mirrorY = compound.getBoolean("mirrorY"); - boolean mirrorZ = compound.getBoolean("mirrorZ"); - int mirrorRadius = compound.getInt("mirrorRadius"); - boolean mirrorDrawLines = compound.getBoolean("mirrorDrawLines"); - boolean mirrorDrawPlanes = compound.getBoolean("mirrorDrawPlanes"); - Mirror.MirrorSettings mirrorSettings = new Mirror.MirrorSettings(mirrorEnabled, mirrorPosition, mirrorX, mirrorY, mirrorZ, mirrorRadius, mirrorDrawLines, mirrorDrawPlanes); + @Override + public void readNBT(Capability capability, IModifierCapability instance, Direction side, INBT nbt) { + CompoundNBT compound = (CompoundNBT) nbt; - //ARRAY - boolean arrayEnabled = compound.getBoolean("arrayEnabled"); - BlockPos arrayOffset = new BlockPos( - compound.getInt("arrayOffsetX"), - compound.getInt("arrayOffsetY"), - compound.getInt("arrayOffsetZ")); - int arrayCount = compound.getInt("arrayCount"); - Array.ArraySettings arraySettings = new Array.ArraySettings(arrayEnabled, arrayOffset, arrayCount); + //MIRROR + boolean mirrorEnabled = compound.getBoolean("mirrorEnabled"); + Vector3d mirrorPosition = new Vector3d( + compound.getDouble("mirrorPosX"), + compound.getDouble("mirrorPosY"), + compound.getDouble("mirrorPosZ")); + boolean mirrorX = compound.getBoolean("mirrorX"); + boolean mirrorY = compound.getBoolean("mirrorY"); + boolean mirrorZ = compound.getBoolean("mirrorZ"); + int mirrorRadius = compound.getInt("mirrorRadius"); + boolean mirrorDrawLines = compound.getBoolean("mirrorDrawLines"); + boolean mirrorDrawPlanes = compound.getBoolean("mirrorDrawPlanes"); + Mirror.MirrorSettings mirrorSettings = new Mirror.MirrorSettings(mirrorEnabled, mirrorPosition, mirrorX, mirrorY, mirrorZ, mirrorRadius, mirrorDrawLines, mirrorDrawPlanes); - int reachUpgrade = compound.getInt("reachUpgrade"); + //ARRAY + boolean arrayEnabled = compound.getBoolean("arrayEnabled"); + BlockPos arrayOffset = new BlockPos( + compound.getInt("arrayOffsetX"), + compound.getInt("arrayOffsetY"), + compound.getInt("arrayOffsetZ")); + int arrayCount = compound.getInt("arrayCount"); + Array.ArraySettings arraySettings = new Array.ArraySettings(arrayEnabled, arrayOffset, arrayCount); - //boolean quickReplace = compound.getBoolean("quickReplace"); //dont load quickreplace + int reachUpgrade = compound.getInt("reachUpgrade"); - //RADIAL MIRROR - boolean radialMirrorEnabled = compound.getBoolean("radialMirrorEnabled"); - Vec3d radialMirrorPosition = new Vec3d( - compound.getDouble("radialMirrorPosX"), - compound.getDouble("radialMirrorPosY"), - compound.getDouble("radialMirrorPosZ")); - int radialMirrorSlices = compound.getInt("radialMirrorSlices"); - boolean radialMirrorAlternate = compound.getBoolean("radialMirrorAlternate"); - int radialMirrorRadius = compound.getInt("radialMirrorRadius"); - boolean radialMirrorDrawLines = compound.getBoolean("radialMirrorDrawLines"); - boolean radialMirrorDrawPlanes = compound.getBoolean("radialMirrorDrawPlanes"); - RadialMirror.RadialMirrorSettings radialMirrorSettings = new RadialMirror.RadialMirrorSettings(radialMirrorEnabled, radialMirrorPosition, - radialMirrorSlices, radialMirrorAlternate, radialMirrorRadius, radialMirrorDrawLines, radialMirrorDrawPlanes); + //boolean quickReplace = compound.getBoolean("quickReplace"); //dont load quickreplace - ModifierSettings modifierSettings = new ModifierSettings(mirrorSettings, arraySettings, radialMirrorSettings, false, reachUpgrade); - instance.setModifierData(modifierSettings); - } - } + //RADIAL MIRROR + boolean radialMirrorEnabled = compound.getBoolean("radialMirrorEnabled"); + Vector3d radialMirrorPosition = new Vector3d( + compound.getDouble("radialMirrorPosX"), + compound.getDouble("radialMirrorPosY"), + compound.getDouble("radialMirrorPosZ")); + int radialMirrorSlices = compound.getInt("radialMirrorSlices"); + boolean radialMirrorAlternate = compound.getBoolean("radialMirrorAlternate"); + int radialMirrorRadius = compound.getInt("radialMirrorRadius"); + boolean radialMirrorDrawLines = compound.getBoolean("radialMirrorDrawLines"); + boolean radialMirrorDrawPlanes = compound.getBoolean("radialMirrorDrawPlanes"); + RadialMirror.RadialMirrorSettings radialMirrorSettings = new RadialMirror.RadialMirrorSettings(radialMirrorEnabled, radialMirrorPosition, + radialMirrorSlices, radialMirrorAlternate, radialMirrorRadius, radialMirrorDrawLines, radialMirrorDrawPlanes); - public static class Provider implements ICapabilitySerializable { + ModifierSettings modifierSettings = new ModifierSettings(mirrorSettings, arraySettings, radialMirrorSettings, false, reachUpgrade); + instance.setModifierData(modifierSettings); + } + } - IModifierCapability inst = modifierCapability.getDefaultInstance(); + public static class Provider implements ICapabilitySerializable { - @Nonnull - @Override - public LazyOptional getCapability(@Nonnull Capability cap, @Nullable Direction side) { - return modifierCapability.orEmpty(cap, LazyOptional.of(() -> inst)); - } + IModifierCapability inst = modifierCapability.getDefaultInstance(); - @Override - public INBT serializeNBT() { - return modifierCapability.getStorage().writeNBT(modifierCapability, inst, null); - } + @Nonnull + @Override + public LazyOptional getCapability(@Nonnull Capability cap, @Nullable Direction side) { + return modifierCapability.orEmpty(cap, LazyOptional.of(() -> inst)); + } - @Override - public void deserializeNBT(INBT nbt) { - modifierCapability.getStorage().readNBT(modifierCapability, inst, null, nbt); - } + @Override + public INBT serializeNBT() { + return modifierCapability.getStorage().writeNBT(modifierCapability, inst, null); + } - } + @Override + public void deserializeNBT(INBT nbt) { + modifierCapability.getStorage().readNBT(modifierCapability, inst, null, nbt); + } - - // Allows for the capability to persist after death. - @SubscribeEvent - public static void clonePlayer(PlayerEvent.Clone event) { - LazyOptional original = event.getOriginal().getCapability(modifierCapability, null); - LazyOptional clone = event.getEntity().getCapability(modifierCapability, null); - clone.ifPresent(cloneModifierCapability -> - original.ifPresent(originalModifierCapability -> - cloneModifierCapability.setModifierData(originalModifierCapability.getModifierData()))); - } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/command/CommandReach.java b/src/main/java/nl/requios/effortlessbuilding/command/CommandReach.java index 74ac3e0..0edd2e5 100644 --- a/src/main/java/nl/requios/effortlessbuilding/command/CommandReach.java +++ b/src/main/java/nl/requios/effortlessbuilding/command/CommandReach.java @@ -14,30 +14,30 @@ import nl.requios.effortlessbuilding.network.PacketHandler; public class CommandReach { - public static void register(CommandDispatcher dispatcher) { - dispatcher.register(Commands.literal("reach").then(Commands.literal("set").then(Commands.argument("level", IntegerArgumentType.integer(0, 3)).executes((context) -> { - return setReachLevel(context.getSource().asPlayer(), IntegerArgumentType.getInteger(context, "level")); - }))).then(Commands.literal("get").executes((context -> { - return getReachLevel(context.getSource().asPlayer()); - })))); - } + public static void register(CommandDispatcher dispatcher) { + dispatcher.register(Commands.literal("reach").then(Commands.literal("set").then(Commands.argument("level", IntegerArgumentType.integer(0, 3)).executes((context) -> { + return setReachLevel(context.getSource().asPlayer(), IntegerArgumentType.getInteger(context, "level")); + }))).then(Commands.literal("get").executes((context -> { + return getReachLevel(context.getSource().asPlayer()); + })))); + } - private static int setReachLevel(ServerPlayerEntity player, int level){ - ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); - modifierSettings.setReachUpgrade(level); - ModifierSettingsManager.setModifierSettings(player, modifierSettings); - //Send to client - PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new ModifierSettingsMessage(modifierSettings)); + private static int setReachLevel(ServerPlayerEntity player, int level) { + ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); + modifierSettings.setReachUpgrade(level); + ModifierSettingsManager.setModifierSettings(player, modifierSettings); + //Send to client + PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new ModifierSettingsMessage(modifierSettings)); - player.sendMessage(new StringTextComponent("Reach level of " + player.getName().getString() + " set to " + modifierSettings.getReachUpgrade())); + player.sendMessage(new StringTextComponent("Reach level of " + player.getName().getString() + " set to " + modifierSettings.getReachUpgrade()), player.getUniqueID()); - return 1; - } + return 1; + } - private static int getReachLevel(ServerPlayerEntity player){ - int reachUpgrade = ModifierSettingsManager.getModifierSettings(player).getReachUpgrade(); - EffortlessBuilding.log(player, "Current reach: level "+reachUpgrade); + private static int getReachLevel(ServerPlayerEntity player) { + int reachUpgrade = ModifierSettingsManager.getModifierSettings(player).getReachUpgrade(); + EffortlessBuilding.log(player, "Current reach: level " + reachUpgrade); - return 1; - } + return 1; + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/compatibility/CompatHelper.java b/src/main/java/nl/requios/effortlessbuilding/compatibility/CompatHelper.java index 1f6efe6..6fa642b 100644 --- a/src/main/java/nl/requios/effortlessbuilding/compatibility/CompatHelper.java +++ b/src/main/java/nl/requios/effortlessbuilding/compatibility/CompatHelper.java @@ -12,7 +12,7 @@ import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.item.ItemRandomizerBag; public class CompatHelper { - //TODO 1.13 compatibility + //TODO 1.13 compatibility // // Get a handle to the dank null item instance. This will remain null if the mod doesn't load // // and all checks will fail, so it works. // @GameRegistry.ObjectHolder("danknull:dank_null") @@ -20,8 +20,8 @@ public class CompatHelper { // // public static IChiselsAndBitsProxy chiselsAndBitsProxy; // - public static void setup() { - //TODO 1.13 compatibility + public static void setup() { + //TODO 1.13 compatibility // if (Loader.isModLoaded("chiselsandbits")) { // // reflection to avoid hard dependency // try { @@ -32,42 +32,40 @@ public class CompatHelper { // } else { // chiselsAndBitsProxy = new DummyChiselsAndBitsProxy(); // } - } + } - // Check if the item given is a proxy for blocks. For now, we check for the randomizer bag, - // /dank/null, or plain old blocks. - public static boolean isItemBlockProxy(ItemStack stack) { - Item item = stack.getItem(); - if (item instanceof BlockItem) - return true; - if ((item instanceof ItemRandomizerBag)) - return true; - //TODO 1.13 compatibility + // Check if the item given is a proxy for blocks. For now, we check for the randomizer bag, + // /dank/null, or plain old blocks. + public static boolean isItemBlockProxy(ItemStack stack) { + Item item = stack.getItem(); + if (item instanceof BlockItem) + return true; + return item instanceof ItemRandomizerBag; + //TODO 1.13 compatibility // if (item == dankNullItem) // return true; - return false; - } + } - // Get the block to be placed by this proxy. For the /dank/null, it's the slot stack - // pointed to by nbt integer selectedIndex. - public static ItemStack getItemBlockFromStack(ItemStack proxy) { - Item proxyItem = proxy.getItem(); + // Get the block to be placed by this proxy. For the /dank/null, it's the slot stack + // pointed to by nbt integer selectedIndex. + public static ItemStack getItemBlockFromStack(ItemStack proxy) { + Item proxyItem = proxy.getItem(); - if (proxyItem instanceof BlockItem) - return proxy; + if (proxyItem instanceof BlockItem) + return proxy; - //Randomizer Bag - if (proxyItem instanceof ItemRandomizerBag) { - ItemStack itemStack = proxy; - while (!(itemStack.getItem() instanceof BlockItem || itemStack.isEmpty())) { - if (itemStack.getItem() instanceof ItemRandomizerBag) - itemStack = ItemRandomizerBag.pickRandomStack(ItemRandomizerBag.getBagInventory(itemStack)); - } - return itemStack; - } + //Randomizer Bag + if (proxyItem instanceof ItemRandomizerBag) { + ItemStack itemStack = proxy; + while (!(itemStack.getItem() instanceof BlockItem || itemStack.isEmpty())) { + if (itemStack.getItem() instanceof ItemRandomizerBag) + itemStack = ItemRandomizerBag.pickRandomStack(ItemRandomizerBag.getBagInventory(itemStack)); + } + return itemStack; + } - //TODO 1.13 compatibility - //Dank Null + //TODO 1.13 compatibility + //Dank Null // if (proxyItem == dankNullItem) { // int index = 0; // if (proxy.hasTagCompound() && proxy.getTagCompound().hasKey("selectedIndex")) @@ -75,58 +73,58 @@ public class CompatHelper { // return proxy.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).getStackInSlot(index); // } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - public static ItemStack getItemBlockByState(ItemStack stack, BlockState state) { - if (state == null) return ItemStack.EMPTY; + public static ItemStack getItemBlockByState(ItemStack stack, BlockState state) { + if (state == null) return ItemStack.EMPTY; - Item blockItem = Item.getItemFromBlock(state.getBlock()); - if (stack.getItem() instanceof BlockItem) - return stack; - else if (stack.getItem() instanceof ItemRandomizerBag) { - IItemHandler bagInventory = ItemRandomizerBag.getBagInventory(stack); - return ItemRandomizerBag.findStack(bagInventory, blockItem); - } - //TODO 1.13 compatibility + Item blockItem = Item.getItemFromBlock(state.getBlock()); + if (stack.getItem() instanceof BlockItem) + return stack; + else if (stack.getItem() instanceof ItemRandomizerBag) { + IItemHandler bagInventory = ItemRandomizerBag.getBagInventory(stack); + return ItemRandomizerBag.findStack(bagInventory, blockItem); + } + //TODO 1.13 compatibility // else if (stack.getItem() == dankNullItem) { // int index = itemHandlerSlotForItem(stack, blockItem); // if (index >= 0) // return stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).getStackInSlot(index); // } - return ItemStack.EMPTY; - } + return ItemStack.EMPTY; + } - // Handle IItemHandler slot stacks not being modifiable. We must call IItemHandler#extractItem, - // because the ItemStack returned by IItemHandler#getStackInSlot isn't modifiable. - public static void shrinkStack(ItemStack origStack, ItemStack curStack, PlayerEntity player) { - //TODO 1.13 compatibility, offhand support - //Hacky way to get the origstack, because given origStack is itemblock stack and never proxy + // Handle IItemHandler slot stacks not being modifiable. We must call IItemHandler#extractItem, + // because the ItemStack returned by IItemHandler#getStackInSlot isn't modifiable. + public static void shrinkStack(ItemStack origStack, ItemStack curStack, PlayerEntity player) { + //TODO 1.13 compatibility, offhand support + //Hacky way to get the origstack, because given origStack is itemblock stack and never proxy // origStack = player.getHeldItem(EnumHand.MAIN_HAND); // if (origStack.getItem() == dankNullItem) { // int index = itemHandlerSlotForItem(origStack, curStack.getItem()); // origStack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).extractItem(index, 1, false); // } else - curStack.shrink(1); - } + curStack.shrink(1); + } - private static int itemHandlerSlotForItem(ItemStack stack, Item blockItem) { - LazyOptional itemHandlerLazyOptional = stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); - IItemHandler handler = itemHandlerLazyOptional.orElse(null); + private static int itemHandlerSlotForItem(ItemStack stack, Item blockItem) { + LazyOptional itemHandlerLazyOptional = stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); + IItemHandler handler = itemHandlerLazyOptional.orElse(null); - if (handler == null) { - EffortlessBuilding.logger.warn("Itemblock proxy has no item handler capability!"); - return -1; - } + if (handler == null) { + EffortlessBuilding.logger.warn("Itemblock proxy has no item handler capability!"); + return -1; + } - for (int i = 0; i < handler.getSlots(); i++) { - ItemStack ref = handler.getStackInSlot(i); - if (ref.getItem() instanceof BlockItem) - if (ref.getItem() == blockItem) - return i; - } - return -1; - } + for (int i = 0; i < handler.getSlots(); i++) { + ItemStack ref = handler.getStackInSlot(i); + if (ref.getItem() instanceof BlockItem) + if (ref.getItem() == blockItem) + return i; + } + return -1; + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/gui/FontRenderHelper.java b/src/main/java/nl/requios/effortlessbuilding/gui/FontRenderHelper.java new file mode 100644 index 0000000..8a85415 --- /dev/null +++ b/src/main/java/nl/requios/effortlessbuilding/gui/FontRenderHelper.java @@ -0,0 +1,71 @@ +package nl.requios.effortlessbuilding.gui; + +import com.mojang.blaze3d.matrix.MatrixStack; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.util.math.vector.Matrix4f; +import net.minecraft.util.math.vector.TransformationMatrix; +import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; + +import java.util.Arrays; +import java.util.List; + +@OnlyIn(Dist.CLIENT) +public class FontRenderHelper { + /* + private static final FontRenderer font = Minecraft.getInstance().fontRenderer; + + public static void drawSplitString(MatrixStack ms, String str, int x, int y, int wrapWidth, int textColor) { + str = trimStringNewline(str); + renderSplitString(ms, str, x, y, wrapWidth, textColor); + } + + private static void renderSplitString(MatrixStack ms, String str, int x, int y, int wrapWidth, int textColor) { + List list = font.listFormattedStringToWidth(str, wrapWidth); + Matrix4f matrix4f = TransformationMatrix.identity().getMatrix(); + + for(String s : list) { + float f = (float)x; + if (font.getBidiFlag()) { + int i = font.getStringWidth(font.bidiReorder(s)); + f += (float)(wrapWidth - i); + } + + font.renderString(s, f, (float)y, textColor, ms.getLast().getMatrix(), false, false); + y += 9; + } + + } + + private static String trimStringNewline(String text) { + while(text != null && text.endsWith("\n")) { + text = text.substring(0, text.length() - 1); + } + + return text; + } + + public static List listFormattedStringToWidth(String str, int wrapWidth) { + return Arrays.asList(wrapFormattedStringToWidth(str, wrapWidth).split("\n")); + } + + public static String wrapFormattedStringToWidth(String str, int wrapWidth) { + String s; + String s1; + for(s = ""; !str.isEmpty(); s = s + s1 + "\n") { + int i = font.sizeStringToWidth(str, wrapWidth); + if (str.length() <= i) { + return s + str; + } + + s1 = str.substring(0, i); + char c0 = str.charAt(i); + boolean flag = c0 == ' ' || c0 == '\n'; + str = TextFormatting.getFormatString(s1) + str.substring(i + (flag ? 1 : 0)); + } + + return s; + }*/ +} diff --git a/src/main/java/nl/requios/effortlessbuilding/gui/RandomizerBagContainer.java b/src/main/java/nl/requios/effortlessbuilding/gui/RandomizerBagContainer.java index a2bfc4b..96f0e5b 100644 --- a/src/main/java/nl/requios/effortlessbuilding/gui/RandomizerBagContainer.java +++ b/src/main/java/nl/requios/effortlessbuilding/gui/RandomizerBagContainer.java @@ -2,8 +2,6 @@ package nl.requios.effortlessbuilding.gui; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Inventory; import net.minecraft.inventory.container.ClickType; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.Slot; @@ -17,122 +15,118 @@ import nl.requios.effortlessbuilding.item.ItemRandomizerBag; public class RandomizerBagContainer extends Container { - private final IItemHandler bagInventory; + private static final int INV_START = ItemRandomizerBag.INV_SIZE, INV_END = INV_START + 26, + HOTBAR_START = INV_END + 1, HOTBAR_END = HOTBAR_START + 8; + private final IItemHandler bagInventory; - private static final int INV_START = ItemRandomizerBag.INV_SIZE, INV_END = INV_START + 26, - HOTBAR_START = INV_END + 1, HOTBAR_END = HOTBAR_START + 8; + public RandomizerBagContainer(int containerId, PlayerInventory playerInventory) { + this(containerId, playerInventory, new ItemStackHandler(ItemRandomizerBag.INV_SIZE)); + } - public RandomizerBagContainer(int containerId, PlayerInventory playerInventory) { - this(containerId, playerInventory, new ItemStackHandler(ItemRandomizerBag.INV_SIZE)); - } + public RandomizerBagContainer(int containerId, PlayerInventory playerInventory, IItemHandler inventory) { + super(EffortlessBuilding.RANDOMIZER_BAG_CONTAINER, containerId); + bagInventory = inventory; - public RandomizerBagContainer(int containerId, PlayerInventory playerInventory, IItemHandler inventory) { - super(EffortlessBuilding.RANDOMIZER_BAG_CONTAINER, containerId); - bagInventory = inventory; + for (int i = 0; i < ItemRandomizerBag.INV_SIZE; ++i) { + this.addSlot(new SlotItemHandler(bagInventory, i, 44 + (18 * i), 20)); + } - for (int i = 0; i < ItemRandomizerBag.INV_SIZE; ++i) { - this.addSlot(new SlotItemHandler(bagInventory, i, 44 + (18 * i), 20)); - } + // add player inventory slots + int i; + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + addSlot(new Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 51 + i * 18)); + } + } - // add player inventory slots - int i; - for (i = 0; i < 3; ++i) { - for (int j = 0; j < 9; ++j) { - addSlot(new Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 51 + i * 18)); - } - } + // add hotbar slots + for (i = 0; i < 9; ++i) { + addSlot(new Slot(playerInventory, i, 8 + i * 18, 109)); + } + } - // add hotbar slots - for (i = 0; i < 9; ++i) { - addSlot(new Slot(playerInventory, i, 8 + i * 18, 109)); - } - } + @Override + public boolean canInteractWith(PlayerEntity playerIn) { + return true; + } - @Override - public boolean canInteractWith(PlayerEntity playerIn) { - return true; - } + @Override + public Slot getSlot(int parSlotIndex) { + if (parSlotIndex >= inventorySlots.size()) + parSlotIndex = inventorySlots.size() - 1; + return super.getSlot(parSlotIndex); + } - @Override - public Slot getSlot(int parSlotIndex) - { - if(parSlotIndex >= inventorySlots.size()) - parSlotIndex = inventorySlots.size() - 1; - return super.getSlot(parSlotIndex); - } + @Override + public ItemStack transferStackInSlot(PlayerEntity playerIn, int slotIndex) { + ItemStack itemstack = ItemStack.EMPTY; + Slot slot = this.inventorySlots.get(slotIndex); - @Override - public ItemStack transferStackInSlot(PlayerEntity playerIn, int slotIndex) { - ItemStack itemstack = ItemStack.EMPTY; - Slot slot = this.inventorySlots.get(slotIndex); + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); + // If item is in our custom inventory + if (slotIndex < INV_START) { + // try to place in player inventory / action bar + if (!this.mergeItemStack(itemstack1, INV_START, HOTBAR_END + 1, true)) { + return ItemStack.EMPTY; + } - // If item is in our custom inventory - if (slotIndex < INV_START) { - // try to place in player inventory / action bar - if (!this.mergeItemStack(itemstack1, INV_START, HOTBAR_END + 1, true)) { - return ItemStack.EMPTY; - } + slot.onSlotChange(itemstack1, itemstack); + } + // Item is in inventory / hotbar, try to place in custom inventory or armor slots + else { + /** + * Implementation number 1: Shift-click into your custom inventory + */ + if (slotIndex >= INV_START) { + // place in custom inventory + if (!this.mergeItemStack(itemstack1, 0, INV_START, false)) { + return ItemStack.EMPTY; + } + } - slot.onSlotChange(itemstack1, itemstack); - } - // Item is in inventory / hotbar, try to place in custom inventory or armor slots - else { - /** - * Implementation number 1: Shift-click into your custom inventory - */ - if (slotIndex >= INV_START) { - // place in custom inventory - if (!this.mergeItemStack(itemstack1, 0, INV_START, false)) { - return ItemStack.EMPTY; - } - } + } - } + if (itemstack1.getCount() == 0) { + slot.putStack(ItemStack.EMPTY); + } else { + slot.onSlotChanged(); + } - if (itemstack1.getCount() == 0) { - slot.putStack(ItemStack.EMPTY); - } else { - slot.onSlotChanged(); - } + if (itemstack1.getCount() == itemstack.getCount()) { + return ItemStack.EMPTY; + } - if (itemstack1.getCount() == itemstack.getCount()) { - return ItemStack.EMPTY; - } + slot.onTake(playerIn, itemstack1); + } - slot.onTake(playerIn, itemstack1); - } + return itemstack; + } - return itemstack; - } + /** + * You should override this method to prevent the player from moving the stack that + * opened the inventory, otherwise if the player moves it, the inventory will not + * be able to save properly + */ + @Override + public ItemStack slotClick(int slot, int dragType, ClickType clickTypeIn, PlayerEntity player) { + // this will prevent the player from interacting with the item that opened the inventory: + if (slot >= 0 && getSlot(slot) != null && getSlot(slot).getStack().equals(player.getHeldItem(Hand.MAIN_HAND))) { + return ItemStack.EMPTY; + } + return super.slotClick(slot, dragType, clickTypeIn, player); + } - /** - * You should override this method to prevent the player from moving the stack that - * opened the inventory, otherwise if the player moves it, the inventory will not - * be able to save properly - */ - @Override - public ItemStack slotClick(int slot, int dragType, ClickType clickTypeIn, PlayerEntity player) { - // this will prevent the player from interacting with the item that opened the inventory: - if (slot >= 0 && getSlot(slot) != null && getSlot(slot).getStack().equals(player.getHeldItem(Hand.MAIN_HAND))) { - return ItemStack.EMPTY; - } - return super.slotClick(slot, dragType, clickTypeIn, player); - } - - /** - * Callback for when the crafting gui is closed. - */ - @Override - public void onContainerClosed(PlayerEntity player) - { - super.onContainerClosed(player); - if(!player.world.isRemote) - { - detectAndSendChanges(); - } - } + /** + * Callback for when the crafting gui is closed. + */ + @Override + public void onContainerClosed(PlayerEntity player) { + super.onContainerClosed(player); + if (!player.world.isRemote) { + detectAndSendChanges(); + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/gui/RandomizerBagScreen.java b/src/main/java/nl/requios/effortlessbuilding/gui/RandomizerBagScreen.java index 2a884e5..89b02af 100644 --- a/src/main/java/nl/requios/effortlessbuilding/gui/RandomizerBagScreen.java +++ b/src/main/java/nl/requios/effortlessbuilding/gui/RandomizerBagScreen.java @@ -1,46 +1,44 @@ package nl.requios.effortlessbuilding.gui; -import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.gui.screen.inventory.ContainerScreen; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.items.IItemHandler; import nl.requios.effortlessbuilding.EffortlessBuilding; @OnlyIn(Dist.CLIENT) public class RandomizerBagScreen extends ContainerScreen { - private static final ResourceLocation guiTextures = - new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/container/randomizerbag.png"); + private static final ResourceLocation guiTextures = + new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/container/randomizerbag.png"); - public RandomizerBagScreen(RandomizerBagContainer randomizerBagContainer, PlayerInventory playerInventory, ITextComponent title) { - super(randomizerBagContainer, playerInventory, title);//new TranslationTextComponent("effortlessbuilding.screen.randomizer_bag")); - ySize = 134; - } + public RandomizerBagScreen(RandomizerBagContainer randomizerBagContainer, PlayerInventory playerInventory, ITextComponent title) { + super(randomizerBagContainer, playerInventory, title);//new TranslationTextComponent("effortlessbuilding.screen.randomizer_bag")); + ySize = 134; + } - @Override - public void render(int mouseX, int mouseY, float partialTicks) { - renderBackground(); - super.render(mouseX, mouseY, partialTicks); - this.renderHoveredToolTip(mouseX, mouseY); - } + @Override + public void render(MatrixStack ms, int mouseX, int mouseY, float partialTicks) { + renderBackground(ms); + super.render(ms, mouseX, mouseY, partialTicks); + this.renderHoveredTooltip(ms, mouseX, mouseY); + } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - font.drawString(this.title.getFormattedText(), 8, 6, 0x404040); - font.drawString(playerInventory.getDisplayName().getFormattedText(), 8, ySize - 96 + 2, 0x404040); - } + @Override + protected void drawGuiContainerForegroundLayer(MatrixStack ms, int mouseX, int mouseY) { + font.func_243246_a(ms, this.title, 8, 6, 0x404040); + font.func_243246_a(ms, playerInventory.getDisplayName(), 8, ySize - 96 + 2, 0x404040); + } - @Override - protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { - RenderSystem.color3f(1.0F, 1.0F, 1.0F); - minecraft.getTextureManager().bindTexture(guiTextures); - int marginHorizontal = (width - xSize) / 2; - int marginVertical = (height - ySize) / 2; - blit(marginHorizontal, marginVertical, 0, 0, xSize, ySize); - } + @Override + protected void drawGuiContainerBackgroundLayer(MatrixStack ms, float partialTicks, int mouseX, int mouseY) { + RenderSystem.color3f(1.0F, 1.0F, 1.0F); + minecraft.getTextureManager().bindTexture(guiTextures); + int marginHorizontal = (width - xSize) / 2; + int marginVertical = (height - ySize) / 2; + blit(ms, marginHorizontal, marginVertical, 0, 0, xSize, ySize); + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/gui/buildmode/PlayerSettingsGui.java b/src/main/java/nl/requios/effortlessbuilding/gui/buildmode/PlayerSettingsGui.java index ba94f1d..3c5b3db 100644 --- a/src/main/java/nl/requios/effortlessbuilding/gui/buildmode/PlayerSettingsGui.java +++ b/src/main/java/nl/requios/effortlessbuilding/gui/buildmode/PlayerSettingsGui.java @@ -1,12 +1,11 @@ package nl.requios.effortlessbuilding.gui.buildmode; +import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; +import mcp.MethodsReturnNonnullByDefault; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.SimpleSound; -import net.minecraft.client.gui.AbstractGui; -import net.minecraft.client.gui.IGuiEventListener; -import net.minecraft.client.gui.screen.LanguageScreen; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.client.gui.widget.list.ExtendedList; @@ -16,6 +15,7 @@ import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -23,229 +23,211 @@ import net.minecraftforge.fml.client.gui.widget.ExtendedButton; import net.minecraftforge.fml.client.gui.widget.Slider; import nl.requios.effortlessbuilding.EffortlessBuilding; +import javax.annotation.ParametersAreNonnullByDefault; + +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault public class PlayerSettingsGui extends Screen { - protected int left, right, top, bottom; + protected int left, right, top, bottom; + protected boolean showShaderList = false; + private Button shaderTypeButton; + private ShaderTypeList shaderTypeList; + private Button closeButton; - private Button shaderTypeButton; - private ShaderTypeList shaderTypeList; - private Button closeButton; + public PlayerSettingsGui() { + super(new TranslationTextComponent("effortlessbuilding.screen.player_settings")); + } - protected boolean showShaderList = false; + @Override + protected void init() { + left = this.width / 2 - 140; + right = this.width / 2 + 140; + top = this.height / 2 - 100; + bottom = this.height / 2 + 100; - public enum ShaderType { - DISSOLVE_BLUE("Dissolve Blue"), - DISSOLVE_ORANGE("Dissolve Orange"); + int yy = top; + shaderTypeList = new ShaderTypeList(this.minecraft); + this.children.add(shaderTypeList); + //TODO set selected name + ITextComponent currentShaderName = ShaderType.DISSOLVE_BLUE.name; + shaderTypeButton = new ExtendedButton(right - 180, yy, 180, 20, currentShaderName, (button) -> { + showShaderList = !showShaderList; + }); + addButton(shaderTypeButton); - public String name; - ShaderType(String name) { - this.name = name; - } - } + yy += 50; + Slider slider = new Slider(right - 200, yy, 200, 20, StringTextComponent.EMPTY, StringTextComponent.EMPTY, 0.5, 2.0, 1.0, true, true, (button) -> { - public PlayerSettingsGui() { - super(new TranslationTextComponent("effortlessbuilding.screen.player_settings")); - } + }); + addButton(slider); - @Override - protected void init() { - left = this.width / 2 - 140; - right = this.width / 2 + 140; - top = this.height / 2 - 100; - bottom = this.height / 2 + 100; + closeButton = new ExtendedButton(left + 50, bottom - 20, 180, 20, new StringTextComponent("Done"), (button) -> this.minecraft.player.closeScreen()); + addButton(closeButton); + } - int yy = top; - shaderTypeList = new ShaderTypeList(this.minecraft); - this.children.add(shaderTypeList); - //TODO set selected name - String currentShaderName = ShaderType.DISSOLVE_BLUE.name; - shaderTypeButton = new ExtendedButton(right - 180, yy, 180, 20, currentShaderName, (button) -> { - showShaderList = !showShaderList; - }); - addButton(shaderTypeButton); + @Override + public void tick() { + super.tick(); + } - yy += 50; - Slider slider = new Slider(right - 200, yy, 200, 20, "", "", 0.5, 2.0, 1.0, true, true, (button) -> { + @Override + public void render(MatrixStack ms, int mouseX, int mouseY, float partialTicks) { + this.renderBackground(ms); - }); - addButton(slider); + int yy = top; + font.drawString(ms, "Shader type", left, yy + 5, 0xFFFFFF); - closeButton = new ExtendedButton(left + 50, bottom - 20, 180, 20, "Done", (button) -> { - this.minecraft.player.closeScreen(); - }); - addButton(closeButton); - } + yy += 50; + font.drawString(ms, "Shader speed", left, yy + 5, 0xFFFFFF); - @Override - public void tick() { - super.tick(); - } + super.render(ms, mouseX, mouseY, partialTicks); - @Override - public void render(int mouseX, int mouseY, float partialTicks) { - this.renderBackground(); + if (showShaderList) + this.shaderTypeList.render(ms, mouseX, mouseY, partialTicks); + } - int yy = top; - font.drawString("Shader type", left, yy + 5, 0xFFFFFF); + @Override + public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { + super.mouseClicked(mouseX, mouseY, mouseButton); + if (showShaderList) { + if (!shaderTypeList.isMouseOver(mouseX, mouseY) && !shaderTypeButton.isMouseOver(mouseX, mouseY)) + showShaderList = false; + } + return true; + } - yy += 50; - font.drawString("Shader speed", left, yy + 5, 0xFFFFFF); + @Override + public void onClose() { + ShaderTypeList.ShaderTypeEntry selectedShader = shaderTypeList.getSelected(); + //TODO save and remove + } - super.render(mouseX, mouseY, partialTicks); + public enum ShaderType { + DISSOLVE_BLUE("Dissolve Blue"), + DISSOLVE_ORANGE("Dissolve Orange"); - if (showShaderList) - this.shaderTypeList.render(mouseX, mouseY, partialTicks); - } + public ITextComponent name; - @Override - public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { - super.mouseClicked(mouseX, mouseY, mouseButton); - if (showShaderList) { - if (!shaderTypeList.isMouseOver(mouseX, mouseY) && !shaderTypeButton.isMouseOver(mouseX, mouseY)) - showShaderList = false; - } - return true; - } + ShaderType(ITextComponent name) { + this.name = name; + } - @Override - public void removed() { - ShaderTypeList.ShaderTypeEntry selectedShader = shaderTypeList.getSelected(); - //TODO save - } + ShaderType(String name) { + this.name = new StringTextComponent(name); + } + } - //Inspired by LanguageScreen - @OnlyIn(Dist.CLIENT) - class ShaderTypeList extends ExtendedList { + //Inspired by LanguageScreen + @OnlyIn(Dist.CLIENT) + class ShaderTypeList extends ExtendedList { - public ShaderTypeList(Minecraft mcIn) { - super(mcIn, 180, 140, top + 20, top + 100, 18); - this.setLeftPos(right - width); + public ShaderTypeList(Minecraft mcIn) { + super(mcIn, 180, 140, top + 20, top + 100, 18); + this.setLeftPos(right - width); - for (int i = 0; i < 40; i++) { + for (int i = 0; i < 40; i++) { - for (ShaderType shaderType : ShaderType.values()) { - ShaderTypeEntry shaderTypeEntry = new ShaderTypeEntry(shaderType); - addEntry(shaderTypeEntry); - //TODO setSelected to this if appropriate - } + for (ShaderType shaderType : ShaderType.values()) { + ShaderTypeEntry shaderTypeEntry = new ShaderTypeEntry(shaderType); + addEntry(shaderTypeEntry); + //TODO setSelected to this if appropriate + } - } + } - if (this.getSelected() != null) { - this.centerScrollOn(this.getSelected()); - } - } + if (this.getSelected() != null) { + this.centerScrollOn(this.getSelected()); + } + } - @Override - public int getRowWidth() { - return width; - } + @Override + public int getRowWidth() { + return width; + } - @Override - public void setSelected(PlayerSettingsGui.ShaderTypeList.ShaderTypeEntry selected) { - super.setSelected(selected); - Minecraft.getInstance().getSoundHandler().play(SimpleSound.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); - EffortlessBuilding.log("Selected shader " + selected.shaderType.name); - shaderTypeButton.setMessage(selected.shaderType.name); + @Override + public void setSelected(PlayerSettingsGui.ShaderTypeList.ShaderTypeEntry selected) { + super.setSelected(selected); + Minecraft.getInstance().getSoundHandler().play(SimpleSound.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + EffortlessBuilding.log("Selected shader " + selected.shaderType.name); + shaderTypeButton.setMessage(selected.shaderType.name); // showShaderList = false; - } + } - @Override - public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) { - if (!showShaderList) return false; - return super.mouseClicked(p_mouseClicked_1_, p_mouseClicked_3_, p_mouseClicked_5_); - } + @Override + public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) { + if (!showShaderList) return false; + return super.mouseClicked(p_mouseClicked_1_, p_mouseClicked_3_, p_mouseClicked_5_); + } - @Override - public boolean mouseReleased(double p_mouseReleased_1_, double p_mouseReleased_3_, int p_mouseReleased_5_) { - if (!showShaderList) return false; - return super.mouseReleased(p_mouseReleased_1_, p_mouseReleased_3_, p_mouseReleased_5_); - } + @Override + public boolean mouseReleased(double p_mouseReleased_1_, double p_mouseReleased_3_, int p_mouseReleased_5_) { + if (!showShaderList) return false; + return super.mouseReleased(p_mouseReleased_1_, p_mouseReleased_3_, p_mouseReleased_5_); + } - @Override - public boolean mouseDragged(double p_mouseDragged_1_, double p_mouseDragged_3_, int p_mouseDragged_5_, double p_mouseDragged_6_, double p_mouseDragged_8_) { - if (!showShaderList) return false; - return super.mouseDragged(p_mouseDragged_1_, p_mouseDragged_3_, p_mouseDragged_5_, p_mouseDragged_6_, p_mouseDragged_8_); - } + @Override + public boolean mouseDragged(double p_mouseDragged_1_, double p_mouseDragged_3_, int p_mouseDragged_5_, double p_mouseDragged_6_, double p_mouseDragged_8_) { + if (!showShaderList) return false; + return super.mouseDragged(p_mouseDragged_1_, p_mouseDragged_3_, p_mouseDragged_5_, p_mouseDragged_6_, p_mouseDragged_8_); + } - @Override - public boolean mouseScrolled(double p_mouseScrolled_1_, double p_mouseScrolled_3_, double p_mouseScrolled_5_) { - if (!showShaderList) return false; - return super.mouseScrolled(p_mouseScrolled_1_, p_mouseScrolled_3_, p_mouseScrolled_5_); - } + @Override + public boolean mouseScrolled(double p_mouseScrolled_1_, double p_mouseScrolled_3_, double p_mouseScrolled_5_) { + if (!showShaderList) return false; + return super.mouseScrolled(p_mouseScrolled_1_, p_mouseScrolled_3_, p_mouseScrolled_5_); + } - @Override - public boolean isMouseOver(double p_isMouseOver_1_, double p_isMouseOver_3_) { - if (!showShaderList) return false; - return super.isMouseOver(p_isMouseOver_1_, p_isMouseOver_3_); - } + @Override + public boolean isMouseOver(double p_isMouseOver_1_, double p_isMouseOver_3_) { + if (!showShaderList) return false; + return super.isMouseOver(p_isMouseOver_1_, p_isMouseOver_3_); + } - protected boolean isFocused() { - return PlayerSettingsGui.this.getFocused() == this; - } + protected boolean isFocused() { + return PlayerSettingsGui.this.getListener() == this; + } - @Override - protected int getScrollbarPosition() { - return right - 6; - } + @Override + protected int getScrollbarPosition() { + return right - 6; + } - @OnlyIn(Dist.CLIENT) - public class ShaderTypeEntry extends ExtendedList.AbstractListEntry { - private final ShaderType shaderType; - - public ShaderTypeEntry(ShaderType shaderType) { - this.shaderType = shaderType; - } - - public void render(int itemIndex, int rowTop, int rowLeft, int rowWidth, int rowHeight, int mouseX, int mouseY, boolean hovered, float partialTicks) { - if (rowTop + 10 > ShaderTypeList.this.y0 && rowTop + rowHeight - 5 < ShaderTypeList.this.y1) - drawString(font, shaderType.name, ShaderTypeList.this.x0 + 8, rowTop + 4, 0xFFFFFF); - } - - @Override - public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) { - if (p_mouseClicked_5_ == 0) { - setSelected(this); - return true; - } else { - return false; - } - } - } - - //From AbstractList, disabled parts - public void render(int p_render_1_, int p_render_2_, float p_render_3_) { - this.renderBackground(); - int i = this.getScrollbarPosition(); - int j = i + 6; - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder bufferbuilder = tessellator.getBuffer(); + //From AbstractList, disabled parts + @Override + public void render(MatrixStack ms, int p_render_1_, int p_render_2_, float p_render_3_) { + this.renderBackground(ms); + int i = this.getScrollbarPosition(); + int j = i + 6; + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder bufferbuilder = tessellator.getBuffer(); // this.minecraft.getTextureManager().bindTexture(AbstractGui.BACKGROUND_LOCATION); - RenderSystem.enableBlend(); - RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE); - RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); - float f = 32.0F; - bufferbuilder.begin(7, DefaultVertexFormats.POSITION_COLOR); - bufferbuilder.pos((double)this.x0, (double)this.y1, 0.0D).color(20, 20, 20, 180).endVertex(); - bufferbuilder.pos((double)this.x1, (double)this.y1, 0.0D).color(20, 20, 20, 180).endVertex(); - bufferbuilder.pos((double)this.x1, (double)this.y0, 0.0D).color(20, 20, 20, 180).endVertex(); - bufferbuilder.pos((double)this.x0, (double)this.y0, 0.0D).color(20, 20, 20, 180).endVertex(); - tessellator.draw(); - int k = this.getRowLeft(); - int l = this.y0 + 4 - (int)this.getScrollAmount(); - if (this.renderHeader) { - this.renderHeader(k, l, tessellator); - } + RenderSystem.enableBlend(); + RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE); + RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); + float f = 32.0F; + bufferbuilder.begin(7, DefaultVertexFormats.POSITION_COLOR); + bufferbuilder.pos(this.x0, this.y1, 0.0D).color(20, 20, 20, 180).endVertex(); + bufferbuilder.pos(this.x1, this.y1, 0.0D).color(20, 20, 20, 180).endVertex(); + bufferbuilder.pos(this.x1, this.y0, 0.0D).color(20, 20, 20, 180).endVertex(); + bufferbuilder.pos(this.x0, this.y0, 0.0D).color(20, 20, 20, 180).endVertex(); + tessellator.draw(); + int k = this.getRowLeft(); + int l = this.y0 + 4 - (int) this.getScrollAmount(); + if (this.renderHeader) { + this.renderHeader(ms, k, l, tessellator); + } - this.renderList(k, l, p_render_1_, p_render_2_, p_render_3_); - RenderSystem.disableDepthTest(); + this.renderList(ms, k, l, p_render_1_, p_render_2_, p_render_3_); + RenderSystem.disableDepthTest(); // this.renderHoleBackground(0, this.y0, 255, 255); // this.renderHoleBackground(this.y1, this.height, 255, 255); - RenderSystem.enableBlend(); - RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE); - RenderSystem.disableAlphaTest(); - RenderSystem.shadeModel(7425); - RenderSystem.disableTexture(); + RenderSystem.enableBlend(); + RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE); + RenderSystem.disableAlphaTest(); + RenderSystem.shadeModel(7425); + RenderSystem.disableTexture(); // int i1 = 4; // bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); // bufferbuilder.pos((double)this.x0, (double)(this.y0 + 4), 0.0D).tex(0.0F, 1.0F).color(0, 0, 0, 0).endVertex(); @@ -260,45 +242,70 @@ public class PlayerSettingsGui extends Screen { // bufferbuilder.pos((double)this.x0, (double)(this.y1 - 4), 0.0D).tex(0.0F, 0.0F).color(0, 0, 0, 0).endVertex(); // tessellator.draw(); - //SCROLLBAR - int j1 = this.getMaxScroll(); - if (j1 > 0) { - int k1 = (int)((float)((this.y1 - this.y0) * (this.y1 - this.y0)) / (float)this.getMaxPosition()); - k1 = MathHelper.clamp(k1, 32, this.y1 - this.y0 - 8); - int l1 = (int)this.getScrollAmount() * (this.y1 - this.y0 - k1) / j1 + this.y0; - if (l1 < this.y0) { - l1 = this.y0; - } + //SCROLLBAR + int j1 = this.getMaxScroll(); + if (j1 > 0) { + int k1 = (int) ((float) ((this.y1 - this.y0) * (this.y1 - this.y0)) / (float) this.getMaxPosition()); + k1 = MathHelper.clamp(k1, 32, this.y1 - this.y0 - 8); + int l1 = (int) this.getScrollAmount() * (this.y1 - this.y0 - k1) / j1 + this.y0; + if (l1 < this.y0) { + l1 = this.y0; + } - bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - bufferbuilder.pos((double)i, (double)this.y1, 0.0D).tex(0.0F, 1.0F).color(0, 0, 0, 255).endVertex(); - bufferbuilder.pos((double)j, (double)this.y1, 0.0D).tex(1.0F, 1.0F).color(0, 0, 0, 255).endVertex(); - bufferbuilder.pos((double)j, (double)this.y0, 0.0D).tex(1.0F, 0.0F).color(0, 0, 0, 255).endVertex(); - bufferbuilder.pos((double)i, (double)this.y0, 0.0D).tex(0.0F, 0.0F).color(0, 0, 0, 255).endVertex(); - tessellator.draw(); - bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - bufferbuilder.pos((double)i, (double)(l1 + k1), 0.0D).tex(0.0F, 1.0F).color(128, 128, 128, 255).endVertex(); - bufferbuilder.pos((double)j, (double)(l1 + k1), 0.0D).tex(1.0F, 1.0F).color(128, 128, 128, 255).endVertex(); - bufferbuilder.pos((double)j, (double)l1, 0.0D).tex(1.0F, 0.0F).color(128, 128, 128, 255).endVertex(); - bufferbuilder.pos((double)i, (double)l1, 0.0D).tex(0.0F, 0.0F).color(128, 128, 128, 255).endVertex(); - tessellator.draw(); - bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - bufferbuilder.pos((double)i, (double)(l1 + k1 - 1), 0.0D).tex(0.0F, 1.0F).color(192, 192, 192, 255).endVertex(); - bufferbuilder.pos((double)(j - 1), (double)(l1 + k1 - 1), 0.0D).tex(1.0F, 1.0F).color(192, 192, 192, 255).endVertex(); - bufferbuilder.pos((double)(j - 1), (double)l1, 0.0D).tex(1.0F, 0.0F).color(192, 192, 192, 255).endVertex(); - bufferbuilder.pos((double)i, (double)l1, 0.0D).tex(0.0F, 0.0F).color(192, 192, 192, 255).endVertex(); - tessellator.draw(); - } + bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + bufferbuilder.pos(i, this.y1, 0.0D).tex(0.0F, 1.0F).color(0, 0, 0, 255).endVertex(); + bufferbuilder.pos(j, this.y1, 0.0D).tex(1.0F, 1.0F).color(0, 0, 0, 255).endVertex(); + bufferbuilder.pos(j, this.y0, 0.0D).tex(1.0F, 0.0F).color(0, 0, 0, 255).endVertex(); + bufferbuilder.pos(i, this.y0, 0.0D).tex(0.0F, 0.0F).color(0, 0, 0, 255).endVertex(); + tessellator.draw(); + bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + bufferbuilder.pos(i, l1 + k1, 0.0D).tex(0.0F, 1.0F).color(128, 128, 128, 255).endVertex(); + bufferbuilder.pos(j, l1 + k1, 0.0D).tex(1.0F, 1.0F).color(128, 128, 128, 255).endVertex(); + bufferbuilder.pos(j, l1, 0.0D).tex(1.0F, 0.0F).color(128, 128, 128, 255).endVertex(); + bufferbuilder.pos(i, l1, 0.0D).tex(0.0F, 0.0F).color(128, 128, 128, 255).endVertex(); + tessellator.draw(); + bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + bufferbuilder.pos(i, l1 + k1 - 1, 0.0D).tex(0.0F, 1.0F).color(192, 192, 192, 255).endVertex(); + bufferbuilder.pos(j - 1, l1 + k1 - 1, 0.0D).tex(1.0F, 1.0F).color(192, 192, 192, 255).endVertex(); + bufferbuilder.pos(j - 1, l1, 0.0D).tex(1.0F, 0.0F).color(192, 192, 192, 255).endVertex(); + bufferbuilder.pos(i, l1, 0.0D).tex(0.0F, 0.0F).color(192, 192, 192, 255).endVertex(); + tessellator.draw(); + } // this.renderDecorations(p_render_1_, p_render_2_); - RenderSystem.enableTexture(); - RenderSystem.shadeModel(7424); - RenderSystem.enableAlphaTest(); - RenderSystem.disableBlend(); - } + RenderSystem.enableTexture(); + RenderSystem.shadeModel(7424); + RenderSystem.enableAlphaTest(); + RenderSystem.disableBlend(); + } - private int getMaxScroll() { - return Math.max(0, this.getMaxPosition() - (this.y1 - this.y0 - 4)); - } - } + private int getMaxScroll() { + return Math.max(0, this.getMaxPosition() - (this.y1 - this.y0 - 4)); + } + + @OnlyIn(Dist.CLIENT) + public class ShaderTypeEntry extends ExtendedList.AbstractListEntry { + private final ShaderType shaderType; + + public ShaderTypeEntry(ShaderType shaderType) { + this.shaderType = shaderType; + } + + @Override + public void render(MatrixStack ms, int itemIndex, int rowTop, int rowLeft, int rowWidth, int rowHeight, int mouseX, int mouseY, boolean hovered, float partialTicks) { + if (rowTop + 10 > ShaderTypeList.this.y0 && rowTop + rowHeight - 5 < ShaderTypeList.this.y1) + drawString(ms, font, shaderType.name, ShaderTypeList.this.x0 + 8, rowTop + 4, 0xFFFFFF); + } + + @Override + public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) { + if (p_mouseClicked_5_ == 0) { + setSelected(this); + return true; + } else { + return false; + } + } + } + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/gui/buildmode/RadialMenu.java b/src/main/java/nl/requios/effortlessbuilding/gui/buildmode/RadialMenu.java index 0d44c19..e8e9b5c 100644 --- a/src/main/java/nl/requios/effortlessbuilding/gui/buildmode/RadialMenu.java +++ b/src/main/java/nl/requios/effortlessbuilding/gui/buildmode/RadialMenu.java @@ -1,492 +1,493 @@ package nl.requios.effortlessbuilding.gui.buildmode; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - +import com.google.common.base.Stopwatch; +import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; +import mcp.MethodsReturnNonnullByDefault; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.renderer.BufferBuilder; +import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.AtlasTexture; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.KeyBinding; import net.minecraft.util.Direction; -import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.ModClientEventHandler; -import nl.requios.effortlessbuilding.ModEventHandler; import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager; import nl.requios.effortlessbuilding.proxy.ClientProxy; import org.apache.commons.lang3.text.WordUtils; import org.lwjgl.opengl.GL11; -import com.google.common.base.Stopwatch; +import javax.annotation.ParametersAreNonnullByDefault; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.BufferBuilder; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.vertex.DefaultVertexFormats; - -import static nl.requios.effortlessbuilding.buildmode.BuildModes.*; +import static nl.requios.effortlessbuilding.buildmode.BuildModes.BuildModeEnum; import static nl.requios.effortlessbuilding.buildmode.ModeOptions.*; /** * From Chisels and Bits by AlgorithmX2 * https://github.com/AlgorithmX2/Chisels-and-Bits/blob/1.12/src/main/java/mod/chiselsandbits/client/gui/ChiselsAndBitsMenu.java */ + +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault public class RadialMenu extends Screen { - private final float TIME_SCALE = 0.01f; - public static final RadialMenu instance = new RadialMenu(); + public static final RadialMenu instance = new RadialMenu(); + private final float TIME_SCALE = 0.01f; + public BuildModeEnum switchTo = null; + public ActionEnum doAction = null; + public boolean actionUsed = false; + private float visibility = 0.0f; + private Stopwatch lastChange = Stopwatch.createStarted(); + + public RadialMenu() { + super(new TranslationTextComponent("effortlessbuilding.screen.radial_menu")); + } + + private float clampVis(final float f) { + return Math.max(0.0f, Math.min(1.0f, f)); + } + + public void raiseVisibility() { + visibility = clampVis(visibility + lastChange.elapsed(TimeUnit.MILLISECONDS) * TIME_SCALE); + lastChange = Stopwatch.createStarted(); + } + + public void decreaseVisibility() { + visibility = clampVis(visibility - lastChange.elapsed(TimeUnit.MILLISECONDS) * TIME_SCALE); + lastChange = Stopwatch.createStarted(); + } + + public void setVisibility(float visibility) { + this.visibility = visibility; + } + + public boolean isVisible() { + return visibility > 0.001; + } + + public void configure(final int scaledWidth, final int scaledHeight) { + Minecraft mc = Minecraft.getInstance(); + font = mc.fontRenderer; + width = scaledWidth; + height = scaledHeight; + } + + @Override + public void render(MatrixStack ms, final int mouseX, final int mouseY, final float partialTicks) { + if (!isVisible()) return; + + BuildModeEnum currentBuildMode = ModeSettingsManager.getModeSettings(Minecraft.getInstance().player).getBuildMode(); + + RenderSystem.pushMatrix(); + RenderSystem.translatef(0.0F, 0.0F, 200.0F); + + final int startColor = (int) (visibility * 98) << 24; + final int endColor = (int) (visibility * 128) << 24; + + fillGradient(ms, 0, 0, width, height, startColor, endColor); + + RenderSystem.disableTexture(); + RenderSystem.enableBlend(); + RenderSystem.disableAlphaTest(); + RenderSystem.blendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); + RenderSystem.shadeModel(GL11.GL_SMOOTH); + final Tessellator tessellator = Tessellator.getInstance(); + final BufferBuilder buffer = tessellator.getBuffer(); + + buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); + + final double middleX = width / 2.0; + final double middleY = height / 2.0; + + //Fix for high def (retina) displays: use custom mouse coordinates + //Borrowed from GameRenderer::updateCameraAndRender + Minecraft mc = Minecraft.getInstance(); + int mouseXX = (int) (mc.mouseHelper.getMouseX() * (double) mc.getMainWindow().getScaledWidth() / (double) mc.getMainWindow().getWidth()); + int mouseYY = (int) (mc.mouseHelper.getMouseY() * (double) mc.getMainWindow().getScaledHeight() / (double) mc.getMainWindow().getHeight()); + + final double mouseXCenter = mouseXX - middleX; + final double mouseYCenter = mouseYY - middleY; + double mouseRadians = Math.atan2(mouseYCenter, mouseXCenter); + + final double ringInnerEdge = 30; + final double ringOuterEdge = 65; + final double textDistance = 75; + final double buttonDistance = 105; + final double quarterCircle = Math.PI / 2.0; + + if (mouseRadians < -quarterCircle) { + mouseRadians = mouseRadians + Math.PI * 2; + } + + final ArrayList modes = new ArrayList(); + final ArrayList buttons = new ArrayList(); + + //Add build modes + for (final BuildModeEnum mode : BuildModeEnum.values()) { + modes.add(new MenuRegion(mode)); + } + + //Add actions + buttons.add(new MenuButton(ActionEnum.UNDO.name, ActionEnum.UNDO, -buttonDistance - 26, -13, Direction.UP)); + buttons.add(new MenuButton(ActionEnum.REDO.name, ActionEnum.REDO, -buttonDistance, -13, Direction.UP)); + buttons.add(new MenuButton(ActionEnum.OPEN_PLAYER_SETTINGS.name, ActionEnum.OPEN_PLAYER_SETTINGS, -buttonDistance - 26 - 13, 13, Direction.DOWN)); + buttons.add(new MenuButton(ActionEnum.OPEN_MODIFIER_SETTINGS.name, ActionEnum.OPEN_MODIFIER_SETTINGS, -buttonDistance - 13, 13, Direction.DOWN)); + buttons.add(new MenuButton(ActionEnum.REPLACE.name, ActionEnum.REPLACE, -buttonDistance + 13, 13, Direction.DOWN)); + + //Add buildmode dependent options + OptionEnum[] options = currentBuildMode.options; + for (int i = 0; i < options.length; i++) { + for (int j = 0; j < options[i].actions.length; j++) { + ActionEnum action = options[i].actions[j]; + buttons.add(new MenuButton(action.name, action, buttonDistance + j * 26, -13 + i * 39, Direction.DOWN)); + } + } + + switchTo = null; + doAction = null; + + //Draw buildmode backgrounds + if (!modes.isEmpty()) { + final int totalModes = Math.max(3, modes.size()); + int currentMode = 0; + final double fragment = Math.PI * 0.005; + final double fragment2 = Math.PI * 0.0025; + final double perObject = 2.0 * Math.PI / totalModes; + + for (int i = 0; i < modes.size(); i++) { + MenuRegion menuRegion = modes.get(i); + final double beginRadians = currentMode * perObject - quarterCircle; + final double endRadians = (currentMode + 1) * perObject - quarterCircle; + + menuRegion.x1 = Math.cos(beginRadians); + menuRegion.x2 = Math.cos(endRadians); + menuRegion.y1 = Math.sin(beginRadians); + menuRegion.y2 = Math.sin(endRadians); + + final double x1m1 = Math.cos(beginRadians + fragment) * ringInnerEdge; + final double x2m1 = Math.cos(endRadians - fragment) * ringInnerEdge; + final double y1m1 = Math.sin(beginRadians + fragment) * ringInnerEdge; + final double y2m1 = Math.sin(endRadians - fragment) * ringInnerEdge; + + final double x1m2 = Math.cos(beginRadians + fragment2) * ringOuterEdge; + final double x2m2 = Math.cos(endRadians - fragment2) * ringOuterEdge; + final double y1m2 = Math.sin(beginRadians + fragment2) * ringOuterEdge; + final double y2m2 = Math.sin(endRadians - fragment2) * ringOuterEdge; + + float r = 0.0f; + float g = 0.0f; + float b = 0.0f; + float a = 0.5f; + + //check if current mode + int buildMode = currentBuildMode.ordinal(); + if (buildMode == i) { + r = 0f; + g = 0.5f; + b = 1f; + a = 0.5f; + //menuRegion.highlighted = true; //draw text + } + + //check if mouse is over this region + final boolean isMouseInQuad = inTriangle(x1m1, y1m1, x2m2, y2m2, x2m1, y2m1, mouseXCenter, mouseYCenter) + || inTriangle(x1m1, y1m1, x1m2, y1m2, x2m2, y2m2, mouseXCenter, mouseYCenter); + + if (beginRadians <= mouseRadians && mouseRadians <= endRadians && isMouseInQuad) { + r = 0.6f; + g = 0.8f; + b = 1f; + a = 0.6f; + menuRegion.highlighted = true; + switchTo = menuRegion.mode; + } + + buffer.pos(middleX + x1m1, middleY + y1m1, getBlitOffset()).color(r, g, b, a).endVertex(); + buffer.pos(middleX + x2m1, middleY + y2m1, getBlitOffset()).color(r, g, b, a).endVertex(); + buffer.pos(middleX + x2m2, middleY + y2m2, getBlitOffset()).color(r, g, b, a).endVertex(); + buffer.pos(middleX + x1m2, middleY + y1m2, getBlitOffset()).color(r, g, b, a).endVertex(); + + currentMode++; + } + } + + //Draw action backgrounds + for (final MenuButton btn : buttons) { + float r = 0.5f; + float g = 0.5f; + float b = 0.5f; + float a = 0.5f; + + //highlight when active option + if (btn.action == getBuildSpeed() || + btn.action == getFill() || + btn.action == getCubeFill() || + btn.action == getRaisedEdge() || + btn.action == getLineThickness() || + btn.action == getCircleStart()) { + r = 0.0f; + g = 0.5f; + b = 1f; + a = 0.6f; + } + + //highlight when mouse over + if (btn.x1 <= mouseXCenter && btn.x2 >= mouseXCenter && btn.y1 <= mouseYCenter && btn.y2 >= mouseYCenter) { + r = 0.6f; + g = 0.8f; + b = 1f; + a = 0.6f; + btn.highlighted = true; + doAction = btn.action; + } + + buffer.pos(middleX + btn.x1, middleY + btn.y1, getBlitOffset()).color(r, g, b, a).endVertex(); + buffer.pos(middleX + btn.x1, middleY + btn.y2, getBlitOffset()).color(r, g, b, a).endVertex(); + buffer.pos(middleX + btn.x2, middleY + btn.y2, getBlitOffset()).color(r, g, b, a).endVertex(); + buffer.pos(middleX + btn.x2, middleY + btn.y1, getBlitOffset()).color(r, g, b, a).endVertex(); + } + + tessellator.draw(); + + RenderSystem.shadeModel(GL11.GL_FLAT); + + RenderSystem.translatef(0f, 0f, 5f); + RenderSystem.enableTexture(); + RenderSystem.color3f(1f, 1f, 1f); + RenderSystem.disableBlend(); + RenderSystem.enableAlphaTest(); + mc.getTextureManager().bindTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE); + + buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); + + //Draw buildmode icons + for (final MenuRegion menuRegion : modes) { + + final double x = (menuRegion.x1 + menuRegion.x2) * 0.5 * (ringOuterEdge * 0.6 + 0.4 * ringInnerEdge); + final double y = (menuRegion.y1 + menuRegion.y2) * 0.5 * (ringOuterEdge * 0.6 + 0.4 * ringInnerEdge); + + final TextureAtlasSprite sprite = ModClientEventHandler.getBuildModeIcon(menuRegion.mode); + + final double x1 = x - 8; + final double x2 = x + 8; + final double y1 = y - 8; + final double y2 = y + 8; + + final float f = 1f; + final float a = 1f; + + final double u1 = 0; + final double u2 = 16; + final double v1 = 0; + final double v2 = 16; + + buffer.pos(middleX + x1, middleY + y1, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); + buffer.pos(middleX + x1, middleY + y2, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); + buffer.pos(middleX + x2, middleY + y2, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); + buffer.pos(middleX + x2, middleY + y1, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); + } + + //Draw action icons + for (final MenuButton button : buttons) { + + final float f = 1f; + final float a = 1f; + + final double u1 = 0; + final double u2 = 16; + final double v1 = 0; + final double v2 = 16; + + final TextureAtlasSprite sprite = ModClientEventHandler.getModeOptionIcon(button.action); + + final double btnmiddleX = (button.x1 + button.x2) / 2 + 0.01; + final double btnmiddleY = (button.y1 + button.y2) / 2 + 0.01; + final double btnx1 = btnmiddleX - 8; + final double btnx2 = btnmiddleX + 8; + final double btny1 = btnmiddleY - 8; + final double btny2 = btnmiddleY + 8; + + buffer.pos(middleX + btnx1, middleY + btny1, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); + buffer.pos(middleX + btnx1, middleY + btny2, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); + buffer.pos(middleX + btnx2, middleY + btny2, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); + buffer.pos(middleX + btnx2, middleY + btny1, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); + } + + tessellator.draw(); + + //Draw strings + //font.drawStringWithShadow("Actions", (int) (middleX - buttonDistance - 13) - font.getStringWidth("Actions") * 0.5f, (int) middleY - 38, 0xffffffff); + + //Draw option strings + for (int i = 0; i < currentBuildMode.options.length; i++) { + OptionEnum option = options[i]; + font.drawStringWithShadow(ms, I18n.format(option.name), (int) (middleX + buttonDistance - 9), (int) middleY - 37 + i * 39, 0xeeeeeeff); + } + + String credits = "Effortless Building"; + font.drawStringWithShadow(ms, credits, width - font.getStringWidth(credits) - 4, height - 10, 0x88888888); + + //Draw buildmode text + for (final MenuRegion menuRegion : modes) { + + if (menuRegion.highlighted) { + final double x = (menuRegion.x1 + menuRegion.x2) * 0.5; + final double y = (menuRegion.y1 + menuRegion.y2) * 0.5; + + int fixed_x = (int) (x * textDistance); + final int fixed_y = (int) (y * textDistance) - font.FONT_HEIGHT / 2; + final String text = I18n.format(menuRegion.mode.name); + + if (x <= -0.2) { + fixed_x -= font.getStringWidth(text); + } else if (-0.2 <= x && x <= 0.2) { + fixed_x -= font.getStringWidth(text) / 2; + } + + font.drawStringWithShadow(ms, text, (int) middleX + fixed_x, (int) middleY + fixed_y, 0xffffffff); + } + } + + //Draw action text + for (final MenuButton button : buttons) { + if (button.highlighted) { + String text = TextFormatting.AQUA + button.name; + int wrap = 120; + String keybind = ""; // FIXME + String keybindFormatted = ""; + + //Add keybind in brackets + if (button.action == ActionEnum.UNDO) { + keybind = ClientProxy.keyBindings[4].getTranslationKey(); + } + if (button.action == ActionEnum.REDO) { + keybind = ClientProxy.keyBindings[5].getTranslationKey(); + } + if (button.action == ActionEnum.REPLACE) { + keybind = ClientProxy.keyBindings[1].getTranslationKey(); + } + if (button.action == ActionEnum.OPEN_MODIFIER_SETTINGS) { + keybind = ClientProxy.keyBindings[0].getTranslationKey(); + } + if (currentBuildMode.options.length > 0) { + //Add (ctrl) to first two actions of first option + if (button.action == currentBuildMode.options[0].actions[0] + || button.action == currentBuildMode.options[0].actions[1]) { + keybind = ClientProxy.keyBindings[6].getTranslationKey(); + if (keybind.equals("Left Control")) keybind = "Ctrl"; + } + } + if (!keybind.isEmpty()) + keybindFormatted = TextFormatting.GRAY + "(" + WordUtils.capitalizeFully(keybind) + ")"; + + if (button.textSide == Direction.WEST) { + + font.drawString(ms, text, (int) (middleX + button.x1 - 8) - font.getStringWidth(text), + (int) (middleY + button.y1 + 6), 0xffffffff); + + } else if (button.textSide == Direction.EAST) { + + font.drawString(ms, text, (int) (middleX + button.x2 + 8), + (int) (middleY + button.y1 + 6), 0xffffffff); + + } else if (button.textSide == Direction.UP || button.textSide == Direction.NORTH) { + + font.drawString(ms, keybindFormatted, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(keybindFormatted) * 0.5), + (int) (middleY + button.y1 - 26), 0xffffffff); + + font.drawString(ms, text, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(text) * 0.5), + (int) (middleY + button.y1 - 14), 0xffffffff); + + } else if (button.textSide == Direction.DOWN || button.textSide == Direction.SOUTH) { + + font.drawString(ms, text, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(text) * 0.5), + (int) (middleY + button.y1 + 26), 0xffffffff); + + font.drawString(ms, keybindFormatted, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(keybindFormatted) * 0.5), + (int) (middleY + button.y1 + 38), 0xffffffff); + + } + + } + } + + RenderSystem.popMatrix(); + } + + private boolean inTriangle(final double x1, final double y1, final double x2, final double y2, + final double x3, final double y3, final double x, final double y) { + final double ab = (x1 - x) * (y2 - y) - (x2 - x) * (y1 - y); + final double bc = (x2 - x) * (y3 - y) - (x3 - x) * (y2 - y); + final double ca = (x3 - x) * (y1 - y) - (x1 - x) * (y3 - y); + return sign(ab) == sign(bc) && sign(bc) == sign(ca); + } + + private int sign(final double n) { + return n > 0 ? 1 : -1; + } + + /** + * Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + @Override + public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { + EffortlessBuilding.log("mouse clicked"); + + KeyBinding.updateKeyBindState(); + KeyBinding.setKeyBindState(ClientProxy.keyBindings[3].getKey(), true); + + if (mouseButton == 0) { + this.minecraft.displayGuiScreen(null); + + if (this.minecraft.currentScreen == null) { + this.minecraft.setGameFocused(true); + } + } + return super.mouseClicked(mouseX, mouseY, mouseButton); + } + + private static class MenuButton { + + public final ActionEnum action; + public double x1, x2; + public double y1, y2; + public boolean highlighted; + public String name; + public Direction textSide; + + public MenuButton(final String name, final ActionEnum action, final double x, final double y, + final Direction textSide) { + this.name = I18n.format(name); + this.action = action; + x1 = x - 10; + x2 = x + 10; + y1 = y - 10; + y2 = y + 10; + this.textSide = textSide; + } + + } + + static class MenuRegion { - private float visibility = 0.0f; - private Stopwatch lastChange = Stopwatch.createStarted(); - public BuildModeEnum switchTo = null; - public ActionEnum doAction = null; - public boolean actionUsed = false; - - public RadialMenu() { - super(new TranslationTextComponent("effortlessbuilding.screen.radial_menu")); - } - - private float clampVis(final float f) { - return Math.max( 0.0f, Math.min( 1.0f, f ) ); - } - - public void raiseVisibility() { - visibility = clampVis( visibility + lastChange.elapsed( TimeUnit.MILLISECONDS ) * TIME_SCALE ); - lastChange = Stopwatch.createStarted(); - } - - public void decreaseVisibility() { - visibility = clampVis( visibility - lastChange.elapsed( TimeUnit.MILLISECONDS ) * TIME_SCALE ); - lastChange = Stopwatch.createStarted(); - } - - public void setVisibility(float visibility) { - this.visibility = visibility; - } - - public boolean isVisible() { - return visibility > 0.001; - } - - public void configure(final int scaledWidth, final int scaledHeight ) { - Minecraft mc = Minecraft.getInstance(); - font = mc.fontRenderer; - width = scaledWidth; - height = scaledHeight; - } - - private static class MenuButton { - - public double x1, x2; - public double y1, y2; - public boolean highlighted; - - public final ActionEnum action; - public String name; - public Direction textSide; - - public MenuButton(final String name, final ActionEnum action, final double x, final double y, - final Direction textSide) { - this.name = I18n.format(name); - this.action = action; - x1 = x - 10; - x2 = x + 10; - y1 = y - 10; - y2 = y + 10; - this.textSide = textSide; - } - - } - - static class MenuRegion { - - public final BuildModeEnum mode; - public double x1, x2; - public double y1, y2; - public boolean highlighted; - - public MenuRegion(final BuildModeEnum mode) { - this.mode = mode; - } - - } - - @Override - public void render(final int mouseX, final int mouseY, final float partialTicks) { - if (!isVisible()) return; - - BuildModeEnum currentBuildMode = ModeSettingsManager.getModeSettings(Minecraft.getInstance().player).getBuildMode(); - - RenderSystem.pushMatrix(); - RenderSystem.translatef( 0.0F, 0.0F, 200.0F ); - - final int startColor = (int) ( visibility * 98 ) << 24; - final int endColor = (int) ( visibility * 128 ) << 24; - - fillGradient(0, 0, width, height, startColor, endColor); - - RenderSystem.disableTexture(); - RenderSystem.enableBlend(); - RenderSystem.disableAlphaTest(); - RenderSystem.blendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); - RenderSystem.shadeModel(GL11.GL_SMOOTH); - final Tessellator tessellator = Tessellator.getInstance(); - final BufferBuilder buffer = tessellator.getBuffer(); - - buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); - - final double middleX = width / 2.0; - final double middleY = height / 2.0; - - //Fix for high def (retina) displays: use custom mouse coordinates - //Borrowed from GameRenderer::updateCameraAndRender - Minecraft mc = Minecraft.getInstance(); - int mouseXX = (int)(mc.mouseHelper.getMouseX() * (double)mc.getMainWindow().getScaledWidth() / (double)mc.getMainWindow().getWidth()); - int mouseYY = (int)(mc.mouseHelper.getMouseY() * (double)mc.getMainWindow().getScaledHeight() / (double)mc.getMainWindow().getHeight()); - - final double mouseXCenter = mouseXX - middleX; - final double mouseYCenter = mouseYY - middleY; - double mouseRadians = Math.atan2(mouseYCenter, mouseXCenter); - - final double ringInnerEdge = 30; - final double ringOuterEdge = 65; - final double textDistance = 75; - final double buttonDistance = 105; - final double quarterCircle = Math.PI / 2.0; - - if ( mouseRadians < -quarterCircle ) { - mouseRadians = mouseRadians + Math.PI * 2; - } - - final ArrayList modes = new ArrayList(); - final ArrayList buttons = new ArrayList(); - - //Add build modes - for (final BuildModeEnum mode : BuildModeEnum.values()) { - modes.add(new MenuRegion(mode)); - } - - //Add actions - buttons.add(new MenuButton(ActionEnum.UNDO.name, ActionEnum.UNDO, -buttonDistance - 26, -13, Direction.UP)); - buttons.add(new MenuButton(ActionEnum.REDO.name, ActionEnum.REDO, -buttonDistance, -13, Direction.UP)); - buttons.add(new MenuButton(ActionEnum.OPEN_PLAYER_SETTINGS.name, ActionEnum.OPEN_PLAYER_SETTINGS, -buttonDistance - 26 - 13, 13, Direction.DOWN)); - buttons.add(new MenuButton(ActionEnum.OPEN_MODIFIER_SETTINGS.name, ActionEnum.OPEN_MODIFIER_SETTINGS, -buttonDistance - 13, 13, Direction.DOWN)); - buttons.add(new MenuButton(ActionEnum.REPLACE.name, ActionEnum.REPLACE, -buttonDistance + 13, 13, Direction.DOWN)); - - //Add buildmode dependent options - OptionEnum[] options = currentBuildMode.options; - for (int i = 0; i < options.length; i++) { - for (int j = 0; j < options[i].actions.length; j++) { - ActionEnum action = options[i].actions[j]; - buttons.add(new MenuButton(action.name, action, buttonDistance + j * 26, -13 + i * 39, Direction.DOWN)); - } - } - - switchTo = null; - doAction = null; - - //Draw buildmode backgrounds - if (!modes.isEmpty()) { - final int totalModes = Math.max( 3, modes.size() ); - int currentMode = 0; - final double fragment = Math.PI * 0.005; - final double fragment2 = Math.PI * 0.0025; - final double perObject = 2.0 * Math.PI / totalModes; - - for (int i = 0; i < modes.size(); i++) { - MenuRegion menuRegion = modes.get(i); - final double beginRadians = currentMode * perObject - quarterCircle; - final double endRadians = (currentMode + 1) * perObject - quarterCircle; - - menuRegion.x1 = Math.cos(beginRadians); - menuRegion.x2 = Math.cos(endRadians); - menuRegion.y1 = Math.sin(beginRadians); - menuRegion.y2 = Math.sin(endRadians); - - final double x1m1 = Math.cos(beginRadians + fragment) * ringInnerEdge; - final double x2m1 = Math.cos(endRadians - fragment) * ringInnerEdge; - final double y1m1 = Math.sin(beginRadians + fragment) * ringInnerEdge; - final double y2m1 = Math.sin(endRadians - fragment) * ringInnerEdge; - - final double x1m2 = Math.cos(beginRadians + fragment2) * ringOuterEdge; - final double x2m2 = Math.cos(endRadians - fragment2) * ringOuterEdge; - final double y1m2 = Math.sin(beginRadians + fragment2) * ringOuterEdge; - final double y2m2 = Math.sin(endRadians - fragment2) * ringOuterEdge; - - float r = 0.0f; - float g = 0.0f; - float b = 0.0f; - float a = 0.5f; - - //check if current mode - int buildMode = currentBuildMode.ordinal(); - if (buildMode == i) { - r = 0f; - g = 0.5f; - b = 1f; - a = 0.5f; - //menuRegion.highlighted = true; //draw text - } - - //check if mouse is over this region - final boolean isMouseInQuad = inTriangle(x1m1, y1m1, x2m2, y2m2, x2m1, y2m1, mouseXCenter, mouseYCenter) - || inTriangle(x1m1, y1m1, x1m2, y1m2, x2m2, y2m2, mouseXCenter, mouseYCenter); - - if (beginRadians <= mouseRadians && mouseRadians <= endRadians && isMouseInQuad) { - r = 0.6f; - g = 0.8f; - b = 1f; - a = 0.6f; - menuRegion.highlighted = true; - switchTo = menuRegion.mode; - } - - buffer.pos(middleX + x1m1, middleY + y1m1, getBlitOffset()).color(r, g, b, a).endVertex(); - buffer.pos(middleX + x2m1, middleY + y2m1, getBlitOffset()).color(r, g, b, a).endVertex(); - buffer.pos(middleX + x2m2, middleY + y2m2, getBlitOffset()).color(r, g, b, a).endVertex(); - buffer.pos(middleX + x1m2, middleY + y1m2, getBlitOffset()).color(r, g, b, a).endVertex(); - - currentMode++; - } - } - - //Draw action backgrounds - for (final MenuButton btn : buttons) { - float r = 0.5f; - float g = 0.5f; - float b = 0.5f; - float a = 0.5f; - - //highlight when active option - if (btn.action == getBuildSpeed() || - btn.action == getFill() || - btn.action == getCubeFill() || - btn.action == getRaisedEdge() || - btn.action == getLineThickness() || - btn.action == getCircleStart()) { - r = 0.0f; - g = 0.5f; - b = 1f; - a = 0.6f; - } - - //highlight when mouse over - if (btn.x1 <= mouseXCenter && btn.x2 >= mouseXCenter && btn.y1 <= mouseYCenter && btn.y2 >= mouseYCenter) { - r = 0.6f; - g = 0.8f; - b = 1f; - a = 0.6f; - btn.highlighted = true; - doAction = btn.action; - } - - buffer.pos(middleX + btn.x1, middleY + btn.y1, getBlitOffset()).color(r, g, b, a).endVertex(); - buffer.pos(middleX + btn.x1, middleY + btn.y2, getBlitOffset()).color(r, g, b, a).endVertex(); - buffer.pos(middleX + btn.x2, middleY + btn.y2, getBlitOffset()).color(r, g, b, a).endVertex(); - buffer.pos(middleX + btn.x2, middleY + btn.y1, getBlitOffset()).color(r, g, b, a).endVertex(); - } - - tessellator.draw(); - - RenderSystem.shadeModel(GL11.GL_FLAT); - - RenderSystem.translatef(0f, 0f, 5f); - RenderSystem.enableTexture(); - RenderSystem.color3f(1f, 1f, 1f); - RenderSystem.disableBlend(); - RenderSystem.enableAlphaTest(); - mc.getTextureManager().bindTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE); - - buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - - //Draw buildmode icons - for (final MenuRegion menuRegion : modes) { - - final double x = (menuRegion.x1 + menuRegion.x2) * 0.5 * (ringOuterEdge * 0.6 + 0.4 * ringInnerEdge); - final double y = (menuRegion.y1 + menuRegion.y2) * 0.5 * (ringOuterEdge * 0.6 + 0.4 * ringInnerEdge); - - final TextureAtlasSprite sprite = ModClientEventHandler.getBuildModeIcon(menuRegion.mode); - - final double x1 = x - 8; - final double x2 = x + 8; - final double y1 = y - 8; - final double y2 = y + 8; - - final float f = 1f; - final float a = 1f; - - final double u1 = 0; - final double u2 = 16; - final double v1 = 0; - final double v2 = 16; - - buffer.pos(middleX + x1, middleY + y1, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); - buffer.pos(middleX + x1, middleY + y2, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); - buffer.pos(middleX + x2, middleY + y2, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); - buffer.pos(middleX + x2, middleY + y1, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); - } - - //Draw action icons - for (final MenuButton button : buttons) { - - final float f = 1f; - final float a = 1f; - - final double u1 = 0; - final double u2 = 16; - final double v1 = 0; - final double v2 = 16; - - final TextureAtlasSprite sprite = ModClientEventHandler.getModeOptionIcon(button.action); - - final double btnmiddleX = (button.x1 + button.x2) / 2 + 0.01; - final double btnmiddleY = (button.y1 + button.y2) / 2 + 0.01; - final double btnx1 = btnmiddleX - 8; - final double btnx2 = btnmiddleX + 8; - final double btny1 = btnmiddleY - 8; - final double btny2 = btnmiddleY + 8; - - buffer.pos(middleX + btnx1, middleY + btny1, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); - buffer.pos(middleX + btnx1, middleY + btny2, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); - buffer.pos(middleX + btnx2, middleY + btny2, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); - buffer.pos(middleX + btnx2, middleY + btny1, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); - } - - tessellator.draw(); - - //Draw strings - //font.drawStringWithShadow("Actions", (int) (middleX - buttonDistance - 13) - font.getStringWidth("Actions") * 0.5f, (int) middleY - 38, 0xffffffff); - - //Draw option strings - for (int i = 0; i < currentBuildMode.options.length; i++) { - OptionEnum option = options[i]; - font.drawStringWithShadow(I18n.format(option.name), (int) (middleX + buttonDistance - 9), (int) middleY - 37 + i * 39, 0xeeeeeeff); - } - - String credits = "Effortless Building"; - font.drawStringWithShadow(credits, width - font.getStringWidth(credits) - 4, height - 10, 0x88888888); - - //Draw buildmode text - for (final MenuRegion menuRegion : modes) { - - if (menuRegion.highlighted) { - final double x = (menuRegion.x1 + menuRegion.x2) * 0.5; - final double y = (menuRegion.y1 + menuRegion.y2) * 0.5; - - int fixed_x = (int) (x * textDistance); - final int fixed_y = (int) (y * textDistance) - font.FONT_HEIGHT / 2; - final String text = I18n.format(menuRegion.mode.name); - - if ( x <= -0.2 ) { - fixed_x -= font.getStringWidth(text); - } else if ( -0.2 <= x && x <= 0.2 ) { - fixed_x -= font.getStringWidth(text) / 2; - } - - font.drawStringWithShadow(text, (int) middleX + fixed_x, (int) middleY + fixed_y, 0xffffffff); - } - } - - //Draw action text - for (final MenuButton button : buttons) { - if (button.highlighted) { - String text = TextFormatting.AQUA + button.name; - int wrap = 120; - String keybind = ""; - String keybindFormatted = ""; - - //Add keybind in brackets - if (button.action == ActionEnum.UNDO) { - keybind = ClientProxy.keyBindings[4].getLocalizedName(); - } - if (button.action == ActionEnum.REDO) { - keybind = ClientProxy.keyBindings[5].getLocalizedName(); - } - if (button.action == ActionEnum.REPLACE) { - keybind = ClientProxy.keyBindings[1].getLocalizedName(); - } - if (button.action == ActionEnum.OPEN_MODIFIER_SETTINGS) { - keybind = ClientProxy.keyBindings[0].getLocalizedName(); - } - if (currentBuildMode.options.length > 0) { - //Add (ctrl) to first two actions of first option - if (button.action == currentBuildMode.options[0].actions[0] - || button.action == currentBuildMode.options[0].actions[1]) { - keybind = ClientProxy.keyBindings[6].getLocalizedName(); - if (keybind.equals("Left Control")) keybind = "Ctrl"; - } - } - if (!keybind.isEmpty()) keybindFormatted = TextFormatting.GRAY + "(" + WordUtils.capitalizeFully(keybind) + ")"; - - if (button.textSide == Direction.WEST) { - - font.drawSplitString( text, (int) (middleX + button.x1 - 8 ) - font.getStringWidth(text), - (int) (middleY + button.y1 + 6), wrap, 0xffffffff); - - } else if (button.textSide == Direction.EAST) { - - font.drawSplitString(text, (int) (middleX + button.x2 + 8), - (int) (middleY + button.y1 + 6 ), wrap, 0xffffffff); - - } else if (button.textSide == Direction.UP || button.textSide == Direction.NORTH) { - - font.drawSplitString( keybindFormatted, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(keybindFormatted) * 0.5), - (int) (middleY + button.y1 - 26), wrap,0xffffffff); - - font.drawSplitString( text, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(text) * 0.5), - (int) (middleY + button.y1 - 14), wrap,0xffffffff); - - } else if (button.textSide == Direction.DOWN || button.textSide == Direction.SOUTH) { - - font.drawSplitString(text, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(text) * 0.5), - (int) (middleY + button.y1 + 26), wrap, 0xffffffff); - - font.drawSplitString(keybindFormatted, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(keybindFormatted) * 0.5), - (int) (middleY + button.y1 + 38), wrap, 0xffffffff); - - } - - } - } - - RenderSystem.popMatrix(); - } - - private boolean inTriangle(final double x1, final double y1, final double x2, final double y2, - final double x3, final double y3, final double x, final double y ) { - final double ab = (x1 - x) * (y2 - y) - (x2 - x) * (y1 - y); - final double bc = (x2 - x) * (y3 - y) - (x3 - x) * (y2 - y); - final double ca = (x3 - x) * (y1 - y) - (x1 - x) * (y3 - y); - return sign(ab) == sign(bc) && sign(bc) == sign(ca); - } - - private int sign(final double n) { - return n > 0 ? 1 : -1; - } - - /** - * Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton - */ - @Override - public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { - EffortlessBuilding.log("mouse clicked"); - - KeyBinding.updateKeyBindState(); - KeyBinding.setKeyBindState(ClientProxy.keyBindings[3].getKey(), true); - - if (mouseButton == 0) { - this.minecraft.displayGuiScreen(null); - - if (this.minecraft.currentScreen == null) { - this.minecraft.setGameFocused(true); - } - } - return super.mouseClicked(mouseX, mouseY, mouseButton); - } + public final BuildModeEnum mode; + public double x1, x2; + public double y1, y2; + public boolean highlighted; + + public MenuRegion(final BuildModeEnum mode) { + this.mode = mode; + } + + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/gui/buildmodifier/ArraySettingsGui.java b/src/main/java/nl/requios/effortlessbuilding/gui/buildmodifier/ArraySettingsGui.java index e060535..52c848a 100644 --- a/src/main/java/nl/requios/effortlessbuilding/gui/buildmodifier/ArraySettingsGui.java +++ b/src/main/java/nl/requios/effortlessbuilding/gui/buildmodifier/ArraySettingsGui.java @@ -1,9 +1,10 @@ package nl.requios.effortlessbuilding.gui.buildmodifier; +import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.Widget; -import net.minecraft.client.gui.widget.button.Button; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -22,181 +23,179 @@ import java.util.List; @OnlyIn(Dist.CLIENT) public class ArraySettingsGui extends GuiCollapsibleScrollEntry { - protected List arrayNumberFieldList = new ArrayList<>(); + protected List arrayNumberFieldList = new ArrayList<>(); - private GuiCheckBoxFixed buttonArrayEnabled; - private GuiNumberField textArrayOffsetX, textArrayOffsetY, textArrayOffsetZ, textArrayCount; + private GuiCheckBoxFixed buttonArrayEnabled; + private GuiNumberField textArrayOffsetX, textArrayOffsetY, textArrayOffsetZ, textArrayCount; - public ArraySettingsGui(GuiScrollPane scrollPane) { - super(scrollPane); - } + public ArraySettingsGui(GuiScrollPane scrollPane) { + super(scrollPane); + } - @Override - public void init(List buttons) { - super.init(buttons); + @Override + public void init(List buttons) { + super.init(buttons); - int y = top; - buttonArrayEnabled = new GuiCheckBoxFixed(left - 15 + 8, y, "", false) { - @Override - public void onClick(double mouseX, double mouseY) { - super.onClick(mouseX, mouseY); - setCollapsed(!buttonArrayEnabled.isChecked()); - } - }; - buttons.add(buttonArrayEnabled); + int y = top; + buttonArrayEnabled = new GuiCheckBoxFixed(left - 15 + 8, y, "", false) { + @Override + public void onClick(double mouseX, double mouseY) { + super.onClick(mouseX, mouseY); + setCollapsed(!buttonArrayEnabled.isChecked()); + } + }; + buttons.add(buttonArrayEnabled); - y = top + 20; - textArrayOffsetX = new GuiNumberField(font, buttons, left + 70, y, 50, 18); - textArrayOffsetX.setNumber(0); - textArrayOffsetX.setTooltip("How much each copy is shifted."); - arrayNumberFieldList.add(textArrayOffsetX); + y = top + 20; + textArrayOffsetX = new GuiNumberField(font, buttons, left + 70, y, 50, 18); + textArrayOffsetX.setNumber(0); + textArrayOffsetX.setTooltip(new StringTextComponent("How much each copy is shifted.")); + arrayNumberFieldList.add(textArrayOffsetX); - textArrayOffsetY = new GuiNumberField(font, buttons, left + 140, y, 50, 18); - textArrayOffsetY.setNumber(0); - textArrayOffsetY.setTooltip("How much each copy is shifted."); - arrayNumberFieldList.add(textArrayOffsetY); + textArrayOffsetY = new GuiNumberField(font, buttons, left + 140, y, 50, 18); + textArrayOffsetY.setNumber(0); + textArrayOffsetY.setTooltip(new StringTextComponent("How much each copy is shifted.")); + arrayNumberFieldList.add(textArrayOffsetY); - textArrayOffsetZ = new GuiNumberField(font, buttons, left + 210, y, 50, 18); - textArrayOffsetZ.setNumber(0); - textArrayOffsetZ.setTooltip("How much each copy is shifted."); - arrayNumberFieldList.add(textArrayOffsetZ); + textArrayOffsetZ = new GuiNumberField(font, buttons, left + 210, y, 50, 18); + textArrayOffsetZ.setNumber(0); + textArrayOffsetZ.setTooltip(new StringTextComponent("How much each copy is shifted.")); + arrayNumberFieldList.add(textArrayOffsetZ); - y = top + 50; - textArrayCount = new GuiNumberField(font, buttons, left + 55, y, 50, 18); - textArrayCount.setNumber(5); - textArrayCount.setTooltip("How many copies should be made."); - arrayNumberFieldList.add(textArrayCount); + y = top + 50; + textArrayCount = new GuiNumberField(font, buttons, left + 55, y, 50, 18); + textArrayCount.setNumber(5); + textArrayCount.setTooltip(new StringTextComponent("How many copies should be made.")); + arrayNumberFieldList.add(textArrayCount); - ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(mc.player); - if (modifierSettings != null) { - Array.ArraySettings a = modifierSettings.getArraySettings(); - buttonArrayEnabled.setIsChecked(a.enabled); - textArrayOffsetX.setNumber(a.offset.getX()); - textArrayOffsetY.setNumber(a.offset.getY()); - textArrayOffsetZ.setNumber(a.offset.getZ()); - textArrayCount.setNumber(a.count); - } + ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(mc.player); + if (modifierSettings != null) { + Array.ArraySettings a = modifierSettings.getArraySettings(); + buttonArrayEnabled.setIsChecked(a.enabled); + textArrayOffsetX.setNumber(a.offset.getX()); + textArrayOffsetY.setNumber(a.offset.getY()); + textArrayOffsetZ.setNumber(a.offset.getZ()); + textArrayCount.setNumber(a.count); + } - setCollapsed(!buttonArrayEnabled.isChecked()); - } + setCollapsed(!buttonArrayEnabled.isChecked()); + } - public void updateScreen() { - arrayNumberFieldList.forEach(GuiNumberField::update); - } + public void updateScreen() { + arrayNumberFieldList.forEach(GuiNumberField::update); + } - @Override - public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, - boolean isSelected, float partialTicks) { - int yy = y; - int offset = 8; + @Override + public void drawEntry(MatrixStack ms, int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, + boolean isSelected, float partialTicks) { + int yy = y; + int offset = 8; - buttonArrayEnabled.render(mouseX, mouseY, partialTicks); - if (buttonArrayEnabled.isChecked()) { - buttonArrayEnabled.y = yy; - font.drawString("Array enabled", left + offset, yy + 2, 0xFFFFFF); + buttonArrayEnabled.render(ms, mouseX, mouseY, partialTicks); + if (buttonArrayEnabled.isChecked()) { + buttonArrayEnabled.y = yy; + font.drawString(ms, "Array enabled", left + offset, yy + 2, 0xFFFFFF); - yy = y + 20; - font.drawString("Offset", left + offset, yy + 5, 0xFFFFFF); - font.drawString("X", left + 50 + offset, yy + 5, 0xFFFFFF); - textArrayOffsetX.y = yy; - font.drawString("Y", left + 120 + offset, yy + 5, 0xFFFFFF); - textArrayOffsetY.y = yy; - font.drawString("Z", left + 190 + offset, yy + 5, 0xFFFFFF); - textArrayOffsetZ.y = yy; + yy = y + 20; + font.drawString(ms, "Offset", left + offset, yy + 5, 0xFFFFFF); + font.drawString(ms, "X", left + 50 + offset, yy + 5, 0xFFFFFF); + textArrayOffsetX.y = yy; + font.drawString(ms, "Y", left + 120 + offset, yy + 5, 0xFFFFFF); + textArrayOffsetY.y = yy; + font.drawString(ms, "Z", left + 190 + offset, yy + 5, 0xFFFFFF); + textArrayOffsetZ.y = yy; - yy = y + 50; - font.drawString("Count", left + offset, yy + 5, 0xFFFFFF); - textArrayCount.y = yy; + yy = y + 50; + font.drawString(ms, "Count", left + offset, yy + 5, 0xFFFFFF); + textArrayCount.y = yy; - int currentReach = Math.max(-1, getArrayReach()); - int maxReach = ReachHelper.getMaxReach(mc.player); - TextFormatting reachColor = isCurrentReachValid(currentReach, maxReach) ? TextFormatting.GRAY : TextFormatting.RED; - String reachText = "Reach: " + reachColor + currentReach + TextFormatting.GRAY + "/" + TextFormatting.GRAY + maxReach; - font.drawString(reachText, left + 176 + offset, yy + 5, 0xFFFFFF); + int currentReach = Math.max(-1, getArrayReach()); + int maxReach = ReachHelper.getMaxReach(mc.player); + TextFormatting reachColor = isCurrentReachValid(currentReach, maxReach) ? TextFormatting.GRAY : TextFormatting.RED; + String reachText = "Reach: " + reachColor + currentReach + TextFormatting.GRAY + "/" + TextFormatting.GRAY + maxReach; + font.drawString(ms, reachText, left + 176 + offset, yy + 5, 0xFFFFFF); - arrayNumberFieldList.forEach(numberField -> numberField.drawNumberField(mouseX, mouseY, partialTicks)); - } else { - buttonArrayEnabled.y = yy; - font.drawString("Array disabled", left + offset, yy + 2, 0x999999); - } + arrayNumberFieldList.forEach(numberField -> numberField.drawNumberField(ms, mouseX, mouseY, partialTicks)); + } else { + buttonArrayEnabled.y = yy; + font.drawString(ms, "Array disabled", left + offset, yy + 2, 0x999999); + } - } + } - public void drawTooltip(Screen guiScreen, int mouseX, int mouseY) { - //Draw tooltips last - if (buttonArrayEnabled.isChecked()) - { - arrayNumberFieldList.forEach(numberField -> numberField.drawTooltip(scrollPane.parent, mouseX, mouseY)); - } - } + public void drawTooltip(MatrixStack ms, Screen guiScreen, int mouseX, int mouseY) { + //Draw tooltips last + if (buttonArrayEnabled.isChecked()) { + arrayNumberFieldList.forEach(numberField -> numberField.drawTooltip(ms, scrollPane.parent, mouseX, mouseY)); + } + } - @Override - public boolean charTyped(char typedChar, int keyCode) { - super.charTyped(typedChar, keyCode); - for (GuiNumberField numberField : arrayNumberFieldList) { - numberField.charTyped(typedChar, keyCode); - } - return true; - } + @Override + public boolean charTyped(char typedChar, int keyCode) { + super.charTyped(typedChar, keyCode); + for (GuiNumberField numberField : arrayNumberFieldList) { + numberField.charTyped(typedChar, keyCode); + } + return true; + } - @Override - public boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY) { - arrayNumberFieldList.forEach(numberField -> numberField.mouseClicked(mouseX, mouseY, mouseEvent)); + @Override + public boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY) { + arrayNumberFieldList.forEach(numberField -> numberField.mouseClicked(mouseX, mouseY, mouseEvent)); - boolean insideArrayEnabledLabel = mouseX >= left && mouseX < right && relativeY >= -2 && relativeY < 12; + boolean insideArrayEnabledLabel = mouseX >= left && mouseX < right && relativeY >= -2 && relativeY < 12; - if (insideArrayEnabledLabel) { - buttonArrayEnabled.playDownSound(this.mc.getSoundHandler()); - buttonArrayEnabled.onClick(mouseX, mouseY); - } + if (insideArrayEnabledLabel) { + buttonArrayEnabled.playDownSound(this.mc.getSoundHandler()); + buttonArrayEnabled.onClick(mouseX, mouseY); + } - return true; - } + return true; + } - public Array.ArraySettings getArraySettings() { - boolean arrayEnabled = buttonArrayEnabled.isChecked(); - BlockPos arrayOffset = new BlockPos(0, 0, 0); - try { - arrayOffset = new BlockPos(textArrayOffsetX.getNumber(), textArrayOffsetY.getNumber(), textArrayOffsetZ.getNumber()); - } catch (NumberFormatException | NullPointerException ex) { - EffortlessBuilding.log(mc.player, "Array offset not a valid number."); - } + public Array.ArraySettings getArraySettings() { + boolean arrayEnabled = buttonArrayEnabled.isChecked(); + BlockPos arrayOffset = new BlockPos(0, 0, 0); + try { + arrayOffset = new BlockPos(textArrayOffsetX.getNumber(), textArrayOffsetY.getNumber(), textArrayOffsetZ.getNumber()); + } catch (NumberFormatException | NullPointerException ex) { + EffortlessBuilding.log(mc.player, "Array offset not a valid number."); + } - int arrayCount = 5; - try { - arrayCount = (int) textArrayCount.getNumber(); - } catch (NumberFormatException | NullPointerException ex) { - EffortlessBuilding.log(mc.player, "Array count not a valid number."); - } + int arrayCount = 5; + try { + arrayCount = (int) textArrayCount.getNumber(); + } catch (NumberFormatException | NullPointerException ex) { + EffortlessBuilding.log(mc.player, "Array count not a valid number."); + } - return new Array.ArraySettings(arrayEnabled, arrayOffset, arrayCount); - } + return new Array.ArraySettings(arrayEnabled, arrayOffset, arrayCount); + } - @Override - protected String getName() { - return "Array"; - } + @Override + protected String getName() { + return "Array"; + } - @Override - protected int getExpandedHeight() { - return 80; - } + @Override + protected int getExpandedHeight() { + return 80; + } - private int getArrayReach() { - try - { - //find largest offset - double x = Math.abs(textArrayOffsetX.getNumber()); - double y = Math.abs(textArrayOffsetY.getNumber()); - double z = Math.abs(textArrayOffsetZ.getNumber()); - double largestOffset = Math.max(Math.max(x, y), z); - return (int) (largestOffset * textArrayCount.getNumber()); - } catch (NumberFormatException | NullPointerException ex) { - return -1; - } - } + private int getArrayReach() { + try { + //find largest offset + double x = Math.abs(textArrayOffsetX.getNumber()); + double y = Math.abs(textArrayOffsetY.getNumber()); + double z = Math.abs(textArrayOffsetZ.getNumber()); + double largestOffset = Math.max(Math.max(x, y), z); + return (int) (largestOffset * textArrayCount.getNumber()); + } catch (NumberFormatException | NullPointerException ex) { + return -1; + } + } - private boolean isCurrentReachValid(int currentReach, int maxReach) { - return currentReach <= maxReach && currentReach > -1; - } + private boolean isCurrentReachValid(int currentReach, int maxReach) { + return currentReach <= maxReach && currentReach > -1; + } } diff --git a/src/main/java/nl/requios/effortlessbuilding/gui/buildmodifier/MirrorSettingsGui.java b/src/main/java/nl/requios/effortlessbuilding/gui/buildmodifier/MirrorSettingsGui.java index df5f3dc..4102ed7 100644 --- a/src/main/java/nl/requios/effortlessbuilding/gui/buildmodifier/MirrorSettingsGui.java +++ b/src/main/java/nl/requios/effortlessbuilding/gui/buildmodifier/MirrorSettingsGui.java @@ -1,10 +1,12 @@ package nl.requios.effortlessbuilding.gui.buildmodifier; +import com.mojang.blaze3d.matrix.MatrixStack; +import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.Widget; import net.minecraft.client.gui.widget.button.Button; -import net.minecraft.client.gui.screen.Screen; import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.Vec3d; +import net.minecraft.util.math.vector.Vector3d; +import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -22,262 +24,261 @@ import java.util.List; @OnlyIn(Dist.CLIENT) public class MirrorSettingsGui extends GuiCollapsibleScrollEntry { - protected static final ResourceLocation BUILDING_ICONS = new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/building_icons.png"); + protected static final ResourceLocation BUILDING_ICONS = new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/building_icons.png"); - protected List